
"""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    =		logging.get_logger(__name__)

snake_case    =		{
    'gpt2': 'https://huggingface.co/gpt2/resolve/main/config.json',
    'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/config.json',
    'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/config.json',
    'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/config.json',
    'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/config.json',
}




class      UpperCamelCase	(       __magic_name__      ):

				"""simple docstring"""



				UpperCAmelCase_				:      List[str]						  =				"gpt2"
				UpperCAmelCase_				:      Any						  =				["past_key_values"]
				UpperCAmelCase_				:      Any						  =				{
				    "hidden_size": "n_embd",
				    "max_position_embeddings": "n_positions",
				    "num_attention_heads": "n_head",
				    "num_hidden_layers": "n_layer",
				}


				def __init__(				self		,	lowercase__=50257		,	lowercase__=1024		,	lowercase__=768		,	lowercase__=12		,	lowercase__=12		,	lowercase__=None		,	lowercase__="gelu_new"		,	lowercase__=0.1		,	lowercase__=0.1		,	lowercase__=0.1		,	lowercase__=1E-5		,	lowercase__=0.02		,	lowercase__="cls_index"		,	lowercase__=True		,	lowercase__=None		,	lowercase__=True		,	lowercase__=0.1		,	lowercase__=True		,	lowercase__=True		,	lowercase__=50256		,	lowercase__=50256		,	lowercase__=False		,	lowercase__=False		,	**lowercase__		,	)    ->    Dict:
									"""simple docstring"""







									SCREAMING_SNAKE_CASE				=	vocab_size
									SCREAMING_SNAKE_CASE				=	n_positions
									SCREAMING_SNAKE_CASE				=	n_embd
									SCREAMING_SNAKE_CASE				=	n_layer
									SCREAMING_SNAKE_CASE				=	n_head
									SCREAMING_SNAKE_CASE				=	n_inner
									SCREAMING_SNAKE_CASE				=	activation_function
									SCREAMING_SNAKE_CASE				=	resid_pdrop
									SCREAMING_SNAKE_CASE				=	embd_pdrop
									SCREAMING_SNAKE_CASE				=	attn_pdrop
									SCREAMING_SNAKE_CASE				=	layer_norm_epsilon
									SCREAMING_SNAKE_CASE				=	initializer_range
									SCREAMING_SNAKE_CASE				=	summary_type
									SCREAMING_SNAKE_CASE				=	summary_use_proj
									SCREAMING_SNAKE_CASE				=	summary_activation
									SCREAMING_SNAKE_CASE				=	summary_first_dropout
									SCREAMING_SNAKE_CASE				=	summary_proj_to_labels
									SCREAMING_SNAKE_CASE				=	scale_attn_weights
									SCREAMING_SNAKE_CASE				=	use_cache
									SCREAMING_SNAKE_CASE				=	scale_attn_by_inverse_layer_idx
									SCREAMING_SNAKE_CASE				=	reorder_and_upcast_attn

									SCREAMING_SNAKE_CASE				=	bos_token_id
									SCREAMING_SNAKE_CASE				=	eos_token_id

									super().__init__(bos_token_id=lowercase__		,	eos_token_id=lowercase__		,	**lowercase__			)






class      UpperCamelCase	(       __magic_name__      ):

				"""simple docstring"""



				def __init__(				self		,	lowercase__		,	lowercase__ = "default"		,	lowercase__ = None		,	lowercase__ = False		,	)    ->    Union[str, Any]:
									"""simple docstring"""







									super().__init__(lowercase__		,	task=lowercase__		,	patching_specs=lowercase__		,	use_past=lowercase__			)
									if not getattr(self._config		,	'pad_token_id'		,	lowercase__			):
														# TODO: how to do that better?
														SCREAMING_SNAKE_CASE				=	0


				@property
				def 							A					(				self			)    ->    Mapping[str, Mapping[int, str]]:
									"""simple docstring"""







									SCREAMING_SNAKE_CASE				=	OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}}			)
									if self.use_past:
														self.fill_with_past_key_values_(lowercase__		,	direction='inputs'			)
														SCREAMING_SNAKE_CASE				=	{0: 'batch', 1: 'past_sequence + sequence'}
									else:
														SCREAMING_SNAKE_CASE				=	{0: 'batch', 1: 'sequence'}

									return common_inputs


				@property
				def 							A					(				self			)    ->    int:
									"""simple docstring"""







									return self._config.n_layer


				@property
				def 							A					(				self			)    ->    int:
									"""simple docstring"""







									return self._config.n_head


				def 							A					(				self		,	lowercase__		,	lowercase__ = -1		,	lowercase__ = -1		,	lowercase__ = False		,	lowercase__ = None		,	)    ->    Mapping[str, Any]:
									"""simple docstring"""







									SCREAMING_SNAKE_CASE				=	super(lowercase__		,	self			).generate_dummy_inputs(
									    lowercase__		,	batch_size=lowercase__		,	seq_length=lowercase__		,	is_pair=lowercase__		,	framework=lowercase__			)

									# We need to order the input in the way they appears in the forward()
									SCREAMING_SNAKE_CASE				=	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

																			SCREAMING_SNAKE_CASE	,    SCREAMING_SNAKE_CASE				=	common_inputs['input_ids'].shape
																			# Not using the same length for past_key_values
																			SCREAMING_SNAKE_CASE				=	seqlen + 2
																			SCREAMING_SNAKE_CASE				=	(
																			    batch,
																			    self.num_attention_heads,
																			    past_key_values_length,
																			    self._config.hidden_size // self.num_attention_heads,
																			)
																			SCREAMING_SNAKE_CASE				=	[
																			    (torch.zeros(lowercase__			), torch.zeros(lowercase__			)) for _ in range(self.num_layers			)
																			]

									SCREAMING_SNAKE_CASE				=	common_inputs['attention_mask']
									if self.use_past:
														SCREAMING_SNAKE_CASE				=	ordered_inputs['attention_mask'].dtype
														SCREAMING_SNAKE_CASE				=	torch.cat(
														    [ordered_inputs['attention_mask'], torch.ones(lowercase__		,	lowercase__		,	dtype=lowercase__			)]		,	dim=1			)

									return ordered_inputs




				@property
				def 							A					(				self			)    ->    int:
									"""simple docstring"""







									return 13


"""simple docstring"""




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

from ...tokenization_utils_fast import AddedToken, PreTrainedTokenizerFast
from ...utils import logging


snake_case    =		logging.get_logger(__name__)

snake_case    =		{'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'}

snake_case    =		{
    'vocab_file': {
        'TsinghuaAI/CPM-Generate': 'https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model',
    },
    'tokenizer_file': {
        'TsinghuaAI/CPM-Generate': 'https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/tokenizer.json',
    },
}




class      UpperCamelCase	(       __magic_name__      ):

				"""simple docstring"""



				def __init__(				self		,	lowercase__=None		,	lowercase__=None		,	lowercase__=False		,	lowercase__=True		,	lowercase__=False		,	lowercase__="<s>"		,	lowercase__="</s>"		,	lowercase__="<unk>"		,	lowercase__="<sep>"		,	lowercase__="<pad>"		,	lowercase__="<cls>"		,	lowercase__="<mask>"		,	lowercase__=["<eop>", "<eod>"]		,	**lowercase__		,	)    ->    int:
									"""simple docstring"""







									SCREAMING_SNAKE_CASE				=	AddedToken(lowercase__		,	lstrip=lowercase__		,	rstrip=lowercase__			) if isinstance(lowercase__		,	lowercase__			) else mask_token

									super().__init__(
									    vocab_file=lowercase__		,	tokenizer_file=lowercase__		,	do_lower_case=lowercase__		,	remove_space=lowercase__		,	keep_accents=lowercase__		,	bos_token=lowercase__		,	eos_token=lowercase__		,	unk_token=lowercase__		,	sep_token=lowercase__		,	pad_token=lowercase__		,	cls_token=lowercase__		,	mask_token=lowercase__		,	additional_special_tokens=lowercase__		,	**lowercase__		,	)

									SCREAMING_SNAKE_CASE				=	3
									SCREAMING_SNAKE_CASE				=	do_lower_case
									SCREAMING_SNAKE_CASE				=	remove_space
									SCREAMING_SNAKE_CASE				=	keep_accents
									SCREAMING_SNAKE_CASE				=	vocab_file
									SCREAMING_SNAKE_CASE				=	False if not self.vocab_file else True

									try:
														import jieba
									except ModuleNotFoundError as error:
														raise error.__class__(
														    'You need to install jieba to use CpmTokenizer or CpmTokenizerFast. '
														    'See https://pypi.org/project/jieba/ for installation.'			)
									SCREAMING_SNAKE_CASE				=	jieba
									SCREAMING_SNAKE_CASE				=	str.maketrans(' \n'		,	'\u2582\u2583'			)


				def 							A					(				self		,	lowercase__		,	lowercase__ = None			)    ->    List[int]:
									"""simple docstring"""







									SCREAMING_SNAKE_CASE				=	[self.sep_token_id]
									SCREAMING_SNAKE_CASE				=	[self.cls_token_id]
									if token_ids_a is None:
														return token_ids_a + sep + cls
									return token_ids_a + sep + token_ids_a + sep + cls


				def 							A					(				self		,	lowercase__		,	lowercase__ = None			)    ->    List[int]:
									"""simple docstring"""







									SCREAMING_SNAKE_CASE				=	[self.sep_token_id]
									SCREAMING_SNAKE_CASE				=	[2]

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


				def 							A					(				self		,	lowercase__		,	lowercase__ = None			)    ->    Tuple[str]:
									"""simple docstring"""







									if not self.can_save_slow_tokenizer:
														raise ValueError(
														    'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow '
														    'tokenizer.'			)

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

									if os.path.abspath(self.vocab_file			) != os.path.abspath(lowercase__			):
														copyfile(self.vocab_file		,	lowercase__			)

									return (out_vocab_file,)


				def 							A					(				self		,	lowercase__		,	*lowercase__		,	**lowercase__			)    ->    Any:
									"""simple docstring"""







									SCREAMING_SNAKE_CASE				=	[
									    ' '.join([x.translate(self.translator			) for x in self.jieba.cut(lowercase__		,	cut_all=lowercase__			)]			)
									    for text in batch_text_or_text_pairs
									]
									return super()._batch_encode_plus(lowercase__		,	*lowercase__		,	**lowercase__			)




				def 							A					(				self		,	*lowercase__		,	**lowercase__			)    ->    Optional[int]:
									"""simple docstring"""







									SCREAMING_SNAKE_CASE				=	super()._decode(*lowercase__		,	**lowercase__			)
									SCREAMING_SNAKE_CASE				=	text.replace(' '		,	''			).replace('\u2582'		,	' '			).replace('\u2583'		,	'\n'			)
									return text
