






from __future__ import annotations

import unittest

from transformers import DistilBertConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

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


if is_tf_available():
 import tensorflow as tf

 from transformers.models.distilbert.modeling_tf_distilbert import (
     TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
     TFDistilBertForMaskedLM,
     TFDistilBertForMultipleChoice,
     TFDistilBertForQuestionAnswering,
     TFDistilBertForSequenceClassification,
     TFDistilBertForTokenClassification,
     TFDistilBertModel,
 )


class 						_a       :






  """simple docstring"""





  def __init__(     self		,		_UpperCAmelCase		,		)			-> Union[str, Any]:
     UpperCamelCase_									=     parent
     UpperCamelCase_									=     13
     UpperCamelCase_									=     7
     UpperCamelCase_									=     True
     UpperCamelCase_									=     True
     UpperCamelCase_									=     False
     UpperCamelCase_									=     True
     UpperCamelCase_									=     99
     UpperCamelCase_									=     32
     UpperCamelCase_									=     2
     UpperCamelCase_									=     4
     UpperCamelCase_									=     37
     UpperCamelCase_									=     'gelu'
     UpperCamelCase_									=     0.1
     UpperCamelCase_									=     0.1
     UpperCamelCase_									=     512
     UpperCamelCase_									=     16
     UpperCamelCase_									=     2
     UpperCamelCase_									=     0.0_2
     UpperCamelCase_									=     3
     UpperCamelCase_									=     4
     UpperCamelCase_									=     None




  def    _UpperCAmelCase     (     self )			-> List[str]:
     UpperCamelCase_									=     ids_tensor([self.batch_size, self.seq_length]		,		self.vocab_size )

     UpperCamelCase_									=     None
     if self.use_input_mask:
        UpperCamelCase_									=     random_attention_mask([self.batch_size, self.seq_length] )

     UpperCamelCase_									=     None
     UpperCamelCase_									=     None
     UpperCamelCase_									=     None
     if self.use_labels:
        UpperCamelCase_									=     ids_tensor([self.batch_size]		,		self.type_sequence_label_size )
        UpperCamelCase_									=     ids_tensor([self.batch_size, self.seq_length]		,		self.num_labels )
        UpperCamelCase_									=     ids_tensor([self.batch_size]		,		self.num_choices )

     UpperCamelCase_									=     DistilBertConfig(
         vocab_size=self.vocab_size		,		dim=self.hidden_size		,		n_layers=self.num_hidden_layers		,		n_heads=self.num_attention_heads		,		hidden_dim=self.intermediate_size		,		hidden_act=self.hidden_act		,		dropout=self.hidden_dropout_prob		,		attention_dropout=self.attention_probs_dropout_prob		,		max_position_embeddings=self.max_position_embeddings		,		initializer_range=self.initializer_range		,		)

     return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> List[str]:
     UpperCamelCase_									=     TFDistilBertModel(config=_UpperCAmelCase )
     UpperCamelCase_									=     {'input_ids': input_ids, 'attention_mask': input_mask}

     UpperCamelCase_									=     model(_UpperCAmelCase )

     UpperCamelCase_									=     [input_ids, input_mask]

     UpperCamelCase_									=     model(_UpperCAmelCase )

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




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Any:
     UpperCamelCase_									=     TFDistilBertForMaskedLM(config=_UpperCAmelCase )
     UpperCamelCase_									=     {'input_ids': input_ids, 'attention_mask': input_mask}
     UpperCamelCase_									=     model(_UpperCAmelCase )
     self.parent.assertEqual(result.logits.shape		,		(self.batch_size, self.seq_length, self.vocab_size) )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Dict:
     UpperCamelCase_									=     TFDistilBertForQuestionAnswering(config=_UpperCAmelCase )
     UpperCamelCase_									=     {
         'input_ids': input_ids,
         'attention_mask': input_mask,
     }
     UpperCamelCase_									=     model(_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		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Optional[int]:
     UpperCamelCase_									=     self.num_labels
     UpperCamelCase_									=     TFDistilBertForSequenceClassification(_UpperCAmelCase )
     UpperCamelCase_									=     {'input_ids': input_ids, 'attention_mask': input_mask}
     UpperCamelCase_									=     model(_UpperCAmelCase )
     self.parent.assertEqual(result.logits.shape		,		(self.batch_size, self.num_labels) )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Union[str, Any]:
     UpperCamelCase_									=     self.num_choices
     UpperCamelCase_									=     TFDistilBertForMultipleChoice(_UpperCAmelCase )
     UpperCamelCase_									=     tf.tile(tf.expand_dims(_UpperCAmelCase		,		1 )		,		(1, self.num_choices, 1) )
     UpperCamelCase_									=     tf.tile(tf.expand_dims(_UpperCAmelCase		,		1 )		,		(1, self.num_choices, 1) )
     UpperCamelCase_									=     {
         'input_ids': multiple_choice_inputs_ids,
         'attention_mask': multiple_choice_input_mask,
     }
     UpperCamelCase_									=     model(_UpperCAmelCase )
     self.parent.assertEqual(result.logits.shape		,		(self.batch_size, self.num_choices) )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Optional[int]:
     UpperCamelCase_									=     self.num_labels
     UpperCamelCase_									=     TFDistilBertForTokenClassification(_UpperCAmelCase )
     UpperCamelCase_									=     {'input_ids': input_ids, 'attention_mask': input_mask}
     UpperCamelCase_									=     model(_UpperCAmelCase )
     self.parent.assertEqual(result.logits.shape		,		(self.batch_size, self.seq_length, self.num_labels) )




  def    _UpperCAmelCase     (     self )			-> Any:
     UpperCamelCase_									=     self.prepare_config_and_inputs()
     ((UpperCamelCase_)		,      (UpperCamelCase_)		,      (UpperCamelCase_)		,      (UpperCamelCase_)		,      (UpperCamelCase_)		,      (UpperCamelCase_))									=     config_and_inputs
     UpperCamelCase_									=     {'input_ids': input_ids, 'attention_mask': input_mask}
     return config, inputs_dict




@require_tf
class 						_a       (  UpperCAmelCase__						,       UpperCAmelCase__						,       unittest.TestCase    ):






  """simple docstring"""





  A_						=   (
      (
          TFDistilBertModel,
          TFDistilBertForMaskedLM,
          TFDistilBertForQuestionAnswering,
          TFDistilBertForSequenceClassification,
          TFDistilBertForTokenClassification,
          TFDistilBertForMultipleChoice,
      )
      if is_tf_available()
      else None
  )
  A_						=   (
      {
          """feature-extraction""": TFDistilBertModel,
          """fill-mask""": TFDistilBertForMaskedLM,
          """question-answering""": TFDistilBertForQuestionAnswering,
          """text-classification""": TFDistilBertForSequenceClassification,
          """token-classification""": TFDistilBertForTokenClassification,
          """zero-shot""": TFDistilBertForSequenceClassification,
      }
      if is_tf_available()
      else {}
  )
  A_						=   False
  A_						=   False




  def    _UpperCAmelCase     (     self )			-> Optional[Any]:
     UpperCamelCase_									=     TFDistilBertModelTester(self )
     UpperCamelCase_									=     ConfigTester(self		,		config_class=_UpperCAmelCase		,		dim=37 )




  def    _UpperCAmelCase     (     self )			-> int:
     self.config_tester.run_common_tests()




  def    _UpperCAmelCase     (     self )			-> Dict:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_distilbert_model(*_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> Tuple:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_distilbert_for_masked_lm(*_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> Union[str, Any]:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_distilbert_for_question_answering(*_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> List[Any]:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_distilbert_for_sequence_classification(*_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> Union[str, Any]:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_distilbert_for_multiple_choice(*_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> List[str]:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_distilbert_for_token_classification(*_UpperCAmelCase )




  @slow
  def    _UpperCAmelCase     (     self )			-> Union[str, Any]:
     for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1] ):
        UpperCamelCase_									=     TFDistilBertModel.from_pretrained(_UpperCAmelCase )
        self.assertIsNotNone(_UpperCAmelCase )




@require_tf
class 						_a       (  unittest.TestCase    ):






  """simple docstring"""





  @slow
  def    _UpperCAmelCase     (     self )			-> str:
     UpperCamelCase_									=     TFDistilBertModel.from_pretrained('distilbert-base-uncased' )
     UpperCamelCase_									=     tf.constant([[0, 1, 2, 3, 4, 5]] )
     UpperCamelCase_									=     model(_UpperCAmelCase )[0]

     UpperCamelCase_									=     [1, 6, 768]
     self.assertEqual(output.shape		,		_UpperCAmelCase )

     UpperCamelCase_									=     tf.constant(
         [
             [
                 [0.1_9_2_6_1_8_8_5, -0.1_3_7_3_2_9_5_5, 0.4_1_1_9_7_9_9],
                 [0.2_2_1_5_0_1_5_6, -0.0_7_4_2_2_6_6_1, 0.3_9_0_3_7_2_0_4],
                 [0.2_2_7_5_6_0_1_8, -0.0_8_9_6_4_1_4, 0.3_7_0_1_4_6_7],
             ]
         ] )
     tf.debugging.assert_near(output[:, :3, :3]		,		_UpperCAmelCase		,		atol=1e-4 )













from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import logging


if TYPE_CHECKING:
 from ...processing_utils import ProcessorMixin
 from ...utils import TensorType


snake_case__      :	Tuple       	=      logging.get_logger(__name__)

snake_case__      :	str       	=      {
    """microsoft/layoutlmv3-base""": """https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json""",
}


class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  A_						=   """layoutlmv3"""




  def __init__(     self		,		_UpperCAmelCase=50265		,		_UpperCAmelCase=768		,		_UpperCAmelCase=12		,		_UpperCAmelCase=12		,		_UpperCAmelCase=3072		,		_UpperCAmelCase="gelu"		,		_UpperCAmelCase=0.1		,		_UpperCAmelCase=0.1		,		_UpperCAmelCase=512		,		_UpperCAmelCase=2		,		_UpperCAmelCase=0.0_2		,		_UpperCAmelCase=1e-5		,		_UpperCAmelCase=1		,		_UpperCAmelCase=0		,		_UpperCAmelCase=2		,		_UpperCAmelCase=1024		,		_UpperCAmelCase=128		,		_UpperCAmelCase=128		,		_UpperCAmelCase=True		,		_UpperCAmelCase=32		,		_UpperCAmelCase=128		,		_UpperCAmelCase=64		,		_UpperCAmelCase=256		,		_UpperCAmelCase=True		,		_UpperCAmelCase=True		,		_UpperCAmelCase=True		,		_UpperCAmelCase=224		,		_UpperCAmelCase=3		,		_UpperCAmelCase=16		,		_UpperCAmelCase=None		,		**_UpperCAmelCase		,		)			-> Tuple:
     super().__init__(
         vocab_size=_UpperCAmelCase		,		hidden_size=_UpperCAmelCase		,		num_hidden_layers=_UpperCAmelCase		,		num_attention_heads=_UpperCAmelCase		,		intermediate_size=_UpperCAmelCase		,		hidden_act=_UpperCAmelCase		,		hidden_dropout_prob=_UpperCAmelCase		,		attention_probs_dropout_prob=_UpperCAmelCase		,		max_position_embeddings=_UpperCAmelCase		,		type_vocab_size=_UpperCAmelCase		,		initializer_range=_UpperCAmelCase		,		layer_norm_eps=_UpperCAmelCase		,		pad_token_id=_UpperCAmelCase		,		bos_token_id=_UpperCAmelCase		,		eos_token_id=_UpperCAmelCase		,		**_UpperCAmelCase		,		)
     UpperCamelCase_									=     max_ad_position_embeddings
     UpperCamelCase_									=     coordinate_size
     UpperCamelCase_									=     shape_size
     UpperCamelCase_									=     has_relative_attention_bias
     UpperCamelCase_									=     rel_pos_bins
     UpperCamelCase_									=     max_rel_pos
     UpperCamelCase_									=     has_spatial_attention_bias
     UpperCamelCase_									=     rel_ad_pos_bins
     UpperCamelCase_									=     max_rel_ad_pos
     UpperCamelCase_									=     text_embed
     UpperCamelCase_									=     visual_embed
     UpperCamelCase_									=     input_size
     UpperCamelCase_									=     num_channels
     UpperCamelCase_									=     patch_size
     UpperCamelCase_									=     classifier_dropout




class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  A_						=   version.parse("""1.12"""    )




  @property
  def    _UpperCAmelCase     (     self )			-> Mapping[str, Mapping[int, str]]:
     # The order of inputs is different for question answering and sequence classification
     if self.task in ["question-answering", "sequence-classification"]:
        return OrderedDict(
            [
                ('input_ids', {0: 'batch', 1: 'sequence'}),
                ('attention_mask', {0: 'batch', 1: 'sequence'}),
                ('bbox', {0: 'batch', 1: 'sequence'}),
                ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
            ] )
     else:
        return OrderedDict(
            [
                ('input_ids', {0: 'batch', 1: 'sequence'}),
                ('bbox', {0: 'batch', 1: 'sequence'}),
                ('attention_mask', {0: 'batch', 1: 'sequence'}),
                ('pixel_values', {0: 'batch', 1: 'num_channels'}),
            ] )




  @property
  def    _UpperCAmelCase     (     self )			-> float:
     return 1e-5




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




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase = -1		,		_UpperCAmelCase = -1		,		_UpperCAmelCase = False		,		_UpperCAmelCase = None		,		_UpperCAmelCase = 3		,		_UpperCAmelCase = 40		,		_UpperCAmelCase = 40		,		)			-> Mapping[str, Any]:
     setattr(processor.image_processor		,		'apply_ocr'		,		_UpperCAmelCase )

     # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
     UpperCamelCase_									=     compute_effective_axis_dimension(
         _UpperCAmelCase		,		fixed_dimension=OnnxConfig.default_fixed_batch		,		num_token_to_add=0 )
     # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
     UpperCamelCase_									=     processor.tokenizer.num_special_tokens_to_add(_UpperCAmelCase )
     UpperCamelCase_									=     compute_effective_axis_dimension(
         _UpperCAmelCase		,		fixed_dimension=OnnxConfig.default_fixed_sequence		,		num_token_to_add=_UpperCAmelCase )
     # Generate dummy inputs according to compute batch and sequence
     UpperCamelCase_									=     [[' '.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size

     # Generate dummy bounding boxes
     UpperCamelCase_									=     [[[48, 84, 73, 128]]] * batch_size

     # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
     # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch)
     UpperCamelCase_									=     self._generate_dummy_images(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )

     UpperCamelCase_									=     dict(
         processor(
             _UpperCAmelCase		,		text=_UpperCAmelCase		,		boxes=_UpperCAmelCase		,		return_tensors=_UpperCAmelCase		,		) )

     return inputs





