





import argparse
import csv
import logging
import os
import random

import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
from tqdm import tqdm, trange

from transformers import (
    CONFIG_NAME,
    WEIGHTS_NAME,
    AdamW,
    OpenAIGPTDoubleHeadsModel,
    OpenAIGPTTokenizer,
    get_linear_schedule_with_warmup,
)


logging.basicConfig(
    format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO
)
snake_case								=							logging.getLogger(__name__)

def 				SCREAMING_SNAKE_CASE__							(	snake_case__	:Optional[Any]      ,				snake_case__	:Dict  )   ->    Tuple:
  _lowercase						    =			np.argmax(UpperCAmelCase_      ,				axis=1  )
  return np.sum(outputs == labels  )

def 				SCREAMING_SNAKE_CASE__							(	snake_case__	:List[Any]  )   ->    int:
  with open(UpperCAmelCase_      ,				encoding='utf_8'  ) as f:
    _lowercase						    =			csv.reader(UpperCAmelCase_  )
    _lowercase						    =			[]
    next(UpperCAmelCase_  )  # skip the first line
    for line in tqdm(UpperCAmelCase_  ):
      output.append((' '.join(line[1:5]  ), line[5], line[6], int(line[-1]  ) - 1)  )
  return output

def 				SCREAMING_SNAKE_CASE__							(	snake_case__	:int      ,				snake_case__	:Optional[int]      ,				snake_case__	:List[Any]      ,				snake_case__	:Any      ,				snake_case__	:int      ,				snake_case__	:Tuple  )   ->    Union[str, Any]:
  _lowercase						    =			[]
  for dataset in encoded_datasets:
    _lowercase						    =			len(UpperCAmelCase_  )
    _lowercase						    =			np.zeros((n_batch, 2, input_len)      ,				dtype=np.intaa  )
    _lowercase						    =			np.zeros((n_batch, 2)      ,				dtype=np.intaa  )
    _lowercase						    =			np.full((n_batch, 2, input_len)      ,				fill_value=-100      ,				dtype=np.intaa  )
    _lowercase						    =			np.zeros((n_batch,)      ,				dtype=np.intaa  )
    for (
        i,
        (story, conta, conta, mc_label),
    ) in enumerate(UpperCAmelCase_  ):
      _lowercase						    =			[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
      _lowercase						    =			[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
      _lowercase						    =			with_conta
      _lowercase						    =			with_conta
      _lowercase						    =			len(UpperCAmelCase_  ) - 1
      _lowercase						    =			len(UpperCAmelCase_  ) - 1
      _lowercase						    =			with_conta
      _lowercase						    =			with_conta
      _lowercase						    =			mc_label
    _lowercase						    =			(input_ids, mc_token_ids, lm_labels, mc_labels)
    tensor_datasets.append(tuple(torch.tensor(UpperCAmelCase_  ) for t in all_inputs  )  )
  return tensor_datasets

def 				SCREAMING_SNAKE_CASE__							(	)   ->    List[str]:
  _lowercase						    =			argparse.ArgumentParser()
  parser.add_argument('--model_name'      ,				type=UpperCAmelCase_      ,				default='openai-gpt'      ,				help='pretrained model name'  )
  parser.add_argument('--do_train'      ,				action='store_true'      ,				help='Whether to run training.'  )
  parser.add_argument('--do_eval'      ,				action='store_true'      ,				help='Whether to run eval on the dev set.'  )
  parser.add_argument(
      '--output_dir'      ,				default=UpperCAmelCase_      ,				type=UpperCAmelCase_      ,				required=UpperCAmelCase_      ,				help='The output directory where the model predictions and checkpoints will be written.'      ,				)
  parser.add_argument('--train_dataset'      ,				type=UpperCAmelCase_      ,				default=''  )
  parser.add_argument('--eval_dataset'      ,				type=UpperCAmelCase_      ,				default=''  )
  parser.add_argument('--seed'      ,				type=UpperCAmelCase_      ,				default=42  )
  parser.add_argument('--num_train_epochs'      ,				type=UpperCAmelCase_      ,				default=3  )
  parser.add_argument('--train_batch_size'      ,				type=UpperCAmelCase_      ,				default=8  )
  parser.add_argument('--eval_batch_size'      ,				type=UpperCAmelCase_      ,				default=16  )
  parser.add_argument('--adam_epsilon'      ,				default=1E-8      ,				type=UpperCAmelCase_      ,				help='Epsilon for Adam optimizer.'  )
  parser.add_argument('--max_grad_norm'      ,				type=UpperCAmelCase_      ,				default=1  )
  parser.add_argument(
      '--max_steps'      ,				default=-1      ,				type=UpperCAmelCase_      ,				help=(
          'If > 0: set total number of training                         steps to perform. Override num_train_epochs.'
      )      ,				)
  parser.add_argument(
      '--gradient_accumulation_steps'      ,				type=UpperCAmelCase_      ,				default=1      ,				help='Number of updates steps to accumulate before                        performing a backward/update pass.'      ,				)
  parser.add_argument('--learning_rate'      ,				type=UpperCAmelCase_      ,				default=6.25E-5  )
  parser.add_argument('--warmup_steps'      ,				default=0      ,				type=UpperCAmelCase_      ,				help='Linear warmup over warmup_steps.'  )
  parser.add_argument('--lr_schedule'      ,				type=UpperCAmelCase_      ,				default='warmup_linear'  )
  parser.add_argument('--weight_decay'      ,				type=UpperCAmelCase_      ,				default=0.01  )
  parser.add_argument('--lm_coef'      ,				type=UpperCAmelCase_      ,				default=0.9  )
  parser.add_argument('--n_valid'      ,				type=UpperCAmelCase_      ,				default=374  )

  parser.add_argument('--server_ip'      ,				type=UpperCAmelCase_      ,				default=''      ,				help='Can be used for distant debugging.'  )
  parser.add_argument('--server_port'      ,				type=UpperCAmelCase_      ,				default=''      ,				help='Can be used for distant debugging.'  )
  _lowercase						    =			parser.parse_args()
  print(UpperCAmelCase_  )

  if args.server_ip and args.server_port:
    # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
    import ptvsd

    print('Waiting for debugger attach'  )
    ptvsd.enable_attach(address=(args.server_ip, args.server_port)      ,				redirect_output=UpperCAmelCase_  )
    ptvsd.wait_for_attach()

  random.seed(args.seed  )
  np.random.seed(args.seed  )
  torch.manual_seed(args.seed  )
  torch.cuda.manual_seed_all(args.seed  )

  _lowercase						    =			torch.device('cuda' if torch.cuda.is_available() else 'cpu'  )
  _lowercase						    =			torch.cuda.device_count()
  logger.info('device: {}, n_gpu {}'.format(UpperCAmelCase_      ,				UpperCAmelCase_  )  )

  if not args.do_train and not args.do_eval:
    raise ValueError('At least one of `do_train` or `do_eval` must be True.'  )

  if not os.path.exists(args.output_dir  ):
    os.makedirs(args.output_dir  )

  # Load tokenizer and model
  # This loading functions also add new tokens and embeddings called `special tokens`
  # These new embeddings will be fine-tuned on the RocStories dataset
  _lowercase						    =			['_start_', '_delimiter_', '_classify_']
  _lowercase						    =			OpenAIGPTTokenizer.from_pretrained(args.model_name  )
  tokenizer.add_tokens(UpperCAmelCase_  )
  _lowercase						    =			tokenizer.convert_tokens_to_ids(UpperCAmelCase_  )
  _lowercase						    =			OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name  )
  model.resize_token_embeddings(len(UpperCAmelCase_  )  )
  model.to(UpperCAmelCase_  )

  # Load and encode the datasets
  def tokenize_and_encode(snake_case__	:Optional[int]  ):
    if isinstance(UpperCAmelCase_      ,				UpperCAmelCase_  ):
      return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(UpperCAmelCase_  )  )
    elif isinstance(UpperCAmelCase_      ,				UpperCAmelCase_  ):
      return obj
    return [tokenize_and_encode(UpperCAmelCase_  ) for o in obj]

  logger.info('Encoding dataset...'  )
  _lowercase						    =			load_rocstories_dataset(args.train_dataset  )
  _lowercase						    =			load_rocstories_dataset(args.eval_dataset  )
  _lowercase						    =			(train_dataset, eval_dataset)
  _lowercase						    =			tokenize_and_encode(UpperCAmelCase_  )

  # Compute the max input length for the Transformer
  _lowercase						    =			model.config.n_positions // 2 - 2
  _lowercase						    =			max(
      len(story[:max_length]  ) + max(len(conta[:max_length]  )      ,				len(conta[:max_length]  )  ) + 3
      for dataset in encoded_datasets
      for story, conta, conta, _ in dataset  )
  _lowercase						    =			min(UpperCAmelCase_      ,				model.config.n_positions  )  # Max size of input for the pre-trained model

  # Prepare inputs tensors and dataloaders
  _lowercase						    =			pre_process_datasets(UpperCAmelCase_      ,				UpperCAmelCase_      ,				UpperCAmelCase_      ,				*UpperCAmelCase_  )
  _lowercase						    =			tensor_datasets[0], tensor_datasets[1]

  _lowercase						    =			TensorDataset(*UpperCAmelCase_  )
  _lowercase						    =			RandomSampler(UpperCAmelCase_  )
  _lowercase						    =			DataLoader(UpperCAmelCase_      ,				sampler=UpperCAmelCase_      ,				batch_size=args.train_batch_size  )

  _lowercase						    =			TensorDataset(*UpperCAmelCase_  )
  _lowercase						    =			SequentialSampler(UpperCAmelCase_  )
  _lowercase						    =			DataLoader(UpperCAmelCase_      ,				sampler=UpperCAmelCase_      ,				batch_size=args.eval_batch_size  )

  # Prepare optimizer
  if args.do_train:
    if args.max_steps > 0:
      _lowercase						    =			args.max_steps
      _lowercase						    =			args.max_steps // (len(UpperCAmelCase_  ) // args.gradient_accumulation_steps) + 1
    else:
      _lowercase						    =			len(UpperCAmelCase_  ) // args.gradient_accumulation_steps * args.num_train_epochs

    _lowercase						    =			list(model.named_parameters()  )
    _lowercase						    =			['bias', 'LayerNorm.bias', 'LayerNorm.weight']
    _lowercase						    =			[
        {
            'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay  )],
            'weight_decay': args.weight_decay,
        },
        {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay  )], 'weight_decay': 0.0},
    ]
    _lowercase						    =			AdamW(UpperCAmelCase_      ,				lr=args.learning_rate      ,				eps=args.adam_epsilon  )
    _lowercase						    =			get_linear_schedule_with_warmup(
        UpperCAmelCase_      ,				num_warmup_steps=args.warmup_steps      ,				num_training_steps=UpperCAmelCase_  )

  if args.do_train:
    _lowercase						    =			0, 0, None
    model.train()
    for _ in trange(int(args.num_train_epochs  )      ,				desc='Epoch'  ):
      _lowercase						    =			0
      _lowercase						    =			0
      _lowercase						    =			tqdm(UpperCAmelCase_      ,				desc='Training'  )
      for step, batch in enumerate(UpperCAmelCase_  ):
        _lowercase						    =			tuple(t.to(UpperCAmelCase_  ) for t in batch  )
        _lowercase						    =			batch
        _lowercase						    =			model(UpperCAmelCase_      ,				mc_token_ids=UpperCAmelCase_      ,				lm_labels=UpperCAmelCase_      ,				mc_labels=UpperCAmelCase_  )
        _lowercase						    =			args.lm_coef * losses[0] + losses[1]
        loss.backward()
        optimizer.step()
        scheduler.step()
        optimizer.zero_grad()
        tr_loss += loss.item()
        _lowercase						    =			(
            loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item()
        )
        nb_tr_steps += 1
        _lowercase						    =			'Training loss: {:.2e} lr: {:.2e}'.format(UpperCAmelCase_      ,				scheduler.get_lr()[0]  )

    # Save a trained model
  if args.do_train:
    # Save a trained model, configuration and tokenizer
    _lowercase						    =			model.module if hasattr(UpperCAmelCase_      ,				'module'  ) else model  # Only save the model itself

    # If we save using the predefined names, we can load using `from_pretrained`
    _lowercase						    =			os.path.join(args.output_dir      ,				UpperCAmelCase_  )
    _lowercase						    =			os.path.join(args.output_dir      ,				UpperCAmelCase_  )

    torch.save(model_to_save.state_dict()      ,				UpperCAmelCase_  )
    model_to_save.config.to_json_file(UpperCAmelCase_  )
    tokenizer.save_vocabulary(args.output_dir  )

    # Load a trained model and vocabulary that you have fine-tuned
    _lowercase						    =			OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir  )
    _lowercase						    =			OpenAIGPTTokenizer.from_pretrained(args.output_dir  )
    model.to(UpperCAmelCase_  )

  if args.do_eval:
    model.eval()
    _lowercase						    =			0, 0
    _lowercase						    =			0, 0
    for batch in tqdm(UpperCAmelCase_      ,				desc='Evaluating'  ):
      _lowercase						    =			tuple(t.to(UpperCAmelCase_  ) for t in batch  )
      _lowercase						    =			batch
      with torch.no_grad():
        _lowercase						    =			model(
            UpperCAmelCase_      ,				mc_token_ids=UpperCAmelCase_      ,				lm_labels=UpperCAmelCase_      ,				mc_labels=UpperCAmelCase_  )

      _lowercase						    =			mc_logits.detach().cpu().numpy()
      _lowercase						    =			mc_labels.to('cpu'  ).numpy()
      _lowercase						    =			accuracy(UpperCAmelCase_      ,				UpperCAmelCase_  )

      eval_loss += mc_loss.mean().item()
      eval_accuracy += tmp_eval_accuracy

      nb_eval_examples += input_ids.size(0  )
      nb_eval_steps += 1

    _lowercase						    =			eval_loss / nb_eval_steps
    _lowercase						    =			eval_accuracy / nb_eval_examples
    _lowercase						    =			tr_loss / nb_tr_steps if args.do_train else None
    _lowercase						    =			{'eval_loss': eval_loss, 'eval_accuracy': eval_accuracy, 'train_loss': train_loss}

    _lowercase						    =			os.path.join(args.output_dir      ,				'eval_results.txt'  )
    with open(UpperCAmelCase_      ,				'w'  ) as writer:
      logger.info('***** Eval results *****'  )
      for key in sorted(result.keys()  ):
        logger.info('  %s = %s'      ,				UpperCAmelCase_      ,				str(result[key]  )  )
        writer.write('%s = %s\n' % (key, str(result[key]  ))  )


if __name__ == "__main__":
      main()




'''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				)


