






'''simple docstring'''
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_longformer import LongformerTokenizer


UpperCamelCase__	=     logging.get_logger(__name__)

UpperCamelCase__	=     {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'}

UpperCamelCase__	=     {
    'vocab_file': {
        'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json',
        'allenai/longformer-large-4096': (
            'https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json'
        ),
        'allenai/longformer-large-4096-finetuned-triviaqa': (
            'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json'
        ),
        'allenai/longformer-base-4096-extra.pos.embd.only': (
            'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json'
        ),
        'allenai/longformer-large-4096-extra.pos.embd.only': (
            'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json'
        ),
    },
    'merges_file': {
        'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt',
        'allenai/longformer-large-4096': (
            'https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt'
        ),
        'allenai/longformer-large-4096-finetuned-triviaqa': (
            'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt'
        ),
        'allenai/longformer-base-4096-extra.pos.embd.only': (
            'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt'
        ),
        'allenai/longformer-large-4096-extra.pos.embd.only': (
            'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt'
        ),
    },
    'tokenizer_file': {
        'allenai/longformer-base-4096': (
            'https://huggingface.co/allenai/longformer-base-4096/resolve/main/tokenizer.json'
        ),
        'allenai/longformer-large-4096': (
            'https://huggingface.co/allenai/longformer-large-4096/resolve/main/tokenizer.json'
        ),
        'allenai/longformer-large-4096-finetuned-triviaqa': (
            'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/tokenizer.json'
        ),
        'allenai/longformer-base-4096-extra.pos.embd.only': (
            'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/tokenizer.json'
        ),
        'allenai/longformer-large-4096-extra.pos.embd.only': (
            'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/tokenizer.json'
        ),
    },
}

UpperCamelCase__	=     {
    'allenai/longformer-base-4096': 4096,
    'allenai/longformer-large-4096': 4096,
    'allenai/longformer-large-4096-finetuned-triviaqa': 4096,
    'allenai/longformer-base-4096-extra.pos.embd.only': 4096,
    'allenai/longformer-large-4096-extra.pos.embd.only': 4096,
}


class     _UpperCAmelCase  (						snake_case     ):
    __lowerCamelCase:				int						    =      VOCAB_FILES_NAMES
    __lowerCamelCase:				Any						    =      PRETRAINED_VOCAB_FILES_MAP
    __lowerCamelCase:				Optional[int]						    =      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    __lowerCamelCase:				Optional[Any]						    =      ['input_ids', 'attention_mask']
    __lowerCamelCase:				Any						    =      LongformerTokenizer




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






       '''simple docstring'''






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

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

       lowercase_		:      Tuple          =       add_prefix_space

       lowercase_		:      Optional[int]          =       "post_processor"
       lowercase_		:      Optional[Any]          =       getattr(self.backend_tokenizer					,       a					,       a     )
       if tokenizer_component_instance:
          lowercase_		:      Optional[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:
             lowercase_		:      int          =       tuple(state["sep"]     )
          if "cls" in state:
             lowercase_		:      str          =       tuple(state["cls"]     )

          lowercase_		:      Union[str, Any]          =       False

          if state.get("add_prefix_space"					,       a     ) != add_prefix_space:
             lowercase_		:      Tuple          =       add_prefix_space
             lowercase_		:      List[str]          =       True

          if state.get("trim_offsets"					,       a     ) != trim_offsets:
             lowercase_		:      List[str]          =       trim_offsets
             lowercase_		:      List[Any]          =       True

          if changes_to_apply:
             lowercase_		:      str          =       getattr(a					,       state.pop("type"     )     )
             lowercase_		:      List[Any]          =       component_class(**a     )
             setattr(self.backend_tokenizer					,       a					,       a     )




    @property
    def 			lowerCAmelCase__			(     self					:    Dict     ):






       '''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 			lowerCAmelCase__			(     self					:    List[Any]					,       a					:    List[Any]     ):






       '''simple docstring'''






       lowercase_		:      Any          =       AddedToken(a					,       lstrip=a					,       rstrip=a     ) if isinstance(a					,       a     ) else value
       lowercase_		:      List[Any]          =       value




    def 			lowerCAmelCase__			(     self					:    Union[str, Any]					,       *a					:    Optional[Any]					,       **a					:    Tuple     ):






       '''simple docstring'''






       lowercase_		:      Dict          =       kwargs.get("is_split_into_words"					,       a     )
       assert self.add_prefix_space or not is_split_into_words, (
           f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
           "to use it with pretokenized inputs."
       )

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




    def 			lowerCAmelCase__			(     self					:    Union[str, Any]					,       *a					:    Any					,       **a					:    List[Any]     ):






       '''simple docstring'''






       lowercase_		:      Union[str, Any]          =       kwargs.get("is_split_into_words"					,       a     )

       assert self.add_prefix_space or not is_split_into_words, (
           f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
           "to use it with pretokenized inputs."
       )

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




    def 			lowerCAmelCase__			(     self					:    Tuple					,       a					:    str					,       a					:    Optional[str] = None     ):






       '''simple docstring'''






       lowercase_		:      Optional[Any]          =       self._tokenizer.model.save(a					,       name=a     )
       return tuple(a     )




    def 			lowerCAmelCase__			(     self					:    List[str]					,       a					:    Any					,       a					:    Optional[int]=None     ):






       '''simple docstring'''






       lowercase_		:      Dict          =       [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 			lowerCAmelCase__			(     self					:    Optional[Any]					,       a					:    List[int]					,       a					:    Optional[List[int]] = None     ):






       '''simple docstring'''






       lowercase_		:      str          =       [self.sep_token_id]
       lowercase_		:      Optional[int]          =       [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]












'''simple docstring'''
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


UpperCamelCase__	=     logging.get_logger(__name__)

UpperCamelCase__	=     {
    '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     _UpperCAmelCase  (						snake_case     ):
    __lowerCamelCase:				List[Any]						    =      'm2m_100'
    __lowerCamelCase:				Union[str, Any]						    =      ['past_key_values']
    __lowerCamelCase:				Union[str, Any]						    =      {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}




    def __init__(     self					:    str					,       a					:    Optional[Any]=1_2_8_1_1_2					,       a					:    Optional[int]=1_0_2_4					,       a					:    Any=1_2					,       a					:    Tuple=4_0_9_6					,       a					:    Any=1_6					,       a					:    Any=1_2					,       a					:    Dict=4_0_9_6					,       a					:    List[str]=1_6					,       a					:    List[Any]=0.05					,       a					:    Optional[int]=0.05					,       a					:    List[Any]=True					,       a					:    List[Any]=True					,       a					:    Union[str, Any]="relu"					,       a					:    Optional[Any]=1_0_2_4					,       a					:    List[str]=0.1					,       a					:    Union[str, Any]=0.1					,       a					:    int=0.0					,       a					:    List[str]=0.02					,       a					:    Optional[int]=2					,       a					:    Tuple=True					,       a					:    List[str]=1					,       a					:    int=0					,       a					:    int=2					,       **a					:    Tuple					,       ):






       '''simple docstring'''






       lowercase_		:      List[str]          =       vocab_size
       lowercase_		:      Tuple          =       max_position_embeddings
       lowercase_		:      int          =       d_model
       lowercase_		:      Optional[int]          =       encoder_ffn_dim
       lowercase_		:      Any          =       encoder_layers
       lowercase_		:      Optional[Any]          =       encoder_attention_heads
       lowercase_		:      List[Any]          =       decoder_ffn_dim
       lowercase_		:      Union[str, Any]          =       decoder_layers
       lowercase_		:      Optional[Any]          =       decoder_attention_heads
       lowercase_		:      Optional[int]          =       dropout
       lowercase_		:      Optional[Any]          =       attention_dropout
       lowercase_		:      Optional[int]          =       activation_dropout
       lowercase_		:      Any          =       activation_function
       lowercase_		:      Optional[Any]          =       init_std
       lowercase_		:      Tuple          =       encoder_layerdrop
       lowercase_		:      Optional[Any]          =       decoder_layerdrop
       lowercase_		:      List[Any]          =       use_cache
       lowercase_		:      Dict          =       encoder_layers
       lowercase_		:      Tuple          =       scale_embedding  # scale factor will be sqrt(d_model) if True

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


class     _UpperCAmelCase  (						snake_case     ):




    @property
    def 			lowerCAmelCase__			(     self					:    Optional[Any]     ):






       '''simple docstring'''






       lowercase_		:      List[Any]          =       OrderedDict(
           [
               ("input_ids", {0: "batch", 1: "encoder_sequence"}),
               ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
           ]     )

       if self.use_past:
          lowercase_		:      Optional[int]          =       {0: "batch"}
          lowercase_		:      str          =       {0: "batch", 1: "past_decoder_sequence + sequence"}
       else:
          lowercase_		:      Optional[Any]          =       {0: "batch", 1: "decoder_sequence"}
          lowercase_		:      Union[str, Any]          =       {0: "batch", 1: "decoder_sequence"}

       if self.use_past:
          self.fill_with_past_key_values_(a					,       direction="inputs"     )
       return common_inputs




    def 			lowerCAmelCase__			(     self					:    Dict					,       a					:    PreTrainedTokenizer					,       a					:    int = -1					,       a					:    int = -1					,       a					:    bool = False					,       a					:    Optional[TensorType] = None					,       ):






       '''simple docstring'''






       lowercase_		:      int          =       compute_effective_axis_dimension(
           a					,       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
       lowercase_		:      Dict          =       tokenizer.num_special_tokens_to_add(a     )
       lowercase_		:      str          =       compute_effective_axis_dimension(
           a					,       fixed_dimension=OnnxConfig.default_fixed_sequence					,       num_token_to_add=a     )

       # Generate dummy inputs according to compute batch and sequence
       lowercase_		:      Union[str, Any]          =       [" ".join([tokenizer.unk_token]     ) * seq_length] * batch_size
       lowercase_		:      Tuple          =       dict(tokenizer(a					,       return_tensors=a     )     )
       return common_inputs




    def 			lowerCAmelCase__			(     self					:    Any					,       a					:    PreTrainedTokenizer					,       a					:    int = -1					,       a					:    int = -1					,       a					:    bool = False					,       a					:    Optional[TensorType] = None					,       ):






       '''simple docstring'''






       lowercase_		:      Optional[Any]          =       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
           a					,       a					,       a					,       a					,       a     )

       # Generate decoder inputs
       lowercase_		:      List[str]          =       seq_length if not self.use_past else 1
       lowercase_		:      Dict          =       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
           a					,       a					,       a					,       a					,       a     )
       lowercase_		:      Union[str, Any]          =       {f"""decoder_{name}""": tensor for name, tensor in decoder_inputs.items()}
       lowercase_		:      Union[str, Any]          =       dict(**a					,       **a     )

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

          lowercase_		:      Dict          =       torch.cat(
              [common_inputs["decoder_attention_mask"], torch.ones(a					,       a     )]					,       dim=1     )

          lowercase_		:      Tuple          =       []
          # If the number of encoder and decoder layers are present in the model configuration, both are considered
          lowercase_      ,						lowercase_		:      Tuple          =       self.num_layers
          lowercase_		:      Optional[Any]          =       min(a					,       a     )
          lowercase_		:      Tuple          =       max(a					,       a     ) - min_num_layers
          lowercase_		:      Optional[int]          =       "encoder" if num_encoder_layers > num_decoder_layers else "decoder"

          for _ in range(a     ):
             common_inputs["past_key_values"].append(
                 (
                     torch.zeros(a     ),
                     torch.zeros(a     ),
                     torch.zeros(a     ),
                     torch.zeros(a     ),
                 )     )
          # TODO: test this.
          lowercase_		:      Union[str, Any]          =       encoder_shape if remaining_side_name == "encoder" else decoder_shape
          for _ in range(a					,       a     ):
             common_inputs["past_key_values"].append((torch.zeros(a     ), torch.zeros(a     ))     )
       return common_inputs





    __lowerCamelCase:				str						    =      _generate_dummy_inputs_for_default_and_seqaseq_lm




