
"""simple docstring"""




from __future__ import annotations

import copy
import inspect
import unittest

import numpy as np

from transformers import is_tf_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_tf, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
    import tensorflow as tf

    from transformers import (
        TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
        TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
        TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
        TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
        TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
        LayoutLMvaConfig,
        TFLayoutLMvaForQuestionAnswering,
        TFLayoutLMvaForSequenceClassification,
        TFLayoutLMvaForTokenClassification,
        TFLayoutLMvaModel,
    )

if is_vision_available():
    from PIL import Image

    from transformers import LayoutLMvaImageProcessor







class   _lowercase						:


     '''simple docstring'''





     def __init__(      self ,			__UpperCamelCase ,			__UpperCamelCase=2 ,			__UpperCamelCase=3 ,			__UpperCamelCase=4 ,			__UpperCamelCase=2 ,			__UpperCamelCase=7 ,			__UpperCamelCase=True ,			__UpperCamelCase=True ,			__UpperCamelCase=True ,			__UpperCamelCase=True ,			__UpperCamelCase=99 ,			__UpperCamelCase=36 ,			__UpperCamelCase=2 ,			__UpperCamelCase=4 ,			__UpperCamelCase=37 ,			__UpperCamelCase="gelu" ,			__UpperCamelCase=0.1 ,			__UpperCamelCase=0.1 ,			__UpperCamelCase=5_12 ,			__UpperCamelCase=16 ,			__UpperCamelCase=2 ,			__UpperCamelCase=0.02 ,			__UpperCamelCase=6 ,			__UpperCamelCase=6 ,			__UpperCamelCase=3 ,			__UpperCamelCase=4 ,			__UpperCamelCase=None ,			__UpperCamelCase=10_00 ,			)->					Any:
          UpperCAmelCase__							: str 							=						parent
          UpperCAmelCase__							: List[Any] 							=						batch_size
          UpperCAmelCase__							: Optional[int] 							=						num_channels
          UpperCAmelCase__							: Optional[int] 							=						image_size
          UpperCAmelCase__							: Dict 							=						patch_size
          UpperCAmelCase__							: List[str] 							=						is_training
          UpperCAmelCase__							: Optional[int] 							=						use_input_mask
          UpperCAmelCase__							: Optional[int] 							=						use_token_type_ids
          UpperCAmelCase__							: List[Any] 							=						use_labels
          UpperCAmelCase__							: str 							=						vocab_size
          UpperCAmelCase__							: Optional[Any] 							=						hidden_size
          UpperCAmelCase__							: Dict 							=						num_hidden_layers
          UpperCAmelCase__							: str 							=						num_attention_heads
          UpperCAmelCase__							: Tuple 							=						intermediate_size
          UpperCAmelCase__							: List[Any] 							=						hidden_act
          UpperCAmelCase__							: Optional[int] 							=						hidden_dropout_prob
          UpperCAmelCase__							: List[str] 							=						attention_probs_dropout_prob
          UpperCAmelCase__							: int 							=						max_position_embeddings
          UpperCAmelCase__							: Union[str, Any] 							=						type_vocab_size
          UpperCAmelCase__							: Dict 							=						type_sequence_label_size
          UpperCAmelCase__							: List[Any] 							=						initializer_range
          UpperCAmelCase__							: List[Any] 							=						coordinate_size
          UpperCAmelCase__							: Tuple 							=						shape_size
          UpperCAmelCase__							: Optional[Any] 							=						num_labels
          UpperCAmelCase__							: Tuple 							=						num_choices
          UpperCAmelCase__							: Optional[Any] 							=						scope
          UpperCAmelCase__							: str 							=						range_bbox

          # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
          UpperCAmelCase__							: Any 							=						text_seq_length
          UpperCAmelCase__							: Union[str, Any] 							=						(image_size // patch_size) ** 2 + 1
          UpperCAmelCase__							: Union[str, Any] 							=						self.text_seq_length + self.image_seq_length



     def  lowerCAmelCase__       (      self  )->					List[str]:
          UpperCAmelCase__							: Dict 							=						ids_tensor([self.batch_size, self.text_seq_length] ,			self.vocab_size  )

          UpperCAmelCase__							: Optional[int] 							=						ids_tensor([self.batch_size, self.text_seq_length, 4] ,			self.range_bbox  )
          UpperCAmelCase__							: Union[str, Any] 							=						bbox.numpy()
          # 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__							: Dict 							=						bbox[i, j, 3]
                         UpperCAmelCase__							: Optional[Any] 							=						bbox[i, j, 1]
                         UpperCAmelCase__							: Union[str, Any] 							=						tmp_coordinate
                    if bbox[i, j, 2] < bbox[i, j, 0]:
                         UpperCAmelCase__							: Any 							=						bbox[i, j, 2]
                         UpperCAmelCase__							: Optional[int] 							=						bbox[i, j, 0]
                         UpperCAmelCase__							: Optional[Any] 							=						tmp_coordinate
          UpperCAmelCase__							: List[str] 							=						tf.constant(__UpperCamelCase  )

          UpperCAmelCase__							: Optional[Any] 							=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

          UpperCAmelCase__							: Optional[int] 							=						None
          if self.use_input_mask:
               UpperCAmelCase__							: Optional[int] 							=						random_attention_mask([self.batch_size, self.text_seq_length]  )

          UpperCAmelCase__							: Optional[Any] 							=						None
          if self.use_token_type_ids:
               UpperCAmelCase__							: int 							=						ids_tensor([self.batch_size, self.text_seq_length] ,			self.type_vocab_size  )

          UpperCAmelCase__							: Union[str, Any] 							=						None
          UpperCAmelCase__							: Tuple 							=						None
          if self.use_labels:
               UpperCAmelCase__							: str 							=						ids_tensor([self.batch_size] ,			self.type_sequence_label_size  )
               UpperCAmelCase__							: Any 							=						ids_tensor([self.batch_size, self.text_seq_length] ,			self.num_labels  )

          UpperCAmelCase__							: Optional[int] 							=						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  lowerCAmelCase__       (      self ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase  )->					int:
          UpperCAmelCase__							: Optional[int] 							=						TFLayoutLMvaModel(config=__UpperCamelCase  )

          # text + image
          UpperCAmelCase__							: Tuple 							=						model(__UpperCamelCase ,			pixel_values=__UpperCamelCase ,			training=__UpperCamelCase  )
          UpperCAmelCase__							: Optional[Any] 							=						model(
              __UpperCamelCase ,			bbox=__UpperCamelCase ,			pixel_values=__UpperCamelCase ,			attention_mask=__UpperCamelCase ,			token_type_ids=__UpperCamelCase ,			training=__UpperCamelCase ,			)
          UpperCAmelCase__							: List[str] 							=						model(__UpperCamelCase ,			bbox=__UpperCamelCase ,			pixel_values=__UpperCamelCase ,			training=__UpperCamelCase  )

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

          # text only
          UpperCAmelCase__							: Optional[Any] 							=						model(__UpperCamelCase ,			training=__UpperCamelCase  )
          self.parent.assertEqual(
              result.last_hidden_state.shape ,			(self.batch_size, self.text_seq_length, self.hidden_size)  )

          # image only
          UpperCAmelCase__							: Any 							=						model({"pixel_values": pixel_values} ,			training=__UpperCamelCase  )
          self.parent.assertEqual(
              result.last_hidden_state.shape ,			(self.batch_size, self.image_seq_length, self.hidden_size)  )



     def  lowerCAmelCase__       (      self ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase  )->					List[str]:
          UpperCAmelCase__							: Dict 							=						self.num_labels
          UpperCAmelCase__							: Any 							=						TFLayoutLMvaForSequenceClassification(config=__UpperCamelCase  )
          UpperCAmelCase__							: Union[str, Any] 							=						model(
              __UpperCamelCase ,			bbox=__UpperCamelCase ,			pixel_values=__UpperCamelCase ,			attention_mask=__UpperCamelCase ,			token_type_ids=__UpperCamelCase ,			labels=__UpperCamelCase ,			training=__UpperCamelCase ,			)
          self.parent.assertEqual(result.logits.shape ,			(self.batch_size, self.num_labels)  )



     def  lowerCAmelCase__       (      self ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase  )->					int:
          UpperCAmelCase__							: int 							=						self.num_labels
          UpperCAmelCase__							: str 							=						TFLayoutLMvaForTokenClassification(config=__UpperCamelCase  )
          UpperCAmelCase__							: Optional[int] 							=						model(
              __UpperCamelCase ,			bbox=__UpperCamelCase ,			pixel_values=__UpperCamelCase ,			attention_mask=__UpperCamelCase ,			token_type_ids=__UpperCamelCase ,			labels=__UpperCamelCase ,			training=__UpperCamelCase ,			)
          self.parent.assertEqual(result.logits.shape ,			(self.batch_size, self.text_seq_length, self.num_labels)  )



     def  lowerCAmelCase__       (      self ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase  )->					List[str]:
          UpperCAmelCase__							: Union[str, Any] 							=						2
          UpperCAmelCase__							: List[str] 							=						TFLayoutLMvaForQuestionAnswering(config=__UpperCamelCase  )
          UpperCAmelCase__							: Optional[Any] 							=						model(
              __UpperCamelCase ,			bbox=__UpperCamelCase ,			pixel_values=__UpperCamelCase ,			attention_mask=__UpperCamelCase ,			token_type_ids=__UpperCamelCase ,			start_positions=__UpperCamelCase ,			end_positions=__UpperCamelCase ,			training=__UpperCamelCase ,			)
          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  lowerCAmelCase__       (      self  )->					List[Any]:
          UpperCAmelCase__							: Tuple 							=						self.prepare_config_and_inputs()
          ((UpperCAmelCase__)							,	(UpperCAmelCase__)							,	(UpperCAmelCase__)							,	(UpperCAmelCase__)							,	(UpperCAmelCase__)							,	(UpperCAmelCase__)							,	(UpperCAmelCase__)							,	(UpperCAmelCase__))							: Tuple 							=						config_and_inputs
          UpperCAmelCase__							: Optional[Any] 							=						{
              "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_tf
class   _lowercase						(       lowerCAmelCase_	,   lowerCAmelCase_	,   unittest.TestCase				):


     '''simple docstring'''





     _A								=							(
         (
             TFLayoutLMvaModel,
             TFLayoutLMvaForQuestionAnswering,
             TFLayoutLMvaForSequenceClassification,
             TFLayoutLMvaForTokenClassification,
         )
         if is_tf_available()
         else ()
     )
     _A								=							(
         {'document-question-answering': TFLayoutLMvaForQuestionAnswering, 'feature-extraction': TFLayoutLMvaModel}
         if is_tf_available()
         else {}
     )

     _A								=							False
     _A								=							False
     _A								=							False



     def  lowerCAmelCase__       (      self ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase  )->					Tuple:
          return True



     def  lowerCAmelCase__       (      self ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase=False  )->					dict:
          UpperCAmelCase__							: Optional[int] 							=						copy.deepcopy(__UpperCamelCase  )

          if model_class in get_values(__UpperCamelCase  ):
               UpperCAmelCase__							: List[Any] 							=						{
                   k: tf.tile(tf.expand_dims(__UpperCamelCase ,			1  ) ,			(1, self.model_tester.num_choices) + (1,) * (v.ndim - 1)  )
                   if isinstance(__UpperCamelCase ,			tf.Tensor  ) and v.ndim > 0
                   else v
                   for k, v in inputs_dict.items()
               }

          if return_labels:
               if model_class in get_values(__UpperCamelCase  ):
                    UpperCAmelCase__							: Dict 							=						tf.ones(self.model_tester.batch_size ,			dtype=tf.intaa  )
               elif model_class in get_values(__UpperCamelCase  ):
                    UpperCAmelCase__							: Union[str, Any] 							=						tf.zeros(self.model_tester.batch_size ,			dtype=tf.intaa  )
                    UpperCAmelCase__							: Optional[int] 							=						tf.zeros(self.model_tester.batch_size ,			dtype=tf.intaa  )
               elif model_class in get_values(__UpperCamelCase  ):
                    UpperCAmelCase__							: List[str] 							=						tf.zeros(self.model_tester.batch_size ,			dtype=tf.intaa  )
               elif model_class in get_values(__UpperCamelCase  ):
                    UpperCAmelCase__							: Tuple 							=						tf.zeros(
                        (self.model_tester.batch_size, self.model_tester.text_seq_length) ,			dtype=tf.intaa  )

          return inputs_dict



     def  lowerCAmelCase__       (      self  )->					int:
          UpperCAmelCase__							: Union[str, Any] 							=						TFLayoutLMvaModelTester(self  )
          UpperCAmelCase__							: str 							=						ConfigTester(self ,			config_class=__UpperCamelCase ,			hidden_size=37  )



     def  lowerCAmelCase__       (      self  )->					str:
          self.config_tester.run_common_tests()



     def  lowerCAmelCase__       (      self  )->					Dict:
          UpperCAmelCase__							,	UpperCAmelCase__							: str 							=						self.model_tester.prepare_config_and_inputs_for_common()
          for model_class in self.all_model_classes:
               UpperCAmelCase__							: Any 							=						model_class(__UpperCamelCase  )
               if getattr(__UpperCamelCase ,			"hf_compute_loss" ,			__UpperCamelCase  ):
                    # The number of elements in the loss should be the same as the number of elements in the label
                    UpperCAmelCase__							: Optional[int] 							=						self._prepare_for_class(inputs_dict.copy() ,			__UpperCamelCase ,			return_labels=__UpperCamelCase  )
                    UpperCAmelCase__							: Dict 							=						prepared_for_class[
                        sorted(prepared_for_class.keys() - inputs_dict.keys() ,			reverse=__UpperCamelCase  )[0]
                    ]
                    UpperCAmelCase__							: Optional[int] 							=						added_label.shape.as_list()[:1]

                    # Test that model correctly compute the loss with kwargs
                    UpperCAmelCase__							: str 							=						self._prepare_for_class(inputs_dict.copy() ,			__UpperCamelCase ,			return_labels=__UpperCamelCase  )
                    UpperCAmelCase__							: Union[str, Any] 							=						prepared_for_class.pop("input_ids"  )

                    UpperCAmelCase__							: Optional[Any] 							=						model(__UpperCamelCase ,			**__UpperCamelCase  )[0]
                    self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]  )

                    # Test that model correctly compute the loss when we mask some positions
                    UpperCAmelCase__							: Optional[Any] 							=						self._prepare_for_class(inputs_dict.copy() ,			__UpperCamelCase ,			return_labels=__UpperCamelCase  )
                    UpperCAmelCase__							: Optional[Any] 							=						prepared_for_class.pop("input_ids"  )
                    if "labels" in prepared_for_class:
                         UpperCAmelCase__							: str 							=						prepared_for_class["labels"].numpy()
                         if len(labels.shape  ) > 1 and labels.shape[1] != 1:
                              UpperCAmelCase__							: List[str] 							=						-1_00
                              UpperCAmelCase__							: Dict 							=						tf.convert_to_tensor(__UpperCamelCase  )
                              UpperCAmelCase__							: Dict 							=						model(__UpperCamelCase ,			**__UpperCamelCase  )[0]
                              self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]  )
                              self.assertTrue(not np.any(np.isnan(loss.numpy()  )  )  )

                # Test that model correctly compute the loss with a dict
                    UpperCAmelCase__							: str 							=						self._prepare_for_class(inputs_dict.copy() ,			__UpperCamelCase ,			return_labels=__UpperCamelCase  )
                    UpperCAmelCase__							: Union[str, Any] 							=						model(__UpperCamelCase  )[0]
                    self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]  )

                    # Test that model correctly compute the loss with a tuple
                    UpperCAmelCase__							: int 							=						self._prepare_for_class(inputs_dict.copy() ,			__UpperCamelCase ,			return_labels=__UpperCamelCase  )

                    # Get keys that were added with the _prepare_for_class function
                    UpperCAmelCase__							: str 							=						prepared_for_class.keys() - inputs_dict.keys()
                    UpperCAmelCase__							: Optional[int] 							=						inspect.signature(model.call  ).parameters
                    UpperCAmelCase__							: Tuple 							=						list(signature.keys()  )

                    # Create a dictionary holding the location of the tensors in the tuple
                    UpperCAmelCase__							: str 							=						{0: "input_ids"}
                    for label_key in label_keys:
                         UpperCAmelCase__							: str 							=						signature_names.index(__UpperCamelCase  )
                         UpperCAmelCase__							: List[Any] 							=						label_key
                    UpperCAmelCase__							: Optional[int] 							=						sorted(tuple_index_mapping.items()  )
                    # Initialize a list with their default values, update the values and convert to a tuple
                    UpperCAmelCase__							: Dict 							=						[]

                    for name in signature_names:
                         if name != "kwargs":
                              list_input.append(signature[name].default  )

                    for index, value in sorted_tuple_index_mapping:
                         UpperCAmelCase__							: List[Any] 							=						prepared_for_class[value]

                    UpperCAmelCase__							: Union[str, Any] 							=						tuple(__UpperCamelCase  )

                    # Send to model
                    UpperCAmelCase__							: str 							=						model(tuple_input[:-1]  )[0]

                    self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]  )



     def  lowerCAmelCase__       (      self  )->					str:
          (
              (
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	
          )							: int 							=						self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase  )



     def  lowerCAmelCase__       (      self  )->					Optional[Any]:
          (
              (
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	
          )							: str 							=						self.model_tester.prepare_config_and_inputs()
          for type in ["absolute", "relative_key", "relative_key_query"]:
               UpperCAmelCase__							: str 							=						type
               self.model_tester.create_and_check_model(__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase  )



     def  lowerCAmelCase__       (      self  )->					Dict:
          (
              (
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	
          )							: List[Any] 							=						self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_sequence_classification(
              __UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase  )



     def  lowerCAmelCase__       (      self  )->					str:
          (
              (
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	
          )							: Optional[Any] 							=						self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_token_classification(
              __UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase  )



     def  lowerCAmelCase__       (      self  )->					int:
          (
              (
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	(
              UpperCAmelCase__
          )							,	
          )							: int 							=						self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_question_answering(
              __UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase  )



     @slow
     def  lowerCAmelCase__       (      self  )->					str:
          for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               UpperCAmelCase__							: int 							=						TFLayoutLMvaModel.from_pretrained(__UpperCamelCase  )
               self.assertIsNotNone(__UpperCamelCase  )





def 							a__ (				):






     '''simple docstring'''
     UpperCAmelCase__							: Optional[int] 							=						Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
     return image







@require_tf
class   _lowercase						(       unittest.TestCase				):


     '''simple docstring'''





     @cached_property
     def  lowerCAmelCase__       (      self  )->					Any:
          return LayoutLMvaImageProcessor(apply_ocr=__UpperCamelCase  ) if is_vision_available() else None



     @slow
     def  lowerCAmelCase__       (      self  )->					List[Any]:
          UpperCAmelCase__							: Optional[Any] 							=						TFLayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base"  )

          UpperCAmelCase__							: List[Any] 							=						self.default_image_processor
          UpperCAmelCase__							: Optional[Any] 							=						prepare_img()
          UpperCAmelCase__							: Union[str, Any] 							=						image_processor(images=__UpperCamelCase ,			return_tensors="tf"  ).pixel_values

          UpperCAmelCase__							: List[str] 							=						tf.constant([[1, 2]]  )
          UpperCAmelCase__							: Optional[int] 							=						tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]]  ) ,			axis=0  )

          # forward pass
          UpperCAmelCase__							: Optional[int] 							=						model(input_ids=__UpperCamelCase ,			bbox=__UpperCamelCase ,			pixel_values=__UpperCamelCase ,			training=__UpperCamelCase  )

          # verify the logits
          UpperCAmelCase__							: str 							=						(1, 1_99, 7_68)
          self.assertEqual(outputs.last_hidden_state.shape ,			__UpperCamelCase  )

          UpperCAmelCase__							: int 							=						tf.constant(
              [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]]  )

          self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] ,			__UpperCamelCase ,			atol=1E-4  )  )





"""simple docstring"""




from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING


A__      :	Union[str, Any]          =    logging.get_logger(__name__)

A__      :	Optional[int]          =    {
    """microsoft/table-transformer-detection""": (
        """https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json"""
    ),
}







class   _lowercase						(       lowerCAmelCase_				):


     '''simple docstring'''





     _A								=							'table-transformer'
     _A								=							['past_key_values']
     _A								=							{
         'hidden_size': 'd_model',
         'num_attention_heads': 'encoder_attention_heads',
     }



     def __init__(      self ,			__UpperCamelCase=True ,			__UpperCamelCase=None ,			__UpperCamelCase=3 ,			__UpperCamelCase=1_00 ,			__UpperCamelCase=6 ,			__UpperCamelCase=20_48 ,			__UpperCamelCase=8 ,			__UpperCamelCase=6 ,			__UpperCamelCase=20_48 ,			__UpperCamelCase=8 ,			__UpperCamelCase=0.0 ,			__UpperCamelCase=0.0 ,			__UpperCamelCase=True ,			__UpperCamelCase="relu" ,			__UpperCamelCase=2_56 ,			__UpperCamelCase=0.1 ,			__UpperCamelCase=0.0 ,			__UpperCamelCase=0.0 ,			__UpperCamelCase=0.02 ,			__UpperCamelCase=1.0 ,			__UpperCamelCase=False ,			__UpperCamelCase="sine" ,			__UpperCamelCase="resnet50" ,			__UpperCamelCase=True ,			__UpperCamelCase=False ,			__UpperCamelCase=1 ,			__UpperCamelCase=5 ,			__UpperCamelCase=2 ,			__UpperCamelCase=1 ,			__UpperCamelCase=1 ,			__UpperCamelCase=5 ,			__UpperCamelCase=2 ,			__UpperCamelCase=0.1 ,			**__UpperCamelCase ,			)->					List[Any]:
          if backbone_config is not None and use_timm_backbone:
               raise ValueError("You can't specify both `backbone_config` and `use_timm_backbone`."  )

          if not use_timm_backbone:
               if backbone_config is None:
                    logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone."  )
                    UpperCAmelCase__							: Any 							=						CONFIG_MAPPING["resnet"](out_features=["stage4"]  )
               elif isinstance(__UpperCamelCase ,			__UpperCamelCase  ):
                    UpperCAmelCase__							: int 							=						backbone_config.get("model_type"  )
                    UpperCAmelCase__							: Optional[Any] 							=						CONFIG_MAPPING[backbone_model_type]
                    UpperCAmelCase__							: int 							=						config_class.from_dict(__UpperCamelCase  )
               # set timm attributes to None
               UpperCAmelCase__							,	UpperCAmelCase__							,	UpperCAmelCase__							: List[str] 							=						None, None, None

          UpperCAmelCase__							: Optional[int] 							=						use_timm_backbone
          UpperCAmelCase__							: Dict 							=						backbone_config
          UpperCAmelCase__							: List[Any] 							=						num_channels
          UpperCAmelCase__							: Any 							=						num_queries
          UpperCAmelCase__							: int 							=						d_model
          UpperCAmelCase__							: Optional[int] 							=						encoder_ffn_dim
          UpperCAmelCase__							: str 							=						encoder_layers
          UpperCAmelCase__							: Dict 							=						encoder_attention_heads
          UpperCAmelCase__							: Optional[Any] 							=						decoder_ffn_dim
          UpperCAmelCase__							: Tuple 							=						decoder_layers
          UpperCAmelCase__							: Optional[Any] 							=						decoder_attention_heads
          UpperCAmelCase__							: List[str] 							=						dropout
          UpperCAmelCase__							: Tuple 							=						attention_dropout
          UpperCAmelCase__							: List[Any] 							=						activation_dropout
          UpperCAmelCase__							: Dict 							=						activation_function
          UpperCAmelCase__							: Optional[Any] 							=						init_std
          UpperCAmelCase__							: List[str] 							=						init_xavier_std
          UpperCAmelCase__							: int 							=						encoder_layerdrop
          UpperCAmelCase__							: Tuple 							=						decoder_layerdrop
          UpperCAmelCase__							: int 							=						encoder_layers
          UpperCAmelCase__							: Dict 							=						auxiliary_loss
          UpperCAmelCase__							: Union[str, Any] 							=						position_embedding_type
          UpperCAmelCase__							: List[str] 							=						backbone
          UpperCAmelCase__							: List[Any] 							=						use_pretrained_backbone
          UpperCAmelCase__							: List[str] 							=						dilation
          # Hungarian matcher
          UpperCAmelCase__							: Dict 							=						class_cost
          UpperCAmelCase__							: Any 							=						bbox_cost
          UpperCAmelCase__							: Tuple 							=						giou_cost
          # Loss coefficients
          UpperCAmelCase__							: Any 							=						mask_loss_coefficient
          UpperCAmelCase__							: Dict 							=						dice_loss_coefficient
          UpperCAmelCase__							: Any 							=						bbox_loss_coefficient
          UpperCAmelCase__							: Tuple 							=						giou_loss_coefficient
          UpperCAmelCase__							: List[Any] 							=						eos_coefficient
          super().__init__(is_encoder_decoder=__UpperCamelCase ,			**__UpperCamelCase  )



     @property
     def  lowerCAmelCase__       (      self  )->					int:
          return self.encoder_attention_heads



     @property
     def  lowerCAmelCase__       (      self  )->					int:
          return self.d_model







class   _lowercase						(       lowerCAmelCase_				):


     '''simple docstring'''





     _A								=							version.parse('1.11'				)



     @property
     def  lowerCAmelCase__       (      self  )->					Mapping[str, Mapping[int, str]]:
          return OrderedDict(
              [
                  ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
                  ("pixel_mask", {0: "batch"}),
              ]  )



     @property
     def  lowerCAmelCase__       (      self  )->					float:
          return 1E-5



     @property
     def  lowerCAmelCase__       (      self  )->					int:
          return 12



