


import unittest

from transformers import XLMConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import (
     XLMForMultipleChoice,
     XLMForQuestionAnswering,
     XLMForQuestionAnsweringSimple,
     XLMForSequenceClassification,
     XLMForTokenClassification,
     XLMModel,
     XLMWithLMHeadModel,
 )
 from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST






class _lowerCamelCase:
       def __init__(   self, lowerCamelCase, lowerCamelCase=13, lowerCamelCase=7, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=False, lowerCamelCase=False, lowerCamelCase=False, lowerCamelCase=2, lowerCamelCase=99, lowerCamelCase=0, lowerCamelCase=32, lowerCamelCase=5, lowerCamelCase=4, lowerCamelCase=0.1, lowerCamelCase=0.1, lowerCamelCase=5_12, lowerCamelCase=2, lowerCamelCase=0.0_2, lowerCamelCase=2, lowerCamelCase=4, lowerCamelCase="last", lowerCamelCase=True, lowerCamelCase=None, lowerCamelCase=0, )			->  str:




           """simple docstring"""

           _lowercase			:				Union[str, Any] 						=						parent
           _lowercase			:				Optional[Any] 						=						batch_size
           _lowercase			:				List[str] 						=						seq_length
           _lowercase			:				int 						=						is_training
           _lowercase			:				List[str] 						=						use_input_lengths
           _lowercase			:				int 						=						use_token_type_ids
           _lowercase			:				Any 						=						use_labels
           _lowercase			:				Union[str, Any] 						=						gelu_activation
           _lowercase			:				List[str] 						=						sinusoidal_embeddings
           _lowercase			:				str 						=						causal
           _lowercase			:				Optional[int] 						=						asm
           _lowercase			:				Union[str, Any] 						=						n_langs
           _lowercase			:				List[Any] 						=						vocab_size
           _lowercase			:				Any 						=						n_special
           _lowercase			:				Any 						=						hidden_size
           _lowercase			:				str 						=						num_hidden_layers
           _lowercase			:				Union[str, Any] 						=						num_attention_heads
           _lowercase			:				Tuple 						=						hidden_dropout_prob
           _lowercase			:				Optional[int] 						=						attention_probs_dropout_prob
           _lowercase			:				Union[str, Any] 						=						max_position_embeddings
           _lowercase			:				List[str] 						=						type_sequence_label_size
           _lowercase			:				Any 						=						initializer_range
           _lowercase			:				int 						=						num_labels
           _lowercase			:				Optional[int] 						=						num_choices
           _lowercase			:				Optional[Any] 						=						summary_type
           _lowercase			:				Optional[Any] 						=						use_proj
           _lowercase			:				int 						=						scope
           _lowercase			:				List[Any] 						=						bos_token_id
       def      UpperCamelCase	(   self)			->  Optional[int]:




           """simple docstring"""

           _lowercase			:				Tuple 						=						ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
           _lowercase			:				List[str] 						=						random_attention_mask([self.batch_size, self.seq_length])

           _lowercase			:				int 						=						None
           if self.use_input_lengths:
               _lowercase			:				Dict 						=						(
                   ids_tensor([self.batch_size], vocab_size=2) + self.seq_length - 2
               )  # small variation of seq_length

           _lowercase			:				Tuple 						=						None
           if self.use_token_type_ids:
               _lowercase			:				Optional[Any] 						=						ids_tensor([self.batch_size, self.seq_length], self.n_langs)

           _lowercase			:				Tuple 						=						None
           _lowercase			:				int 						=						None
           _lowercase			:				int 						=						None
           if self.use_labels:
               _lowercase			:				str 						=						ids_tensor([self.batch_size], self.type_sequence_label_size)
               _lowercase			:				str 						=						ids_tensor([self.batch_size, self.seq_length], self.num_labels)
               _lowercase			:				Dict 						=						ids_tensor([self.batch_size], 2).float()
               _lowercase			:				Tuple 						=						ids_tensor([self.batch_size], self.num_choices)

           _lowercase			:				Dict 						=						self.get_config()

           return (
               config,
               input_ids,
               token_type_ids,
               input_lengths,
               sequence_labels,
               token_labels,
               is_impossible_labels,
               choice_labels,
               input_mask,
           )
       def      UpperCamelCase	(   self)			->  Union[str, Any]:




           """simple docstring"""

           return XLMConfig(
               vocab_size=self.vocab_size, n_special=self.n_special, emb_dim=self.hidden_size, n_layers=self.num_hidden_layers, n_heads=self.num_attention_heads, dropout=self.hidden_dropout_prob, attention_dropout=self.attention_probs_dropout_prob, gelu_activation=self.gelu_activation, sinusoidal_embeddings=self.sinusoidal_embeddings, asm=self.asm, causal=self.causal, n_langs=self.n_langs, max_position_embeddings=self.max_position_embeddings, initializer_range=self.initializer_range, summary_type=self.summary_type, use_proj=self.use_proj, num_labels=self.num_labels, bos_token_id=self.bos_token_id, )
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, )			->  Tuple:




           """simple docstring"""

           _lowercase			:				List[Any] 						=						XLMModel(config=lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase			:				str 						=						model(lowerCamelCase, lengths=lowerCamelCase, langs=lowerCamelCase)
           _lowercase			:				int 						=						model(lowerCamelCase, langs=lowerCamelCase)
           _lowercase			:				Any 						=						model(lowerCamelCase)
           self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, )			->  List[Any]:




           """simple docstring"""

           _lowercase			:				Dict 						=						XLMWithLMHeadModel(lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()

           _lowercase			:				int 						=						model(lowerCamelCase, token_type_ids=lowerCamelCase, labels=lowerCamelCase)
           self.parent.assertEqual(result.loss.shape, ())
           self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, )			->  str:




           """simple docstring"""

           _lowercase			:				Tuple 						=						XLMForQuestionAnsweringSimple(lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()

           _lowercase			:				Dict 						=						model(lowerCamelCase)

           _lowercase			:				List[str] 						=						model(lowerCamelCase, start_positions=lowerCamelCase, end_positions=lowerCamelCase)
           _lowercase			:				Any 						=						outputs
           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, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, )			->  Union[str, Any]:




           """simple docstring"""

           _lowercase			:				Tuple 						=						XLMForQuestionAnswering(lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()

           _lowercase			:				Optional[Any] 						=						model(lowerCamelCase)

           _lowercase			:				List[Any] 						=						model(
               lowerCamelCase, start_positions=lowerCamelCase, end_positions=lowerCamelCase, cls_index=lowerCamelCase, is_impossible=lowerCamelCase, p_mask=lowerCamelCase, )

           _lowercase			:				List[str] 						=						model(
               lowerCamelCase, start_positions=lowerCamelCase, end_positions=lowerCamelCase, cls_index=lowerCamelCase, is_impossible=lowerCamelCase, )

           ((_lowercase)						,							)			:				Optional[Any] 						=						result_with_labels.to_tuple()

           _lowercase			:				List[str] 						=						model(lowerCamelCase, start_positions=lowerCamelCase, end_positions=lowerCamelCase)

           ((_lowercase)						,							)			:				Any 						=						result_with_labels.to_tuple()

           self.parent.assertEqual(result_with_labels.loss.shape, ())
           self.parent.assertEqual(result.start_top_log_probs.shape, (self.batch_size, model.config.start_n_top))
           self.parent.assertEqual(result.start_top_index.shape, (self.batch_size, model.config.start_n_top))
           self.parent.assertEqual(
               result.end_top_log_probs.shape, (self.batch_size, model.config.start_n_top * model.config.end_n_top))
           self.parent.assertEqual(
               result.end_top_index.shape, (self.batch_size, model.config.start_n_top * model.config.end_n_top))
           self.parent.assertEqual(result.cls_logits.shape, (self.batch_size,))
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, )			->  int:




           """simple docstring"""

           _lowercase			:				Optional[Any] 						=						XLMForSequenceClassification(lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()

           _lowercase			:				Optional[int] 						=						model(lowerCamelCase)
           _lowercase			:				Optional[int] 						=						model(lowerCamelCase, labels=lowerCamelCase)
           self.parent.assertEqual(result.loss.shape, ())
           self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, )			->  List[str]:




           """simple docstring"""

           _lowercase			:				Any 						=						self.num_labels
           _lowercase			:				str 						=						XLMForTokenClassification(lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()

           _lowercase			:				int 						=						model(lowerCamelCase, attention_mask=lowerCamelCase, labels=lowerCamelCase)
           self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, )			->  Dict:




           """simple docstring"""

           _lowercase			:				Optional[Any] 						=						self.num_choices
           _lowercase			:				Optional[int] 						=						XLMForMultipleChoice(config=lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase			:				Optional[Any] 						=						input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
           _lowercase			:				int 						=						token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
           _lowercase			:				Optional[Any] 						=						input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
           _lowercase			:				List[str] 						=						model(
               lowerCamelCase, attention_mask=lowerCamelCase, token_type_ids=lowerCamelCase, labels=lowerCamelCase, )
           self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))




       def      UpperCamelCase	(   self)			->  Tuple:




           """simple docstring"""

           _lowercase			:				Dict 						=						self.prepare_config_and_inputs()
           (
               (
               _lowercase
           )						,							(
               _lowercase
           )						,							(
               _lowercase
           )						,							(
               _lowercase
           )						,							(
               _lowercase
           )						,							(
               _lowercase
           )						,							(
               _lowercase
           )						,							(
               _lowercase
           )						,							(
               _lowercase
           )						,							
           )			:				Optional[Any] 						=						config_and_inputs
           _lowercase			:				List[str] 						=						{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths}
           return config, inputs_dict






@require_torch
class _lowerCamelCase(		_a,					_a,					_a,					unittest.TestCase  ):
       lowercase_					:      Any       					=     (
           (
               XLMModel,
               XLMWithLMHeadModel,
               XLMForQuestionAnswering,
               XLMForSequenceClassification,
               XLMForQuestionAnsweringSimple,
               XLMForTokenClassification,
               XLMForMultipleChoice,
           )
           if is_torch_available()
           else ()
       )
       lowercase_					:      Optional[int]       					=     (
           (XLMWithLMHeadModel,) if is_torch_available() else ()
       )  # TODO (PVP): Check other models whether language generation is also applicable
       lowercase_					:      Union[str, Any]       					=     (
           {
               """feature-extraction""": XLMModel,
               """fill-mask""": XLMWithLMHeadModel,
               """question-answering""": XLMForQuestionAnsweringSimple,
               """text-classification""": XLMForSequenceClassification,
               """text-generation""": XLMWithLMHeadModel,
               """token-classification""": XLMForTokenClassification,
               """zero-shot""": XLMForSequenceClassification,
           }
           if is_torch_available()
           else {}
       )
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase)			->  Optional[int]:




           """simple docstring"""

           if (
               pipeline_test_casse_name == "QAPipelineTests"
               and tokenizer_name is not None
               and not tokenizer_name.endswith('Fast')
           ):
               # `QAPipelineTests` fails for a few models when the slower tokenizer are used.
               # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
               # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
               return True

           return False
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase=False)			->  Optional[int]:




           """simple docstring"""

           _lowercase			:				Any 						=						super()._prepare_for_class(lowerCamelCase, lowerCamelCase, return_labels=lowerCamelCase)

           if return_labels:
               if model_class.__name__ == "XLMForQuestionAnswering":
                   _lowercase			:				Any 						=						torch.zeros(
                       self.model_tester.batch_size, dtype=torch.long, device=lowerCamelCase)
                   _lowercase			:				Dict 						=						torch.zeros(
                       self.model_tester.batch_size, dtype=torch.long, device=lowerCamelCase)

           return inputs_dict
       def      UpperCamelCase	(   self)			->  int:




           """simple docstring"""

           _lowercase			:				Union[str, Any] 						=						XLMModelTester(self)
           _lowercase			:				List[str] 						=						ConfigTester(self, config_class=lowerCamelCase, emb_dim=37)
       def      UpperCamelCase	(   self)			->  Tuple:




           """simple docstring"""

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




           """simple docstring"""

           _lowercase			:				Optional[Any] 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_xlm_model(*lowerCamelCase)
       def      UpperCamelCase	(   self)			->  List[str]:




           """simple docstring"""

           _lowercase			:				str 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_xlm_lm_head(*lowerCamelCase)
       def      UpperCamelCase	(   self)			->  Optional[Any]:




           """simple docstring"""

           _lowercase			:				Optional[Any] 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_xlm_simple_qa(*lowerCamelCase)
       def      UpperCamelCase	(   self)			->  int:




           """simple docstring"""

           _lowercase			:				str 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_xlm_qa(*lowerCamelCase)
       def      UpperCamelCase	(   self)			->  List[str]:




           """simple docstring"""

           _lowercase			:				Dict 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_xlm_sequence_classif(*lowerCamelCase)
       def      UpperCamelCase	(   self)			->  Dict:




           """simple docstring"""

           _lowercase			:				Union[str, Any] 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_xlm_token_classif(*lowerCamelCase)
       def      UpperCamelCase	(   self)			->  Any:




           """simple docstring"""

           _lowercase			:				str 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_xlm_for_multiple_choice(*lowerCamelCase)
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase=False, lowerCamelCase=1)			->  int:




           """simple docstring"""

           self.assertIsInstance(lowerCamelCase, lowerCamelCase)
           self.assertListEqual(
               [isinstance(lowerCamelCase, lowerCamelCase) for iter_attentions in attentions], [True] * len(lowerCamelCase))
           self.assertEqual(len(lowerCamelCase), (max_length - min_length) * num_beam_groups)

           for idx, iter_attentions in enumerate(lowerCamelCase):
               # adds PAD dummy token
               _lowercase			:				Dict 						=						min_length + idx + 1
               _lowercase			:				int 						=						min_length + idx + 1

               _lowercase			:				Dict 						=						(
                   batch_size * num_beam_groups,
                   config.num_attention_heads,
                   tgt_len,
                   src_len,
               )
               # check attn size
               self.assertListEqual(
                   [layer_attention.shape for layer_attention in iter_attentions], [expected_shape] * len(lowerCamelCase))
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase=False, lowerCamelCase=1)			->  List[Any]:




           """simple docstring"""

           self.assertIsInstance(lowerCamelCase, lowerCamelCase)
           self.assertListEqual(
               [isinstance(lowerCamelCase, lowerCamelCase) for iter_hidden_states in hidden_states], [True] * len(lowerCamelCase), )
           self.assertEqual(len(lowerCamelCase), (max_length - min_length) * num_beam_groups)

           for idx, iter_hidden_states in enumerate(lowerCamelCase):
               # adds PAD dummy token
               _lowercase			:				int 						=						min_length + idx + 1
               _lowercase			:				int 						=						(batch_size * num_beam_groups, seq_len, config.hidden_size)
               # check hidden size
               self.assertListEqual(
                   [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states], [expected_shape] * len(lowerCamelCase), )
           pass




       @slow
       def      UpperCamelCase	(   self)			->  int:




           """simple docstring"""

           for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _lowercase			:				Dict 						=						XLMModel.from_pretrained(lowerCamelCase)
               self.assertIsNotNone(lowerCamelCase)






@require_torch
class _lowerCamelCase(		unittest.TestCase  ):
       @slow
       def      UpperCamelCase	(   self)			->  Union[str, Any]:




           """simple docstring"""

           _lowercase			:				Tuple 						=						XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048')
           model.to(lowerCamelCase)
           _lowercase			:				Union[str, Any] 						=						torch.tensor([[14, 4_47]], dtype=torch.long, device=lowerCamelCase)  # the president
           _lowercase			:				Any 						=						[
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
           ]  # the president the president the president the president the president the president the president the president the president the president
           # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference
           _lowercase			:				str 						=						model.generate(lowerCamelCase, do_sample=lowerCamelCase)
           self.assertListEqual(output_ids[0].cpu().numpy().tolist(), lowerCamelCase)









import json
from typing import List, Optional, Tuple

from tokenizers import pre_tokenizers, processors

from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bart import BartTokenizer


_lowerCAmelCase				:   Optional[Any]						       =						logging.get_logger(__name__)


_lowerCAmelCase				:   List[str]						       =						{'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''}

# See all BART models at https://huggingface.co/models?filter=bart
_lowerCAmelCase				:   int						       =						{
    '''vocab_file''': {
        '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/vocab.json''',
        '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/vocab.json''',
        '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json''',
        '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json''',
        '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json''',
        '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json''',
    },
    '''merges_file''': {
        '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/merges.txt''',
        '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/merges.txt''',
        '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt''',
        '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt''',
        '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt''',
        '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt''',
    },
    '''tokenizer_file''': {
        '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json''',
        '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json''',
        '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json''',
        '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json''',
        '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json''',
        '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json''',
    },
}

_lowerCAmelCase				:   Optional[int]						       =						{
    '''facebook/bart-base''': 1_024,
    '''facebook/bart-large''': 1_024,
    '''facebook/bart-large-mnli''': 1_024,
    '''facebook/bart-large-cnn''': 1_024,
    '''facebook/bart-large-xsum''': 1_024,
    '''yjernite/bart_eli5''': 1_024,
}


class        __magic_name__	(				lowerCamelCase__				):





     """simple docstring"""



     __UpperCamelCase            =  VOCAB_FILES_NAMES
     __UpperCamelCase            =  PRETRAINED_VOCAB_FILES_MAP
     __UpperCamelCase            =  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     __UpperCamelCase            =  ['''input_ids''', '''attention_mask''']
     __UpperCamelCase            =  BartTokenizer



     def __init__(				self							:List[str]      ,   snake_case							:Tuple=None      ,   snake_case							:Union[str, Any]=None      ,   snake_case							:Union[str, Any]=None      ,   snake_case							:List[Any]="replace"      ,   snake_case							:List[str]="<s>"      ,   snake_case							:Optional[int]="</s>"      ,   snake_case							:Union[str, Any]="</s>"      ,   snake_case							:Optional[Any]="<s>"      ,   snake_case							:List[Any]="<unk>"      ,   snake_case							:Optional[Any]="<pad>"      ,   snake_case							:Dict="<mask>"      ,   snake_case							:int=False      ,   snake_case							:List[Any]=True      ,   **snake_case							:Union[str, Any]      ,   ):





        '''simple docstring'''




        super().__init__(
            snake_case      ,   snake_case      ,   tokenizer_file=snake_case      ,   errors=snake_case      ,   bos_token=snake_case      ,   eos_token=snake_case      ,   sep_token=snake_case      ,   cls_token=snake_case      ,   unk_token=snake_case      ,   pad_token=snake_case      ,   mask_token=snake_case      ,   add_prefix_space=snake_case      ,   trim_offsets=snake_case      ,   **snake_case      ,   )

        A_       :					Optional[Any]        =      json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()	)
        if pre_tok_state.get("add_prefix_space"      ,   snake_case	) != add_prefix_space:
           A_       :					Dict        =      getattr(snake_case      ,   pre_tok_state.pop("type"	)	)
           A_       :					List[str]        =      add_prefix_space
           A_       :					int        =      pre_tok_class(**snake_case	)

        A_       :					Any        =      add_prefix_space

        # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
        A_       :					Tuple        =      "post_processor"
        A_       :					Union[str, Any]        =      getattr(self.backend_tokenizer      ,   snake_case      ,   snake_case	)
        if tokenizer_component_instance:
           A_       :					Any        =      json.loads(tokenizer_component_instance.__getstate__()	)

           # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
           if "sep" in state:
              A_       :					List[Any]        =      tuple(state["sep"]	)
           if "cls" in state:
              A_       :					str        =      tuple(state["cls"]	)

           A_       :					int        =      False

           if state.get("add_prefix_space"      ,   snake_case	) != add_prefix_space:
              A_       :					List[Any]        =      add_prefix_space
              A_       :					Union[str, Any]        =      True

           if state.get("trim_offsets"      ,   snake_case	) != trim_offsets:
              A_       :					int        =      trim_offsets
              A_       :					str        =      True

           if changes_to_apply:
              A_       :					Tuple        =      getattr(snake_case      ,   state.pop("type"	)	)
              A_       :					Union[str, Any]        =      component_class(**snake_case	)
              setattr(self.backend_tokenizer      ,   snake_case      ,   snake_case	)



     @property
     def     SCREAMING_SNAKE_CASE		(				self							:List[Any]	):





        '''simple docstring'''




        if self._mask_token is None:
           if self.verbose:
              logger.error("Using mask_token, but it is not set yet."	)
           return None
        return str(self._mask_token	)



     @mask_token.setter
     def     SCREAMING_SNAKE_CASE		(				self							:Tuple      ,   snake_case							:Dict	):





        '''simple docstring'''




        A_       :					Optional[int]        =      AddedToken(snake_case      ,   lstrip=snake_case      ,   rstrip=snake_case	) if isinstance(snake_case      ,   snake_case	) else value
        A_       :					List[Any]        =      value



     def     SCREAMING_SNAKE_CASE		(				self							:Tuple      ,   *snake_case							:str      ,   **snake_case							:str	):





        '''simple docstring'''




        A_       :					Tuple        =      kwargs.get("is_split_into_words"      ,   snake_case	)

        if is_split_into_words and not self.add_prefix_space:
           raise ValueError(
               f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
               "to use it with pretokenized inputs."	)

        return super()._batch_encode_plus(*snake_case      ,   **snake_case	)



     def     SCREAMING_SNAKE_CASE		(				self							:Union[str, Any]      ,   *snake_case							:Any      ,   **snake_case							:Optional[Any]	):





        '''simple docstring'''




        A_       :					List[Any]        =      kwargs.get("is_split_into_words"      ,   snake_case	)

        if is_split_into_words and not self.add_prefix_space:
           raise ValueError(
               f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
               "to use it with pretokenized inputs."	)

        return super()._encode_plus(*snake_case      ,   **snake_case	)



     def     SCREAMING_SNAKE_CASE		(				self							:int      ,   snake_case							:str      ,   snake_case							:Optional[str] = None	):





        '''simple docstring'''




        A_       :					Any        =      self._tokenizer.model.save(snake_case      ,   name=snake_case	)
        return tuple(snake_case	)



     def     SCREAMING_SNAKE_CASE		(				self							:Dict      ,   snake_case							:List[str]      ,   snake_case							:Optional[int]=None	):





        '''simple docstring'''




        A_       :					str        =      [self.bos_token_id] + token_ids_a + [self.eos_token_id]
        if token_ids_a is None:
           return output

        return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]





     def     SCREAMING_SNAKE_CASE		(				self							:int      ,   snake_case							:List[int]      ,   snake_case							:Optional[List[int]] = None	):





        '''simple docstring'''




        A_       :					Dict        =      [self.sep_token_id]
        A_       :					List[str]        =      [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]
