

"""simple docstring"""





import argparse
import logging
import os
from pathlib import Path
from typing import Any, Dict

import pytorch_lightning as pl
from pytorch_lightning.utilities import rank_zero_info

from transformers import (
    AdamW,
    AutoConfig,
    AutoModel,
    AutoModelForPreTraining,
    AutoModelForQuestionAnswering,
    AutoModelForSeqaSeqLM,
    AutoModelForSequenceClassification,
    AutoModelForTokenClassification,
    AutoModelWithLMHead,
    AutoTokenizer,
    PretrainedConfig,
    PreTrainedTokenizer,
)
from transformers.optimization import (
    Adafactor,
    get_cosine_schedule_with_warmup,
    get_cosine_with_hard_restarts_schedule_with_warmup,
    get_linear_schedule_with_warmup,
    get_polynomial_decay_schedule_with_warmup,
)
from transformers.utils.versions import require_version


__UpperCamelCase    : Union[str, Any]				 =						logging.getLogger(__name__)

require_version('''pytorch_lightning>=1.0.4''')

__UpperCamelCase    : Any				 =						{
    '''base''': AutoModel,
    '''sequence-classification''': AutoModelForSequenceClassification,
    '''question-answering''': AutoModelForQuestionAnswering,
    '''pretraining''': AutoModelForPreTraining,
    '''token-classification''': AutoModelForTokenClassification,
    '''language-modeling''': AutoModelWithLMHead,
    '''summarization''': AutoModelForSeqaSeqLM,
    '''translation''': AutoModelForSeqaSeqLM,
}


# update this and the import above to support new schedulers from transformers.optimization
__UpperCamelCase    : Union[str, Any]				 =						{
    '''linear''': get_linear_schedule_with_warmup,
    '''cosine''': get_cosine_schedule_with_warmup,
    '''cosine_w_restarts''': get_cosine_with_hard_restarts_schedule_with_warmup,
    '''polynomial''': get_polynomial_decay_schedule_with_warmup,
    # '': get_constant_schedule,             # not supported for now
    # '': get_constant_schedule_with_warmup, # not supported for now
}
__UpperCamelCase    : Dict				 =						sorted(arg_to_scheduler.keys())
__UpperCamelCase    : Any				 =						'''{''' + ''', '''.join(arg_to_scheduler_choices) + '''}'''







class 							SCREAMING_SNAKE_CASE   (						pl.LightningModule			):






					"""simple docstring"""



					def __init__(			self     :							Dict  ,lowercase_     :							argparse.Namespace  ,lowercase_     :							Optional[Any]=None  ,lowercase_     :							Optional[Any]="base"  ,lowercase_     :							int=None  ,lowercase_     :							Optional[Any]=None  ,lowercase_     :							Optional[Any]=None  ,**lowercase_     :							Dict  ,):
						super().__init__()
						# TODO: move to self.save_hyperparameters()
						# self.save_hyperparameters()
						# can also expand arguments into trainer signature for easier reading

						self.save_hyperparameters(lowercase_						)
						lowerCAmelCase__      :		Optional[int]    							=      0
						lowerCAmelCase__      :		int    							=      Path(self.hparams.output_dir						)
						lowerCAmelCase__      :		Optional[int]    							=      self.hparams.cache_dir if self.hparams.cache_dir else None
						if config is None:
							lowerCAmelCase__      :		Optional[int]    							=      AutoConfig.from_pretrained(
							    self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path  ,**({'''num_labels''': num_labels} if num_labels is not None else {})  ,cache_dir=lowercase_  ,**lowercase_  ,)
						else:
							lowerCAmelCase__      :		PretrainedConfig    							=      config

						lowerCAmelCase__      :		Tuple    							=      ('''encoder_layerdrop''', '''decoder_layerdrop''', '''dropout''', '''attention_dropout''')
						for p in extra_model_params:
							if getattr(self.hparams  ,lowercase_  ,lowercase_						):
								assert hasattr(self.config  ,lowercase_						), F'model config doesn\'t have a `{p}` attribute'
								setattr(self.config  ,lowercase_  ,getattr(self.hparams  ,lowercase_						)						)

						if tokenizer is None:
							lowerCAmelCase__      :		Tuple    							=      AutoTokenizer.from_pretrained(
							    self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path  ,cache_dir=lowercase_  ,)
						else:
							lowerCAmelCase__      :		PreTrainedTokenizer    							=      tokenizer
						lowerCAmelCase__      :		List[str]    							=      MODEL_MODES[mode]
						if model is None:
							lowerCAmelCase__      :		Dict    							=      self.model_type.from_pretrained(
							    self.hparams.model_name_or_path  ,from_tf=bool('''.ckpt''' in self.hparams.model_name_or_path						)  ,config=self.config  ,cache_dir=lowercase_  ,)
						else:
							lowerCAmelCase__      :		str    							=      model







					def 			__lowerCAmelCase					(			self     :							List[str]  ,*lowercase_     :							str  ,**lowercase_     :							Optional[int]						):
						lowerCAmelCase__      :		List[Any]    							=      self.model_type.from_pretrained(*lowercase_  ,**lowercase_						)







					def 			__lowerCAmelCase					(			self     :							List[Any]						):
						lowerCAmelCase__      :		str    							=      arg_to_scheduler[self.hparams.lr_scheduler]
						lowerCAmelCase__      :		List[str]    							=      get_schedule_func(
						    self.opt  ,num_warmup_steps=self.hparams.warmup_steps  ,num_training_steps=self.total_steps()						)
						lowerCAmelCase__      :		str    							=      {'''scheduler''': scheduler, '''interval''': '''step''', '''frequency''': 1}
						return scheduler







					def 			__lowerCAmelCase					(			self     :							Optional[int]						):
						lowerCAmelCase__      :		Dict    							=      self.model
						lowerCAmelCase__      :		Tuple    							=      ['''bias''', '''LayerNorm.weight''']
						lowerCAmelCase__      :		int    							=      [
						    {
						        '''params''': [
						            p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay						)
						        ],  # check this named paramters
						        '''weight_decay''': self.hparams.weight_decay,
						    },
						    {
						        '''params''': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay						)],
						        '''weight_decay''': 0.0,
						    },
						]
						if self.hparams.adafactor:
							lowerCAmelCase__      :		Tuple    							=      Adafactor(
							    lowercase_  ,lr=self.hparams.learning_rate  ,scale_parameter=lowercase_  ,relative_step=lowercase_						)

						else:
							lowerCAmelCase__      :		Dict    							=      AdamW(
							    lowercase_  ,lr=self.hparams.learning_rate  ,eps=self.hparams.adam_epsilon						)
						lowerCAmelCase__      :		Optional[Any]    							=      optimizer

						lowerCAmelCase__      :		Dict    							=      self.get_lr_scheduler()

						return [optimizer], [scheduler]







					def 			__lowerCAmelCase					(			self     :							Tuple  ,lowercase_     :							Dict  ,lowercase_     :							List[str]						):
						return self.validation_step(lowercase_  ,lowercase_						)







					def 			__lowerCAmelCase					(			self     :							Tuple  ,lowercase_     :							List[Any]						):
						return self.validation_end(lowercase_						)







					def 			__lowerCAmelCase					(			self     :							List[str]						):
						lowerCAmelCase__      :		List[Any]    							=      max(1  ,self.hparams.gpus						)  # TODO: consider num_tpu_cores
						lowerCAmelCase__      :		Dict    							=      self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices
						return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs







					def 			__lowerCAmelCase					(			self     :							Union[str, Any]  ,lowercase_     :							List[Any]						):
						if stage == "test":
							lowerCAmelCase__      :		int    							=      len(self.test_dataloader().dataset						)
						else:
							lowerCAmelCase__      :		Optional[Any]    							=      self.get_dataloader('''train'''  ,self.hparams.train_batch_size  ,shuffle=lowercase_						)
							lowerCAmelCase__      :		Optional[int]    							=      len(self.train_dataloader().dataset						)







					def 			__lowerCAmelCase					(			self     :							int  ,lowercase_     :							str  ,lowercase_     :							int  ,lowercase_     :							bool = False						):
						raise NotImplementedError('''You must implement this for your task'''						)







					def 			__lowerCAmelCase					(			self     :							Tuple						):
						return self.train_loader







					def 			__lowerCAmelCase					(			self     :							Optional[Any]						):
						return self.get_dataloader('''dev'''  ,self.hparams.eval_batch_size  ,shuffle=lowercase_						)







					def 			__lowerCAmelCase					(			self     :							Dict						):
						return self.get_dataloader('''test'''  ,self.hparams.eval_batch_size  ,shuffle=lowercase_						)







					def 			__lowerCAmelCase					(			self     :							Optional[Any]  ,lowercase_     :							Optional[Any]						):
						return os.path.join(
						    self.hparams.data_dir  ,'''cached_{}_{}_{}'''.format(
						        lowercase_  ,list(filter(lowercase_  ,self.hparams.model_name_or_path.split('''/'''						)						)						).pop()  ,str(self.hparams.max_seq_length						)  ,)  ,)







					@pl.utilities.rank_zero_only
					def 			__lowerCAmelCase					(			self     :							List[Any]  ,lowercase_     :							Dict[str, Any]						):
						lowerCAmelCase__      :		Optional[int]    							=      self.output_dir.joinpath('''best_tfmr'''						)
						lowerCAmelCase__      :		Dict    							=      self.step_count
						self.model.save_pretrained(lowercase_						)
						self.tokenizer.save_pretrained(lowercase_						)







					@staticmethod
					def 			__lowerCAmelCase					(			lowercase_     :							Any  ,lowercase_     :							Dict						):
						parser.add_argument(
						    '''--model_name_or_path'''  ,default=lowercase_  ,type=lowercase_  ,required=lowercase_  ,help='''Path to pretrained model or model identifier from huggingface.co/models'''  ,)
						parser.add_argument(
						    '''--config_name'''  ,default=''''''  ,type=lowercase_  ,help='''Pretrained config name or path if not the same as model_name'''						)
						parser.add_argument(
						    '''--tokenizer_name'''  ,default=lowercase_  ,type=lowercase_  ,help='''Pretrained tokenizer name or path if not the same as model_name'''  ,)
						parser.add_argument(
						    '''--cache_dir'''  ,default=str(Path(lowercase_						).parent / '''test_run''' / '''cache'''						)  ,type=lowercase_  ,help='''Where do you want to store the pre-trained models downloaded from huggingface.co'''  ,)
						parser.add_argument(
						    '''--encoder_layerdrop'''  ,type=lowercase_  ,help='''Encoder layer dropout probability (Optional). Goes into model.config'''  ,)
						parser.add_argument(
						    '''--decoder_layerdrop'''  ,type=lowercase_  ,help='''Decoder layer dropout probability (Optional). Goes into model.config'''  ,)
						parser.add_argument(
						    '''--dropout'''  ,type=lowercase_  ,help='''Dropout probability (Optional). Goes into model.config'''  ,)
						parser.add_argument(
						    '''--attention_dropout'''  ,type=lowercase_  ,help='''Attention dropout probability (Optional). Goes into model.config'''  ,)
						parser.add_argument('''--learning_rate'''  ,default=5E-5  ,type=lowercase_  ,help='''The initial learning rate for Adam.'''						)
						parser.add_argument(
						    '''--lr_scheduler'''  ,default='''linear'''  ,choices=lowercase_  ,metavar=lowercase_  ,type=lowercase_  ,help='''Learning rate scheduler'''  ,)
						parser.add_argument('''--weight_decay'''  ,default=0.0  ,type=lowercase_  ,help='''Weight decay if we apply some.'''						)
						parser.add_argument('''--adam_epsilon'''  ,default=1E-8  ,type=lowercase_  ,help='''Epsilon for Adam optimizer.'''						)
						parser.add_argument('''--warmup_steps'''  ,default=0  ,type=lowercase_  ,help='''Linear warmup over warmup_steps.'''						)
						parser.add_argument('''--num_workers'''  ,default=4  ,type=lowercase_  ,help='''kwarg passed to DataLoader'''						)
						parser.add_argument('''--num_train_epochs'''  ,dest='''max_epochs'''  ,default=3  ,type=lowercase_						)
						parser.add_argument('''--train_batch_size'''  ,default=3_2  ,type=lowercase_						)
						parser.add_argument('''--eval_batch_size'''  ,default=3_2  ,type=lowercase_						)
						parser.add_argument('''--adafactor'''  ,action='''store_true'''						)







class 							SCREAMING_SNAKE_CASE   (						pl.Callback			):






					"""simple docstring"""



					def 			__lowerCAmelCase					(			self     :							Optional[int]  ,lowercase_     :							Union[str, Any]  ,lowercase_     :							List[Any]						):
						if (
						    trainer.is_global_zero and trainer.global_rank == 0
						):  # we initialize the retriever only on master worker with RAY. In new pytorch-lightning accelorators are removed.
							pl_module.model.rag.retriever.init_retrieval()  # better to use hook functions.







class 							SCREAMING_SNAKE_CASE   (						pl.Callback			):






					"""simple docstring"""



					def 			__lowerCAmelCase					(			self     :							Optional[int]  ,lowercase_     :							List[Any]  ,lowercase_     :							Dict						):
						# print(pl_module.model.rag)
						for name, param in pl_module.model.rag.named_parameters():
							if param.grad is None:
								print(lowercase_						)







class 							SCREAMING_SNAKE_CASE   (						pl.Callback			):






					"""simple docstring"""



					def 			__lowerCAmelCase					(			self     :							List[Any]  ,lowercase_     :							Optional[Any]  ,lowercase_     :							Optional[int]						):
						lowerCAmelCase__      :		List[str]    							=      trainer.lr_schedulers[0]['''scheduler''']
						lowerCAmelCase__      :		Optional[int]    							=      {F'lr_group_{i}': lr for i, lr in enumerate(lr_scheduler.get_lr()						)}
						pl_module.logger.log_metrics(lowercase_						)







					def 			__lowerCAmelCase					(			self     :							int  ,lowercase_     :							pl.Trainer  ,lowercase_     :							pl.LightningModule						):
						rank_zero_info('''***** Validation results *****'''						)
						lowerCAmelCase__      :		List[Any]    							=      trainer.callback_metrics
						# Log results
						for key in sorted(lowercase_						):
							if key not in ["log", "progress_bar"]:
								rank_zero_info('''{} = {}\n'''.format(lowercase_  ,str(metrics[key]						)						)						)







					def 			__lowerCAmelCase					(			self     :							List[str]  ,lowercase_     :							pl.Trainer  ,lowercase_     :							pl.LightningModule						):
						rank_zero_info('''***** Test results *****'''						)
						lowerCAmelCase__      :		List[Any]    							=      trainer.callback_metrics
						# Log and save results to file
						lowerCAmelCase__      :		str    							=      os.path.join(pl_module.hparams.output_dir  ,'''test_results.txt'''						)
						with open(lowercase_  ,'''w'''						) as writer:
							for key in sorted(lowercase_						):
								if key not in ["log", "progress_bar"]:
									rank_zero_info('''{} = {}\n'''.format(lowercase_  ,str(metrics[key]						)						)						)
									writer.write('''{} = {}\n'''.format(lowercase_  ,str(metrics[key]						)						)						)

def     __SCREAMING_SNAKE_CASE    ( A_		,	A_					):
	#  To allow all pl args uncomment the following line
	#  parser = pl.Trainer.add_argparse_args(parser)
	parser.add_argument(
	    '''--output_dir'''		,	default=str(Path(A_					).parent / '''test_run''' / '''model_checkpoints'''					)		,	type=A_		,	help='''The output directory where the model predictions and checkpoints will be written.'''		,	)
	parser.add_argument(
	    '''--fp16'''		,	action='''store_true'''		,	help='''Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit'''		,	)

	parser.add_argument(
	    '''--fp16_opt_level'''		,	type=A_		,	default='''O2'''		,	help=(
	        '''For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].'''
	        '''See details at https://nvidia.github.io/apex/amp.html'''
	    )		,	)
	parser.add_argument('''--n_tpu_cores'''		,	dest='''tpu_cores'''		,	type=A_					)
	parser.add_argument('''--max_grad_norm'''		,	dest='''gradient_clip_val'''		,	default=1.0		,	type=A_		,	help='''Max gradient norm'''					)
	parser.add_argument('''--do_train'''		,	action='''store_true'''		,	help='''Whether to run training.'''					)
	parser.add_argument('''--do_predict'''		,	action='''store_true'''		,	help='''Whether to run predictions on the test set.'''					)
	parser.add_argument(
	    '''--gradient_accumulation_steps'''		,	dest='''accumulate_grad_batches'''		,	type=A_		,	default=1		,	help='''Number of updates steps to accumulate before performing a backward/update pass.'''		,	)
	parser.add_argument('''--seed'''		,	type=A_		,	default=42		,	help='''random seed for initialization'''					)
	parser.add_argument(
	    '''--data_dir'''		,	default=str(Path(A_					).parent / '''test_run''' / '''dummy-train-data'''					)		,	type=A_		,	help='''The input data dir. Should contain the training files for the CoNLL-2003 NER task.'''		,	)





def     __SCREAMING_SNAKE_CASE    ( A_		,	A_		,	A_=None		,	A_=True		,	A_=[]		,	A_=None		,	A_=None		,	**A_		,	):
	pl.seed_everything(args.seed					)

	# init model
	lowerCAmelCase__      :		Optional[int]    							=      Path(model.hparams.output_dir					)
	odir.mkdir(exist_ok=A_					)

	# add custom checkpoints
	if checkpoint_callback is None:
		lowerCAmelCase__      :		Optional[Any]    							=      pl.callbacks.ModelCheckpoint(
		    filepath=args.output_dir		,	prefix='''checkpoint'''		,	monitor='''val_loss'''		,	mode='''min'''		,	save_top_k=1					)
	if early_stopping_callback:
		extra_callbacks.append(A_					)
	if logging_callback is None:
		lowerCAmelCase__      :		Optional[int]    							=      LoggingCallback()

	lowerCAmelCase__      :		Optional[Any]    							=      {}

	if args.fpaa:
		lowerCAmelCase__      :		int    							=      16

	if args.gpus > 1:
		lowerCAmelCase__      :		List[Any]    							=      '''auto'''
		lowerCAmelCase__      :		Optional[Any]    							=      '''ddp'''

	lowerCAmelCase__      :		str    							=      args.accumulate_grad_batches
	lowerCAmelCase__      :		Tuple    							=      None
	lowerCAmelCase__      :		List[str]    							=      '''auto'''

	lowerCAmelCase__      :		Dict    							=      pl.Trainer.from_argparse_args(
	    A_		,	weights_summary=A_		,	callbacks=[logging_callback] + extra_callbacks + [InitCallback()] + [checkpoint_callback]		,	logger=A_		,	val_check_interval=1		,	num_sanity_val_steps=2		,	**A_		,	)

	if args.do_train:
		trainer.fit(A_					)

	else:
		print('''RAG modeling tests with new set functions successfuly executed!'''					)
	return trainer







"""simple docstring"""





import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_distilbert import DistilBertTokenizer


__UpperCamelCase    : List[Any]				 =						logging.get_logger(__name__)

__UpperCamelCase    : Dict				 =						{'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''}

__UpperCamelCase    : List[Any]				 =						{
    '''vocab_file''': {
        '''distilbert-base-uncased''': '''https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt''',
        '''distilbert-base-uncased-distilled-squad''': (
            '''https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt'''
        ),
        '''distilbert-base-cased''': '''https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt''',
        '''distilbert-base-cased-distilled-squad''': (
            '''https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt'''
        ),
        '''distilbert-base-german-cased''': '''https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt''',
        '''distilbert-base-multilingual-cased''': (
            '''https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt'''
        ),
    },
    '''tokenizer_file''': {
        '''distilbert-base-uncased''': '''https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json''',
        '''distilbert-base-uncased-distilled-squad''': (
            '''https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json'''
        ),
        '''distilbert-base-cased''': '''https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json''',
        '''distilbert-base-cased-distilled-squad''': (
            '''https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json'''
        ),
        '''distilbert-base-german-cased''': (
            '''https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json'''
        ),
        '''distilbert-base-multilingual-cased''': (
            '''https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json'''
        ),
    },
}

__UpperCamelCase    : Union[str, Any]				 =						{
    '''distilbert-base-uncased''': 5_1_2,
    '''distilbert-base-uncased-distilled-squad''': 5_1_2,
    '''distilbert-base-cased''': 5_1_2,
    '''distilbert-base-cased-distilled-squad''': 5_1_2,
    '''distilbert-base-german-cased''': 5_1_2,
    '''distilbert-base-multilingual-cased''': 5_1_2,
}


__UpperCamelCase    : int				 =						{
    '''distilbert-base-uncased''': {'''do_lower_case''': True},
    '''distilbert-base-uncased-distilled-squad''': {'''do_lower_case''': True},
    '''distilbert-base-cased''': {'''do_lower_case''': False},
    '''distilbert-base-cased-distilled-squad''': {'''do_lower_case''': False},
    '''distilbert-base-german-cased''': {'''do_lower_case''': False},
    '''distilbert-base-multilingual-cased''': {'''do_lower_case''': False},
}







class 							SCREAMING_SNAKE_CASE   (						a_			):






					"""simple docstring"""



					lowercase__												=			VOCAB_FILES_NAMES
					lowercase__												=			PRETRAINED_VOCAB_FILES_MAP
					lowercase__												=			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
					lowercase__												=			PRETRAINED_INIT_CONFIGURATION
					lowercase__												=			["input_ids", "attention_mask"]
					lowercase__												=			DistilBertTokenizer







					def __init__(			self     :							int  ,lowercase_     :							List[str]=None  ,lowercase_     :							int=None  ,lowercase_     :							str=True  ,lowercase_     :							Union[str, Any]="[UNK]"  ,lowercase_     :							List[str]="[SEP]"  ,lowercase_     :							List[str]="[PAD]"  ,lowercase_     :							List[str]="[CLS]"  ,lowercase_     :							List[str]="[MASK]"  ,lowercase_     :							Tuple=True  ,lowercase_     :							Tuple=None  ,**lowercase_     :							str  ,):
						super().__init__(
						    lowercase_  ,tokenizer_file=lowercase_  ,do_lower_case=lowercase_  ,unk_token=lowercase_  ,sep_token=lowercase_  ,pad_token=lowercase_  ,cls_token=lowercase_  ,mask_token=lowercase_  ,tokenize_chinese_chars=lowercase_  ,strip_accents=lowercase_  ,**lowercase_  ,)

						lowerCAmelCase__      :		Tuple    							=      json.loads(self.backend_tokenizer.normalizer.__getstate__()						)
						if (
						    normalizer_state.get('''lowercase'''  ,lowercase_						) != do_lower_case
						    or normalizer_state.get('''strip_accents'''  ,lowercase_						) != strip_accents
						    or normalizer_state.get('''handle_chinese_chars'''  ,lowercase_						) != tokenize_chinese_chars
						):
							lowerCAmelCase__      :		Union[str, Any]    							=      getattr(lowercase_  ,normalizer_state.pop('''type'''						)						)
							lowerCAmelCase__      :		Optional[int]    							=      do_lower_case
							lowerCAmelCase__      :		List[str]    							=      strip_accents
							lowerCAmelCase__      :		int    							=      tokenize_chinese_chars
							lowerCAmelCase__      :		Dict    							=      normalizer_class(**lowercase_						)

						lowerCAmelCase__      :		Tuple    							=      do_lower_case







					def 			__lowerCAmelCase					(			self     :							str  ,lowercase_     :							Tuple  ,lowercase_     :							Optional[Any]=None						):
						lowerCAmelCase__      :		Any    							=      [self.cls_token_id] + token_ids_a + [self.sep_token_id]

						if token_ids_a:
							output += token_ids_a + [self.sep_token_id]

						return output







					def 			__lowerCAmelCase					(			self     :							int  ,lowercase_     :							List[int]  ,lowercase_     :							Optional[List[int]] = None						):
						lowerCAmelCase__      :		Dict    							=      [self.sep_token_id]
						lowerCAmelCase__      :		Dict    							=      [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						) * [0] + len(token_ids_a + sep						) * [1]







					def 			__lowerCAmelCase					(			self     :							Any  ,lowercase_     :							str  ,lowercase_     :							Optional[str] = None						):
						lowerCAmelCase__      :		Any    							=      self._tokenizer.model.save(lowercase_  ,name=lowercase_						)
						return tuple(lowercase_						)




