






"""simple docstring"""




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

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


_snake_case          =   logging.get_logger(__name__)

_snake_case          =   '▁'

_snake_case          =   {'vocab_file': 'sentencepiece.bpe.model'}

_snake_case          =   {
    'vocab_file': {
        'facebook/xglm-564M': 'https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model',
    }
}

_snake_case          =   {
    'facebook/xglm-564M': 2048,
}






class        UpperCamelCase			(	_A      ):
 UpperCamelCase					:       Tuple			=					VOCAB_FILES_NAMES
 UpperCamelCase					:       List[Any]			=					PRETRAINED_VOCAB_FILES_MAP
 UpperCamelCase					:       str			=					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 UpperCamelCase					:       List[Any]			=					['''input_ids''', '''attention_mask''']


 def __init__(     self		:						Optional[Any]							,						UpperCAmelCase__		:						List[str]							,						UpperCAmelCase__		:						str="<s>"							,						UpperCAmelCase__		:						Optional[int]="</s>"							,						UpperCAmelCase__		:						str="</s>"							,						UpperCAmelCase__		:						Optional[Any]="<s>"							,						UpperCAmelCase__		:						Optional[int]="<unk>"							,						UpperCAmelCase__		:						Optional[int]="<pad>"							,						UpperCAmelCase__		:						Optional[Dict[str, Any]] = None							,						**UpperCAmelCase__		:						str							,						)					->       None:
   _a  :       str             =	{} if sp_model_kwargs is None else sp_model_kwargs

   # Compatibility with the original tokenizer
   _a  :       Any             =	7
   _a  :       Dict             =	[f"""<madeupword{i}>""" for i in range(self.num_madeup_words							)]

   _a  :       List[Any]             =	kwargs.get("""additional_special_tokens"""							,						[]							)
   kwargs["additional_special_tokens"] += [
       word for word in madeup_words if word not in kwargs["additional_special_tokens"]
   ]

   super().__init__(
       bos_token=UpperCamelCase__							,						eos_token=UpperCamelCase__							,						unk_token=UpperCamelCase__							,						sep_token=UpperCamelCase__							,						cls_token=UpperCamelCase__							,						pad_token=UpperCamelCase__							,						sp_model_kwargs=self.sp_model_kwargs							,						**UpperCamelCase__							,						)

   _a  :       Dict             =	spm.SentencePieceProcessor(**self.sp_model_kwargs							)
   self.sp_model.Load(str(UpperCamelCase__							)							)
   _a  :       Dict             =	vocab_file

   # Original fairseq vocab and spm vocab must be "aligned":
   # Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
   # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
   # fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
   # spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

   # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
   _a  :       Union[str, Any]             =	1

   # Mimic fairseq token-to-id alignment for the first 4 token
   _a  :       Dict             =	{"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3}

   _a  :       Tuple             =	len(self.sp_model							)
   _a  :       List[Any]             =	{f"""<madeupword{i}>""": sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words							)}
   self.fairseq_tokens_to_ids.update(UpperCamelCase__							)

   _a  :       Any             =	{v: k for k, v in self.fairseq_tokens_to_ids.items()}


 def __getstate__(     self		:						Union[str, Any]							)					->       List[str]:
   _a  :       Any             =	self.__dict__.copy()
   _a  :       Optional[int]             =	None
   _a  :       Union[str, Any]             =	self.sp_model.serialized_model_proto()
   return state


 def __setstate__(     self		:						List[str]							,						UpperCAmelCase__		:						str							)					->       List[Any]:
   _a  :       Optional[int]             =	d

   # for backward compatibility
   if not hasattr(self							,						"""sp_model_kwargs"""							):
     _a  :       Dict             =	{}

   _a  :       Union[str, Any]             =	spm.SentencePieceProcessor(**self.sp_model_kwargs							)
   self.sp_model.LoadFromSerializedProto(self.sp_model_proto							)


 def _lowercase	(     self		:						Union[str, Any]							,						UpperCAmelCase__		:						List[int]							,						UpperCAmelCase__		:						Optional[List[int]] = None							)					->       List[int]:






   if token_ids_a is None:
     return [self.sep_token_id] + token_ids_a
   _a  :       Union[str, Any]             =	[self.sep_token_id]
   return sep + token_ids_a + sep + sep + token_ids_a


 def _lowercase	(     self		:						Optional[Any]							,						UpperCAmelCase__		:						List[int]							,						UpperCAmelCase__		:						Optional[List[int]] = None							,						UpperCAmelCase__		:						bool = False							)					->       List[int]:






   if already_has_special_tokens:
     return super().get_special_tokens_mask(
         token_ids_a=UpperCamelCase__							,						token_ids_a=UpperCamelCase__							,						already_has_special_tokens=UpperCamelCase__							)

   if token_ids_a is None:
     return [1] + ([0] * len(UpperCamelCase__							))
   return [1] + ([0] * len(UpperCamelCase__							)) + [1, 1] + ([0] * len(UpperCamelCase__							))


 def _lowercase	(     self		:						int							,						UpperCAmelCase__		:						List[int]							,						UpperCAmelCase__		:						Optional[List[int]] = None							)					->       List[int]:
   _a  :       Optional[int]             =	[self.sep_token_id]

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


 @property
 def _lowercase	(     self		:						Tuple							)					->       List[Any]:
   return len(self.sp_model							) + self.fairseq_offset + self.num_madeup_words


 def _lowercase	(     self		:						Optional[int]							)					->       Tuple:
   _a  :       Any             =	{self.convert_ids_to_tokens(UpperCamelCase__							): i for i in range(self.vocab_size							)}
   vocab.update(self.added_tokens_encoder							)
   return vocab


 def _lowercase	(     self		:						Any							,						UpperCAmelCase__		:						str							)					->       List[str]:
   return self.sp_model.encode(UpperCamelCase__							,						out_type=UpperCamelCase__							)


 def _lowercase	(     self		:						List[Any]							,						UpperCAmelCase__		:						Optional[int]							)					->       List[Any]:






   if token in self.fairseq_tokens_to_ids:
     return self.fairseq_tokens_to_ids[token]
   _a  :       Any             =	self.sp_model.PieceToId(UpperCamelCase__							)

   # Need to return unknown token if the SP model returned 0
   return spm_id + self.fairseq_offset if spm_id else self.unk_token_id


 def _lowercase	(     self		:						str							,						UpperCAmelCase__		:						str							)					->       Tuple:






   if index in self.fairseq_ids_to_tokens:
     return self.fairseq_ids_to_tokens[index]
   return self.sp_model.IdToPiece(index - self.fairseq_offset							)


 def _lowercase	(     self		:						Dict							,						UpperCAmelCase__		:						Any							)					->       Optional[Any]:
   _a  :       Tuple             =	"""""".join(UpperCamelCase__							).replace(UpperCamelCase__							,						""" """							).strip()
   return out_string







 def _lowercase	(     self		:						Optional[int]							,						UpperCAmelCase__		:						str							,						UpperCAmelCase__		:						Optional[str] = None							)					->       Tuple[str]:






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

   if os.path.abspath(self.vocab_file							) != os.path.abspath(UpperCamelCase__							) and os.path.isfile(self.vocab_file							):
     copyfile(self.vocab_file							,						UpperCamelCase__							)
   elif not os.path.isfile(self.vocab_file							):
     with open(UpperCamelCase__							,						"""wb"""							) as fi:
       _a  :       Any             =	self.sp_model.serialized_model_proto()
       fi.write(UpperCamelCase__							)

   return (out_vocab_file,)



from ...configuration_utils import PretrainedConfig
from ...utils import logging


__lowerCAmelCase			:     Union[str, Any]           =   logging.get_logger(__name__)

__lowerCAmelCase			:     Tuple           =   {
    'google/pegasus-large': 'https://huggingface.co/google/pegasus-large/resolve/main/config.json',
    # See all PEGASUS models at https://huggingface.co/models?filter=pegasus
}




class        UpperCAmelCase_			( _A     ):


  '''simple docstring'''







  a__           =		"""pegasus"""
  a__           =		["""past_key_values"""]
  a__           =		{"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}
  def __init__( self			: Optional[int]			,							UpperCamelCase__			: Optional[int]=5_0265			,							UpperCamelCase__			: Optional[int]=1024			,							UpperCamelCase__			: Any=12			,							UpperCamelCase__			: Union[str, Any]=4096			,							UpperCamelCase__			: Any=16			,							UpperCamelCase__			: Union[str, Any]=12			,							UpperCamelCase__			: List[str]=4096			,							UpperCamelCase__			: Tuple=16			,							UpperCamelCase__			: Optional[int]=0.0			,							UpperCamelCase__			: List[Any]=0.0			,							UpperCamelCase__			: List[str]=True			,							UpperCamelCase__			: List[Any]=True			,							UpperCamelCase__			: List[Any]="gelu"			,							UpperCamelCase__			: List[Any]=1024			,							UpperCamelCase__			: Optional[Any]=0.1			,							UpperCamelCase__			: str=0.0			,							UpperCamelCase__			: Any=0.0			,							UpperCamelCase__			: Union[str, Any]=0.02			,							UpperCamelCase__			: Any=0			,							UpperCamelCase__			: int=False			,							UpperCamelCase__			: Any=0			,							UpperCamelCase__			: List[str]=1			,							UpperCamelCase__			: Tuple=1			,							**UpperCamelCase__			: Union[str, Any]			,							)			->	str:







    """simple docstring"""






    __magic_name__				     =       vocab_size
    __magic_name__				     =       max_position_embeddings
    __magic_name__				     =       d_model
    __magic_name__				     =       encoder_ffn_dim
    __magic_name__				     =       encoder_layers
    __magic_name__				     =       encoder_attention_heads
    __magic_name__				     =       decoder_ffn_dim
    __magic_name__				     =       decoder_layers
    __magic_name__				     =       decoder_attention_heads
    __magic_name__				     =       dropout
    __magic_name__				     =       attention_dropout
    __magic_name__				     =       activation_dropout
    __magic_name__				     =       activation_function
    __magic_name__				     =       init_std
    __magic_name__				     =       encoder_layerdrop
    __magic_name__				     =       decoder_layerdrop
    __magic_name__				     =       use_cache
    __magic_name__				     =       encoder_layers
    __magic_name__				     =       scale_embedding  # scale factor will be sqrt(d_model) if True
    super().__init__(
        pad_token_id=UpperCamelCase__			,							eos_token_id=UpperCamelCase__			,							is_encoder_decoder=UpperCamelCase__			,							decoder_start_token_id=UpperCamelCase__			,							forced_eos_token_id=UpperCamelCase__			,							**UpperCamelCase__			,							)
  @property
  def 							_lowercase							( self			: List[Any]    )			->	int:







    """simple docstring"""






    return self.encoder_attention_heads





  @property
  def 							_lowercase							( self			: Dict    )			->	int:







    """simple docstring"""






    return self.d_model

