import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import MaskaFormerConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch

				from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel

				if is_vision_available():
								from transformers import MaskaFormerImageProcessor

if is_vision_available():
				from PIL import Image





class     lowerCAmelCase__     :


		'''simple docstring'''






		def __init__(       self     :     Optional[int]     ,  snake_case__     :     List[str]     ,  snake_case__     :     List[Any]=2     ,  snake_case__     :     Optional[Any]=True     ,  snake_case__     :     Optional[int]=False     ,  snake_case__     :     List[Any]=1_0     ,  snake_case__     :     Dict=3     ,  snake_case__     :     Union[str, Any]=3_2 * 8     ,  snake_case__     :     Any=3_2 * 8     ,  snake_case__     :     int=4     ,  snake_case__     :     Optional[int]=6_4     ,  )      ->	Optional[Any]:
				_lowerCamelCase				   =  parent
				_lowerCamelCase				   =  batch_size
				_lowerCamelCase				   =  is_training
				_lowerCamelCase				   =  use_auxiliary_loss
				_lowerCamelCase				   =  num_queries
				_lowerCamelCase				   =  num_channels
				_lowerCamelCase				   =  min_size
				_lowerCamelCase				   =  max_size
				_lowerCamelCase				   =  num_labels
				_lowerCamelCase				   =  hidden_dim
				_lowerCamelCase				   =  hidden_dim
		def   _snake_case       (       self     :     Any		)      ->	Dict:
				_lowerCamelCase				   =  floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]		).to(
				    snake_case__		)

				_lowerCamelCase				   =  torch.ones([self.batch_size, self.min_size, self.max_size]     ,  device=snake_case__		)

				_lowerCamelCase				   =  (
				    torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]     ,  device=snake_case__		) > 0.5
				).float()
				_lowerCamelCase				   =  (torch.rand((self.batch_size, self.num_labels)     ,  device=snake_case__		) > 0.5).long()

				_lowerCamelCase				   =  self.get_config()
				return config, pixel_values, pixel_mask, mask_labels, class_labels
		def   _snake_case       (       self     :     Optional[Any]		)      ->	Optional[Any]:
				_lowerCamelCase				   =  MaskaFormerConfig(
				    hidden_size=self.hidden_dim     ,  )
				_lowerCamelCase				   =  self.num_queries
				_lowerCamelCase				   =  self.num_labels

				_lowerCamelCase				   =  [1, 1, 1, 1]
				_lowerCamelCase				   =  self.num_channels

				_lowerCamelCase				   =  6_4
				_lowerCamelCase				   =  1_2_8
				_lowerCamelCase				   =  self.hidden_dim
				_lowerCamelCase				   =  self.hidden_dim
				_lowerCamelCase				   =  self.hidden_dim
				return config
		def   _snake_case       (       self     :     Dict		)      ->	Any:
				_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase				   =  self.prepare_config_and_inputs()
				_lowerCamelCase				   =  {'pixel_values': pixel_values, 'pixel_mask': pixel_mask}
				return config, inputs_dict
		def   _snake_case       (       self     :     List[str]     ,  snake_case__     :     str     ,  snake_case__     :     Optional[Any]		)      ->	str:
				_lowerCamelCase				   =  output.encoder_hidden_states
				_lowerCamelCase				   =  output.pixel_decoder_hidden_states
				_lowerCamelCase				   =  output.transformer_decoder_hidden_states

				self.parent.assertTrue(len(snake_case__		)     ,  len(config.backbone_config.depths		)		)
				self.parent.assertTrue(len(snake_case__		)     ,  len(config.backbone_config.depths		)		)
				self.parent.assertTrue(len(snake_case__		)     ,  config.decoder_layers		)
		def   _snake_case       (       self     :     Any     ,  snake_case__     :     List[Any]     ,  snake_case__     :     Union[str, Any]     ,  snake_case__     :     Optional[int]     ,  snake_case__     :     Any=False		)      ->	str:
				with torch.no_grad():
						_lowerCamelCase				   =  MaskaFormerModel(config=snake_case__		)
						model.to(snake_case__		)
						model.eval()

						_lowerCamelCase				   =  model(pixel_values=snake_case__     ,  pixel_mask=snake_case__		)
						_lowerCamelCase				   =  model(snake_case__     ,  output_hidden_states=snake_case__		)

				self.parent.assertEqual(
				    output.transformer_decoder_last_hidden_state.shape     ,  (self.batch_size, self.num_queries, self.hidden_dim)     ,  )
				# let's ensure the other two hidden state exists
				self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None		)
				self.parent.assertTrue(output.encoder_last_hidden_state is not None		)

				if output_hidden_states:
						self.check_output_hidden_state(snake_case__     ,  snake_case__		)



		def   _snake_case       (       self     :     Tuple     ,  snake_case__     :     Union[str, Any]     ,  snake_case__     :     Any     ,  snake_case__     :     Union[str, Any]     ,  snake_case__     :     Optional[Any]     ,  snake_case__     :     Any		)      ->	List[Any]:
				_lowerCamelCase				   =  MaskaFormerForUniversalSegmentation(config=snake_case__		)
				model.to(snake_case__		)
				model.eval()

				def comm_check_on_output(snake_case__     :     Optional[int]		):
						# let's still check that all the required stuff is there
						self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None		)
						self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None		)
						self.parent.assertTrue(result.encoder_last_hidden_state is not None		)
						# okay, now we need to check the logits shape
						# due to the encoder compression, masks have a //4 spatial size
						self.parent.assertEqual(
						    result.masks_queries_logits.shape     ,  (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4)     ,  )
						# + 1 for null class
						self.parent.assertEqual(
						    result.class_queries_logits.shape     ,  (self.batch_size, self.num_queries, self.num_labels + 1)		)

				with torch.no_grad():
						_lowerCamelCase				   =  model(pixel_values=snake_case__     ,  pixel_mask=snake_case__		)
						_lowerCamelCase				   =  model(snake_case__		)

						comm_check_on_output(snake_case__		)

						_lowerCamelCase				   =  model(
						    pixel_values=snake_case__     ,  pixel_mask=snake_case__     ,  mask_labels=snake_case__     ,  class_labels=snake_case__		)

				comm_check_on_output(snake_case__		)

				self.parent.assertTrue(result.loss is not None		)
				self.parent.assertEqual(result.loss.shape     ,  torch.Size([1]		)		)





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


		'''simple docstring'''






		lowerCAmelCase_     =   (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
		lowerCAmelCase_     =   {'feature-extraction': MaskaFormerModel} if is_torch_available() else {}

		lowerCAmelCase_     =   False
		lowerCAmelCase_     =   False
		lowerCAmelCase_     =   False
		lowerCAmelCase_     =   False
		def   _snake_case       (       self     :     Optional[Any]		)      ->	Dict:
				_lowerCamelCase				   =  MaskaFormerModelTester(self		)
				_lowerCamelCase				   =  ConfigTester(self     ,  config_class=snake_case__     ,  has_text_modality=snake_case__		)
		def   _snake_case       (       self     :     int		)      ->	Optional[int]:
				self.config_tester.run_common_tests()
		def   _snake_case       (       self     :     Optional[Any]		)      ->	List[Any]:
				_lowerCamelCase   ,							_lowerCamelCase				   =  self.model_tester.prepare_config_and_inputs_for_common()
				self.model_tester.create_and_check_maskaformer_model(snake_case__     ,  **snake_case__     ,  output_hidden_states=snake_case__		)
		def   _snake_case       (       self     :     str		)      ->	List[Any]:
				_lowerCamelCase				   =  self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*snake_case__		)
		@unittest.skip(reason='Mask2Former does not use inputs_embeds'		)
		def   _snake_case       (       self     :     int		)      ->	Optional[int]:
				pass
		@unittest.skip(reason='Mask2Former does not have a get_input_embeddings method'		)
		def   _snake_case       (       self     :     Dict		)      ->	Dict:
				pass
		@unittest.skip(reason='Mask2Former is not a generative model'		)
		def   _snake_case       (       self     :     Union[str, Any]		)      ->	List[str]:
				pass
		@unittest.skip(reason='Mask2Former does not use token embeddings'		)
		def   _snake_case       (       self     :     Dict		)      ->	List[str]:
				pass
		@require_torch_multi_gpu
		@unittest.skip(
		    reason='Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'		)
		def   _snake_case       (       self     :     Optional[Any]		)      ->	List[Any]:
				pass
		@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'		)
		def   _snake_case       (       self     :     Optional[int]		)      ->	int:
				pass
		def   _snake_case       (       self     :     List[str]		)      ->	Optional[Any]:
				_lowerCamelCase   ,							_lowerCamelCase				   =  self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
						_lowerCamelCase				   =  model_class(snake_case__		)
						_lowerCamelCase				   =  inspect.signature(model.forward		)
						# signature.parameters is an OrderedDict => so arg_names order is deterministic
						_lowerCamelCase				   =  [*signature.parameters.keys()]

						_lowerCamelCase				   =  ['pixel_values']
						self.assertListEqual(arg_names[:1]     ,  snake_case__		)
		@slow
		def   _snake_case       (       self     :     Optional[int]		)      ->	Union[str, Any]:
				for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
						_lowerCamelCase				   =  MaskaFormerModel.from_pretrained(snake_case__		)
						self.assertIsNotNone(snake_case__		)
		def   _snake_case       (       self     :     Tuple		)      ->	str:
				_lowerCamelCase				   =  (self.model_tester.min_size,) * 2
				_lowerCamelCase				   =  {
				    'pixel_values': torch.randn((2, 3, *size)     ,  device=snake_case__		),
				    'mask_labels': torch.randn((2, 1_0, *size)     ,  device=snake_case__		),
				    'class_labels': torch.zeros(2     ,  1_0     ,  device=snake_case__		).long(),
				}
				_lowerCamelCase				   =  self.model_tester.get_config()

				_lowerCamelCase				   =  MaskaFormerForUniversalSegmentation(snake_case__		).to(snake_case__		)
				_lowerCamelCase				   =  model(**snake_case__		)
				self.assertTrue(outputs.loss is not None		)
		def   _snake_case       (       self     :     Any		)      ->	Dict:
				_lowerCamelCase   ,							_lowerCamelCase				   =  self.model_tester.prepare_config_and_inputs_for_common()
				self.model_tester.create_and_check_maskaformer_model(snake_case__     ,  **snake_case__     ,  output_hidden_states=snake_case__		)
		def   _snake_case       (       self     :     List[Any]		)      ->	Optional[Any]:
				_lowerCamelCase   ,							_lowerCamelCase				   =  self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
						_lowerCamelCase				   =  model_class(snake_case__		).to(snake_case__		)
						_lowerCamelCase				   =  model(**snake_case__     ,  output_attentions=snake_case__		)
						self.assertTrue(outputs.attentions is not None		)
		def   _snake_case       (       self     :     Tuple		)      ->	List[str]:
				if not self.model_tester.is_training:
						return

				_lowerCamelCase				   =  self.all_model_classes[1]
				_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase				   =  self.model_tester.prepare_config_and_inputs()

				_lowerCamelCase				   =  model_class(snake_case__		)
				model.to(snake_case__		)
				model.train()

				_lowerCamelCase				   =  model(snake_case__     ,  mask_labels=snake_case__     ,  class_labels=snake_case__		).loss
				loss.backward()



		def   _snake_case       (       self     :     Tuple		)      ->	Union[str, Any]:
				_lowerCamelCase				   =  self.all_model_classes[1]
				_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase				   =  self.model_tester.prepare_config_and_inputs()
				_lowerCamelCase				   =  True
				_lowerCamelCase				   =  True

				_lowerCamelCase				   =  model_class(snake_case__		).to(snake_case__		)
				model.train()

				_lowerCamelCase				   =  model(snake_case__     ,  mask_labels=snake_case__     ,  class_labels=snake_case__		)

				_lowerCamelCase				   =  outputs.encoder_hidden_states[0]
				encoder_hidden_states.retain_grad()

				_lowerCamelCase				   =  outputs.pixel_decoder_hidden_states[0]
				pixel_decoder_hidden_states.retain_grad()

				_lowerCamelCase				   =  outputs.transformer_decoder_hidden_states[0]
				transformer_decoder_hidden_states.retain_grad()

				_lowerCamelCase				   =  outputs.attentions[0]
				attentions.retain_grad()

				outputs.loss.backward(retain_graph=snake_case__		)

				self.assertIsNotNone(encoder_hidden_states.grad		)
				self.assertIsNotNone(pixel_decoder_hidden_states.grad		)
				self.assertIsNotNone(transformer_decoder_hidden_states.grad		)
				self.assertIsNotNone(attentions.grad		)



A						=			1e-4


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





@require_vision
@slow
class     lowerCAmelCase__     (				unittest.TestCase			):


		'''simple docstring'''






		@cached_property
		def   _snake_case       (       self     :     Tuple		)      ->	Union[str, Any]:
				return "facebook/mask2former-swin-small-coco-instance"
		@cached_property
		def   _snake_case       (       self     :     int		)      ->	int:
				return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints		) if is_vision_available() else None
		def   _snake_case       (       self     :     Optional[int]		)      ->	Optional[Any]:
				_lowerCamelCase				   =  MaskaFormerModel.from_pretrained(self.model_checkpoints		).to(snake_case__		)
				_lowerCamelCase				   =  self.default_image_processor
				_lowerCamelCase				   =  prepare_img()
				_lowerCamelCase				   =  image_processor(snake_case__     ,  return_tensors='pt'		).to(snake_case__		)
				_lowerCamelCase				   =  inputs['pixel_values'].shape
				# check size is divisible by 32
				self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0		)
				# check size
				self.assertEqual(snake_case__     ,  (1, 3, 3_8_4, 3_8_4)		)

				with torch.no_grad():
						_lowerCamelCase				   =  model(**snake_case__		)

				_lowerCamelCase				   =  torch.tensor(
				    [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]]		).to(snake_case__		)
				self.assertTrue(
				    torch.allclose(
				        outputs.encoder_last_hidden_state[0, 0, :3, :3]     ,  snake_case__     ,  atol=snake_case__		)		)

				_lowerCamelCase				   =  torch.tensor(
				    [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]]		).to(snake_case__		)
				self.assertTrue(
				    torch.allclose(
				        outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]     ,  snake_case__     ,  atol=snake_case__		)		)

				_lowerCamelCase				   =  torch.tensor(
				    [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]]		).to(snake_case__		)
				self.assertTrue(
				    torch.allclose(
				        outputs.transformer_decoder_last_hidden_state[0, :3, :3]     ,  snake_case__     ,  atol=snake_case__		)		)
		def   _snake_case       (       self     :     Dict		)      ->	List[Any]:
				_lowerCamelCase				   =  MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints		).to(snake_case__		).eval()
				_lowerCamelCase				   =  self.default_image_processor
				_lowerCamelCase				   =  prepare_img()
				_lowerCamelCase				   =  image_processor(snake_case__     ,  return_tensors='pt'		).to(snake_case__		)
				_lowerCamelCase				   =  inputs['pixel_values'].shape
				# check size is divisible by 32
				self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0		)
				# check size
				self.assertEqual(snake_case__     ,  (1, 3, 3_8_4, 3_8_4)		)

				with torch.no_grad():
						_lowerCamelCase				   =  model(**snake_case__		)
				# masks_queries_logits
				_lowerCamelCase				   =  outputs.masks_queries_logits
				self.assertEqual(
				    masks_queries_logits.shape     ,  (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)		)
				_lowerCamelCase				   =  [
				    [-8.7839, -9.0056, -8.8121],
				    [-7.4104, -7.0313, -6.5401],
				    [-6.6105, -6.3427, -6.4675],
				]
				_lowerCamelCase				   =  torch.tensor(snake_case__		).to(snake_case__		)
				self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]     ,  snake_case__     ,  atol=snake_case__		)		)
				# class_queries_logits
				_lowerCamelCase				   =  outputs.class_queries_logits
				self.assertEqual(class_queries_logits.shape     ,  (1, model.config.num_queries, model.config.num_labels + 1)		)
				_lowerCamelCase				   =  torch.tensor(
				    [
				        [1.8324, -8.0835, -4.1922],
				        [0.8450, -9.0050, -3.6053],
				        [0.3045, -7.7293, -3.0275],
				    ]		).to(snake_case__		)
				self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]     ,  snake_case__     ,  atol=snake_case__		)		)



		def   _snake_case       (       self     :     List[Any]		)      ->	Optional[Any]:
				_lowerCamelCase				   =  MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints		).to(snake_case__		).eval()
				_lowerCamelCase				   =  self.default_image_processor

				_lowerCamelCase				   =  image_processor(
				    [np.zeros((3, 8_0_0, 1_3_3_3)		), np.zeros((3, 8_0_0, 1_3_3_3)		)]     ,  segmentation_maps=[np.zeros((3_8_4, 3_8_4)		).astype(np.floataa		), np.zeros((3_8_4, 3_8_4)		).astype(np.floataa		)]     ,  return_tensors='pt'     ,  )

				_lowerCamelCase				   =  inputs['pixel_values'].to(snake_case__		)
				_lowerCamelCase				   =  [el.to(snake_case__		) for el in inputs['mask_labels']]
				_lowerCamelCase				   =  [el.to(snake_case__		) for el in inputs['class_labels']]

				with torch.no_grad():
						_lowerCamelCase				   =  model(**snake_case__		)

				self.assertTrue(outputs.loss is not None		)
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		)		)