'''simple docstring'''




import os
import unicodedata
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

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


__SCREAMING_SNAKE_CASE       :     Union[str, Any]     =  logging.get_logger(__name__)
__SCREAMING_SNAKE_CASE       :     Tuple     =  {"""vocab_file""": """spiece.model"""}

__SCREAMING_SNAKE_CASE       :     int     =  {
    """vocab_file""": {
        """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""",
        """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""",
        """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""",
        """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""",
        """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""",
        """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""",
        """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""",
        """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""",
    }
}

__SCREAMING_SNAKE_CASE       :     int     =  {
    """albert-base-v1""": 512,
    """albert-large-v1""": 512,
    """albert-xlarge-v1""": 512,
    """albert-xxlarge-v1""": 512,
    """albert-base-v2""": 512,
    """albert-large-v2""": 512,
    """albert-xlarge-v2""": 512,
    """albert-xxlarge-v2""": 512,
}

__SCREAMING_SNAKE_CASE       :     Tuple     =  """▁"""

class 	lowerCamelCase_	(snake_case__    ):
      '''simple docstring'''

      __UpperCamelCase:  Tuple						=						VOCAB_FILES_NAMES
      __UpperCamelCase:  List[Any]						=						PRETRAINED_VOCAB_FILES_MAP
      __UpperCamelCase:  int						=						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES




      def __init__(       self						:				Dict						,					A						:				Optional[int]						,					A						:				Any=True						,					A						:				List[Any]=True						,					A						:				Optional[Any]=False						,					A						:				Any="[CLS]"						,					A						:				List[str]="[SEP]"						,					A						:				str="<unk>"						,					A						:				Any="[SEP]"						,					A						:				int="<pad>"						,					A						:				Union[str, Any]="[CLS]"						,					A						:				List[str]="[MASK]"						,					A						:				Optional[Dict[str, Any]] = None						,					**A						:				int						,					):
             # Mask token behave like a normal word, i.e. include the space before it and
             # is included in the raw text, there should be a match in a non-normalized sentence.
             _UpperCAmelCase     :  Any							      =    (
                 AddedToken(A						,					lstrip=A						,					rstrip=A						,					normalized=A       )
                 if isinstance(A						,					A       )
                 else mask_token
             )

             _UpperCAmelCase     :  Any							      =    {} if sp_model_kwargs is None else sp_model_kwargs

             super().__init__(
                 do_lower_case=A						,					remove_space=A						,					keep_accents=A						,					bos_token=A						,					eos_token=A						,					unk_token=A						,					sep_token=A						,					pad_token=A						,					cls_token=A						,					mask_token=A						,					sp_model_kwargs=self.sp_model_kwargs						,					**A						,					)

             _UpperCAmelCase     :  List[Any]							      =    do_lower_case
             _UpperCAmelCase     :  str							      =    remove_space
             _UpperCAmelCase     :  Optional[Any]							      =    keep_accents
             _UpperCAmelCase     :  Optional[int]							      =    vocab_file

             _UpperCAmelCase     :  Optional[int]							      =    spm.SentencePieceProcessor(**self.sp_model_kwargs       )
             self.sp_model.Load(A       )




      @property
      def      _A	(       self						:				str       ):
             return len(self.sp_model       )




      def      _A	(       self						:				Any       ):
             _UpperCAmelCase     :  Any							      =    {self.convert_ids_to_tokens(A       ): i for i in range(self.vocab_size       )}
             vocab.update(self.added_tokens_encoder       )
             return vocab




      def __getstate__(       self						:				Optional[int]       ):
             _UpperCAmelCase     :  int							      =    self.__dict__.copy()
             _UpperCAmelCase     :  List[str]							      =    None
             return state




      def __setstate__(       self						:				List[str]						,					A						:				int       ):
             _UpperCAmelCase     :  Dict							      =    d

             # for backward compatibility
             if not hasattr(self						,					"sp_model_kwargs"       ):
                    _UpperCAmelCase     :  Optional[int]							      =    {}

             _UpperCAmelCase     :  str							      =    spm.SentencePieceProcessor(**self.sp_model_kwargs       )
             self.sp_model.Load(self.vocab_file       )




      def      _A	(       self						:				List[Any]						,					A						:				Optional[int]       ):
             if self.remove_space:
                    _UpperCAmelCase     :  int							      =    " ".join(inputs.strip().split()       )
             else:
                    _UpperCAmelCase     :  Tuple							      =    inputs
             _UpperCAmelCase     :  Optional[Any]							      =    outputs.replace("``"						,					"\""       ).replace("''"						,					"\""       )

             if not self.keep_accents:
                    _UpperCAmelCase     :  Union[str, Any]							      =    unicodedata.normalize("NFKD"						,					A       )
                    _UpperCAmelCase     :  List[Any]							      =    "".join([c for c in outputs if not unicodedata.combining(A       )]       )
             if self.do_lower_case:
                    _UpperCAmelCase     :  int							      =    outputs.lower()

             return outputs




      def      _A	(       self						:				str						,					A						:				str       ):
             _UpperCAmelCase     :  Union[str, Any]							      =    self.preprocess_text(A       )
             _UpperCAmelCase     :  Optional[int]							      =    self.sp_model.encode(A						,					out_type=A       )
             _UpperCAmelCase     :  int							      =    []
             for piece in pieces:
                    if len(A       ) > 1 and piece[-1] == str(","       ) and piece[-2].isdigit():
                           _UpperCAmelCase     :  Dict							      =    self.sp_model.EncodeAsPieces(piece[:-1].replace(A						,					""       )       )
                           if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
                                  if len(cur_pieces[0]       ) == 1:
                                         _UpperCAmelCase     :  Optional[Any]							      =    cur_pieces[1:]
                                  else:
                                         _UpperCAmelCase     :  Dict							      =    cur_pieces[0][1:]
                           cur_pieces.append(piece[-1]       )
                           new_pieces.extend(A       )
                    else:
                           new_pieces.append(A       )

             return new_pieces




      def      _A	(       self						:				Union[str, Any]						,					A						:				Optional[Any]       ):
             return self.sp_model.PieceToId(A       )




      def      _A	(       self						:				int						,					A						:				Optional[Any]       ):
             return self.sp_model.IdToPiece(A       )




      def      _A	(       self						:				int						,					A						:				Tuple       ):
             _UpperCAmelCase     :  List[str]							      =    []
             _UpperCAmelCase     :  List[Any]							      =    ""
             _UpperCAmelCase     :  Tuple							      =    False
             for token in tokens:
                    # make sure that special tokens are not decoded using sentencepiece model
                    if token in self.all_special_tokens:
                           if not prev_is_special:
                                  out_string += " "
                           out_string += self.sp_model.decode(A       ) + token
                           _UpperCAmelCase     :  Optional[int]							      =    True
                           _UpperCAmelCase     :  List[str]							      =    []
                    else:
                           current_sub_tokens.append(A       )
                           _UpperCAmelCase     :  List[Any]							      =    False
             out_string += self.sp_model.decode(A       )
             return out_string.strip()




      def      _A	(       self						:				List[Any]						,					A						:				List[int]						,					A						:				Optional[List[int]] = None       ):
             _UpperCAmelCase     :  List[str]							      =    [self.sep_token_id]
             _UpperCAmelCase     :  Tuple							      =    [self.cls_token_id]
             if token_ids_a is None:
                    return cls + token_ids_a + sep
             return cls + token_ids_a + sep + token_ids_a + sep




      def      _A	(       self						:				Tuple						,					A						:				List[int]						,					A						:				Optional[List[int]] = None						,					A						:				bool = False       ):

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

             if token_ids_a is not None:
                    return [1] + ([0] * len(A       )) + [1] + ([0] * len(A       )) + [1]
             return [1] + ([0] * len(A       )) + [1]




      def      _A	(       self						:				int						,					A						:				List[int]						,					A						:				Optional[List[int]] = None       ):
             _UpperCAmelCase     :  Tuple							      =    [self.sep_token_id]
             _UpperCAmelCase     :  List[str]							      =    [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      _A	(       self						:				Union[str, Any]						,					A						:				str						,					A						:				Optional[str] = None       ):
             if not os.path.isdir(A       ):
                    logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""       )
                    return
             _UpperCAmelCase     :  Union[str, Any]							      =    os.path.join(
                 A						,					(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]       )

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

             return (out_vocab_file,)


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


__SCREAMING_SNAKE_CASE       :     str     =  logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE       :     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 	lowerCamelCase_	(snake_case__    ):
      '''simple docstring'''

      def __init__(       self						:				Any						,					A						:				Optional[int]=None						,					A						:				Tuple=None						,					*A						:				Tuple						,					**A						:				List[str]       ):
             super().__init__(*A						,					**A       )

             if config is None:
                    assert isinstance(self.model						,					A       ), (
                        "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is"
                        F""" {self.model.__class__}"""
                    )
                    _UpperCAmelCase     :  str							      =    self.model.config
             else:
                    _UpperCAmelCase     :  List[str]							      =    config

             _UpperCAmelCase     :  List[Any]							      =    data_args
             _UpperCAmelCase     :  str							      =    self.config.tgt_vocab_size if isinstance(self.config						,					A       ) 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:
                    _UpperCAmelCase     :  Optional[Any]							      =    torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id       )
             else:
                    # dynamically import label_smoothed_nll_loss
                    from utils import label_smoothed_nll_loss

                    _UpperCAmelCase     :  Dict							      =    label_smoothed_nll_loss




      def      _A	(       self						:				Tuple						,					A						:				int       ):
             if self.optimizer is None:
                    _UpperCAmelCase     :  Tuple							      =    ["bias", "LayerNorm.weight"]
                    _UpperCAmelCase     :  str							      =    [
                        {
                            "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,
                        },
                    ]
                    _UpperCAmelCase     :  int							      =    Adafactor if self.args.adafactor else AdamW
                    if self.args.adafactor:
                           _UpperCAmelCase     :  List[str]							      =    Adafactor
                           _UpperCAmelCase     :  List[Any]							      =    {"scale_parameter": False, "relative_step": False}
                    else:
                           _UpperCAmelCase     :  List[str]							      =    AdamW
                           _UpperCAmelCase     :  List[str]							      =    {
                               "betas": (self.args.adam_betaa, self.args.adam_betaa),
                               "eps": self.args.adam_epsilon,
                           }
                    _UpperCAmelCase     :  List[Any]							      =    self.args.learning_rate
                    if self.sharded_ddp:
                           _UpperCAmelCase     :  List[Any]							      =    OSS(
                               params=A						,					optim=A						,					**A						,					)
                    else:
                           _UpperCAmelCase     :  Union[str, Any]							      =    optimizer_cls(A						,					**A       )

             if self.lr_scheduler is None:
                    _UpperCAmelCase     :  List[str]							      =    self._get_lr_scheduler(A       )
             else:  # ignoring --lr_scheduler
                    logger.warning("scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored."       )




      def      _A	(       self						:				List[str]						,					A						:				Optional[int]       ):
             _UpperCAmelCase     :  List[str]							      =    arg_to_scheduler[self.args.lr_scheduler]
             if self.args.lr_scheduler == "constant":
                    _UpperCAmelCase     :  Optional[Any]							      =    schedule_func(self.optimizer       )
             elif self.args.lr_scheduler == "constant_w_warmup":
                    _UpperCAmelCase     :  str							      =    schedule_func(self.optimizer						,					num_warmup_steps=self.args.warmup_steps       )
             else:
                    _UpperCAmelCase     :  str							      =    schedule_func(
                        self.optimizer						,					num_warmup_steps=self.args.warmup_steps						,					num_training_steps=A       )
             return scheduler




      def      _A	(       self						:				Tuple       ):
             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						:				Any						,					A						:				Union[str, Any]						,					A						:				Union[str, Any]						,					A						:				List[Any]       ):
             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
                           _UpperCAmelCase     :  List[str]							      =    model(**A						,					use_cache=A       )[0]
                           _UpperCAmelCase     :  int							      =    self.loss_fn(logits.view(-1						,					logits.shape[-1]       )						,					labels.view(-1       )       )
                    else:
                           # compute usual loss via models
                           _UpperCAmelCase      ,  _UpperCAmelCase     :  Any							      =    model(**A						,					labels=A						,					use_cache=A       )[:2]
             else:
                    # compute label smoothed loss
                    _UpperCAmelCase     :  Optional[int]							      =    model(**A						,					use_cache=A       )[0]
                    _UpperCAmelCase     :  List[str]							      =    torch.nn.functional.log_softmax(A						,					dim=-1       )
                    _UpperCAmelCase      ,  _UpperCAmelCase     :  Union[str, Any]							      =    self.loss_fn(A						,					A						,					self.args.label_smoothing						,					ignore_index=self.config.pad_token_id       )
             return loss, logits




      def      _A	(       self						:				List[str]						,					A						:				Optional[int]						,					A						:				Optional[int]       ):
             _UpperCAmelCase     :  Union[str, Any]							      =    inputs.pop("labels"       )
             _UpperCAmelCase      ,  _UpperCAmelCase     :  Optional[int]							      =    self._compute_loss(A						,					A						,					A       )
             return loss




      def      _A	(       self						:				List[str]						,					A						:				nn.Module						,					A						:				Dict[str, Union[torch.Tensor, Any]]						,					A						:				bool						,					A						:				Optional[List[str]] = None						,					):
             _UpperCAmelCase     :  List[str]							      =    self._prepare_inputs(A       )

             _UpperCAmelCase     :  Dict							      =    {
                 "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:
                    _UpperCAmelCase     :  Dict							      =    self.model.generate(
                        inputs["input_ids"]						,					attention_mask=inputs["attention_mask"]						,					**A						,					)
                    # in case the batch is shorter than max length, the output should be padded
                    if generated_tokens.shape[-1] < gen_kwargs["max_length"]:
                           _UpperCAmelCase     :  int							      =    self._pad_tensors_to_max_len(A						,					gen_kwargs["max_length"]       )

             _UpperCAmelCase     :  Any							      =    inputs.pop("labels"       )
             with torch.no_grad():
                    # compute loss on predict data
                    _UpperCAmelCase      ,  _UpperCAmelCase     :  str							      =    self._compute_loss(A						,					A						,					A       )

             _UpperCAmelCase     :  List[str]							      =    loss.mean().detach()
             if self.args.prediction_loss_only:
                    return (loss, None, None)

             _UpperCAmelCase     :  str							      =    generated_tokens if self.args.predict_with_generate else logits

             if labels.shape[-1] < gen_kwargs["max_length"]:
                    _UpperCAmelCase     :  Optional[Any]							      =    self._pad_tensors_to_max_len(A						,					gen_kwargs["max_length"]       )

             return (loss, logits, labels)





      def      _A	(       self						:				Dict						,					A						:				int						,					A						:				List[str]       ):
             # If PAD token is not defined at least EOS token has to be defined
             _UpperCAmelCase     :  Union[str, Any]							      =    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}"""       )

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

