





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


  '''simple docstring'''







  def __init__(      self      :					Union[str, Any]      ,				UpperCamelCase      :					Optional[int]      ,				UpperCamelCase      :					Any=2      ,				UpperCamelCase      :					Optional[Any]=3      ,				UpperCamelCase      :					Union[str, Any]=4      ,				UpperCamelCase      :					Optional[int]=2      ,				UpperCamelCase      :					Tuple=7      ,				UpperCamelCase      :					Optional[int]=True      ,				UpperCamelCase      :					Dict=True      ,				UpperCamelCase      :					List[Any]=True      ,				UpperCamelCase      :					Optional[Any]=True      ,				UpperCamelCase      :					Dict=99      ,				UpperCamelCase      :					List[Any]=36      ,				UpperCamelCase      :					Any=2      ,				UpperCamelCase      :					str=4      ,				UpperCamelCase      :					List[str]=37      ,				UpperCamelCase      :					List[str]="gelu"      ,				UpperCamelCase      :					Union[str, Any]=0.1      ,				UpperCamelCase      :					int=0.1      ,				UpperCamelCase      :					List[Any]=5_12      ,				UpperCamelCase      :					int=16      ,				UpperCamelCase      :					Tuple=2      ,				UpperCamelCase      :					Optional[int]=0.02      ,				UpperCamelCase      :					Optional[int]=6      ,				UpperCamelCase      :					Dict=6      ,				UpperCamelCase      :					Optional[int]=3      ,				UpperCamelCase      :					Union[str, Any]=4      ,				UpperCamelCase      :					Union[str, Any]=None      ,				UpperCamelCase      :					Optional[int]=10_00      ,				):


    '''simple docstring'''





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

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







  def UpperCamelCase_ (      self      :					List[str]							):


    '''simple docstring'''





    _snake_case   :				List[Any]														=	ids_tensor([self.batch_size, self.text_seq_length]      ,				self.vocab_size							)

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

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

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

    _snake_case   :				List[str]														=	None
    if self.use_token_type_ids:
      _snake_case   :				int														=	ids_tensor([self.batch_size, self.text_seq_length]      ,				self.type_vocab_size							)

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

    _snake_case   :				Optional[Any]														=	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      :					List[str]      ,				UpperCamelCase      :					str      ,				UpperCamelCase      :					List[str]      ,				UpperCamelCase      :					Optional[int]      ,				UpperCamelCase      :					List[str]      ,				UpperCamelCase      :					str      ,				UpperCamelCase      :					List[Any]							):


    '''simple docstring'''





    _snake_case   :				Any														=	TFLayoutLMvaModel(config=UpperCamelCase							)

    # text + image
    _snake_case   :				Tuple														=	model(UpperCamelCase      ,				pixel_values=UpperCamelCase      ,				training=UpperCamelCase							)
    _snake_case   :				str														=	model(
        UpperCamelCase      ,				bbox=UpperCamelCase      ,				pixel_values=UpperCamelCase      ,				attention_mask=UpperCamelCase      ,				token_type_ids=UpperCamelCase      ,				training=UpperCamelCase      ,				)
    _snake_case   :				Any														=	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
    _snake_case   :				Optional[int]														=	model(UpperCamelCase      ,				training=UpperCamelCase							)
    self.parent.assertEqual(
        result.last_hidden_state.shape      ,				(self.batch_size, self.text_seq_length, self.hidden_size)							)

    # image only
    _snake_case   :				List[str]														=	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 UpperCamelCase_ (      self      :					List[str]      ,				UpperCamelCase      :					int      ,				UpperCamelCase      :					int      ,				UpperCamelCase      :					Optional[Any]      ,				UpperCamelCase      :					Tuple      ,				UpperCamelCase      :					Optional[Any]      ,				UpperCamelCase      :					Any      ,				UpperCamelCase      :					Optional[int]							):


    '''simple docstring'''





    _snake_case   :				int														=	self.num_labels
    _snake_case   :				Any														=	TFLayoutLMvaForSequenceClassification(config=UpperCamelCase							)
    _snake_case   :				Tuple														=	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 UpperCamelCase_ (      self      :					Optional[Any]      ,				UpperCamelCase      :					Dict      ,				UpperCamelCase      :					Optional[Any]      ,				UpperCamelCase      :					Any      ,				UpperCamelCase      :					List[str]      ,				UpperCamelCase      :					Any      ,				UpperCamelCase      :					Optional[int]      ,				UpperCamelCase      :					Optional[Any]							):


    '''simple docstring'''





    _snake_case   :				Union[str, Any]														=	self.num_labels
    _snake_case   :				Optional[int]														=	TFLayoutLMvaForTokenClassification(config=UpperCamelCase							)
    _snake_case   :				str														=	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 UpperCamelCase_ (      self      :					int      ,				UpperCamelCase      :					Dict      ,				UpperCamelCase      :					str      ,				UpperCamelCase      :					List[Any]      ,				UpperCamelCase      :					Optional[int]      ,				UpperCamelCase      :					List[str]      ,				UpperCamelCase      :					List[str]      ,				UpperCamelCase      :					List[Any]							):


    '''simple docstring'''





    _snake_case   :				Union[str, Any]														=	2
    _snake_case   :				Optional[Any]														=	TFLayoutLMvaForQuestionAnswering(config=UpperCamelCase							)
    _snake_case   :				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 UpperCamelCase_ (      self      :					str							):


    '''simple docstring'''





    _snake_case   :				List[str]														=	self.prepare_config_and_inputs()
    ((_snake_case)							,					(_snake_case)							,					(_snake_case)							,					(_snake_case)							,					(_snake_case)							,					(_snake_case)							,					(_snake_case)							,					(_snake_case))   :				Optional[Any]														=	config_and_inputs
    _snake_case   :				List[str]														=	{
        '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        _lowerCAmelCase    (			UpperCAmelCase_							,    UpperCAmelCase_							,    unittest.TestCase							):


  '''simple docstring'''
  a_							:       Any      					=(
      (
          TFLayoutLMvaModel,
          TFLayoutLMvaForQuestionAnswering,
          TFLayoutLMvaForSequenceClassification,
          TFLayoutLMvaForTokenClassification,
      )
      if is_tf_available()
      else ()
  )
  a_							:       Tuple      					=(
      {"""document-question-answering""": TFLayoutLMvaForQuestionAnswering, """feature-extraction""": TFLayoutLMvaModel}
      if is_tf_available()
      else {}
  )

  a_							:       int      					=False
  a_							:       Union[str, Any]      					=False
  a_							:       Optional[int]      					=False







  def UpperCamelCase_ (      self      :					List[str]      ,				UpperCamelCase      :					List[Any]      ,				UpperCamelCase      :					List[Any]      ,				UpperCamelCase      :					List[Any]      ,				UpperCamelCase      :					int      ,				UpperCamelCase      :					str							):


    '''simple docstring'''





    return True







  def UpperCamelCase_ (      self      :					Optional[Any]      ,				UpperCamelCase      :					Union[str, Any]      ,				UpperCamelCase      :					int      ,				UpperCamelCase      :					Optional[Any]=False							):


    '''simple docstring'''





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

    if model_class in get_values(UpperCamelCase							):
      _snake_case   :				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							):
        _snake_case   :				Optional[int]														=	tf.ones(self.model_tester.batch_size      ,				dtype=tf.intaa							)
      elif model_class in get_values(UpperCamelCase							):
        _snake_case   :				str														=	tf.zeros(self.model_tester.batch_size      ,				dtype=tf.intaa							)
        _snake_case   :				Optional[Any]														=	tf.zeros(self.model_tester.batch_size      ,				dtype=tf.intaa							)
      elif model_class in get_values(UpperCamelCase							):
        _snake_case   :				List[Any]														=	tf.zeros(self.model_tester.batch_size      ,				dtype=tf.intaa							)
      elif model_class in get_values(UpperCamelCase							):
        _snake_case   :				Any														=	tf.zeros(
            (self.model_tester.batch_size, self.model_tester.text_seq_length)      ,				dtype=tf.intaa							)

    return inputs_dict







  def UpperCamelCase_ (      self      :					int							):


    '''simple docstring'''





    _snake_case   :				List[str]														=	TFLayoutLMvaModelTester(self							)
    _snake_case   :				Union[str, Any]														=	ConfigTester(self      ,				config_class=UpperCamelCase      ,				hidden_size=37							)







  def UpperCamelCase_ (      self      :					Dict							):


    '''simple docstring'''





    self.config_tester.run_common_tests()







  def UpperCamelCase_ (      self      :					List[str]							):


    '''simple docstring'''





    _snake_case							,					_snake_case   :				Any														=	self.model_tester.prepare_config_and_inputs_for_common()
    for model_class in self.all_model_classes:
      _snake_case   :				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
        _snake_case   :				str														=	self._prepare_for_class(inputs_dict.copy()      ,				UpperCamelCase      ,				return_labels=UpperCamelCase							)
        _snake_case   :				Optional[Any]														=	prepared_for_class[
            sorted(prepared_for_class.keys() - inputs_dict.keys()      ,				reverse=UpperCamelCase							)[0]
        ]
        _snake_case   :				Tuple														=	added_label.shape.as_list()[:1]

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

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

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

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

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

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

        _snake_case   :				int														=	tuple(UpperCamelCase							)

        # Send to model
        _snake_case   :				Tuple														=	model(tuple_input[:-1]							)[0]

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







  def UpperCamelCase_ (      self      :					List[Any]							):


    '''simple docstring'''





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







  def UpperCamelCase_ (      self      :					Union[str, Any]							):


    '''simple docstring'''





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







  def UpperCamelCase_ (      self      :					int							):


    '''simple docstring'''





    (
        (
        _snake_case
    )							,					(
        _snake_case
    )							,					(
        _snake_case
    )							,					(
        _snake_case
    )							,					(
        _snake_case
    )							,					(
        _snake_case
    )							,					(
        _snake_case
    )							,					(
        _snake_case
    )							,					
    )   :				Optional[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 UpperCamelCase_ (      self      :					List[Any]							):


    '''simple docstring'''





    (
        (
        _snake_case
    )							,					(
        _snake_case
    )							,					(
        _snake_case
    )							,					(
        _snake_case
    )							,					(
        _snake_case
    )							,					(
        _snake_case
    )							,					(
        _snake_case
    )							,					(
        _snake_case
    )							,					
    )   :				List[str]														=	self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_token_classification(
        UpperCamelCase      ,				UpperCamelCase      ,				UpperCamelCase      ,				UpperCamelCase      ,				UpperCamelCase      ,				UpperCamelCase      ,				UpperCamelCase							)







  def UpperCamelCase_ (      self      :					Optional[int]							):


    '''simple docstring'''





    (
        (
        _snake_case
    )							,					(
        _snake_case
    )							,					(
        _snake_case
    )							,					(
        _snake_case
    )							,					(
        _snake_case
    )							,					(
        _snake_case
    )							,					(
        _snake_case
    )							,					(
        _snake_case
    )							,					
    )   :				Optional[Any]														=	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 UpperCamelCase_ (      self      :					Tuple							):


    '''simple docstring'''





    for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
      _snake_case   :				Union[str, Any]														=	TFLayoutLMvaModel.from_pretrained(UpperCamelCase							)
      self.assertIsNotNone(UpperCamelCase							)




def     lowerCamelCase_	(      )->		int:
  _snake_case   :				Optional[int]														=	Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
  return image







@require_tf
class        _lowerCAmelCase    (			unittest.TestCase							):


  '''simple docstring'''







  @cached_property
  def UpperCamelCase_ (      self      :					List[str]							):


    '''simple docstring'''





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







  @slow
  def UpperCamelCase_ (      self      :					List[Any]							):


    '''simple docstring'''





    _snake_case   :				List[str]														=	TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base'							)

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

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

    # forward pass
    _snake_case   :				str														=	model(input_ids=UpperCamelCase      ,				bbox=UpperCamelCase      ,				pixel_values=UpperCamelCase      ,				training=UpperCamelCase							)

    # verify the logits
    _snake_case   :				List[Any]														=	(1, 1_99, 7_68)
    self.assertEqual(outputs.last_hidden_state.shape      ,				UpperCamelCase							)

    _snake_case   :				List[Any]														=	tf.constant(
        [[-0.05_29, 0.36_18, 0.16_32], [-0.15_87, -0.16_67, -0.04_00], [-0.15_57, -0.16_71, -0.05_05]]							)

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











# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import os

from accelerate.utils import ComputeEnvironment

from .cluster import get_cluster_input
from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file  # noqa: F401
from .config_utils import _ask_field, _ask_options, _convert_compute_environment  # noqa: F401
from .sagemaker import get_sagemaker_input


lowerCAmelCase_						   =    """Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine"""


def     lowerCamelCase_	(      )->		Tuple:
  _snake_case   :				int														=	_ask_options(
      'In which compute environment are you running?'    ,							['This machine', 'AWS (Amazon SageMaker)']    ,							_convert_compute_environment    ,							)
  if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
    _snake_case   :				int														=	get_sagemaker_input()
  else:
    _snake_case   :				Any														=	get_cluster_input()
  return config


def     lowerCamelCase_	(      lowerCAmelCase:	str=None				)->		Any:
  if subparsers is not None:
    _snake_case   :				List[Any]														=	subparsers.add_parser('config'    ,							description=lowerCAmelCase				)
  else:
    _snake_case   :				Dict														=	argparse.ArgumentParser('Accelerate config command'    ,							description=lowerCAmelCase				)

  parser.add_argument(
      '--config_file'    ,							default=lowerCAmelCase    ,							help=(
          'The path to use to store the config file. Will default to a file named default_config.yaml in the cache '
          'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have '
          'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed '
          'with \'huggingface\'.'
      )    ,							)

  if subparsers is not None:
    parser.set_defaults(func=lowerCAmelCase				)
  return parser


def     lowerCamelCase_	(      lowerCAmelCase:	Any				)->		Any:
  _snake_case   :				Dict														=	get_user_input()
  if args.config_file is not None:
    _snake_case   :				List[str]														=	args.config_file
  else:
    if not os.path.isdir(lowerCAmelCase				):
      os.makedirs(lowerCAmelCase				)
    _snake_case   :				Union[str, Any]														=	default_yaml_config_file

  if config_file.endswith('.json'				):
    config.to_json_file(lowerCAmelCase				)
  else:
    config.to_yaml_file(lowerCAmelCase				)
  print(F"""accelerate configuration saved at {config_file}"""				)


def     lowerCamelCase_	(      )->		Dict:
  _snake_case   :				List[str]														=	config_command_parser()
  _snake_case   :				str														=	parser.parse_args()
  config_command(lowerCAmelCase				)


if __name__ == "__main__":
      main()




