



'''simple docstring'''
from collections import OrderedDict
from typing import Any, List, Mapping, Optional

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging


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


snake_case_					:      Optional[Any]    			=    {
    'Salesforce/codegen-350M-nl': 'https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json',
    'Salesforce/codegen-350M-multi': 'https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json',
    'Salesforce/codegen-350M-mono': 'https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json',
    'Salesforce/codegen-2B-nl': 'https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json',
    'Salesforce/codegen-2B-multi': 'https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json',
    'Salesforce/codegen-2B-mono': 'https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json',
    'Salesforce/codegen-6B-nl': 'https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json',
    'Salesforce/codegen-6B-multi': 'https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json',
    'Salesforce/codegen-6B-mono': 'https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json',
    'Salesforce/codegen-16B-nl': 'https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json',
    'Salesforce/codegen-16B-multi': 'https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json',
    'Salesforce/codegen-16B-mono': 'https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json',
}






class 				lowercase__      (				lowercase  ):
	lowercase__    							=     """codegen"""
	lowercase__    							=     {
	    """max_position_embeddings""": """n_positions""",
	    """hidden_size""": """n_embd""",
	    """num_attention_heads""": """n_head""",
	    """num_hidden_layers""": """n_layer""",
	}





	def __init__(					self   :							int					,lowerCamelCase__   :							List[str]=50400					,lowerCamelCase__   :							Tuple=2048					,lowerCamelCase__   :							Optional[int]=2048					,lowerCamelCase__   :							str=4096					,lowerCamelCase__   :							Optional[int]=28					,lowerCamelCase__   :							int=16					,lowerCamelCase__   :							List[Any]=64					,lowerCamelCase__   :							str=None					,lowerCamelCase__   :							Optional[int]="gelu_new"					,lowerCamelCase__   :							Dict=0.0					,lowerCamelCase__   :							str=0.0					,lowerCamelCase__   :							Any=0.0					,lowerCamelCase__   :							str=1E-5					,lowerCamelCase__   :							str=0.0_2					,lowerCamelCase__   :							Union[str, Any]=True					,lowerCamelCase__   :							Tuple=50256					,lowerCamelCase__   :							Any=50256					,lowerCamelCase__   :							Any=False					,**lowerCamelCase__   :							List[Any]					,):







							'''simple docstring'''
							_UpperCamelCase   :						List[str]												=  vocab_size
							_UpperCamelCase   :						Any												=  n_ctx
							_UpperCamelCase   :						Optional[int]												=  n_positions
							_UpperCamelCase   :						List[str]												=  n_embd
							_UpperCamelCase   :						Any												=  n_layer
							_UpperCamelCase   :						List[str]												=  n_head
							_UpperCamelCase   :						List[str]												=  n_inner
							_UpperCamelCase   :						List[str]												=  rotary_dim
							_UpperCamelCase   :						Dict												=  activation_function
							_UpperCamelCase   :						str												=  resid_pdrop
							_UpperCamelCase   :						str												=  embd_pdrop
							_UpperCamelCase   :						Any												=  attn_pdrop
							_UpperCamelCase   :						List[str]												=  layer_norm_epsilon
							_UpperCamelCase   :						Optional[int]												=  initializer_range
							_UpperCamelCase   :						List[str]												=  use_cache

							_UpperCamelCase   :						Union[str, Any]												=  bos_token_id
							_UpperCamelCase   :						str												=  eos_token_id

							super().__init__(
							    bos_token_id=lowerCamelCase__					,eos_token_id=lowerCamelCase__					,tie_word_embeddings=lowerCamelCase__					,**lowerCamelCase__					)






class 				lowercase__      (				lowercase  ):





	def __init__(					self   :							Dict					,lowerCamelCase__   :							PretrainedConfig					,lowerCamelCase__   :							str = "default"					,lowerCamelCase__   :							List[PatchingSpec] = None					,lowerCamelCase__   :							bool = False					,):







							'''simple docstring'''
							super().__init__(lowerCamelCase__					,task=lowerCamelCase__					,patching_specs=lowerCamelCase__					,use_past=lowerCamelCase__					)
							if not getattr(self._config					,'pad_token_id'					,lowerCamelCase__					):
													# TODO: how to do that better?
													_UpperCamelCase   :						List[str]												=  0





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







							'''simple docstring'''
							_UpperCamelCase   :						Tuple												=  OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}}					)
							if self.use_past:
													self.fill_with_past_key_values_(lowerCamelCase__					,direction='inputs'					)
													_UpperCamelCase   :						Union[str, Any]												=  {0: 'batch', 1: 'past_sequence + sequence'}
							else:
													_UpperCamelCase   :						Tuple												=  {0: 'batch', 1: 'sequence'}

							return common_inputs





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







							'''simple docstring'''
							return self._config.n_layer





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







							'''simple docstring'''
							return self._config.n_head





	def       UpperCamelCase_    (					self   :							int					,lowerCamelCase__   :							PreTrainedTokenizer					,lowerCamelCase__   :							int = -1					,lowerCamelCase__   :							int = -1					,lowerCamelCase__   :							bool = False					,lowerCamelCase__   :							Optional[TensorType] = None					,):







							'''simple docstring'''
							_UpperCamelCase   :						Optional[Any]												=  super(lowerCamelCase__					,self					).generate_dummy_inputs(
							    lowerCamelCase__					,batch_size=lowerCamelCase__					,seq_length=lowerCamelCase__					,is_pair=lowerCamelCase__					,framework=lowerCamelCase__					)

							# We need to order the input in the way they appears in the forward()
							_UpperCamelCase   :						int												=  OrderedDict({'input_ids': common_inputs['input_ids']}					)

							# Need to add the past_keys
							if self.use_past:
													if not is_torch_available():
																			raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'					)
													else:
																			import torch

																			_UpperCamelCase							,     _UpperCamelCase   :						str												=  common_inputs['input_ids'].shape
																			# Not using the same length for past_key_values
																			_UpperCamelCase   :						List[Any]												=  seqlen + 2
																			_UpperCamelCase   :						Optional[int]												=  (
																			    batch,
																			    self.num_attention_heads,
																			    past_key_values_length,
																			    self._config.hidden_size // self.num_attention_heads,
																			)
																			_UpperCamelCase   :						Dict												=  [
																			    (torch.zeros(lowerCamelCase__					), torch.zeros(lowerCamelCase__					)) for _ in range(self.num_layers					)
																			]

							_UpperCamelCase   :						List[Any]												=  common_inputs['attention_mask']
							if self.use_past:
													_UpperCamelCase   :						Tuple												=  ordered_inputs['attention_mask'].dtype
													_UpperCamelCase   :						Dict												=  torch.cat(
													    [ordered_inputs['attention_mask'], torch.ones(lowerCamelCase__					,lowerCamelCase__					,dtype=lowerCamelCase__					)]					,dim=1					)

							return ordered_inputs





	@property
	def       UpperCamelCase_    (					self   :							List[str]					):







							'''simple docstring'''
							return 13







'''simple docstring'''
import json
import os
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union

import sentencepiece

from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer
from ...utils import logging


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

snake_case_					:      Tuple    			=    '▁'

snake_case_					:      List[str]    			=    {
    'vocab_file': 'vocab.json',
    'spm_file': 'sentencepiece.bpe.model',
    'tokenizer_config_file': 'tokenizer_config.json',
}

snake_case_					:      Tuple    			=    {
    'vocab_file': {
        'facebook/m2m100_418M': 'https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json',
        'facebook/m2m100_1.2B': 'https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json',
    },
    'spm_file': {
        'facebook/m2m100_418M': 'https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model',
        'facebook/m2m100_1.2B': 'https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model',
    },
    'tokenizer_config_file': {
        'facebook/m2m100_418M': 'https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json',
        'facebook/m2m100_1.2B': 'https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json',
    },
}

snake_case_					:      Union[str, Any]    			=    {
    'facebook/m2m100_418M': 1024,
}

# fmt: off
snake_case_					:      List[Any]    			=    {
    'm2m100': ['af', 'am', 'ar', 'ast', 'az', 'ba', 'be', 'bg', 'bn', 'br', 'bs', 'ca', 'ceb', 'cs', 'cy', 'da', 'de', 'el', 'en', 'es', 'et', 'fa', 'ff', 'fi', 'fr', 'fy', 'ga', 'gd', 'gl', 'gu', 'ha', 'he', 'hi', 'hr', 'ht', 'hu', 'hy', 'id', 'ig', 'ilo', 'is', 'it', 'ja', 'jv', 'ka', 'kk', 'km', 'kn', 'ko', 'lb', 'lg', 'ln', 'lo', 'lt', 'lv', 'mg', 'mk', 'ml', 'mn', 'mr', 'ms', 'my', 'ne', 'nl', 'no', 'ns', 'oc', 'or', 'pa', 'pl', 'ps', 'pt', 'ro', 'ru', 'sd', 'si', 'sk', 'sl', 'so', 'sq', 'sr', 'ss', 'su', 'sv', 'sw', 'ta', 'th', 'tl', 'tn', 'tr', 'uk', 'ur', 'uz', 'vi', 'wo', 'xh', 'yi', 'yo', 'zh', 'zu'],
    'wmt21': ['en', 'ha', 'is', 'ja', 'cs', 'ru', 'zh', 'de']
}






class 				lowercase__      (				lowercase  ):
	lowercase__    							=     VOCAB_FILES_NAMES
	lowercase__    							=     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	lowercase__    							=     PRETRAINED_VOCAB_FILES_MAP
	lowercase__    							=     ["""input_ids""", """attention_mask"""]

	lowercase__    							=     []
	lowercase__    							=     []





	def __init__(					self   :							Union[str, Any]					,lowerCamelCase__   :							List[str]					,lowerCamelCase__   :							List[str]					,lowerCamelCase__   :							Dict=None					,lowerCamelCase__   :							Optional[int]=None					,lowerCamelCase__   :							Optional[int]="<s>"					,lowerCamelCase__   :							Optional[int]="</s>"					,lowerCamelCase__   :							str="</s>"					,lowerCamelCase__   :							Union[str, Any]="<pad>"					,lowerCamelCase__   :							Optional[int]="<unk>"					,lowerCamelCase__   :							str="m2m100"					,lowerCamelCase__   :							Optional[Dict[str, Any]] = None					,lowerCamelCase__   :							Optional[Any]=8					,**lowerCamelCase__   :							str					,):







							'''simple docstring'''
							_UpperCamelCase   :						int												=  {} if sp_model_kwargs is None else sp_model_kwargs

							_UpperCamelCase   :						Optional[int]												=  language_codes
							_UpperCamelCase   :						Union[str, Any]												=  FAIRSEQ_LANGUAGE_CODES[language_codes]
							_UpperCamelCase   :						str												=  {lang_code: F'__{lang_code}__' for lang_code in fairseq_language_code}

							_UpperCamelCase   :						Optional[Any]												=  kwargs.get('additional_special_tokens'					,[]					)
							kwargs["additional_special_tokens"] += [
							    self.get_lang_token(lowerCamelCase__					)
							    for lang_code in fairseq_language_code
							    if self.get_lang_token(lowerCamelCase__					) not in kwargs["additional_special_tokens"]
							]

							super().__init__(
							    src_lang=lowerCamelCase__					,tgt_lang=lowerCamelCase__					,bos_token=lowerCamelCase__					,eos_token=lowerCamelCase__					,sep_token=lowerCamelCase__					,unk_token=lowerCamelCase__					,pad_token=lowerCamelCase__					,language_codes=lowerCamelCase__					,sp_model_kwargs=self.sp_model_kwargs					,num_madeup_words=lowerCamelCase__					,**lowerCamelCase__					,)

							_UpperCamelCase   :						Any												=  vocab_file
							_UpperCamelCase   :						int												=  load_json(lowerCamelCase__					)
							_UpperCamelCase   :						int												=  {v: k for k, v in self.encoder.items()}
							_UpperCamelCase   :						Any												=  spm_file
							_UpperCamelCase   :						Optional[Any]												=  load_spm(lowerCamelCase__					,self.sp_model_kwargs					)

							_UpperCamelCase   :						Union[str, Any]												=  len(self.encoder					)

							_UpperCamelCase   :						Dict												=  {
							    self.get_lang_token(lowerCamelCase__					): self.encoder_size + i for i, lang_code in enumerate(lowerCamelCase__					)
							}
							_UpperCamelCase   :						Any												=  {lang_code: self.encoder_size + i for i, lang_code in enumerate(lowerCamelCase__					)}
							_UpperCamelCase   :						Dict												=  {v: k for k, v in self.lang_token_to_id.items()}

							_UpperCamelCase   :						Any												=  src_lang if src_lang is not None else 'en'
							_UpperCamelCase   :						int												=  tgt_lang
							_UpperCamelCase   :						Optional[int]												=  self.get_lang_id(self._src_lang					)
							self.set_src_lang_special_tokens(self._src_lang					)

							_UpperCamelCase   :						List[Any]												=  num_madeup_words





	@property
	def       UpperCamelCase_    (					self   :							int					):







							'''simple docstring'''
							return len(self.encoder					) + len(self.lang_token_to_id					)





	@property
	def       UpperCamelCase_    (					self   :							Optional[int]					):







							'''simple docstring'''
							return self._src_lang





	@src_lang.setter
	def       UpperCamelCase_    (					self   :							List[Any]					,lowerCamelCase__   :							str					):







							'''simple docstring'''
							_UpperCamelCase   :						Tuple												=  new_src_lang
							self.set_src_lang_special_tokens(self._src_lang					)





	def       UpperCamelCase_    (					self   :							Union[str, Any]					,lowerCamelCase__   :							str					):







							'''simple docstring'''
							return self.sp_model.encode(lowerCamelCase__					,out_type=lowerCamelCase__					)





	def       UpperCamelCase_    (					self   :							Union[str, Any]					,lowerCamelCase__   :							str					):







							'''simple docstring'''
							if token in self.lang_token_to_id:
													return self.lang_token_to_id[token]
							return self.encoder.get(lowerCamelCase__					,self.encoder[self.unk_token]					)





	def       UpperCamelCase_    (					self   :							List[str]					,lowerCamelCase__   :							int					):







							'''simple docstring'''
							if index in self.id_to_lang_token:
													return self.id_to_lang_token[index]
							return self.decoder.get(lowerCamelCase__					,self.unk_token					)





	def       UpperCamelCase_    (					self   :							List[str]					,lowerCamelCase__   :							Union[str, Any]					):







							'''simple docstring'''
							_UpperCamelCase   :						List[Any]												=  []
							_UpperCamelCase   :						Union[str, Any]												=  ''
							for token in tokens:
													# make sure that special tokens are not decoded using sentencepiece model
													if token in self.all_special_tokens:
																			out_string += self.sp_model.decode(lowerCamelCase__					) + token
																			_UpperCamelCase   :						Optional[int]												=  []
													else:
																			current_sub_tokens.append(lowerCamelCase__					)
							out_string += self.sp_model.decode(lowerCamelCase__					)
							return out_string.strip()





	def       UpperCamelCase_    (					self   :							List[str]					,lowerCamelCase__   :							List[int]					,lowerCamelCase__   :							Optional[List[int]] = None					,lowerCamelCase__   :							bool = False					):







							'''simple docstring'''

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

							_UpperCamelCase   :						Tuple												=  [1] * len(self.prefix_tokens					)
							_UpperCamelCase   :						str												=  [1] * len(self.suffix_tokens					)
							if token_ids_a is None:
													return prefix_ones + ([0] * len(lowerCamelCase__					)) + suffix_ones
							return prefix_ones + ([0] * len(lowerCamelCase__					)) + ([0] * len(lowerCamelCase__					)) + suffix_ones





	def       UpperCamelCase_    (					self   :							List[str]					,lowerCamelCase__   :							List[int]					,lowerCamelCase__   :							Optional[List[int]] = None					):







							'''simple docstring'''
							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   :							Dict					):







							'''simple docstring'''
							_UpperCamelCase   :						List[Any]												=  {self.convert_ids_to_tokens(lowerCamelCase__					): i for i in range(self.vocab_size					)}
							vocab.update(self.added_tokens_encoder					)
							return vocab





	def __getstate__(					self   :							Any					):







							'''simple docstring'''
							_UpperCamelCase   :						Dict												=  self.__dict__.copy()
							_UpperCamelCase   :						int												=  None
							return state





	def __setstate__(					self   :							Optional[int]					,lowerCamelCase__   :							Dict					):







							'''simple docstring'''
							_UpperCamelCase   :						Dict												=  d

							# for backward compatibility
							if not hasattr(self					,'sp_model_kwargs'					):
													_UpperCamelCase   :						int												=  {}

							_UpperCamelCase   :						Dict												=  load_spm(self.spm_file					,self.sp_model_kwargs					)





	def       UpperCamelCase_    (					self   :							str					,lowerCamelCase__   :							str					,lowerCamelCase__   :							Optional[str] = None					):







							'''simple docstring'''
							_UpperCamelCase   :						int												=  Path(lowerCamelCase__					)
							if not save_dir.is_dir():
													raise OSError(F'{save_directory} should be a directory'					)
							_UpperCamelCase   :						List[str]												=  save_dir / (
							    (filename_prefix + '-' if filename_prefix else '') + self.vocab_files_names['vocab_file']
							)
							_UpperCamelCase   :						Optional[Any]												=  save_dir / (
							    (filename_prefix + '-' if filename_prefix else '') + self.vocab_files_names['spm_file']
							)

							save_json(self.encoder					,lowerCamelCase__					)

							if os.path.abspath(self.spm_file					) != os.path.abspath(lowerCamelCase__					) and os.path.isfile(self.spm_file					):
													copyfile(self.spm_file					,lowerCamelCase__					)
							elif not os.path.isfile(self.spm_file					):
													with open(lowerCamelCase__					,'wb'					) as fi:
																			_UpperCamelCase   :						Union[str, Any]												=  self.sp_model.serialized_model_proto()
																			fi.write(lowerCamelCase__					)

							return (str(lowerCamelCase__					), str(lowerCamelCase__					))





	def       UpperCamelCase_    (					self   :							Tuple					,lowerCamelCase__   :							List[str]					,lowerCamelCase__   :							str = "en"					,lowerCamelCase__   :							Optional[List[str]] = None					,lowerCamelCase__   :							str = "ro"					,**lowerCamelCase__   :							List[Any]					,):







							'''simple docstring'''
							_UpperCamelCase   :						Optional[Any]												=  src_lang
							_UpperCamelCase   :						Any												=  tgt_lang
							self.set_src_lang_special_tokens(self.src_lang					)
							return super().prepare_seqaseq_batch(lowerCamelCase__					,lowerCamelCase__					,**lowerCamelCase__					)





	def       UpperCamelCase_    (					self   :							int					,lowerCamelCase__   :							List[str]					,lowerCamelCase__   :							Optional[str]					,lowerCamelCase__   :							Optional[str]					,**lowerCamelCase__   :							Optional[int]					):







							'''simple docstring'''
							if src_lang is None or tgt_lang is None:
													raise ValueError('Translation requires a `src_lang` and a `tgt_lang` for this model'					)
							_UpperCamelCase   :						int												=  src_lang
							_UpperCamelCase   :						Any												=  self(lowerCamelCase__					,add_special_tokens=lowerCamelCase__					,**lowerCamelCase__					)
							_UpperCamelCase   :						List[Any]												=  self.get_lang_id(lowerCamelCase__					)
							_UpperCamelCase   :						Any												=  tgt_lang_id
							return inputs





	def       UpperCamelCase_    (					self   :							Dict					):







							'''simple docstring'''
							self.set_src_lang_special_tokens(self.src_lang					)





	def       UpperCamelCase_    (					self   :							str					):







							'''simple docstring'''
							self.set_tgt_lang_special_tokens(self.tgt_lang					)





	def       UpperCamelCase_    (					self   :							str					,lowerCamelCase__   :							str					):







							'''simple docstring'''
							_UpperCamelCase   :						Union[str, Any]												=  self.get_lang_token(lowerCamelCase__					)
							_UpperCamelCase   :						str												=  self.lang_token_to_id[lang_token]
							_UpperCamelCase   :						Any												=  [self.cur_lang_id]
							_UpperCamelCase   :						Union[str, Any]												=  [self.eos_token_id]





	def       UpperCamelCase_    (					self   :							List[Any]					,lowerCamelCase__   :							str					):







							'''simple docstring'''
							_UpperCamelCase   :						Optional[Any]												=  self.get_lang_token(lowerCamelCase__					)
							_UpperCamelCase   :						Union[str, Any]												=  self.lang_token_to_id[lang_token]
							_UpperCamelCase   :						Union[str, Any]												=  [self.cur_lang_id]
							_UpperCamelCase   :						List[str]												=  [self.eos_token_id]





	def       UpperCamelCase_    (					self   :							Any					,lowerCamelCase__   :							str					):







							'''simple docstring'''
							return self.lang_code_to_token[lang]





	def       UpperCamelCase_    (					self   :							List[Any]					,lowerCamelCase__   :							str					):







							'''simple docstring'''
							_UpperCamelCase   :						List[str]												=  self.get_lang_token(lowerCamelCase__					)
							return self.lang_token_to_id[lang_token]






def A__       (	UpperCAmelCase_    ,    UpperCAmelCase_				):
						_UpperCamelCase   :						Union[str, Any]												=  sentencepiece.SentencePieceProcessor(**UpperCAmelCase_				)
						spm.Load(str(UpperCAmelCase_				)				)
						return spm






def A__       (	UpperCAmelCase_				):
						with open(UpperCAmelCase_    ,    'r'				) as f:
												return json.load(UpperCAmelCase_				)






def A__       (	UpperCAmelCase_    ,    UpperCAmelCase_				):
						with open(UpperCAmelCase_    ,    'w'				) as f:
												json.dump(UpperCAmelCase_    ,    UpperCAmelCase_    ,    indent=2				)


