


from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


__snake_case   							=						logging.get_logger(__name__)






def 		_A		(		_lowercase )					-> List[int]:


     """simple docstring"""


     if isinstance(_lowercase					,  np.ndarray ):
          return list(tensor.shape )

     __UpperCamelCase =			tf.shape(_lowercase )

     if tensor.shape == tf.TensorShape(_lowercase ):
          return dynamic

     __UpperCamelCase =			tensor.shape.as_list()

     return [dynamic[i] if s is None else s for i, s in enumerate(_lowercase )]






def 		_A		(		_lowercase					,  _lowercase = None					,  _lowercase = None )					-> tf.Tensor:


     """simple docstring"""


     return tf.nn.softmax(logits=logits + 1e-9					,  axis=_lowercase					,  name=_lowercase )






def 		_A		(		_lowercase					,  _lowercase					,  _lowercase					,  _lowercase=1e-5					,  _lowercase=-1 )					-> str:


     """simple docstring"""


     if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(_lowercase					,  _lowercase ):
          raise NotImplementedError('Only 1D weight and bias tensors are supported for now, with only a single axis.' )

     # Get mean and variance on the axis to be normalized
     __UpperCamelCase,    __UpperCamelCase =			tf.nn.moments(_lowercase					,  axes=[axis]					,  keepdims=_lowercase )

     if axis != -1:
          # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions
          # on every dimension except axis
          __UpperCamelCase =			[1] * inputs.shape.rank
          __UpperCamelCase =			shape_list(_lowercase )[axis]
          __UpperCamelCase =			tf.reshape(_lowercase					,  _lowercase )
          __UpperCamelCase =			tf.reshape(_lowercase					,  _lowercase )

     # Compute layer normalization using the batch_normalization
     # function.
     __UpperCamelCase =			tf.nn.batch_normalization(
         _lowercase					,  _lowercase					,  _lowercase					,  offset=_lowercase					,  scale=_lowercase					,  variance_epsilon=_lowercase					,  )
     return outputs






def 		_A		(		_lowercase					,  _lowercase=0					,  _lowercase=-1 )					-> Tuple:


     """simple docstring"""


     if end_dim < 0:
          end_dim += input.shape.rank
     if start_dim < 0:
          start_dim += input.shape.rank

     if start_dim == end_dim:
          return input

     __UpperCamelCase =			tf.shape(_lowercase )
     __UpperCamelCase =			tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] )
     __UpperCamelCase =			tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]]					,  axis=0 )
     return tf.reshape(_lowercase					,  _lowercase )






def 		_A		(		_lowercase )					-> tf.Tensor:


     """simple docstring"""


     if not isinstance(_lowercase					,  tf.Tensor ):
          __UpperCamelCase =			tf.convert_to_tensor(_lowercase )  # Catches stray NumPy inputs
     if encoder_attention_mask.shape.rank == 3:
          __UpperCamelCase =			encoder_attention_mask[:, None, :, :]
     if encoder_attention_mask.shape.rank == 2:
          __UpperCamelCase =			encoder_attention_mask[:, None, None, :]
     # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
     # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow
     # /transformer/transformer_layers.py#L270
     # encoder_extended_attention_mask = (encoder_extended_attention_mask ==
     # encoder_extended_attention_mask.transpose(-1, -2))
     __UpperCamelCase =			(
         tf.cast(1					,  encoder_attention_mask.dtype ) - encoder_extended_attention_mask
     ) * encoder_extended_attention_mask.dtype.min

     return encoder_extended_attention_mask






def 		_A		(		_lowercase					,  _lowercase					,  _lowercase = "input_ids" )					-> None:


     """simple docstring"""


     tf.debugging.assert_less(
         _lowercase					,  tf.cast(_lowercase					,  dtype=tensor.dtype )					,  message=(
             f'''The maximum value of {tensor_name} ({tf.math.reduce_max(_lowercase )}) must be smaller than the embedding '''
             f'''layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.'''
         )					,  )






def 		_A		(		_lowercase					,  _lowercase					,  _lowercase )					-> Optional[int]:


     """simple docstring"""


     __UpperCamelCase =			6_45_12
     # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
     # because in that case even chunking the array would not make the saving
     # possible.
     __UpperCamelCase =			[x for x in data if len(_lowercase ) > HDF5_OBJECT_HEADER_LIMIT]

     # Expecting this to never be true.
     if bad_attributes:
          raise RuntimeError(
              'The following attributes cannot be saved to HDF5 file because '
              f'''they are larger than {HDF5_OBJECT_HEADER_LIMIT} '''
              f'''bytes: {bad_attributes}''' )

     __UpperCamelCase =			np.asarray(_lowercase )

     __UpperCamelCase =			1
     __UpperCamelCase =			np.array_split(_lowercase					,  _lowercase )

     # This will never loop forever thanks to the test above.
     while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data ):
          num_chunks += 1
          __UpperCamelCase =			np.array_split(_lowercase					,  _lowercase )

     if num_chunks > 1:
          for chunk_id, chunk_data in enumerate(_lowercase ):
               __UpperCamelCase =			chunk_data
     else:
          __UpperCamelCase =			data






def 		_A		(		_lowercase					,  _lowercase )					-> Tuple:


     """simple docstring"""


     if name in group.attrs:
          __UpperCamelCase =			[n.decode('utf8' ) if hasattr(_lowercase					,  'decode' ) else n for n in group.attrs[name]]
     else:
          __UpperCamelCase =			[]
          __UpperCamelCase =			0
          while "%s%d" % (name, chunk_id) in group.attrs:
               data.extend(
                   [n.decode('utf8' ) if hasattr(_lowercase					,  'decode' ) else n for n in group.attrs['%s%d' % (name, chunk_id)]] )
               chunk_id += 1
     return data






def 		_A		(		_lowercase )					-> Tuple:


     """simple docstring"""


     def _expand_single_ad_tensor(_lowercase ):
          if isinstance(_lowercase					,  tf.Tensor ) and t.shape.rank == 1:
               return tf.expand_dims(_lowercase					,  axis=-1 )
          return t

     return tf.nest.map_structure(_expand_single_ad_tensor					,  _lowercase )









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]
