






from __future__ import annotations

import unittest

from transformers import DebertaConfig, 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 import (
		    TFDebertaForMaskedLM,
		    TFDebertaForQuestionAnswering,
		    TFDebertaForSequenceClassification,
		    TFDebertaForTokenClassification,
		    TFDebertaModel,
		)





class __lowerCamelCase				:





	"""simple docstring"""






	def __init__(							self ,					UpperCAmelCase ,					UpperCAmelCase=13 ,					UpperCAmelCase=7 ,					UpperCAmelCase=True ,					UpperCAmelCase=True ,					UpperCAmelCase=True ,					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.02 ,					UpperCAmelCase=3 ,					UpperCAmelCase=4 ,					UpperCAmelCase=None ,					):
							"""simple docstring"""







							_UpperCAmelCase             =    parent
							_UpperCAmelCase             =    13
							_UpperCAmelCase             =    7
							_UpperCAmelCase             =    True
							_UpperCAmelCase             =    True
							_UpperCAmelCase             =    True
							_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             =    False
							_UpperCAmelCase             =    -1
							_UpperCAmelCase             =    True
							_UpperCAmelCase             =    2
							_UpperCAmelCase             =    0.02
							_UpperCAmelCase             =    3
							_UpperCAmelCase             =    4
							_UpperCAmelCase             =    None

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_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
							if self.use_token_type_ids:
													_UpperCAmelCase             =    ids_tensor([self.batch_size, self.seq_length] ,					self.type_vocab_size					)

							_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             =    DebertaConfig(
							    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 ,					relative_attention=self.relative_attention ,					max_relative_positions=self.max_relative_positions ,					position_biased_input=self.position_biased_input ,					initializer_range=self.initializer_range ,					return_dict=UpperCAmelCase ,					)

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

	def  UpperCamelCase					(							self ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase					):
							"""simple docstring"""







							_UpperCAmelCase             =    TFDebertaModel(config=UpperCAmelCase					)
							_UpperCAmelCase             =    {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}

							_UpperCAmelCase             =    [input_ids, input_mask]
							_UpperCAmelCase             =    model(UpperCAmelCase					)

							_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 ,					UpperCAmelCase					):
							"""simple docstring"""







							_UpperCAmelCase             =    TFDebertaForMaskedLM(config=UpperCAmelCase					)
							_UpperCAmelCase             =    {
							    'input_ids': input_ids,
							    'attention_mask': input_mask,
							    'token_type_ids': token_type_ids,
							}
							_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 ,					UpperCAmelCase					):
							"""simple docstring"""







							_UpperCAmelCase             =    self.num_labels
							_UpperCAmelCase             =    TFDebertaForSequenceClassification(config=UpperCAmelCase					)
							_UpperCAmelCase             =    {
							    'input_ids': input_ids,
							    'attention_mask': input_mask,
							    'token_type_ids': token_type_ids,
							}

							_UpperCAmelCase             =    model(UpperCAmelCase					)
							self.parent.assertEqual(result.logits.shape ,					(self.batch_size, self.num_labels)					)

	def  UpperCamelCase					(							self ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase					):
							"""simple docstring"""







							_UpperCAmelCase             =    self.num_labels
							_UpperCAmelCase             =    TFDebertaForTokenClassification(config=UpperCAmelCase					)
							_UpperCAmelCase             =    {
							    'input_ids': input_ids,
							    'attention_mask': input_mask,
							    'token_type_ids': token_type_ids,
							}
							_UpperCAmelCase             =    model(UpperCAmelCase					)
							self.parent.assertEqual(result.logits.shape ,					(self.batch_size, self.seq_length, self.num_labels)					)

	def  UpperCamelCase					(							self ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase					):
							"""simple docstring"""







							_UpperCAmelCase             =    TFDebertaForQuestionAnswering(config=UpperCAmelCase					)
							_UpperCAmelCase             =    {
							    'input_ids': input_ids,
							    'attention_mask': input_mask,
							    'token_type_ids': token_type_ids,
							}

							_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					):
							"""simple docstring"""







							_UpperCAmelCase             =    self.prepare_config_and_inputs()
							(
							    (
							    _UpperCAmelCase
							)      ,				(
							    _UpperCAmelCase
							)      ,				(
							    _UpperCAmelCase
							)      ,				(
							    _UpperCAmelCase
							)      ,				(
							    _UpperCAmelCase
							)      ,				(
							    _UpperCAmelCase
							)      ,				(
							    _UpperCAmelCase
							)      ,				
							)             =    config_and_inputs
							_UpperCAmelCase             =    {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
							return config, inputs_dict





@require_tf
class __lowerCamelCase				(   snake_case__  , snake_case__  , unittest.TestCase):





	"""simple docstring"""






	UpperCamelCase__			=   (
	    (
	        TFDebertaModel,
	        TFDebertaForMaskedLM,
	        TFDebertaForQuestionAnswering,
	        TFDebertaForSequenceClassification,
	        TFDebertaForTokenClassification,
	    )
	    if is_tf_available()
	    else ()
	)
	UpperCamelCase__			=   (
	    {
	        "feature-extraction": TFDebertaModel,
	        "fill-mask": TFDebertaForMaskedLM,
	        "question-answering": TFDebertaForQuestionAnswering,
	        "text-classification": TFDebertaForSequenceClassification,
	        "token-classification": TFDebertaForTokenClassification,
	        "zero-shot": TFDebertaForSequenceClassification,
	    }
	    if is_tf_available()
	    else {}
	)

	UpperCamelCase__			=   False
	UpperCamelCase__			=   False

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    TFDebertaModelTester(self					)
							_UpperCAmelCase             =    ConfigTester(self ,					config_class=UpperCAmelCase ,					hidden_size=37					)

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							self.config_tester.run_common_tests()

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*UpperCAmelCase					)

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase					)

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase					)

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase					)

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase					)

	@slow
	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    TFDebertaModel.from_pretrained('kamalkraj/deberta-base'					)
							self.assertIsNotNone(UpperCAmelCase					)





@require_tf
class __lowerCamelCase				(   unittest.TestCase):





	"""simple docstring"""






	@unittest.skip(reason='Model not available yet'					)
	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							pass

	@slow
	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    TFDebertaModel.from_pretrained('kamalkraj/deberta-base'					)
							_UpperCAmelCase             =    tf.constant([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]]					)
							_UpperCAmelCase             =    tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]					)
							_UpperCAmelCase             =    model(UpperCAmelCase ,					attention_mask=UpperCAmelCase					)[0]

							_UpperCAmelCase             =    tf.constant(
							    [
							        [
							            [-0.59_85_58_96, -0.80_55_25_66, -0.8_46_21_35],
							            [1.4_48_40_25, -0.93_48_37_94, -0.80_59_30_85],
							            [0.3_12_27_41, 0.00_31_60_59, -1.4_13_13_77],
							        ]
							    ]					)
							tf.debugging.assert_near(output[:, 1:4, 1:4] ,					UpperCAmelCase ,					atol=1e-4					)








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

from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import TensorType, is_torch_available, logging


_a   			=						logging.get_logger(__name__)

_a   			=						{
    '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/config.json''',
    # See all M2M100 models at https://huggingface.co/models?filter=m2m_100
}





class __lowerCamelCase				(   snake_case__):





	"""simple docstring"""






	UpperCamelCase__			=   "m2m_100"
	UpperCamelCase__			=   ["past_key_values"]
	UpperCamelCase__			=   {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}

	def __init__(							self ,					UpperCAmelCase=12_8112 ,					UpperCAmelCase=1024 ,					UpperCAmelCase=12 ,					UpperCAmelCase=4096 ,					UpperCAmelCase=16 ,					UpperCAmelCase=12 ,					UpperCAmelCase=4096 ,					UpperCAmelCase=16 ,					UpperCAmelCase=0.05 ,					UpperCAmelCase=0.05 ,					UpperCAmelCase=True ,					UpperCAmelCase=True ,					UpperCAmelCase="relu" ,					UpperCAmelCase=1024 ,					UpperCAmelCase=0.1 ,					UpperCAmelCase=0.1 ,					UpperCAmelCase=0.0 ,					UpperCAmelCase=0.02 ,					UpperCAmelCase=2 ,					UpperCAmelCase=True ,					UpperCAmelCase=1 ,					UpperCAmelCase=0 ,					UpperCAmelCase=2 ,					**UpperCAmelCase ,					):
							"""simple docstring"""







							_UpperCAmelCase             =    vocab_size
							_UpperCAmelCase             =    max_position_embeddings
							_UpperCAmelCase             =    d_model
							_UpperCAmelCase             =    encoder_ffn_dim
							_UpperCAmelCase             =    encoder_layers
							_UpperCAmelCase             =    encoder_attention_heads
							_UpperCAmelCase             =    decoder_ffn_dim
							_UpperCAmelCase             =    decoder_layers
							_UpperCAmelCase             =    decoder_attention_heads
							_UpperCAmelCase             =    dropout
							_UpperCAmelCase             =    attention_dropout
							_UpperCAmelCase             =    activation_dropout
							_UpperCAmelCase             =    activation_function
							_UpperCAmelCase             =    init_std
							_UpperCAmelCase             =    encoder_layerdrop
							_UpperCAmelCase             =    decoder_layerdrop
							_UpperCAmelCase             =    use_cache
							_UpperCAmelCase             =    encoder_layers
							_UpperCAmelCase             =    scale_embedding  # scale factor will be sqrt(d_model) if True

							super().__init__(
							    pad_token_id=UpperCAmelCase ,					bos_token_id=UpperCAmelCase ,					eos_token_id=UpperCAmelCase ,					is_encoder_decoder=UpperCAmelCase ,					decoder_start_token_id=UpperCAmelCase ,					**UpperCAmelCase ,					)





class __lowerCamelCase				(   snake_case__):





	"""simple docstring"""






	@property
	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    OrderedDict(
							    [
							        ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
							        ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
							    ]					)

							if self.use_past:
													_UpperCAmelCase             =    {0: 'batch'}
													_UpperCAmelCase             =    {0: 'batch', 1: 'past_decoder_sequence + sequence'}
							else:
													_UpperCAmelCase             =    {0: 'batch', 1: 'decoder_sequence'}
													_UpperCAmelCase             =    {0: 'batch', 1: 'decoder_sequence'}

							if self.use_past:
													self.fill_with_past_key_values_(UpperCAmelCase ,					direction='inputs'					)
							return common_inputs

	def  UpperCamelCase					(							self ,					UpperCAmelCase ,					UpperCAmelCase = -1 ,					UpperCAmelCase = -1 ,					UpperCAmelCase = False ,					UpperCAmelCase = None ,					):
							"""simple docstring"""







							_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             =    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([tokenizer.unk_token]					) * seq_length] * batch_size
							_UpperCAmelCase             =    dict(tokenizer(UpperCAmelCase ,					return_tensors=UpperCAmelCase					)					)
							return common_inputs

	def  UpperCamelCase					(							self ,					UpperCAmelCase ,					UpperCAmelCase = -1 ,					UpperCAmelCase = -1 ,					UpperCAmelCase = False ,					UpperCAmelCase = None ,					):
							"""simple docstring"""







							_UpperCAmelCase             =    self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
							    UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase					)

							# Generate decoder inputs
							_UpperCAmelCase             =    seq_length if not self.use_past else 1
							_UpperCAmelCase             =    self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
							    UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase					)
							_UpperCAmelCase             =    {F"""decoder_{name}""": tensor for name, tensor in decoder_inputs.items()}
							_UpperCAmelCase             =    dict(**UpperCAmelCase ,					**UpperCAmelCase					)

							if self.use_past:
													if not is_torch_available():
																			raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'					)
													else:
																			import torch
													_UpperCAmelCase      ,				_UpperCAmelCase             =    common_inputs['input_ids'].shape
													_UpperCAmelCase             =    common_inputs['decoder_input_ids'].shape[1]
													_UpperCAmelCase      ,				_UpperCAmelCase             =    self.num_attention_heads
													_UpperCAmelCase             =    (
													    batch,
													    num_encoder_attention_heads,
													    encoder_seq_length,
													    self._config.hidden_size // num_encoder_attention_heads,
													)
													_UpperCAmelCase             =    decoder_seq_length + 3
													_UpperCAmelCase             =    (
													    batch,
													    num_decoder_attention_heads,
													    decoder_past_length,
													    self._config.hidden_size // num_decoder_attention_heads,
													)

													_UpperCAmelCase             =    torch.cat(
													    [common_inputs['decoder_attention_mask'], torch.ones(UpperCAmelCase ,					UpperCAmelCase					)] ,					dim=1					)

													_UpperCAmelCase             =    []
													# If the number of encoder and decoder layers are present in the model configuration, both are considered
													_UpperCAmelCase      ,				_UpperCAmelCase             =    self.num_layers
													_UpperCAmelCase             =    min(UpperCAmelCase ,					UpperCAmelCase					)
													_UpperCAmelCase             =    max(UpperCAmelCase ,					UpperCAmelCase					) - min_num_layers
													_UpperCAmelCase             =    'encoder' if num_encoder_layers > num_decoder_layers else 'decoder'

													for _ in range(UpperCAmelCase					):
																			common_inputs["past_key_values"].append(
																			    (
																			        torch.zeros(UpperCAmelCase					),
																			        torch.zeros(UpperCAmelCase					),
																			        torch.zeros(UpperCAmelCase					),
																			        torch.zeros(UpperCAmelCase					),
																			    )					)
													# TODO: test this.
													_UpperCAmelCase             =    encoder_shape if remaining_side_name == 'encoder' else decoder_shape
													for _ in range(UpperCAmelCase ,					UpperCAmelCase					):
																			common_inputs["past_key_values"].append((torch.zeros(UpperCAmelCase					), torch.zeros(UpperCAmelCase					))					)
							return common_inputs

	UpperCamelCase__			=   _generate_dummy_inputs_for_default_and_seqaseq_lm
