






'''simple docstring'''
import inspect
from typing import Callable, List, Optional, Union

import torch
from transformers import (
    CLIPImageProcessor,
    CLIPTextModel,
    CLIPTokenizer,
    WhisperForConditionalGeneration,
    WhisperProcessor,
)

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.utils import logging


UpperCamelCase__			=      logging.get_logger(__name__)  # pylint: disable=invalid-name


class 							_UpperCAmelCase    (		SCREAMING_SNAKE_CASE_      ):




    def __init__(      self	:							Tuple	,  a	:							WhisperForConditionalGeneration	,  a	:							WhisperProcessor	,  a	:							AutoencoderKL	,  a	:							CLIPTextModel	,  a	:							CLIPTokenizer	,  a	:							UNetaDConditionModel	,  a	:							Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]	,  a	:							StableDiffusionSafetyChecker	,  a	:							CLIPImageProcessor	,  ):






       '''simple docstring'''






       super().__init__()

       if safety_checker is None:
          logger.warning(
              f"""You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"""
              " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
              " results in services or applications open to the public. Both the diffusers team and Hugging Face"
              " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
              " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
              " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."      )

       self.register_modules(
           speech_model=snake_case__	,  speech_processor=snake_case__	,  vae=snake_case__	,  text_encoder=snake_case__	,  tokenizer=snake_case__	,  unet=snake_case__	,  scheduler=snake_case__	,  feature_extractor=snake_case__	,  )




    def 					lowerCAmelCase__					(      self	:							List[Any]	,  a	:							Optional[Union[str, int]] = "auto"      ):






       '''simple docstring'''






       if slice_size == "auto":
          lowercase_						:     int							     =  self.unet.config.attention_head_dim // 2
       self.unet.set_attention_slice(snake_case__      )




    def 					lowerCAmelCase__					(      self	:							Optional[Any]      ):






       '''simple docstring'''






       self.enable_attention_slicing(snake_case__      )





    @torch.no_grad()
    def __call__(      self	:							Union[str, Any]	,  a	:							List[Any]	,  a	:							str=1_6_0_0_0	,  a	:							int = 5_1_2	,  a	:							int = 5_1_2	,  a	:							int = 5_0	,  a	:							float = 7.5	,  a	:							Optional[Union[str, List[str]]] = None	,  a	:							Optional[int] = 1	,  a	:							float = 0.0	,  a	:							Optional[torch.Generator] = None	,  a	:							Optional[torch.FloatTensor] = None	,  a	:							Optional[str] = "pil"	,  a	:							bool = True	,  a	:							Optional[Callable[[int, int, torch.FloatTensor], None]] = None	,  a	:							int = 1	,  **a	:							List[Any]	,  ):






       '''simple docstring'''






       lowercase_						:     Dict							     =  self.speech_processor.feature_extractor(
           snake_case__	,  return_tensors="pt"	,  sampling_rate=snake_case__      ).input_features.to(self.device      )
       lowercase_						:     Optional[int]							     =  self.speech_model.generate(snake_case__	,  max_length=4_8_0_0_0_0      )

       lowercase_						:     Optional[Any]							     =  self.speech_processor.tokenizer.batch_decode(snake_case__	,  skip_special_tokens=snake_case__	,  normalize=snake_case__      )[
           0
       ]

       if isinstance(snake_case__	,  snake_case__      ):
          lowercase_						:     List[Any]							     =  1
       elif isinstance(snake_case__	,  snake_case__      ):
          lowercase_						:     Any							     =  len(snake_case__      )
       else:
          raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(snake_case__      )}"""      )

       if height % 8 != 0 or width % 8 != 0:
          raise ValueError(f"""`height` and `width` have to be divisible by 8 but are {height} and {width}."""      )

       if (callback_steps is None) or (
           callback_steps is not None and (not isinstance(snake_case__	,  snake_case__      ) or callback_steps <= 0)
       ):
          raise ValueError(
              f"""`callback_steps` has to be a positive integer but is {callback_steps} of type"""
              f""" {type(snake_case__      )}."""      )

       # get prompt text embeddings
       lowercase_						:     Tuple							     =  self.tokenizer(
           snake_case__	,  padding="max_length"	,  max_length=self.tokenizer.model_max_length	,  return_tensors="pt"	,  )
       lowercase_						:     List[Any]							     =  text_inputs.input_ids

       if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
          lowercase_						:     Optional[int]							     =  self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]      )
          logger.warning(
              "The following part of your input was truncated because CLIP can only handle sequences up to"
              f""" {self.tokenizer.model_max_length} tokens: {removed_text}"""      )
          lowercase_						:     Tuple							     =  text_input_ids[:, : self.tokenizer.model_max_length]
       lowercase_						:     Union[str, Any]							     =  self.text_encoder(text_input_ids.to(self.device      )      )[0]

       # duplicate text embeddings for each generation per prompt, using mps friendly method
       lowercase_     ,		lowercase_     ,		lowercase_						:     Dict							     =  text_embeddings.shape
       lowercase_						:     Optional[Any]							     =  text_embeddings.repeat(1	,  snake_case__	,  1      )
       lowercase_						:     List[Any]							     =  text_embeddings.view(bs_embed * num_images_per_prompt	,  snake_case__	,  -1      )

       # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
       # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
       # corresponds to doing no classifier free guidance.
       lowercase_						:     str							     =  guidance_scale > 1.0
       # get unconditional embeddings for classifier free guidance
       if do_classifier_free_guidance:
          lowercase_						:     List[Any]							     =  4_2
          if negative_prompt is None:
             lowercase_						:     Union[str, Any]							     =  [""] * batch_size
          elif type(snake_case__      ) is not type(snake_case__      ):
             raise TypeError(
                 f"""`negative_prompt` should be the same type to `prompt`, but got {type(snake_case__      )} !="""
                 f""" {type(snake_case__      )}."""      )
          elif isinstance(snake_case__	,  snake_case__      ):
             lowercase_						:     Any							     =  [negative_prompt]
          elif batch_size != len(snake_case__      ):
             raise ValueError(
                 f"""`negative_prompt`: {negative_prompt} has batch size {len(snake_case__      )}, but `prompt`:"""
                 f""" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"""
                 " the batch size of `prompt`."      )
          else:
             lowercase_						:     List[Any]							     =  negative_prompt

          lowercase_						:     int							     =  text_input_ids.shape[-1]
          lowercase_						:     Tuple							     =  self.tokenizer(
              snake_case__	,  padding="max_length"	,  max_length=snake_case__	,  truncation=snake_case__	,  return_tensors="pt"	,  )
          lowercase_						:     List[Any]							     =  self.text_encoder(uncond_input.input_ids.to(self.device      )      )[0]

          # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
          lowercase_						:     Optional[int]							     =  uncond_embeddings.shape[1]
          lowercase_						:     Optional[Any]							     =  uncond_embeddings.repeat(1	,  snake_case__	,  1      )
          lowercase_						:     Union[str, Any]							     =  uncond_embeddings.view(batch_size * num_images_per_prompt	,  snake_case__	,  -1      )

          # For classifier free guidance, we need to do two forward passes.
          # Here we concatenate the unconditional and text embeddings into a single batch
          # to avoid doing two forward passes
          lowercase_						:     Optional[Any]							     =  torch.cat([uncond_embeddings, text_embeddings]      )

       # get the initial random noise unless the user supplied it

       # Unlike in other pipelines, latents need to be generated in the target device
       # for 1-to-1 results reproducibility with the CompVis implementation.
       # However this currently doesn't work in `mps`.
       lowercase_						:     List[str]							     =  (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
       lowercase_						:     Tuple							     =  text_embeddings.dtype
       if latents is None:
          if self.device.type == "mps":
             # randn does not exist on mps
             lowercase_						:     Any							     =  torch.randn(snake_case__	,  generator=snake_case__	,  device="cpu"	,  dtype=snake_case__      ).to(
                 self.device      )
          else:
             lowercase_						:     Union[str, Any]							     =  torch.randn(snake_case__	,  generator=snake_case__	,  device=self.device	,  dtype=snake_case__      )
       else:
          if latents.shape != latents_shape:
             raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}"""      )
          lowercase_						:     List[str]							     =  latents.to(self.device      )

       # set timesteps
       self.scheduler.set_timesteps(snake_case__      )

       # Some schedulers like PNDM have timesteps as arrays
       # It's more optimized to move all timesteps to correct device beforehand
       lowercase_						:     Dict							     =  self.scheduler.timesteps.to(self.device      )

       # scale the initial noise by the standard deviation required by the scheduler
       lowercase_						:     Optional[Any]							     =  latents * self.scheduler.init_noise_sigma

       # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
       # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
       # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
       # and should be between [0, 1]
       lowercase_						:     Optional[Any]							     =  "eta" in set(inspect.signature(self.scheduler.step      ).parameters.keys()      )
       lowercase_						:     List[str]							     =  {}
       if accepts_eta:
          lowercase_						:     Optional[Any]							     =  eta

       for i, t in enumerate(self.progress_bar(snake_case__      )      ):
          # expand the latents if we are doing classifier free guidance
          lowercase_						:     List[Any]							     =  torch.cat([latents] * 2      ) if do_classifier_free_guidance else latents
          lowercase_						:     int							     =  self.scheduler.scale_model_input(snake_case__	,  snake_case__      )

          # predict the noise residual
          lowercase_						:     str							     =  self.unet(snake_case__	,  snake_case__	,  encoder_hidden_states=snake_case__      ).sample

          # perform guidance
          if do_classifier_free_guidance:
             lowercase_     ,		lowercase_						:     Dict							     =  noise_pred.chunk(2      )
             lowercase_						:     int							     =  noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

          # compute the previous noisy sample x_t -> x_t-1
          lowercase_						:     Optional[int]							     =  self.scheduler.step(snake_case__	,  snake_case__	,  snake_case__	,  **snake_case__      ).prev_sample

          # call the callback, if provided
          if callback is not None and i % callback_steps == 0:
             callback(snake_case__	,  snake_case__	,  snake_case__      )

       lowercase_						:     List[Any]							     =  1 / 0.1_8215 * latents
       lowercase_						:     Union[str, Any]							     =  self.vae.decode(snake_case__      ).sample

       lowercase_						:     Optional[int]							     =  (image / 2 + 0.5).clamp(0	,  1      )

       # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
       lowercase_						:     Optional[Any]							     =  image.cpu().permute(0	,  2	,  3	,  1      ).float().numpy()

       if output_type == "pil":
          lowercase_						:     str							     =  self.numpy_to_pil(snake_case__      )

       if not return_dict:
          return image

       return StableDiffusionPipelineOutput(images=snake_case__	,  nsfw_content_detected=snake_case__      )





import copy
import unittest

from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch

				from transformers import (
				    MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
				    MODEL_FOR_QUESTION_ANSWERING_MAPPING,
				    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
				    MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
				    LayoutLMvaConfig,
				    LayoutLMvaForQuestionAnswering,
				    LayoutLMvaForSequenceClassification,
				    LayoutLMvaForTokenClassification,
				    LayoutLMvaModel,
				)
				from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
				from PIL import Image

				from transformers import LayoutLMvaImageProcessor





class     lowerCAmelCase__     :


		'''simple docstring'''






		def __init__(       self     :     Union[str, Any]     ,  snake_case__     :     int     ,  snake_case__     :     List[str]=2     ,  snake_case__     :     List[str]=3     ,  snake_case__     :     Tuple=4     ,  snake_case__     :     Optional[Any]=2     ,  snake_case__     :     int=7     ,  snake_case__     :     Optional[Any]=True     ,  snake_case__     :     Union[str, Any]=True     ,  snake_case__     :     Tuple=True     ,  snake_case__     :     int=True     ,  snake_case__     :     Optional[Any]=9_9     ,  snake_case__     :     Optional[Any]=3_6     ,  snake_case__     :     Tuple=3     ,  snake_case__     :     int=4     ,  snake_case__     :     Tuple=3_7     ,  snake_case__     :     Union[str, Any]="gelu"     ,  snake_case__     :     Any=0.1     ,  snake_case__     :     Optional[int]=0.1     ,  snake_case__     :     Dict=5_1_2     ,  snake_case__     :     Optional[int]=1_6     ,  snake_case__     :     Dict=2     ,  snake_case__     :     Dict=0.02     ,  snake_case__     :     List[Any]=6     ,  snake_case__     :     int=6     ,  snake_case__     :     Tuple=3     ,  snake_case__     :     List[Any]=4     ,  snake_case__     :     List[str]=None     ,  snake_case__     :     Optional[Any]=1_0_0_0     ,  )      ->	Optional[int]:
				_lowerCamelCase				   =  parent
				_lowerCamelCase				   =  batch_size
				_lowerCamelCase				   =  num_channels
				_lowerCamelCase				   =  image_size
				_lowerCamelCase				   =  patch_size
				_lowerCamelCase				   =  text_seq_length
				_lowerCamelCase				   =  is_training
				_lowerCamelCase				   =  use_input_mask
				_lowerCamelCase				   =  use_token_type_ids
				_lowerCamelCase				   =  use_labels
				_lowerCamelCase				   =  vocab_size
				_lowerCamelCase				   =  hidden_size
				_lowerCamelCase				   =  num_hidden_layers
				_lowerCamelCase				   =  num_attention_heads
				_lowerCamelCase				   =  intermediate_size
				_lowerCamelCase				   =  hidden_act
				_lowerCamelCase				   =  hidden_dropout_prob
				_lowerCamelCase				   =  attention_probs_dropout_prob
				_lowerCamelCase				   =  max_position_embeddings
				_lowerCamelCase				   =  type_vocab_size
				_lowerCamelCase				   =  type_sequence_label_size
				_lowerCamelCase				   =  initializer_range
				_lowerCamelCase				   =  coordinate_size
				_lowerCamelCase				   =  shape_size
				_lowerCamelCase				   =  num_labels
				_lowerCamelCase				   =  num_choices
				_lowerCamelCase				   =  scope
				_lowerCamelCase				   =  range_bbox

				# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
				_lowerCamelCase				   =  text_seq_length
				_lowerCamelCase				   =  (image_size // patch_size) ** 2 + 1
				_lowerCamelCase				   =  self.text_seq_length + self.image_seq_length
		def   _snake_case       (       self     :     int		)      ->	Any:
				_lowerCamelCase				   =  ids_tensor([self.batch_size, self.text_seq_length]     ,  self.vocab_size		)

				_lowerCamelCase				   =  ids_tensor([self.batch_size, self.text_seq_length, 4]     ,  self.range_bbox		)
				# Ensure that bbox is legal
				for i in range(bbox.shape[0]		):
						for j in range(bbox.shape[1]		):
								if bbox[i, j, 3] < bbox[i, j, 1]:
										_lowerCamelCase				   =  bbox[i, j, 3]
										_lowerCamelCase				   =  bbox[i, j, 1]
										_lowerCamelCase				   =  t
								if bbox[i, j, 2] < bbox[i, j, 0]:
										_lowerCamelCase				   =  bbox[i, j, 2]
										_lowerCamelCase				   =  bbox[i, j, 0]
										_lowerCamelCase				   =  t

				_lowerCamelCase				   =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

				_lowerCamelCase				   =  None
				if self.use_input_mask:
						_lowerCamelCase				   =  random_attention_mask([self.batch_size, self.text_seq_length]		)

				_lowerCamelCase				   =  None
				if self.use_token_type_ids:
						_lowerCamelCase				   =  ids_tensor([self.batch_size, self.text_seq_length]     ,  self.type_vocab_size		)

				_lowerCamelCase				   =  None
				_lowerCamelCase				   =  None
				if self.use_labels:
						_lowerCamelCase				   =  ids_tensor([self.batch_size]     ,  self.type_sequence_label_size		)
						_lowerCamelCase				   =  ids_tensor([self.batch_size, self.text_seq_length]     ,  self.num_labels		)

				_lowerCamelCase				   =  LayoutLMvaConfig(
				    vocab_size=self.vocab_size     ,  hidden_size=self.hidden_size     ,  num_hidden_layers=self.num_hidden_layers     ,  num_attention_heads=self.num_attention_heads     ,  intermediate_size=self.intermediate_size     ,  hidden_act=self.hidden_act     ,  hidden_dropout_prob=self.hidden_dropout_prob     ,  attention_probs_dropout_prob=self.attention_probs_dropout_prob     ,  max_position_embeddings=self.max_position_embeddings     ,  type_vocab_size=self.type_vocab_size     ,  initializer_range=self.initializer_range     ,  coordinate_size=self.coordinate_size     ,  shape_size=self.shape_size     ,  input_size=self.image_size     ,  patch_size=self.patch_size     ,  )

				return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels
		def   _snake_case       (       self     :     Optional[int]     ,  snake_case__     :     Optional[Any]     ,  snake_case__     :     Any     ,  snake_case__     :     str     ,  snake_case__     :     Tuple     ,  snake_case__     :     Dict     ,  snake_case__     :     Optional[int]     ,  snake_case__     :     int     ,  snake_case__     :     Optional[Any]		)      ->	Any:
				_lowerCamelCase				   =  LayoutLMvaModel(config=snake_case__		)
				model.to(snake_case__		)
				model.eval()

				# text + image
				_lowerCamelCase				   =  model(snake_case__     ,  pixel_values=snake_case__		)
				_lowerCamelCase				   =  model(
				    snake_case__     ,  bbox=snake_case__     ,  pixel_values=snake_case__     ,  attention_mask=snake_case__     ,  token_type_ids=snake_case__		)
				_lowerCamelCase				   =  model(snake_case__     ,  bbox=snake_case__     ,  pixel_values=snake_case__     ,  token_type_ids=snake_case__		)
				_lowerCamelCase				   =  model(snake_case__     ,  bbox=snake_case__     ,  pixel_values=snake_case__		)

				self.parent.assertEqual(result.last_hidden_state.shape     ,  (self.batch_size, self.seq_length, self.hidden_size)		)

				# text only
				_lowerCamelCase				   =  model(snake_case__		)
				self.parent.assertEqual(
				    result.last_hidden_state.shape     ,  (self.batch_size, self.text_seq_length, self.hidden_size)		)

				# image only
				_lowerCamelCase				   =  model(pixel_values=snake_case__		)
				self.parent.assertEqual(
				    result.last_hidden_state.shape     ,  (self.batch_size, self.image_seq_length, self.hidden_size)		)
		def   _snake_case       (       self     :     Any     ,  snake_case__     :     Tuple     ,  snake_case__     :     Union[str, Any]     ,  snake_case__     :     Optional[int]     ,  snake_case__     :     List[Any]     ,  snake_case__     :     Any     ,  snake_case__     :     str     ,  snake_case__     :     str     ,  snake_case__     :     int		)      ->	List[Any]:
				_lowerCamelCase				   =  self.num_labels
				_lowerCamelCase				   =  LayoutLMvaForSequenceClassification(snake_case__		)
				model.to(snake_case__		)
				model.eval()
				_lowerCamelCase				   =  model(
				    snake_case__     ,  bbox=snake_case__     ,  pixel_values=snake_case__     ,  attention_mask=snake_case__     ,  token_type_ids=snake_case__     ,  labels=snake_case__     ,  )
				self.parent.assertEqual(result.logits.shape     ,  (self.batch_size, self.num_labels)		)
		def   _snake_case       (       self     :     Dict     ,  snake_case__     :     Tuple     ,  snake_case__     :     Optional[Any]     ,  snake_case__     :     str     ,  snake_case__     :     str     ,  snake_case__     :     Any     ,  snake_case__     :     List[str]     ,  snake_case__     :     Tuple     ,  snake_case__     :     Dict		)      ->	Optional[Any]:
				_lowerCamelCase				   =  self.num_labels
				_lowerCamelCase				   =  LayoutLMvaForTokenClassification(config=snake_case__		)
				model.to(snake_case__		)
				model.eval()
				_lowerCamelCase				   =  model(
				    snake_case__     ,  bbox=snake_case__     ,  pixel_values=snake_case__     ,  attention_mask=snake_case__     ,  token_type_ids=snake_case__     ,  labels=snake_case__     ,  )
				self.parent.assertEqual(result.logits.shape     ,  (self.batch_size, self.text_seq_length, self.num_labels)		)
		def   _snake_case       (       self     :     str     ,  snake_case__     :     int     ,  snake_case__     :     Optional[int]     ,  snake_case__     :     str     ,  snake_case__     :     List[str]     ,  snake_case__     :     List[Any]     ,  snake_case__     :     List[Any]     ,  snake_case__     :     int     ,  snake_case__     :     Any		)      ->	Dict:
				_lowerCamelCase				   =  LayoutLMvaForQuestionAnswering(config=snake_case__		)
				model.to(snake_case__		)
				model.eval()
				_lowerCamelCase				   =  model(
				    snake_case__     ,  bbox=snake_case__     ,  pixel_values=snake_case__     ,  attention_mask=snake_case__     ,  token_type_ids=snake_case__     ,  start_positions=snake_case__     ,  end_positions=snake_case__     ,  )
				self.parent.assertEqual(result.start_logits.shape     ,  (self.batch_size, self.seq_length)		)
				self.parent.assertEqual(result.end_logits.shape     ,  (self.batch_size, self.seq_length)		)



		def   _snake_case       (       self     :     str		)      ->	List[str]:
				_lowerCamelCase				   =  self.prepare_config_and_inputs()
				(
				    (
				    _lowerCamelCase
				)   ,							(
				    _lowerCamelCase
				)   ,							(
				    _lowerCamelCase
				)   ,							(
				    _lowerCamelCase
				)   ,							(
				    _lowerCamelCase
				)   ,							(
				    _lowerCamelCase
				)   ,							(
				    _lowerCamelCase
				)   ,							(
				    _lowerCamelCase
				)   ,							
				)				   =  config_and_inputs
				_lowerCamelCase				   =  {
				    'input_ids': input_ids,
				    'bbox': bbox,
				    'pixel_values': pixel_values,
				    'token_type_ids': token_type_ids,
				    'attention_mask': input_mask,
				}
				return config, inputs_dict





@require_torch
class     lowerCAmelCase__     (				SCREAMING_SNAKE_CASE_     ,SCREAMING_SNAKE_CASE_     ,unittest.TestCase			):


		'''simple docstring'''






		lowerCAmelCase_     =   False
		lowerCAmelCase_     =   False
		lowerCAmelCase_     =   False

		lowerCAmelCase_     =   (
		    (
		        LayoutLMvaModel,
		        LayoutLMvaForSequenceClassification,
		        LayoutLMvaForTokenClassification,
		        LayoutLMvaForQuestionAnswering,
		    )
		    if is_torch_available()
		    else ()
		)
		lowerCAmelCase_     =   (
		    {'document-question-answering': LayoutLMvaForQuestionAnswering, 'feature-extraction': LayoutLMvaModel}
		    if is_torch_available()
		    else {}
		)
		def   _snake_case       (       self     :     Union[str, Any]     ,  snake_case__     :     Tuple     ,  snake_case__     :     Optional[Any]     ,  snake_case__     :     int     ,  snake_case__     :     Tuple     ,  snake_case__     :     Union[str, Any]		)      ->	str:
				# `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual
				# embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has
				# the sequence dimension of the text embedding only.
				# (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`)
				return True
		def   _snake_case       (       self     :     str		)      ->	Any:
				_lowerCamelCase				   =  LayoutLMvaModelTester(self		)
				_lowerCamelCase				   =  ConfigTester(self     ,  config_class=snake_case__     ,  hidden_size=3_7		)
		def   _snake_case       (       self     :     List[str]     ,  snake_case__     :     str     ,  snake_case__     :     List[Any]     ,  snake_case__     :     Dict=False		)      ->	str:
				_lowerCamelCase				   =  copy.deepcopy(snake_case__		)
				if model_class in get_values(snake_case__		):
						_lowerCamelCase				   =  {
						    k: v.unsqueeze(1		).expand(-1     ,  self.model_tester.num_choices     ,  -1		).contiguous()
						    if isinstance(snake_case__     ,  torch.Tensor		) and v.ndim > 1
						    else v
						    for k, v in inputs_dict.items()
						}
				if return_labels:
						if model_class in get_values(snake_case__		):
								_lowerCamelCase				   =  torch.ones(self.model_tester.batch_size     ,  dtype=torch.long     ,  device=snake_case__		)
						elif model_class in get_values(snake_case__		):
								_lowerCamelCase				   =  torch.zeros(
								    self.model_tester.batch_size     ,  dtype=torch.long     ,  device=snake_case__		)
								_lowerCamelCase				   =  torch.zeros(
								    self.model_tester.batch_size     ,  dtype=torch.long     ,  device=snake_case__		)
						elif model_class in [
						    *get_values(snake_case__		),
						]:
								_lowerCamelCase				   =  torch.zeros(
								    self.model_tester.batch_size     ,  dtype=torch.long     ,  device=snake_case__		)
						elif model_class in [
						    *get_values(snake_case__		),
						]:
								_lowerCamelCase				   =  torch.zeros(
								    (self.model_tester.batch_size, self.model_tester.text_seq_length)     ,  dtype=torch.long     ,  device=snake_case__     ,  )

				return inputs_dict
		def   _snake_case       (       self     :     Any		)      ->	List[str]:
				self.config_tester.run_common_tests()
		def   _snake_case       (       self     :     int		)      ->	Optional[int]:
				_lowerCamelCase				   =  self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*snake_case__		)
		def   _snake_case       (       self     :     int		)      ->	Any:
				_lowerCamelCase				   =  self.model_tester.prepare_config_and_inputs()
				for type in ["absolute", "relative_key", "relative_key_query"]:
						_lowerCamelCase				   =  type
						self.model_tester.create_and_check_model(*snake_case__		)
		def   _snake_case       (       self     :     int		)      ->	Any:
				_lowerCamelCase				   =  self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_sequence_classification(*snake_case__		)
		def   _snake_case       (       self     :     Any		)      ->	Any:
				_lowerCamelCase				   =  self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_token_classification(*snake_case__		)
		def   _snake_case       (       self     :     int		)      ->	List[Any]:
				_lowerCamelCase				   =  self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_question_answering(*snake_case__		)



		@slow
		def   _snake_case       (       self     :     Optional[int]		)      ->	List[Any]:
				for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						_lowerCamelCase				   =  LayoutLMvaModel.from_pretrained(snake_case__		)
						self.assertIsNotNone(snake_case__		)



def 	lowerCamelCase					(	)   ->    List[Any]:
		_lowerCamelCase				   =  Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
		return image





@require_torch
class     lowerCAmelCase__     (				unittest.TestCase			):


		'''simple docstring'''






		@cached_property
		def   _snake_case       (       self     :     int		)      ->	Any:
				return LayoutLMvaImageProcessor(apply_ocr=snake_case__		) if is_vision_available() else None



		@slow
		def   _snake_case       (       self     :     List[str]		)      ->	Tuple:
				_lowerCamelCase				   =  LayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base'		).to(snake_case__		)

				_lowerCamelCase				   =  self.default_image_processor
				_lowerCamelCase				   =  prepare_img()
				_lowerCamelCase				   =  image_processor(images=snake_case__     ,  return_tensors='pt'		).pixel_values.to(snake_case__		)

				_lowerCamelCase				   =  torch.tensor([[1, 2]]		)
				_lowerCamelCase				   =  torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]		).unsqueeze(0		)

				# forward pass
				_lowerCamelCase				   =  model(
				    input_ids=input_ids.to(snake_case__		)     ,  bbox=bbox.to(snake_case__		)     ,  pixel_values=pixel_values.to(snake_case__		)     ,  )

				# verify the logits
				_lowerCamelCase				   =  torch.Size((1, 1_9_9, 7_6_8)		)
				self.assertEqual(outputs.last_hidden_state.shape     ,  snake_case__		)

				_lowerCamelCase				   =  torch.tensor(
				    [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]]		).to(snake_case__		)

				self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]     ,  snake_case__     ,  atol=1e-4		)		)