





'''simple docstring'''


from typing import Any, Dict, List, Optional, Tuple, Union

import torch
from torch import nn
from torch.utils.data import DistributedSampler, RandomSampler

from transformers import PreTrainedModel, Trainer, logging
from transformers.integrations import is_fairscale_available
from transformers.models.fsmt.configuration_fsmt import FSMTConfig
from transformers.optimization import (
    Adafactor,
    AdamW,
    get_constant_schedule,
    get_constant_schedule_with_warmup,
    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.trainer_pt_utils import get_tpu_sampler
from transformers.training_args import ParallelMode
from transformers.utils import is_torch_tpu_available


if is_fairscale_available():
		from fairscale.optim import OSS


lowerCAmelCase_   :   Dict       =					logging.get_logger(__name__)

lowerCAmelCase_   :   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,
    'constant': get_constant_schedule,
    'constant_w_warmup': get_constant_schedule_with_warmup,
}






class       UpperCamelCase__  (		UpperCamelCase_     ):







	def __init__(				self			:   Union[str, Any] , lowerCamelCase			:   Union[str, Any]=None , lowerCamelCase			:   Optional[int]=None , *lowerCamelCase			:   Dict , **lowerCamelCase			:   str		):




				'''simple docstring'''
				super().__init__(*UpperCamelCase__ , **UpperCamelCase__		)

				if config is None:
							assert isinstance(self.model , UpperCamelCase__		), (
							    "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is"
							    F''' {self.model.__class__}'''
							)
							a__     = self.model.config
				else:
							a__     = config

				a__     = data_args
				a__     = self.config.tgt_vocab_size if isinstance(self.config , UpperCamelCase__		) else self.config.vocab_size

				if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss):
							assert self.config.pad_token_id is not None, (
							    "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss"
							    " calculation or doing label smoothing."
							)

				if self.config.pad_token_id is None and self.config.eos_token_id is not None:
							logger.warning(
							    F'''The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for'''
							    " padding.."		)

				if self.args.label_smoothing == 0:
							a__     = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id		)
				else:
							# dynamically import label_smoothed_nll_loss
							from utils import label_smoothed_nll_loss

							a__     = label_smoothed_nll_loss







	def 						__a   (				self			:   Any , lowerCamelCase			:   int		):




				'''simple docstring'''





				if self.optimizer is None:
							a__     = ['''bias''', '''LayerNorm.weight''']
							a__     = [
							    {
							        '''params''': [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay		)],
							        '''weight_decay''': self.args.weight_decay,
							    },
							    {
							        '''params''': [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay		)],
							        '''weight_decay''': 0.0,
							    },
							]
							a__     = Adafactor if self.args.adafactor else AdamW
							if self.args.adafactor:
										a__     = Adafactor
										a__     = {'''scale_parameter''': False, '''relative_step''': False}
							else:
										a__     = AdamW
										a__     = {
										    '''betas''': (self.args.adam_betaa, self.args.adam_betaa),
										    '''eps''': self.args.adam_epsilon,
										}
							a__     = self.args.learning_rate
							if self.sharded_ddp:
										a__     = OSS(
										    params=UpperCamelCase__ , optim=UpperCamelCase__ , **UpperCamelCase__ , )
							else:
										a__     = optimizer_cls(UpperCamelCase__ , **UpperCamelCase__		)

				if self.lr_scheduler is None:
							a__     = self._get_lr_scheduler(UpperCamelCase__		)
				else:  # ignoring --lr_scheduler
							logger.warning("scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored."		)







	def 						__a   (				self			:   Union[str, Any] , lowerCamelCase			:   List[Any]		):




				'''simple docstring'''
				a__     = arg_to_scheduler[self.args.lr_scheduler]
				if self.args.lr_scheduler == "constant":
							a__     = schedule_func(self.optimizer		)
				elif self.args.lr_scheduler == "constant_w_warmup":
							a__     = schedule_func(self.optimizer , num_warmup_steps=self.args.warmup_steps		)
				else:
							a__     = schedule_func(
							    self.optimizer , num_warmup_steps=self.args.warmup_steps , num_training_steps=UpperCamelCase__		)
				return scheduler







	def 						__a   (				self			:   Any		):




				'''simple docstring'''





				if isinstance(self.train_dataset , torch.utils.data.IterableDataset		):
							return None
				elif is_torch_tpu_available():
							return get_tpu_sampler(self.train_dataset		)
				else:
							if self.args.sortish_sampler:
										self.train_dataset.make_sortish_sampler(
										    self.args.per_device_train_batch_size , distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) , )

							return (
							    RandomSampler(self.train_dataset		)
							    if self.args.local_rank == -1
							    else DistributedSampler(self.train_dataset		)
							)







	def 						__a   (				self			:   Union[str, Any] , lowerCamelCase			:   Tuple , lowerCamelCase			:   Union[str, Any] , lowerCamelCase			:   List[str]		):




				'''simple docstring'''





				if self.args.label_smoothing == 0:
							if self.data_args is not None and self.data_args.ignore_pad_token_for_loss:
										# force training to ignore pad token
										a__     = model(**UpperCamelCase__ , use_cache=UpperCamelCase__		)[0]
										a__     = self.loss_fn(logits.view(-1 , logits.shape[-1]		) , labels.view(-1		)		)
							else:
										# compute usual loss via models
										a__     = model(**UpperCamelCase__ , labels=UpperCamelCase__ , use_cache=UpperCamelCase__		)[:2]
				else:
							# compute label smoothed loss
							a__     = model(**UpperCamelCase__ , use_cache=UpperCamelCase__		)[0]
							a__     = torch.nn.functional.log_softmax(UpperCamelCase__ , dim=-1		)
							a__     = self.loss_fn(UpperCamelCase__ , UpperCamelCase__ , self.args.label_smoothing , ignore_index=self.config.pad_token_id		)
				return loss, logits







	def 						__a   (				self			:   str , lowerCamelCase			:   Dict , lowerCamelCase			:   Union[str, Any]		):




				'''simple docstring'''
				a__     = inputs.pop("labels"		)
				a__     = self._compute_loss(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__		)
				return loss







	def 						__a   (				self			:   str , lowerCamelCase			:   nn.Module , lowerCamelCase			:   Dict[str, Union[torch.Tensor, Any]] , lowerCamelCase			:   bool , lowerCamelCase			:   Optional[List[str]] = None , ):




				'''simple docstring'''
				a__     = self._prepare_inputs(UpperCamelCase__		)

				a__     = {
				    '''max_length''': self.data_args.val_max_target_length
				    if self.data_args is not None
				    else self.config.max_length,
				    '''num_beams''': self.data_args.eval_beams if self.data_args is not None else self.config.num_beams,
				}

				if self.args.predict_with_generate and not self.args.prediction_loss_only:
							a__     = self.model.generate(
							    inputs["input_ids"] , attention_mask=inputs["attention_mask"] , **UpperCamelCase__ , )
							# in case the batch is shorter than max length, the output should be padded
							if generated_tokens.shape[-1] < gen_kwargs["max_length"]:
										a__     = self._pad_tensors_to_max_len(UpperCamelCase__ , gen_kwargs["max_length"]		)

				a__     = inputs.pop("labels"		)
				with torch.no_grad():
							# compute loss on predict data
							a__     = self._compute_loss(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__		)

				a__     = loss.mean().detach()
				if self.args.prediction_loss_only:
							return (loss, None, None)

				a__     = generated_tokens if self.args.predict_with_generate else logits

				if labels.shape[-1] < gen_kwargs["max_length"]:
							a__     = self._pad_tensors_to_max_len(UpperCamelCase__ , gen_kwargs["max_length"]		)

				return (loss, logits, labels)







	def 						__a   (				self			:   List[str] , lowerCamelCase			:   Optional[int] , lowerCamelCase			:   Optional[int]		):




				'''simple docstring'''
				a__     = self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id

				if pad_token_id is None:
							raise ValueError(
							    "Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be"
							    F''' padded to `max_length`={max_length}'''		)

				a__     = pad_token_id * torch.ones(
				    (tensor.shape[0], max_length) , dtype=tensor.dtype , device=tensor.device		)
				a__     = tensor
				return padded_tensor










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


lowerCAmelCase_   :   str       =					logging.get_logger(__name__)

lowerCAmelCase_   :   Optional[Any]       =					"▁"

lowerCAmelCase_   :   Union[str, Any]       =					{"vocab_file": "sentencepiece.bpe.model"}

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

lowerCAmelCase_   :   Optional[int]       =					{
    "facebook/xglm-564M": 2048,
}






class       UpperCamelCase__  (		__lowerCAmelCase     ):
	lowerCAmelCase__					:			int								=						VOCAB_FILES_NAMES
	lowerCAmelCase__					:			Optional[int]								=						PRETRAINED_VOCAB_FILES_MAP
	lowerCAmelCase__					:			Tuple								=						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	lowerCAmelCase__					:			Optional[int]								=						["input_ids", "attention_mask"]







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




				'''simple docstring'''
				a__     = {} if sp_model_kwargs is None else sp_model_kwargs

				# Compatibility with the original tokenizer
				a__     = 7
				a__     = [F'''<madeupword{i}>''' for i in range(self.num_madeup_words		)]

				a__     = 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=lowerCamelCase , eos_token=lowerCamelCase , unk_token=lowerCamelCase , sep_token=lowerCamelCase , cls_token=lowerCamelCase , pad_token=lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **lowerCamelCase , )

				a__     = spm.SentencePieceProcessor(**self.sp_model_kwargs		)
				self.sp_model.Load(str(lowerCamelCase		)		)
				a__     = 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__     = 1

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

				a__     = len(self.sp_model		)
				a__     = {F'''<madeupword{i}>''': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words		)}
				self.fairseq_tokens_to_ids.update(lowerCamelCase		)

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







	def __getstate__(				self			:   Optional[Any]		):




				'''simple docstring'''
				a__     = self.__dict__.copy()
				a__     = None
				a__     = self.sp_model.serialized_model_proto()
				return state







	def __setstate__(				self			:   Dict , lowerCamelCase			:   List[Any]		):




				'''simple docstring'''
				a__     = d

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

				a__     = spm.SentencePieceProcessor(**self.sp_model_kwargs		)
				self.sp_model.LoadFromSerializedProto(self.sp_model_proto		)







	def 						__a   (				self			:   Union[str, Any] , lowerCamelCase			:   List[int] , lowerCamelCase			:   Optional[List[int]] = None		):




				'''simple docstring'''

				if token_ids_a is None:
							return [self.sep_token_id] + token_ids_a
				a__     = [self.sep_token_id]
				return sep + token_ids_a + sep + sep + token_ids_a







	def 						__a   (				self			:   int , 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		)

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







	def 						__a   (				self			:   Dict , lowerCamelCase			:   List[int] , lowerCamelCase			:   Optional[List[int]] = None		):




				'''simple docstring'''
				a__     = [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 						__a   (				self			:   List[str]		):




				'''simple docstring'''
				return len(self.sp_model		) + self.fairseq_offset + self.num_madeup_words







	def 						__a   (				self			:   Dict		):




				'''simple docstring'''
				a__     = {self.convert_ids_to_tokens(lowerCamelCase		): i for i in range(self.vocab_size		)}
				vocab.update(self.added_tokens_encoder		)
				return vocab







	def 						__a   (				self			:   int , lowerCamelCase			:   str		):




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







	def 						__a   (				self			:   List[str] , lowerCamelCase			:   Union[str, Any]		):




				'''simple docstring'''
				if token in self.fairseq_tokens_to_ids:
							return self.fairseq_tokens_to_ids[token]
				a__     = self.sp_model.PieceToId(lowerCamelCase		)

				# 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 						__a   (				self			:   Any , lowerCamelCase			:   List[str]		):




				'''simple docstring'''
				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 						__a   (				self			:   int , lowerCamelCase			:   Optional[Any]		):




				'''simple docstring'''
				a__     = "".join(lowerCamelCase		).replace(lowerCamelCase , " "		).strip()
				return out_string







	def 						__a   (				self			:   int , lowerCamelCase			:   str , lowerCamelCase			:   Optional[str] = None		):




				'''simple docstring'''
				if not os.path.isdir(lowerCamelCase		):
							logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''		)
							return
				a__     = os.path.join(
				    lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]		)

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

				return (out_vocab_file,)



