


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


      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__=1000				,    ):
            lowercase      : int        =		parent
            lowercase      : Union[str, Any]        =		batch_size
            lowercase      : Tuple        =		num_channels
            lowercase      : List[str]        =		image_size
            lowercase      : str        =		patch_size
            lowercase      : Optional[Any]        =		is_training
            lowercase      : Optional[Any]        =		use_input_mask
            lowercase      : Tuple        =		use_token_type_ids
            lowercase      : Union[str, Any]        =		use_labels
            lowercase      : str        =		vocab_size
            lowercase      : int        =		hidden_size
            lowercase      : Any        =		num_hidden_layers
            lowercase      : Dict        =		num_attention_heads
            lowercase      : List[str]        =		intermediate_size
            lowercase      : Union[str, Any]        =		hidden_act
            lowercase      : Optional[int]        =		hidden_dropout_prob
            lowercase      : Dict        =		attention_probs_dropout_prob
            lowercase      : Optional[Any]        =		max_position_embeddings
            lowercase      : Optional[Any]        =		type_vocab_size
            lowercase      : str        =		type_sequence_label_size
            lowercase      : Tuple        =		initializer_range
            lowercase      : List[Any]        =		coordinate_size
            lowercase      : Optional[int]        =		shape_size
            lowercase      : List[Any]        =		num_labels
            lowercase      : int        =		num_choices
            lowercase      : str        =		scope
            lowercase      : Optional[int]        =		range_bbox

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


      def 							__lowerCamelCase      (				self		):
            lowercase      : List[Any]        =		ids_tensor([self.batch_size, self.text_seq_length]				,    self.vocab_size		)

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

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

            lowercase      : List[str]        =		None
            if self.use_input_mask:
                  lowercase      : int        =		random_attention_mask([self.batch_size, self.text_seq_length]		)

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

            lowercase      : Any        =		None
            lowercase      : Dict        =		None
            if self.use_labels:
                  lowercase      : str        =		ids_tensor([self.batch_size]				,    self.type_sequence_label_size		)
                  lowercase      : int        =		ids_tensor([self.batch_size, self.text_seq_length]				,    self.num_labels		)

            lowercase      : List[str]        =		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				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__		):
            lowercase      : int        =		TFLayoutLMvaModel(config=lowerCAmelCase_		)

            # text + image
            lowercase      : Tuple        =		model(lowerCAmelCase_				,    pixel_values=lowerCAmelCase_				,    training=lowerCAmelCase_		)
            lowercase      : Tuple        =		model(
                lowerCAmelCase_				,    bbox=lowerCAmelCase_				,    pixel_values=lowerCAmelCase_				,    attention_mask=lowerCAmelCase_				,    token_type_ids=lowerCAmelCase_				,    training=lowerCAmelCase_				,    )
            lowercase      : str        =		model(lowerCAmelCase_				,    bbox=lowerCAmelCase_				,    pixel_values=lowerCAmelCase_				,    training=lowerCAmelCase_		)

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

            # text only
            lowercase      : Any        =		model(lowerCAmelCase_				,    training=lowerCAmelCase_		)
            self.parent.assertEqual(
                result.last_hidden_state.shape				,    (self.batch_size, self.text_seq_length, self.hidden_size)		)

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


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


      def 							__lowerCamelCase      (				self				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__		):
            lowercase      : List[Any]        =		self.num_labels
            lowercase      : Dict        =		TFLayoutLMvaForTokenClassification(config=lowerCAmelCase_		)
            lowercase      : int        =		model(
                lowerCAmelCase_				,    bbox=lowerCAmelCase_				,    pixel_values=lowerCAmelCase_				,    attention_mask=lowerCAmelCase_				,    token_type_ids=lowerCAmelCase_				,    labels=lowerCAmelCase_				,    training=lowerCAmelCase_				,    )
            self.parent.assertEqual(result.logits.shape				,    (self.batch_size, self.text_seq_length, self.num_labels)		)


      def 							__lowerCamelCase      (				self				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__		):
            lowercase      : Optional[Any]        =		2
            lowercase      : int        =		TFLayoutLMvaForQuestionAnswering(config=lowerCAmelCase_		)
            lowercase      : Any        =		model(
                lowerCAmelCase_				,    bbox=lowerCAmelCase_				,    pixel_values=lowerCAmelCase_				,    attention_mask=lowerCAmelCase_				,    token_type_ids=lowerCAmelCase_				,    start_positions=lowerCAmelCase_				,    end_positions=lowerCAmelCase_				,    training=lowerCAmelCase_				,    )
            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		):
            lowercase      : Union[str, Any]        =		self.prepare_config_and_inputs()
            ((lowercase) ,      (lowercase) ,      (lowercase) ,      (lowercase) ,      (lowercase) ,      (lowercase) ,      (lowercase) ,      (lowercase))      : Dict        =		config_and_inputs
            lowercase      : Optional[int]        =		{
                '''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 					__SCREAMING_SNAKE_CASE (      _a	,    _a	,    unittest.TestCase ):
      A					:				List[Any]     				=  (
          (
              TFLayoutLMvaModel,
              TFLayoutLMvaForQuestionAnswering,
              TFLayoutLMvaForSequenceClassification,
              TFLayoutLMvaForTokenClassification,
          )
          if is_tf_available()
          else ()
      )
      A					:				Optional[int]     				=  (
          {'document-question-answering': TFLayoutLMvaForQuestionAnswering, 'feature-extraction': TFLayoutLMvaModel}
          if is_tf_available()
          else {}
      )

      A					:				Tuple     				=  False
      A					:				Any     				=  False
      A					:				int     				=  False


      def 							__lowerCamelCase      (				self				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__		):
            return True


      def 							__lowerCamelCase      (				self				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__=False		):
            lowercase      : List[str]        =		copy.deepcopy(lowerCAmelCase_		)

            if model_class in get_values(lowerCAmelCase_		):
                  lowercase      : Tuple        =		{
                      k: tf.tile(tf.expand_dims(lowerCAmelCase_				,    1		)				,    (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1)		)
                      if isinstance(lowerCAmelCase_				,    tf.Tensor		) and v.ndim > 0
                      else v
                      for k, v in inputs_dict.items()
                  }

            if return_labels:
                  if model_class in get_values(lowerCAmelCase_		):
                        lowercase      : Any        =		tf.ones(self.model_tester.batch_size				,    dtype=tf.intaa		)
                  elif model_class in get_values(lowerCAmelCase_		):
                        lowercase      : str        =		tf.zeros(self.model_tester.batch_size				,    dtype=tf.intaa		)
                        lowercase      : List[str]        =		tf.zeros(self.model_tester.batch_size				,    dtype=tf.intaa		)
                  elif model_class in get_values(lowerCAmelCase_		):
                        lowercase      : Tuple        =		tf.zeros(self.model_tester.batch_size				,    dtype=tf.intaa		)
                  elif model_class in get_values(lowerCAmelCase_		):
                        lowercase      : Any        =		tf.zeros(
                            (self.model_tester.batch_size, self.model_tester.text_seq_length)				,    dtype=tf.intaa		)

            return inputs_dict


      def 							__lowerCamelCase      (				self		):
            lowercase      : Optional[int]        =		TFLayoutLMvaModelTester(self		)
            lowercase      : Optional[Any]        =		ConfigTester(self				,    config_class=lowerCAmelCase_				,    hidden_size=37		)


      def 							__lowerCamelCase      (				self		):
            self.config_tester.run_common_tests()


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

                        # Test that model correctly compute the loss with kwargs
                        lowercase      : List[Any]        =		self._prepare_for_class(inputs_dict.copy()				,    lowerCAmelCase_				,    return_labels=lowerCAmelCase_		)
                        lowercase      : str        =		prepared_for_class.pop('''input_ids'''		)

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

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

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

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

                        for index, value in sorted_tuple_index_mapping:
                              lowercase      : int        =		prepared_for_class[value]

                        lowercase      : str        =		tuple(lowerCAmelCase_		)

                        # Send to model
                        lowercase      : Any        =		model(tuple_input[:-1]		)[0]

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


      def 							__lowerCamelCase      (				self		):
            (
                (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      				
            )      : List[Any]        =		self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_		)


      def 							__lowerCamelCase      (				self		):
            (
                (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      				
            )      : List[str]        =		self.model_tester.prepare_config_and_inputs()
            for type in ["absolute", "relative_key", "relative_key_query"]:
                  lowercase      : List[Any]        =		type
                  self.model_tester.create_and_check_model(lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_		)


      def 							__lowerCamelCase      (				self		):
            (
                (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      				
            )      : Optional[Any]        =		self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_sequence_classification(
                lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_		)


      def 							__lowerCamelCase      (				self		):
            (
                (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      				
            )      : Optional[int]        =		self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_token_classification(
                lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_		)


      def 							__lowerCamelCase      (				self		):
            (
                (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      (
                lowercase				
            ) ,      				
            )      : Optional[int]        =		self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_question_answering(
                lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_				,    lowerCAmelCase_		)






      @slow
      def 							__lowerCamelCase      (				self		):


            for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  lowercase      : Dict        =		TFLayoutLMvaModel.from_pretrained(lowerCAmelCase_		)
                  self.assertIsNotNone(lowerCAmelCase_		)





def       __lowercase						(    )     ->Optional[int]:







      """simple docstring"""

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







@require_tf
class 					__SCREAMING_SNAKE_CASE (      unittest.TestCase ):


      @cached_property
      def 							__lowerCamelCase      (				self		):
            return LayoutLMvaImageProcessor(apply_ocr=lowerCAmelCase_		) if is_vision_available() else None






      @slow
      def 							__lowerCamelCase      (				self		):
            lowercase      : Optional[Any]        =		TFLayoutLMvaModel.from_pretrained('''microsoft/layoutlmv3-base'''		)

            lowercase      : List[str]        =		self.default_image_processor
            lowercase      : Union[str, Any]        =		prepare_img()
            lowercase      : Tuple        =		image_processor(images=lowerCAmelCase_				,    return_tensors='''tf'''		).pixel_values

            lowercase      : Any        =		tf.constant([[1, 2]]		)
            lowercase      : Dict        =		tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]]		)				,    axis=0		)

            # forward pass
            lowercase      : List[Any]        =		model(input_ids=lowerCAmelCase_				,    bbox=lowerCAmelCase_				,    pixel_values=lowerCAmelCase_				,    training=lowerCAmelCase_		)

            # verify the logits
            lowercase      : Dict        =		(1, 199, 768)
            self.assertEqual(outputs.last_hidden_state.shape				,    lowerCAmelCase_		)

            lowercase      : Optional[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]				,    lowerCAmelCase_				,    atol=1E-4		)		)







'''simple docstring'''


import pytest

from datasets.splits import SplitDict, SplitInfo
from datasets.utils.py_utils import asdict
@pytest.mark.parametrize(
    '''split_dict'''					,		[
        SplitDict(),
        SplitDict({'''train''': SplitInfo(name='''train'''					,		num_bytes=1337					,		num_examples=42					,		dataset_name='''my_dataset''' )} ),
        SplitDict({'''train''': SplitInfo(name='''train'''					,		num_bytes=1337					,		num_examples=42 )} ),
        SplitDict({'''train''': SplitInfo()} ),
    ]					,		)
def 						snake_case_       (UpperCamelCase			:    SplitDict ):





							'''simple docstring'''


							_a      	=							split_dict._to_yaml_list()
							assert len(UpperCamelCase ) == len(UpperCamelCase )
							_a      	=							SplitDict._from_yaml_list(UpperCamelCase )
							for split_name, split_info in split_dict.items():
														# dataset_name field is deprecated, and is therefore not part of the YAML dump
														_a      	=							None
														# the split name of split_dict takes over the name of the split info object
														_a      	=							split_name
							assert split_dict == reloaded

@pytest.mark.parametrize(
    '''split_info'''					,		[SplitInfo(), SplitInfo(dataset_name=UpperCamelCase ), SplitInfo(dataset_name='''my_dataset''' )] )
def 						snake_case_       (UpperCamelCase			:    List[str] ):





							'''simple docstring'''


							_a      	=							asdict(SplitDict({'''train''': split_info} ) )
							assert "dataset_name" in split_dict_asdict["train"]
							assert split_dict_asdict["train"]["dataset_name"] == split_info.dataset_name

