
_UpperCAmelCase :			str              =	[
    999,
    800,
    799,
    600,
    599,
    500,
    400,
    399,
    377,
    355,
    333,
    311,
    288,
    266,
    244,
    222,
    200,
    199,
    177,
    155,
    133,
    111,
    88,
    66,
    44,
    22,
    0,
]

_UpperCAmelCase :			Any              =	[
    999,
    976,
    952,
    928,
    905,
    882,
    858,
    857,
    810,
    762,
    715,
    714,
    572,
    429,
    428,
    286,
    285,
    238,
    190,
    143,
    142,
    118,
    95,
    71,
    47,
    24,
    0,
]

_UpperCAmelCase :			List[Any]              =	[
    999,
    988,
    977,
    966,
    955,
    944,
    933,
    922,
    911,
    900,
    899,
    879,
    859,
    840,
    820,
    800,
    799,
    766,
    733,
    700,
    699,
    650,
    600,
    599,
    500,
    499,
    400,
    399,
    350,
    300,
    299,
    266,
    233,
    200,
    199,
    179,
    159,
    140,
    120,
    100,
    99,
    88,
    77,
    66,
    55,
    44,
    33,
    22,
    11,
    0,
]

_UpperCAmelCase :			Tuple              =	[
    999,
    995,
    992,
    989,
    985,
    981,
    978,
    975,
    971,
    967,
    964,
    961,
    957,
    956,
    951,
    947,
    942,
    937,
    933,
    928,
    923,
    919,
    914,
    913,
    908,
    903,
    897,
    892,
    887,
    881,
    876,
    871,
    870,
    864,
    858,
    852,
    846,
    840,
    834,
    828,
    827,
    820,
    813,
    806,
    799,
    792,
    785,
    784,
    777,
    770,
    763,
    756,
    749,
    742,
    741,
    733,
    724,
    716,
    707,
    699,
    698,
    688,
    677,
    666,
    656,
    655,
    645,
    634,
    623,
    613,
    612,
    598,
    584,
    570,
    569,
    555,
    541,
    527,
    526,
    505,
    484,
    483,
    462,
    440,
    439,
    396,
    395,
    352,
    351,
    308,
    307,
    264,
    263,
    220,
    219,
    176,
    132,
    88,
    44,
    0,
]

_UpperCAmelCase :			Union[str, Any]              =	[
    999,
    997,
    995,
    992,
    990,
    988,
    986,
    984,
    981,
    979,
    977,
    975,
    972,
    970,
    968,
    966,
    964,
    961,
    959,
    957,
    956,
    954,
    951,
    949,
    946,
    944,
    941,
    939,
    936,
    934,
    931,
    929,
    926,
    924,
    921,
    919,
    916,
    914,
    913,
    910,
    907,
    905,
    902,
    899,
    896,
    893,
    891,
    888,
    885,
    882,
    879,
    877,
    874,
    871,
    870,
    867,
    864,
    861,
    858,
    855,
    852,
    849,
    846,
    843,
    840,
    837,
    834,
    831,
    828,
    827,
    824,
    821,
    817,
    814,
    811,
    808,
    804,
    801,
    798,
    795,
    791,
    788,
    785,
    784,
    780,
    777,
    774,
    770,
    766,
    763,
    760,
    756,
    752,
    749,
    746,
    742,
    741,
    737,
    733,
    730,
    726,
    722,
    718,
    714,
    710,
    707,
    703,
    699,
    698,
    694,
    690,
    685,
    681,
    677,
    673,
    669,
    664,
    660,
    656,
    655,
    650,
    646,
    641,
    636,
    632,
    627,
    622,
    618,
    613,
    612,
    607,
    602,
    596,
    591,
    586,
    580,
    575,
    570,
    569,
    563,
    557,
    551,
    545,
    539,
    533,
    527,
    526,
    519,
    512,
    505,
    498,
    491,
    484,
    483,
    474,
    466,
    457,
    449,
    440,
    439,
    428,
    418,
    407,
    396,
    395,
    381,
    366,
    352,
    351,
    330,
    308,
    307,
    286,
    264,
    263,
    242,
    220,
    219,
    176,
    175,
    132,
    131,
    88,
    44,
    0,
]

_UpperCAmelCase :			List[str]              =	[
    999,
    991,
    982,
    974,
    966,
    958,
    950,
    941,
    933,
    925,
    916,
    908,
    900,
    899,
    874,
    850,
    825,
    800,
    799,
    700,
    600,
    500,
    400,
    300,
    200,
    100,
    0,
]

_UpperCAmelCase :			Tuple              =	[
    999,
    992,
    985,
    978,
    971,
    964,
    957,
    949,
    942,
    935,
    928,
    921,
    914,
    907,
    900,
    899,
    879,
    859,
    840,
    820,
    800,
    799,
    766,
    733,
    700,
    699,
    650,
    600,
    599,
    500,
    499,
    400,
    399,
    300,
    299,
    200,
    199,
    100,
    99,
    0,
]

_UpperCAmelCase :			Dict              =	[
    999,
    996,
    992,
    989,
    985,
    982,
    979,
    975,
    972,
    968,
    965,
    961,
    958,
    955,
    951,
    948,
    944,
    941,
    938,
    934,
    931,
    927,
    924,
    920,
    917,
    914,
    910,
    907,
    903,
    900,
    899,
    891,
    884,
    876,
    869,
    861,
    853,
    846,
    838,
    830,
    823,
    815,
    808,
    800,
    799,
    788,
    777,
    766,
    755,
    744,
    733,
    722,
    711,
    700,
    699,
    688,
    677,
    666,
    655,
    644,
    633,
    622,
    611,
    600,
    599,
    585,
    571,
    557,
    542,
    528,
    514,
    500,
    499,
    485,
    471,
    457,
    442,
    428,
    414,
    400,
    399,
    379,
    359,
    340,
    320,
    300,
    299,
    279,
    259,
    240,
    220,
    200,
    199,
    166,
    133,
    100,
    99,
    66,
    33,
    0,
]


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     lowercase :



		def __init__(			self    ,				A_    ,				A_=2    ,				A_=3    ,				A_=4    ,				A_=2    ,				A_=7    ,				A_=True    ,				A_=True    ,				A_=True    ,				A_=True    ,				A_=99    ,				A_=36    ,				A_=3    ,				A_=4    ,				A_=37    ,				A_="gelu"    ,				A_=0.1    ,				A_=0.1    ,				A_=512    ,				A_=16    ,				A_=2    ,				A_=0.02    ,				A_=6    ,				A_=6    ,				A_=3    ,				A_=4    ,				A_=None    ,				A_=1_000    ,				)  -> str:
				"""simple docstring"""
				UpperCamelCase          =					parent
				UpperCamelCase          =					batch_size
				UpperCamelCase          =					num_channels
				UpperCamelCase          =					image_size
				UpperCamelCase          =					patch_size
				UpperCamelCase          =					text_seq_length
				UpperCamelCase          =					is_training
				UpperCamelCase          =					use_input_mask
				UpperCamelCase          =					use_token_type_ids
				UpperCamelCase          =					use_labels
				UpperCamelCase          =					vocab_size
				UpperCamelCase          =					hidden_size
				UpperCamelCase          =					num_hidden_layers
				UpperCamelCase          =					num_attention_heads
				UpperCamelCase          =					intermediate_size
				UpperCamelCase          =					hidden_act
				UpperCamelCase          =					hidden_dropout_prob
				UpperCamelCase          =					attention_probs_dropout_prob
				UpperCamelCase          =					max_position_embeddings
				UpperCamelCase          =					type_vocab_size
				UpperCamelCase          =					type_sequence_label_size
				UpperCamelCase          =					initializer_range
				UpperCamelCase          =					coordinate_size
				UpperCamelCase          =					shape_size
				UpperCamelCase          =					num_labels
				UpperCamelCase          =					num_choices
				UpperCamelCase          =					scope
				UpperCamelCase          =					range_bbox

				# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
				UpperCamelCase          =					text_seq_length
				UpperCamelCase          =					(image_size // patch_size) ** 2 + 1
				UpperCamelCase          =					self.text_seq_length + self.image_seq_length



		def __UpperCamelCase			(			self	)  -> Optional[int]:
				"""simple docstring"""
				UpperCamelCase          =					ids_tensor([self.batch_size, self.text_seq_length]    ,				self.vocab_size	)

				UpperCamelCase          =					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]:
										UpperCamelCase          =					bbox[i, j, 3]
										UpperCamelCase          =					bbox[i, j, 1]
										UpperCamelCase          =					t
								if bbox[i, j, 2] < bbox[i, j, 0]:
										UpperCamelCase          =					bbox[i, j, 2]
										UpperCamelCase          =					bbox[i, j, 0]
										UpperCamelCase          =					t

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

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

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

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

				UpperCamelCase          =					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 __UpperCamelCase			(			self    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_	)  -> int:
				"""simple docstring"""
				UpperCamelCase          =					LayoutLMvaModel(config=A_	)
				model.to(A_	)
				model.eval()

				# text + image
				UpperCamelCase          =					model(A_    ,				pixel_values=A_	)
				UpperCamelCase          =					model(
				    A_    ,				bbox=A_    ,				pixel_values=A_    ,				attention_mask=A_    ,				token_type_ids=A_	)
				UpperCamelCase          =					model(A_    ,				bbox=A_    ,				pixel_values=A_    ,				token_type_ids=A_	)
				UpperCamelCase          =					model(A_    ,				bbox=A_    ,				pixel_values=A_	)

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

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

				# image only
				UpperCamelCase          =					model(pixel_values=A_	)
				self.parent.assertEqual(
				    result.last_hidden_state.shape    ,				(self.batch_size, self.image_seq_length, self.hidden_size)	)



		def __UpperCamelCase			(			self    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_	)  -> Optional[Any]:
				"""simple docstring"""
				UpperCamelCase          =					self.num_labels
				UpperCamelCase          =					LayoutLMvaForSequenceClassification(A_	)
				model.to(A_	)
				model.eval()
				UpperCamelCase          =					model(
				    A_    ,				bbox=A_    ,				pixel_values=A_    ,				attention_mask=A_    ,				token_type_ids=A_    ,				labels=A_    ,				)
				self.parent.assertEqual(result.logits.shape    ,				(self.batch_size, self.num_labels)	)



		def __UpperCamelCase			(			self    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_	)  -> Dict:
				"""simple docstring"""
				UpperCamelCase          =					self.num_labels
				UpperCamelCase          =					LayoutLMvaForTokenClassification(config=A_	)
				model.to(A_	)
				model.eval()
				UpperCamelCase          =					model(
				    A_    ,				bbox=A_    ,				pixel_values=A_    ,				attention_mask=A_    ,				token_type_ids=A_    ,				labels=A_    ,				)
				self.parent.assertEqual(result.logits.shape    ,				(self.batch_size, self.text_seq_length, self.num_labels)	)



		def __UpperCamelCase			(			self    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_	)  -> List[str]:
				"""simple docstring"""
				UpperCamelCase          =					LayoutLMvaForQuestionAnswering(config=A_	)
				model.to(A_	)
				model.eval()
				UpperCamelCase          =					model(
				    A_    ,				bbox=A_    ,				pixel_values=A_    ,				attention_mask=A_    ,				token_type_ids=A_    ,				start_positions=A_    ,				end_positions=A_    ,				)
				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 __UpperCamelCase			(			self	)  -> int:
				"""simple docstring"""
				UpperCamelCase          =					self.prepare_config_and_inputs()
				(
				    (
				    UpperCamelCase
				)     ,  (
				    UpperCamelCase
				)     ,  (
				    UpperCamelCase
				)     ,  (
				    UpperCamelCase
				)     ,  (
				    UpperCamelCase
				)     ,  (
				    UpperCamelCase
				)     ,  (
				    UpperCamelCase
				)     ,  (
				    UpperCamelCase
				)     ,  
				)          =					config_and_inputs
				UpperCamelCase          =					{
				    '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     lowercase (		_SCREAMING_SNAKE_CASE  ,       _SCREAMING_SNAKE_CASE  ,       unittest.TestCase       ):
		__lowercase	:	Tuple     					=    False
		__lowercase	:	List[Any]     					=    False
		__lowercase	:	str     					=    False

		__lowercase	:	Tuple     					=    (
		    (
		        LayoutLMvaModel,
		        LayoutLMvaForSequenceClassification,
		        LayoutLMvaForTokenClassification,
		        LayoutLMvaForQuestionAnswering,
		    )
		    if is_torch_available()
		    else ()
		)
		__lowercase	:	List[str]     					=    (
		    {"document-question-answering": LayoutLMvaForQuestionAnswering, "feature-extraction": LayoutLMvaModel}
		    if is_torch_available()
		    else {}
		)



		def __UpperCamelCase			(			self    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_	)  -> int:
				"""simple docstring"""
				# `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 __UpperCamelCase			(			self	)  -> Any:
				"""simple docstring"""
				UpperCamelCase          =					LayoutLMvaModelTester(self	)
				UpperCamelCase          =					ConfigTester(self    ,				config_class=A_    ,				hidden_size=37	)



		def __UpperCamelCase			(			self    ,				A_    ,				A_    ,				A_=False	)  -> int:
				"""simple docstring"""
				UpperCamelCase          =					copy.deepcopy(A_	)
				if model_class in get_values(A_	):
						UpperCamelCase          =					{
						    k: v.unsqueeze(1	).expand(-1    ,				self.model_tester.num_choices    ,				-1	).contiguous()
						    if isinstance(A_    ,				torch.Tensor	) and v.ndim > 1
						    else v
						    for k, v in inputs_dict.items()
						}
				if return_labels:
						if model_class in get_values(A_	):
								UpperCamelCase          =					torch.ones(self.model_tester.batch_size    ,				dtype=torch.long    ,				device=A_	)
						elif model_class in get_values(A_	):
								UpperCamelCase          =					torch.zeros(
								    self.model_tester.batch_size    ,				dtype=torch.long    ,				device=A_	)
								UpperCamelCase          =					torch.zeros(
								    self.model_tester.batch_size    ,				dtype=torch.long    ,				device=A_	)
						elif model_class in [
						    *get_values(A_	),
						]:
								UpperCamelCase          =					torch.zeros(
								    self.model_tester.batch_size    ,				dtype=torch.long    ,				device=A_	)
						elif model_class in [
						    *get_values(A_	),
						]:
								UpperCamelCase          =					torch.zeros(
								    (self.model_tester.batch_size, self.model_tester.text_seq_length)    ,				dtype=torch.long    ,				device=A_    ,				)

				return inputs_dict



		def __UpperCamelCase			(			self	)  -> Optional[int]:
				"""simple docstring"""
				self.config_tester.run_common_tests()



		def __UpperCamelCase			(			self	)  -> str:
				"""simple docstring"""
				UpperCamelCase          =					self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*A_	)



		def __UpperCamelCase			(			self	)  -> Any:
				"""simple docstring"""
				UpperCamelCase          =					self.model_tester.prepare_config_and_inputs()
				for type in ["absolute", "relative_key", "relative_key_query"]:
						UpperCamelCase          =					type
						self.model_tester.create_and_check_model(*A_	)



		def __UpperCamelCase			(			self	)  -> List[Any]:
				"""simple docstring"""
				UpperCamelCase          =					self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_sequence_classification(*A_	)



		def __UpperCamelCase			(			self	)  -> Optional[Any]:
				"""simple docstring"""
				UpperCamelCase          =					self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_token_classification(*A_	)



		def __UpperCamelCase			(			self	)  -> Union[str, Any]:
				"""simple docstring"""
				UpperCamelCase          =					self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_question_answering(*A_	)



		@slow
		def __UpperCamelCase			(			self	)  -> Optional[int]:
				"""simple docstring"""
				for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						UpperCamelCase          =					LayoutLMvaModel.from_pretrained(A_	)
						self.assertIsNotNone(A_	)






def 				A	( )       ->  int:
		'''simple docstring'''

		UpperCamelCase          =					Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
		return image


@require_torch
class     lowercase (		unittest.TestCase       ):



		@cached_property
		def __UpperCamelCase			(			self	)  -> Any:
				"""simple docstring"""
				return LayoutLMvaImageProcessor(apply_ocr=A_	) if is_vision_available() else None



		@slow
		def __UpperCamelCase			(			self	)  -> Optional[int]:
				"""simple docstring"""
				UpperCamelCase          =					LayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base'	).to(A_	)

				UpperCamelCase          =					self.default_image_processor
				UpperCamelCase          =					prepare_img()
				UpperCamelCase          =					image_processor(images=A_    ,				return_tensors='pt'	).pixel_values.to(A_	)

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

				# forward pass
				UpperCamelCase          =					model(
				    input_ids=input_ids.to(A_	)    ,				bbox=bbox.to(A_	)    ,				pixel_values=pixel_values.to(A_	)    ,				)

				# verify the logits
				UpperCamelCase          =					torch.Size((1, 199, 768)	)
				self.assertEqual(outputs.last_hidden_state.shape    ,				A_	)

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

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