


'''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    UpperCAmelCase_	:
       '''simple docstring'''






       def __init__(     self ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE=2 ,					__SCREAMING_SNAKE_CASE=3 ,					__SCREAMING_SNAKE_CASE=4 ,					__SCREAMING_SNAKE_CASE=2 ,					__SCREAMING_SNAKE_CASE=7 ,					__SCREAMING_SNAKE_CASE=True ,					__SCREAMING_SNAKE_CASE=True ,					__SCREAMING_SNAKE_CASE=True ,					__SCREAMING_SNAKE_CASE=True ,					__SCREAMING_SNAKE_CASE=99 ,					__SCREAMING_SNAKE_CASE=36 ,					__SCREAMING_SNAKE_CASE=2 ,					__SCREAMING_SNAKE_CASE=4 ,					__SCREAMING_SNAKE_CASE=37 ,					__SCREAMING_SNAKE_CASE="gelu" ,					__SCREAMING_SNAKE_CASE=0.1 ,					__SCREAMING_SNAKE_CASE=0.1 ,					__SCREAMING_SNAKE_CASE=512 ,					__SCREAMING_SNAKE_CASE=16 ,					__SCREAMING_SNAKE_CASE=2 ,					__SCREAMING_SNAKE_CASE=0.02 ,					__SCREAMING_SNAKE_CASE=6 ,					__SCREAMING_SNAKE_CASE=6 ,					__SCREAMING_SNAKE_CASE=3 ,					__SCREAMING_SNAKE_CASE=4 ,					__SCREAMING_SNAKE_CASE=None ,					__SCREAMING_SNAKE_CASE=1_000 ,					):




              """simple docstring"""




              UpperCamelCase    :	Tuple   	=		parent
              UpperCamelCase    :	Union[str, Any]   	=		batch_size
              UpperCamelCase    :	Union[str, Any]   	=		num_channels
              UpperCamelCase    :	int   	=		image_size
              UpperCamelCase    :	int   	=		patch_size
              UpperCamelCase    :	int   	=		is_training
              UpperCamelCase    :	int   	=		use_input_mask
              UpperCamelCase    :	int   	=		use_token_type_ids
              UpperCamelCase    :	Union[str, Any]   	=		use_labels
              UpperCamelCase    :	Tuple   	=		vocab_size
              UpperCamelCase    :	Optional[int]   	=		hidden_size
              UpperCamelCase    :	int   	=		num_hidden_layers
              UpperCamelCase    :	List[Any]   	=		num_attention_heads
              UpperCamelCase    :	Tuple   	=		intermediate_size
              UpperCamelCase    :	Tuple   	=		hidden_act
              UpperCamelCase    :	str   	=		hidden_dropout_prob
              UpperCamelCase    :	int   	=		attention_probs_dropout_prob
              UpperCamelCase    :	Optional[Any]   	=		max_position_embeddings
              UpperCamelCase    :	Optional[int]   	=		type_vocab_size
              UpperCamelCase    :	Any   	=		type_sequence_label_size
              UpperCamelCase    :	Optional[Any]   	=		initializer_range
              UpperCamelCase    :	Dict   	=		coordinate_size
              UpperCamelCase    :	Optional[int]   	=		shape_size
              UpperCamelCase    :	str   	=		num_labels
              UpperCamelCase    :	Any   	=		num_choices
              UpperCamelCase    :	Union[str, Any]   	=		scope
              UpperCamelCase    :	Optional[Any]   	=		range_bbox

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






       def  _lowercase   (     self						):




              """simple docstring"""




              UpperCamelCase    :	Union[str, Any]   	=		ids_tensor([self.batch_size, self.text_seq_length] ,					self.vocab_size						)

              UpperCamelCase    :	Union[str, Any]   	=		ids_tensor([self.batch_size, self.text_seq_length, 4] ,					self.range_bbox						)
              UpperCamelCase    :	List[str]   	=		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    :	Union[str, Any]   	=		bbox[i, j, 1]
                                   UpperCamelCase    :	Union[str, Any]   	=		tmp_coordinate
                            if bbox[i, j, 2] < bbox[i, j, 0]:
                                   UpperCamelCase    :	Union[str, Any]   	=		bbox[i, j, 2]
                                   UpperCamelCase    :	str   	=		bbox[i, j, 0]
                                   UpperCamelCase    :	Tuple   	=		tmp_coordinate
              UpperCamelCase    :	Optional[Any]   	=		tf.constant(__SCREAMING_SNAKE_CASE						)

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

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

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

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

              UpperCamelCase    :	Dict   	=		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  _lowercase   (     self ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE						):




              """simple docstring"""




              UpperCamelCase    :	Tuple   	=		TFLayoutLMvaModel(config=__SCREAMING_SNAKE_CASE						)

              # text + image
              UpperCamelCase    :	Dict   	=		model(__SCREAMING_SNAKE_CASE ,					pixel_values=__SCREAMING_SNAKE_CASE ,					training=__SCREAMING_SNAKE_CASE						)
              UpperCamelCase    :	str   	=		model(
                  __SCREAMING_SNAKE_CASE ,					bbox=__SCREAMING_SNAKE_CASE ,					pixel_values=__SCREAMING_SNAKE_CASE ,					attention_mask=__SCREAMING_SNAKE_CASE ,					token_type_ids=__SCREAMING_SNAKE_CASE ,					training=__SCREAMING_SNAKE_CASE ,					)
              UpperCamelCase    :	Optional[Any]   	=		model(__SCREAMING_SNAKE_CASE ,					bbox=__SCREAMING_SNAKE_CASE ,					pixel_values=__SCREAMING_SNAKE_CASE ,					training=__SCREAMING_SNAKE_CASE						)

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

              # text only
              UpperCamelCase    :	int   	=		model(__SCREAMING_SNAKE_CASE ,					training=__SCREAMING_SNAKE_CASE						)
              self.parent.assertEqual(
                  result.last_hidden_state.shape ,					(self.batch_size, self.text_seq_length, self.hidden_size)						)

              # image only
              UpperCamelCase    :	List[Any]   	=		model({'''pixel_values''': pixel_values} ,					training=__SCREAMING_SNAKE_CASE						)
              self.parent.assertEqual(
                  result.last_hidden_state.shape ,					(self.batch_size, self.image_seq_length, self.hidden_size)						)






       def  _lowercase   (     self ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE						):




              """simple docstring"""




              UpperCamelCase    :	List[Any]   	=		self.num_labels
              UpperCamelCase    :	str   	=		TFLayoutLMvaForSequenceClassification(config=__SCREAMING_SNAKE_CASE						)
              UpperCamelCase    :	List[str]   	=		model(
                  __SCREAMING_SNAKE_CASE ,					bbox=__SCREAMING_SNAKE_CASE ,					pixel_values=__SCREAMING_SNAKE_CASE ,					attention_mask=__SCREAMING_SNAKE_CASE ,					token_type_ids=__SCREAMING_SNAKE_CASE ,					labels=__SCREAMING_SNAKE_CASE ,					training=__SCREAMING_SNAKE_CASE ,					)
              self.parent.assertEqual(result.logits.shape ,					(self.batch_size, self.num_labels)						)






       def  _lowercase   (     self ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE						):




              """simple docstring"""




              UpperCamelCase    :	List[str]   	=		self.num_labels
              UpperCamelCase    :	Dict   	=		TFLayoutLMvaForTokenClassification(config=__SCREAMING_SNAKE_CASE						)
              UpperCamelCase    :	Optional[Any]   	=		model(
                  __SCREAMING_SNAKE_CASE ,					bbox=__SCREAMING_SNAKE_CASE ,					pixel_values=__SCREAMING_SNAKE_CASE ,					attention_mask=__SCREAMING_SNAKE_CASE ,					token_type_ids=__SCREAMING_SNAKE_CASE ,					labels=__SCREAMING_SNAKE_CASE ,					training=__SCREAMING_SNAKE_CASE ,					)
              self.parent.assertEqual(result.logits.shape ,					(self.batch_size, self.text_seq_length, self.num_labels)						)






       def  _lowercase   (     self ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE						):




              """simple docstring"""




              UpperCamelCase    :	List[str]   	=		2
              UpperCamelCase    :	Optional[int]   	=		TFLayoutLMvaForQuestionAnswering(config=__SCREAMING_SNAKE_CASE						)
              UpperCamelCase    :	Any   	=		model(
                  __SCREAMING_SNAKE_CASE ,					bbox=__SCREAMING_SNAKE_CASE ,					pixel_values=__SCREAMING_SNAKE_CASE ,					attention_mask=__SCREAMING_SNAKE_CASE ,					token_type_ids=__SCREAMING_SNAKE_CASE ,					start_positions=__SCREAMING_SNAKE_CASE ,					end_positions=__SCREAMING_SNAKE_CASE ,					training=__SCREAMING_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  _lowercase   (     self						):




              """simple docstring"""




              UpperCamelCase    :	Optional[Any]   	=		self.prepare_config_and_inputs()
              (UpperCamelCase)    :	Optional[Any]   	=		config_and_inputs
              UpperCamelCase    :	Union[str, 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    UpperCAmelCase_	(							_a,     _a,     unittest.TestCase):
       '''simple docstring'''
       __UpperCamelCase      :     Optional[int]							=					(
           (
               TFLayoutLMvaModel,
               TFLayoutLMvaForQuestionAnswering,
               TFLayoutLMvaForSequenceClassification,
               TFLayoutLMvaForTokenClassification,
           )
           if is_tf_available()
           else ()
       )
       __UpperCamelCase      :     Any							=					(
           {"document-question-answering": TFLayoutLMvaForQuestionAnswering, "feature-extraction": TFLayoutLMvaModel}
           if is_tf_available()
           else {}
       )

       __UpperCamelCase      :     Tuple							=					False
       __UpperCamelCase      :     Any							=					False
       __UpperCamelCase      :     Dict							=					False






       def  _lowercase   (     self ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE						):




              """simple docstring"""




              return True






       def  _lowercase   (     self ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE=False						):




              """simple docstring"""




              UpperCamelCase    :	List[str]   	=		copy.deepcopy(__SCREAMING_SNAKE_CASE						)

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

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

              return inputs_dict






       def  _lowercase   (     self						):




              """simple docstring"""




              UpperCamelCase    :	int   	=		TFLayoutLMvaModelTester(self						)
              UpperCamelCase    :	int   	=		ConfigTester(self ,					config_class=__SCREAMING_SNAKE_CASE ,					hidden_size=37						)






       def  _lowercase   (     self						):




              """simple docstring"""




              self.config_tester.run_common_tests()






       def  _lowercase   (     self						):




              """simple docstring"""




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

                            # Test that model correctly compute the loss with kwargs
                            UpperCamelCase    :	Optional[int]   	=		self._prepare_for_class(inputs_dict.copy() ,					__SCREAMING_SNAKE_CASE ,					return_labels=__SCREAMING_SNAKE_CASE						)
                            UpperCamelCase    :	Optional[Any]   	=		prepared_for_class.pop('''input_ids'''						)

                            UpperCamelCase    :	Optional[int]   	=		model(__SCREAMING_SNAKE_CASE ,					**__SCREAMING_SNAKE_CASE						)[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    :	List[str]   	=		self._prepare_for_class(inputs_dict.copy() ,					__SCREAMING_SNAKE_CASE ,					return_labels=__SCREAMING_SNAKE_CASE						)
                            UpperCamelCase    :	Tuple   	=		prepared_for_class.pop('''input_ids'''						)
                            if "labels" in prepared_for_class:
                                   UpperCamelCase    :	Optional[Any]   	=		prepared_for_class['''labels'''].numpy()
                                   if len(labels.shape						) > 1 and labels.shape[1] != 1:
                                          UpperCamelCase    :	Any   	=		-100
                                          UpperCamelCase    :	Union[str, Any]   	=		tf.convert_to_tensor(__SCREAMING_SNAKE_CASE						)
                                          UpperCamelCase    :	Optional[int]   	=		model(__SCREAMING_SNAKE_CASE ,					**__SCREAMING_SNAKE_CASE						)[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    :	Union[str, Any]   	=		self._prepare_for_class(inputs_dict.copy() ,					__SCREAMING_SNAKE_CASE ,					return_labels=__SCREAMING_SNAKE_CASE						)
                            UpperCamelCase    :	List[str]   	=		model(__SCREAMING_SNAKE_CASE						)[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    :	Optional[int]   	=		self._prepare_for_class(inputs_dict.copy() ,					__SCREAMING_SNAKE_CASE ,					return_labels=__SCREAMING_SNAKE_CASE						)

                            # Get keys that were added with the _prepare_for_class function
                            UpperCamelCase    :	Dict   	=		prepared_for_class.keys() - inputs_dict.keys()
                            UpperCamelCase    :	str   	=		inspect.signature(model.call						).parameters
                            UpperCamelCase    :	Tuple   	=		list(signature.keys()						)

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

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

                            for index, value in sorted_tuple_index_mapping:
                                   UpperCamelCase    :	Dict   	=		prepared_for_class[value]

                            UpperCamelCase    :	List[str]   	=		tuple(__SCREAMING_SNAKE_CASE						)

                            # Send to model
                            UpperCamelCase    :	Optional[int]   	=		model(tuple_input[:-1]						)[0]

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






       def  _lowercase   (     self						):




              """simple docstring"""




              (
                  UpperCamelCase 
              )    :	Optional[int]   	=		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_model(__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE						)






       def  _lowercase   (     self						):




              """simple docstring"""




              (
                  UpperCamelCase 
              )    :	Dict   	=		self.model_tester.prepare_config_and_inputs()
              for type in ["absolute", "relative_key", "relative_key_query"]:
                     UpperCamelCase    :	Any   	=		type
                     self.model_tester.create_and_check_model(__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE						)






       def  _lowercase   (     self						):




              """simple docstring"""




              (
                  UpperCamelCase 
              )    :	Optional[int]   	=		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_for_sequence_classification(
                  __SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE						)






       def  _lowercase   (     self						):




              """simple docstring"""




              (
                  UpperCamelCase 
              )    :	List[Any]   	=		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_for_token_classification(
                  __SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE						)






       def  _lowercase   (     self						):




              """simple docstring"""




              (
                  UpperCamelCase 
              )    :	Optional[int]   	=		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_for_question_answering(
                  __SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE						)






       @slow
       def  _lowercase   (     self						):




              """simple docstring"""




              for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                     UpperCamelCase    :	Optional[Any]   	=		TFLayoutLMvaModel.from_pretrained(__SCREAMING_SNAKE_CASE						)
                     self.assertIsNotNone(__SCREAMING_SNAKE_CASE						)




def      a	(							):






       """simple docstring"""





       UpperCamelCase    :	List[Any]   	=		Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''       )
       return image



@require_tf
class    UpperCAmelCase_	(							unittest.TestCase):
       '''simple docstring'''






       @cached_property
       def  _lowercase   (     self						):




              """simple docstring"""




              return LayoutLMvaImageProcessor(apply_ocr=__SCREAMING_SNAKE_CASE						) if is_vision_available() else None






       @slow
       def  _lowercase   (     self						):




              """simple docstring"""




              UpperCamelCase    :	str   	=		TFLayoutLMvaModel.from_pretrained('''microsoft/layoutlmv3-base'''						)

              UpperCamelCase    :	str   	=		self.default_image_processor
              UpperCamelCase    :	Optional[int]   	=		prepare_img()
              UpperCamelCase    :	Any   	=		image_processor(images=__SCREAMING_SNAKE_CASE ,					return_tensors='''tf'''						).pixel_values

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

              # forward pass
              UpperCamelCase    :	List[str]   	=		model(input_ids=__SCREAMING_SNAKE_CASE ,					bbox=__SCREAMING_SNAKE_CASE ,					pixel_values=__SCREAMING_SNAKE_CASE ,					training=__SCREAMING_SNAKE_CASE						)

              # verify the logits
              UpperCamelCase    :	str   	=		(1, 199, 768)
              self.assertEqual(outputs.last_hidden_state.shape ,					__SCREAMING_SNAKE_CASE						)

              UpperCamelCase    :	Dict   	=		tf.constant(
                  [[-0.0_529, 0.3_618, 0.1_632], [-0.1_587, -0.1_667, -0.0_400], [-0.1_557, -0.1_671, -0.0_505]]						)

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





from .imports import is_tqdm_available


if is_tqdm_available():
  from tqdm.auto import tqdm as _tqdm

from ..state import PartialState


def      a	(							SCREAMING_SNAKE_CASE_      :		bool = True							,			*SCREAMING_SNAKE_CASE_      :		List[str]							,			**SCREAMING_SNAKE_CASE_      :		Tuple       ):






       """simple docstring"""





       if not is_tqdm_available():
              raise ImportError('''Accelerate\'s `tqdm` module requires `tqdm` to be installed. Please run `pip install tqdm`.'''       )
       UpperCamelCase    :	int   	=		False
       if main_process_only:
              UpperCamelCase    :	int   	=		PartialState().local_process_index == 0
       return _tqdm(*SCREAMING_SNAKE_CASE_							,			**SCREAMING_SNAKE_CASE_							,			disable=SCREAMING_SNAKE_CASE_       )

