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


_lowercase						: Optional[Any]						=						logging.get_logger(__name__)

_lowercase						: 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     __magic_name__						(    _UpperCAmelCase):







			def __init__(	self				:  Dict				,			lowercase_				:  Optional[int]=None				,			lowercase_				:  Dict=None				,			*lowercase_				:  Optional[int]				,			**lowercase_				:  Any    ):
										super().__init__(*lowercase_				,			**lowercase_    )

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

										lowercase_					:			Tuple										=       data_args
										lowercase_					:			Optional[Any]										=       self.config.tgt_vocab_size if isinstance(self.config				,			lowercase_    ) 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:
																	lowercase_					:			List[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

																	lowercase_					:			Optional[Any]										=       label_smoothed_nll_loss







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

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







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Any				,			lowercase_				:  int    ):
										lowercase_					:			Any										=       arg_to_scheduler[self.args.lr_scheduler]
										if self.args.lr_scheduler == "constant":
																	lowercase_					:			Optional[int]										=       schedule_func(self.optimizer    )
										elif self.args.lr_scheduler == "constant_w_warmup":
																	lowercase_					:			Tuple										=       schedule_func(self.optimizer				,			num_warmup_steps=self.args.warmup_steps    )
										else:
																	lowercase_					:			Optional[int]										=       schedule_func(
																	    self.optimizer				,			num_warmup_steps=self.args.warmup_steps				,			num_training_steps=lowercase_    )
										return scheduler







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







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Optional[Any]				,			lowercase_				:  Union[str, Any]				,			lowercase_				:  Any    ):
										lowercase_					:			List[Any]										=       inputs.pop("""labels"""    )
										lowercase_						,						lowercase_					:			Optional[Any]										=       self._compute_loss(lowercase_				,			lowercase_				,			lowercase_    )
										return loss







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Optional[Any]				,			lowercase_				:  nn.Module				,			lowercase_				:  Dict[str, Union[torch.Tensor, Any]]				,			lowercase_				:  bool				,			lowercase_				:  Optional[List[str]] = None				,			):
										lowercase_					:			Optional[int]										=       self._prepare_inputs(lowercase_    )

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

										lowercase_					:			str										=       inputs.pop("""labels"""    )
										with torch.no_grad():
																	# compute loss on predict data
																	lowercase_						,						lowercase_					:			Union[str, Any]										=       self._compute_loss(lowercase_				,			lowercase_				,			lowercase_    )

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

										lowercase_					:			Optional[int]										=       generated_tokens if self.args.predict_with_generate else logits

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

										return (loss, logits, labels)







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Optional[Any]				,			lowercase_				:  int				,			lowercase_				:  int    ):
										# If PAD token is not defined at least EOS token has to be defined
										lowercase_					:			Optional[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}'''    )

										lowercase_					:			List[Any]										=       pad_token_id * torch.ones(
										    (tensor.shape[0], max_length)				,			dtype=tensor.dtype				,			device=tensor.device    )
										lowercase_					:			Dict										=       tensor
										return padded_tensor






'''simple docstring'''




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

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


if is_sentencepiece_available():
						from .tokenization_albert import AlbertTokenizer
else:
						_lowercase						: int						=						None

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

_lowercase						: Dict						=						{
    "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",
    },
    "tokenizer_file": {
        "albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/tokenizer.json",
        "albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/tokenizer.json",
        "albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/tokenizer.json",
        "albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/tokenizer.json",
        "albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/tokenizer.json",
        "albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/tokenizer.json",
        "albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/tokenizer.json",
        "albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/tokenizer.json",
    },
}

_lowercase						: 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,
}

_lowercase						: Tuple						=						"▁"





class     __magic_name__						(    _UpperCAmelCase):
			UpperCamelCase__				=       VOCAB_FILES_NAMES
			UpperCamelCase__				=       PRETRAINED_VOCAB_FILES_MAP
			UpperCamelCase__				=       PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			UpperCamelCase__				=       AlbertTokenizer







			def __init__(	self				:  Optional[Any]				,			lowercase_				:  Union[str, Any]=None				,			lowercase_				:  str=None				,			lowercase_				:  Any=True				,			lowercase_				:  Optional[int]=True				,			lowercase_				:  List[str]=False				,			lowercase_				:  Optional[int]="[CLS]"				,			lowercase_				:  Any="[SEP]"				,			lowercase_				:  int="<unk>"				,			lowercase_				:  Any="[SEP]"				,			lowercase_				:  int="<pad>"				,			lowercase_				:  Tuple="[CLS]"				,			lowercase_				:  Dict="[MASK]"				,			**lowercase_				:  Optional[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.
										lowercase_					:			Tuple										=       (
										    AddedToken(lowercase_				,			lstrip=lowercase_				,			rstrip=lowercase_				,			normalized=lowercase_    )
										    if isinstance(lowercase_				,			lowercase_    )
										    else mask_token
										)

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

										lowercase_					:			Optional[int]										=       do_lower_case
										lowercase_					:			Any										=       remove_space
										lowercase_					:			Dict										=       keep_accents
										lowercase_					:			Optional[int]										=       vocab_file
										lowercase_					:			Any										=       False if not self.vocab_file else True







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Tuple				,			lowercase_				:  List[int]				,			lowercase_				:  Optional[List[int]] = None    ):
										lowercase_					:			Tuple										=       [self.sep_token_id]
										lowercase_					:			str										=       [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 	SCREAMING_SNAKE_CASE_     (	self				:  Any				,			lowercase_				:  List[int]				,			lowercase_				:  Optional[List[int]] = None    ):
										lowercase_					:			Union[str, Any]										=       [self.sep_token_id]
										lowercase_					:			int										=       [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 	SCREAMING_SNAKE_CASE_     (	self				:  Union[str, Any]				,			lowercase_				:  str				,			lowercase_				:  Optional[str] = None    ):
										if not self.can_save_slow_tokenizer:
																	raise ValueError(
																	    """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """
																	    """tokenizer."""    )

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

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

										return (out_vocab_file,)





