




from __future__ import annotations

import unittest

from transformers import DebertaVaConfig, 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 (
		    TFDebertaVaForMaskedLM,
		    TFDebertaVaForQuestionAnswering,
		    TFDebertaVaForSequenceClassification,
		    TFDebertaVaForTokenClassification,
		    TFDebertaVaModel,
		)




class 			UpperCAmelCase_      :




							'''simple docstring'''



							def __init__(					self       :	str       ,     a       :	Tuple       ,     a       :	Any=13       ,     a       :	List[str]=7       ,     a       :	List[str]=True       ,     a       :	str=True       ,     a       :	str=True       ,     a       :	Tuple=True       ,     a       :	Dict=99       ,     a       :	Optional[Any]=32       ,     a       :	List[str]=2       ,     a       :	Any=4       ,     a       :	str=37       ,     a       :	str="gelu"       ,     a       :	Tuple=0.1       ,     a       :	Optional[int]=0.1       ,     a       :	Any=512       ,     a       :	Optional[int]=16       ,     a       :	List[str]=2       ,     a       :	List[Any]=0.02       ,     a       :	List[Any]=False       ,     a       :	List[Any]=True       ,     a       :	List[Any]="None"       ,     a       :	int=3       ,     a       :	List[Any]=4       ,     a       :	List[str]=None       ,     )			->					Optional[Any]:
										SCREAMING_SNAKE_CASE           =					parent
										SCREAMING_SNAKE_CASE           =					batch_size
										SCREAMING_SNAKE_CASE           =					seq_length
										SCREAMING_SNAKE_CASE           =					is_training
										SCREAMING_SNAKE_CASE           =					use_input_mask
										SCREAMING_SNAKE_CASE           =					use_token_type_ids
										SCREAMING_SNAKE_CASE           =					use_labels
										SCREAMING_SNAKE_CASE           =					vocab_size
										SCREAMING_SNAKE_CASE           =					hidden_size
										SCREAMING_SNAKE_CASE           =					num_hidden_layers
										SCREAMING_SNAKE_CASE           =					num_attention_heads
										SCREAMING_SNAKE_CASE           =					intermediate_size
										SCREAMING_SNAKE_CASE           =					hidden_act
										SCREAMING_SNAKE_CASE           =					hidden_dropout_prob
										SCREAMING_SNAKE_CASE           =					attention_probs_dropout_prob
										SCREAMING_SNAKE_CASE           =					max_position_embeddings
										SCREAMING_SNAKE_CASE           =					type_vocab_size
										SCREAMING_SNAKE_CASE           =					type_sequence_label_size
										SCREAMING_SNAKE_CASE           =					initializer_range
										SCREAMING_SNAKE_CASE           =					num_labels
										SCREAMING_SNAKE_CASE           =					num_choices
										SCREAMING_SNAKE_CASE           =					relative_attention
										SCREAMING_SNAKE_CASE           =					position_biased_input
										SCREAMING_SNAKE_CASE           =					pos_att_type
										SCREAMING_SNAKE_CASE           =					scope





							def    _UpperCAmelCase     (					self       :	Any			)			->					int:
										SCREAMING_SNAKE_CASE           =					ids_tensor([self.batch_size, self.seq_length]       ,     self.vocab_size			)

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

										SCREAMING_SNAKE_CASE           =					None
										if self.use_token_type_ids:
													SCREAMING_SNAKE_CASE           =					ids_tensor([self.batch_size, self.seq_length]       ,     self.type_vocab_size			)

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

										SCREAMING_SNAKE_CASE           =					DebertaVaConfig(
										    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       ,     position_biased_input=self.position_biased_input       ,     initializer_range=self.initializer_range       ,     return_dict=a       ,     )

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





							def    _UpperCAmelCase     (					self       :	str       ,     a       :	Optional[Any]       ,     a       :	int       ,     a       :	List[Any]       ,     a       :	List[Any]       ,     a       :	str       ,     a       :	Dict       ,     a       :	Dict			)			->					Tuple:
										SCREAMING_SNAKE_CASE           =					TFDebertaVaModel(config=a			)
										SCREAMING_SNAKE_CASE           =					{"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}

										SCREAMING_SNAKE_CASE           =					[input_ids, input_mask]
										SCREAMING_SNAKE_CASE           =					model(a			)

										SCREAMING_SNAKE_CASE           =					model(a			)

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





							def    _UpperCAmelCase     (					self       :	Any       ,     a       :	Optional[int]       ,     a       :	Union[str, Any]       ,     a       :	List[Any]       ,     a       :	Dict       ,     a       :	Dict       ,     a       :	Dict       ,     a       :	int			)			->					List[Any]:
										SCREAMING_SNAKE_CASE           =					TFDebertaVaForMaskedLM(config=a			)
										SCREAMING_SNAKE_CASE           =					{
										    """input_ids""": input_ids,
										    """attention_mask""": input_mask,
										    """token_type_ids""": token_type_ids,
										}
										SCREAMING_SNAKE_CASE           =					model(a			)
										self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.seq_length, self.vocab_size)			)





							def    _UpperCAmelCase     (					self       :	List[str]       ,     a       :	Dict       ,     a       :	Optional[Any]       ,     a       :	Optional[Any]       ,     a       :	Dict       ,     a       :	str       ,     a       :	List[Any]       ,     a       :	Union[str, Any]			)			->					Any:
										SCREAMING_SNAKE_CASE           =					self.num_labels
										SCREAMING_SNAKE_CASE           =					TFDebertaVaForSequenceClassification(config=a			)
										SCREAMING_SNAKE_CASE           =					{
										    """input_ids""": input_ids,
										    """attention_mask""": input_mask,
										    """token_type_ids""": token_type_ids,
										}

										SCREAMING_SNAKE_CASE           =					model(a			)
										self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.num_labels)			)





							def    _UpperCAmelCase     (					self       :	Tuple       ,     a       :	Dict       ,     a       :	Optional[int]       ,     a       :	Optional[int]       ,     a       :	Optional[Any]       ,     a       :	List[Any]       ,     a       :	Any       ,     a       :	List[Any]			)			->					Optional[int]:
										SCREAMING_SNAKE_CASE           =					self.num_labels
										SCREAMING_SNAKE_CASE           =					TFDebertaVaForTokenClassification(config=a			)
										SCREAMING_SNAKE_CASE           =					{
										    """input_ids""": input_ids,
										    """attention_mask""": input_mask,
										    """token_type_ids""": token_type_ids,
										}
										SCREAMING_SNAKE_CASE           =					model(a			)
										self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.seq_length, self.num_labels)			)





							def    _UpperCAmelCase     (					self       :	int       ,     a       :	str       ,     a       :	Any       ,     a       :	Dict       ,     a       :	Optional[int]       ,     a       :	Dict       ,     a       :	Any       ,     a       :	List[Any]			)			->					Optional[int]:
										SCREAMING_SNAKE_CASE           =					TFDebertaVaForQuestionAnswering(config=a			)
										SCREAMING_SNAKE_CASE           =					{
										    """input_ids""": input_ids,
										    """attention_mask""": input_mask,
										    """token_type_ids""": token_type_ids,
										}

										SCREAMING_SNAKE_CASE           =					model(a			)
										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       :	List[str]			)			->					Optional[Any]:
										SCREAMING_SNAKE_CASE           =					self.prepare_config_and_inputs()
										(
										    (
										    SCREAMING_SNAKE_CASE
										)     ,  (
										    SCREAMING_SNAKE_CASE
										)     ,  (
										    SCREAMING_SNAKE_CASE
										)     ,  (
										    SCREAMING_SNAKE_CASE
										)     ,  (
										    SCREAMING_SNAKE_CASE
										)     ,  (
										    SCREAMING_SNAKE_CASE
										)     ,  (
										    SCREAMING_SNAKE_CASE
										)     ,  
										)           =					config_and_inputs
										SCREAMING_SNAKE_CASE           =					{"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
										return config, inputs_dict





@require_tf
class 			UpperCAmelCase_      (   A		,      A		,      unittest.TestCase       ):




							'''simple docstring'''



							a__						  =     (
							    (
							        TFDebertaVaModel,
							        TFDebertaVaForMaskedLM,
							        TFDebertaVaForQuestionAnswering,
							        TFDebertaVaForSequenceClassification,
							        TFDebertaVaForTokenClassification,
							    )
							    if is_tf_available()
							    else ()
							)
							a__						  =     (
							    {
							        '''feature-extraction''': TFDebertaVaModel,
							        '''fill-mask''': TFDebertaVaForMaskedLM,
							        '''question-answering''': TFDebertaVaForQuestionAnswering,
							        '''text-classification''': TFDebertaVaForSequenceClassification,
							        '''token-classification''': TFDebertaVaForTokenClassification,
							        '''zero-shot''': TFDebertaVaForSequenceClassification,
							    }
							    if is_tf_available()
							    else {}
							)

							a__						  =     False
							a__						  =     False





							def    _UpperCAmelCase     (					self       :	Tuple			)			->					Optional[Any]:
										SCREAMING_SNAKE_CASE           =					TFDebertaVaModelTester(self			)
										SCREAMING_SNAKE_CASE           =					ConfigTester(self       ,     config_class=a       ,     hidden_size=37			)





							def    _UpperCAmelCase     (					self       :	List[str]			)			->					List[Any]:
										self.config_tester.run_common_tests()





							def    _UpperCAmelCase     (					self       :	Optional[Any]			)			->					List[Any]:
										SCREAMING_SNAKE_CASE           =					self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*a			)





							def    _UpperCAmelCase     (					self       :	Dict			)			->					Tuple:
										SCREAMING_SNAKE_CASE           =					self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_masked_lm(*a			)





							def    _UpperCAmelCase     (					self       :	Optional[int]			)			->					List[Any]:
										SCREAMING_SNAKE_CASE           =					self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_question_answering(*a			)





							def    _UpperCAmelCase     (					self       :	Optional[Any]			)			->					List[str]:
										SCREAMING_SNAKE_CASE           =					self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_sequence_classification(*a			)





							def    _UpperCAmelCase     (					self       :	int			)			->					List[str]:
										SCREAMING_SNAKE_CASE           =					self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_token_classification(*a			)







							@slow
							def    _UpperCAmelCase     (					self       :	Any			)			->					Dict:
										SCREAMING_SNAKE_CASE           =					TFDebertaVaModel.from_pretrained("""kamalkraj/deberta-v2-xlarge"""			)
										self.assertIsNotNone(a			)





@require_tf
class 			UpperCAmelCase_      (   unittest.TestCase       ):




							'''simple docstring'''



							@unittest.skip(reason="""Model not available yet"""			)
							def    _UpperCAmelCase     (					self       :	Optional[int]			)			->					Dict:
										pass







							@slow
							def    _UpperCAmelCase     (					self       :	Dict			)			->					Dict:
										SCREAMING_SNAKE_CASE           =					TFDebertaVaModel.from_pretrained("""kamalkraj/deberta-v2-xlarge"""			)
										SCREAMING_SNAKE_CASE           =					tf.constant([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]]			)
										SCREAMING_SNAKE_CASE           =					tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]			)
										SCREAMING_SNAKE_CASE           =					model(a       ,     attention_mask=a			)[0]

										SCREAMING_SNAKE_CASE           =					tf.constant(
										    [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]]			)
										tf.debugging.assert_near(output[:, 1:4, 1:4]       ,     a       ,     atol=1E-4			)












import os
from shutil import copyfile
from typing import List, Optional, Tuple

from tokenizers import processors

from ...tokenization_utils import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
		from .tokenization_mbart import MBartTokenizer
else:
		__A						:							Tuple							=  None


__A						:							Any							=  logging.get_logger(__name__)


__A						:							Union[str, Any]							=  {"""vocab_file""": """sentencepiece.bpe.model""", """tokenizer_file""": """tokenizer.json"""}

__A						:							List[Any]							=  {
    """vocab_file""": {
        """facebook/mbart-large-en-ro""": (
            """https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model"""
        ),
        """facebook/mbart-large-cc25""": (
            """https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model"""
        ),
    },
    """tokenizer_file""": {
        """facebook/mbart-large-en-ro""": """https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/tokenizer.json""",
        """facebook/mbart-large-cc25""": """https://huggingface.co/facebook/mbart-large-cc25/resolve/main/tokenizer.json""",
    },
}

__A						:							int							=  {
    """facebook/mbart-large-en-ro""": 1_0_2_4,
    """facebook/mbart-large-cc25""": 1_0_2_4,
}

# fmt: off
__A						:							List[Any]							=  ["""ar_AR""", """cs_CZ""", """de_DE""", """en_XX""", """es_XX""", """et_EE""", """fi_FI""", """fr_XX""", """gu_IN""", """hi_IN""", """it_IT""", """ja_XX""", """kk_KZ""", """ko_KR""", """lt_LT""", """lv_LV""", """my_MM""", """ne_NP""", """nl_XX""", """ro_RO""", """ru_RU""", """si_LK""", """tr_TR""", """vi_VN""", """zh_CN"""]




class 			UpperCAmelCase_      (   A       ):




							'''simple docstring'''



							a__						  =     VOCAB_FILES_NAMES
							a__						  =     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							a__						  =     PRETRAINED_VOCAB_FILES_MAP
							a__						  =     ['''input_ids''', '''attention_mask''']
							a__						  =     MBartTokenizer

							a__						  =     []
							a__						  =     []





							def __init__(					self       :	str       ,     a       :	List[Any]=None       ,     a       :	Optional[int]=None       ,     a       :	str="<s>"       ,     a       :	Tuple="</s>"       ,     a       :	Optional[int]="</s>"       ,     a       :	int="<s>"       ,     a       :	List[str]="<unk>"       ,     a       :	Tuple="<pad>"       ,     a       :	Dict="<mask>"       ,     a       :	Optional[Any]=None       ,     a       :	List[Any]=None       ,     a       :	Any=None       ,     **a       :	Optional[Any]       ,     )			->					Any:
										# Mask token behave like a normal word, i.e. include the space before it
										SCREAMING_SNAKE_CASE           =					AddedToken(a       ,     lstrip=a       ,     rstrip=a			) if isinstance(a       ,     a			) else mask_token

										super().__init__(
										    vocab_file=a       ,     tokenizer_file=a       ,     bos_token=a       ,     eos_token=a       ,     sep_token=a       ,     cls_token=a       ,     unk_token=a       ,     pad_token=a       ,     mask_token=a       ,     src_lang=a       ,     tgt_lang=a       ,     additional_special_tokens=a       ,     **a       ,     )

										SCREAMING_SNAKE_CASE           =					vocab_file
										SCREAMING_SNAKE_CASE           =					False if not self.vocab_file else True

										SCREAMING_SNAKE_CASE           =					FAIRSEQ_LANGUAGE_CODES.copy()

										if additional_special_tokens is not None:
													# Only add those special tokens if they are not already there.
													_additional_special_tokens.extend(
													    [t for t in additional_special_tokens if t not in _additional_special_tokens]			)

										self.add_special_tokens({"""additional_special_tokens""": _additional_special_tokens}			)
										SCREAMING_SNAKE_CASE           =					{
										    lang_code: self.convert_tokens_to_ids(a			) for lang_code in FAIRSEQ_LANGUAGE_CODES
										}

										SCREAMING_SNAKE_CASE           =					src_lang if src_lang is not None else """en_XX"""
										SCREAMING_SNAKE_CASE           =					self.convert_tokens_to_ids(self._src_lang			)
										SCREAMING_SNAKE_CASE           =					tgt_lang
										self.set_src_lang_special_tokens(self._src_lang			)





							@property
							def    _UpperCAmelCase     (					self       :	int			)			->					str:
										return self._src_lang





							@src_lang.setter
							def    _UpperCAmelCase     (					self       :	List[Any]       ,     a       :	str			)			->					None:
										SCREAMING_SNAKE_CASE           =					new_src_lang
										self.set_src_lang_special_tokens(self._src_lang			)





							def    _UpperCAmelCase     (					self       :	Dict       ,     a       :	List[int]       ,     a       :	Optional[List[int]] = None			)			->					List[int]:
										if token_ids_a is None:
													return self.prefix_tokens + token_ids_a + self.suffix_tokens
										# We don't expect to process pairs, but leave the pair logic for API consistency
										return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens





							def    _UpperCAmelCase     (					self       :	Tuple       ,     a       :	List[int]       ,     a       :	Optional[List[int]] = None			)			->					List[int]:
										SCREAMING_SNAKE_CASE           =					[self.sep_token_id]
										SCREAMING_SNAKE_CASE           =					[self.cls_token_id]

										if token_ids_a is None:
													return len(cls + token_ids_a + sep			) * [0]
										return len(cls + token_ids_a + sep + sep + token_ids_a + sep			) * [0]





							def    _UpperCAmelCase     (					self       :	Optional[Any]       ,     a       :	Optional[int]       ,     a       :	str       ,     a       :	Optional[str]       ,     a       :	Optional[str]       ,     **a       :	Optional[Any]			)			->					Optional[Any]:
										if src_lang is None or tgt_lang is None:
													raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model"""			)
										SCREAMING_SNAKE_CASE           =					src_lang
										SCREAMING_SNAKE_CASE           =					self(a       ,     add_special_tokens=a       ,     return_tensors=a       ,     **a			)
										SCREAMING_SNAKE_CASE           =					self.convert_tokens_to_ids(a			)
										SCREAMING_SNAKE_CASE           =					tgt_lang_id
										return inputs





							def    _UpperCAmelCase     (					self       :	str       ,     a       :	List[str]       ,     a       :	str = "en_XX"       ,     a       :	Optional[List[str]] = None       ,     a       :	str = "ro_RO"       ,     **a       :	List[str]       ,     )			->					BatchEncoding:
										SCREAMING_SNAKE_CASE           =					src_lang
										SCREAMING_SNAKE_CASE           =					tgt_lang
										return super().prepare_seqaseq_batch(a       ,     a       ,     **a			)





							def    _UpperCAmelCase     (					self       :	Optional[Any]			)			->					str:
										return self.set_src_lang_special_tokens(self.src_lang			)





							def    _UpperCAmelCase     (					self       :	str			)			->					List[str]:
										return self.set_tgt_lang_special_tokens(self.tgt_lang			)





							def    _UpperCAmelCase     (					self       :	Dict       ,     a       :	List[str]			)			->					None:
										SCREAMING_SNAKE_CASE           =					self.convert_tokens_to_ids(a			)
										SCREAMING_SNAKE_CASE           =					[]
										SCREAMING_SNAKE_CASE           =					[self.eos_token_id, self.cur_lang_code]

										SCREAMING_SNAKE_CASE           =					self.convert_ids_to_tokens(self.prefix_tokens			)
										SCREAMING_SNAKE_CASE           =					self.convert_ids_to_tokens(self.suffix_tokens			)

										SCREAMING_SNAKE_CASE           =					processors.TemplateProcessing(
										    single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str       ,     pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str       ,     special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str       ,     self.prefix_tokens + self.suffix_tokens			)			)       ,     )





							def    _UpperCAmelCase     (					self       :	Dict       ,     a       :	str			)			->					None:
										SCREAMING_SNAKE_CASE           =					self.convert_tokens_to_ids(a			)
										SCREAMING_SNAKE_CASE           =					[]
										SCREAMING_SNAKE_CASE           =					[self.eos_token_id, self.cur_lang_code]

										SCREAMING_SNAKE_CASE           =					self.convert_ids_to_tokens(self.prefix_tokens			)
										SCREAMING_SNAKE_CASE           =					self.convert_ids_to_tokens(self.suffix_tokens			)

										SCREAMING_SNAKE_CASE           =					processors.TemplateProcessing(
										    single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str       ,     pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str       ,     special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str       ,     self.prefix_tokens + self.suffix_tokens			)			)       ,     )







							def    _UpperCAmelCase     (					self       :	Dict       ,     a       :	str       ,     a       :	Optional[str] = None			)			->					Tuple[str]:
										if not self.can_save_slow_tokenizer:
													raise ValueError(
													    """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """
													    """tokenizer."""			)

										if not os.path.isdir(a			):
													logger.error(f"""Vocabulary path ({save_directory}) should be a directory."""			)
													return
										SCREAMING_SNAKE_CASE           =					os.path.join(
										    a       ,     (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]			)

										if os.path.abspath(self.vocab_file			) != os.path.abspath(a			):
													copyfile(self.vocab_file       ,     a			)

										return (out_vocab_file,)






