

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__       = logging.get_logger(__name__)

lowerCAmelCase__       = {
    "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		: List[Any]			,						lowerCAmelCase__		: Union[str, Any]=None			,						lowerCAmelCase__		: List[str]=None			,						*lowerCAmelCase__		: str			,						**lowerCAmelCase__		: Optional[Any]    )    ->      Dict:
			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__}"
					)
					UpperCAmelCase					      =  self.model.config
			else:
					UpperCAmelCase					      =  config

			UpperCAmelCase					      =  data_args
			UpperCAmelCase					      =  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:
					UpperCAmelCase					      =  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					      =  label_smoothed_nll_loss


	def _UpperCamelCase	(						self		: Union[str, Any]			,						lowerCAmelCase__		: Optional[Any]    )    ->      Dict:






			if self.optimizer is None:
					UpperCAmelCase					      =  ["bias", "LayerNorm.weight"]
					UpperCAmelCase					      =  [
					    {
					        "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					      =  Adafactor if self.args.adafactor else AdamW
					if self.args.adafactor:
							UpperCAmelCase					      =  Adafactor
							UpperCAmelCase					      =  {"scale_parameter": False, "relative_step": False}
					else:
							UpperCAmelCase					      =  AdamW
							UpperCAmelCase					      =  {
							    "betas": (self.args.adam_betaa, self.args.adam_betaa),
							    "eps": self.args.adam_epsilon,
							}
					UpperCAmelCase					      =  self.args.learning_rate
					if self.sharded_ddp:
							UpperCAmelCase					      =  OSS(
							    params=lowercase__			,						optim=lowercase__			,						**lowercase__			,						)
					else:
							UpperCAmelCase					      =  optimizer_cls(lowercase__			,						**lowercase__    )

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


	def _UpperCamelCase	(						self		: Tuple			,						lowerCAmelCase__		: Union[str, Any]    )    ->      str:
			UpperCAmelCase					      =  arg_to_scheduler[self.args.lr_scheduler]
			if self.args.lr_scheduler == "constant":
					UpperCAmelCase					      =  schedule_func(self.optimizer    )
			elif self.args.lr_scheduler == "constant_w_warmup":
					UpperCAmelCase					      =  schedule_func(self.optimizer			,						num_warmup_steps=self.args.warmup_steps    )
			else:
					UpperCAmelCase					      =  schedule_func(
					    self.optimizer			,						num_warmup_steps=self.args.warmup_steps			,						num_training_steps=lowercase__    )
			return scheduler


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


	def _UpperCamelCase	(						self		: Tuple			,						lowerCAmelCase__		: Dict			,						lowerCAmelCase__		: Optional[Any]    )    ->      Optional[int]:
			UpperCAmelCase					      =  inputs.pop("labels"    )
			UpperCAmelCase					      =  self._compute_loss(lowercase__			,						lowercase__			,						lowercase__    )
			return loss


	def _UpperCamelCase	(						self		: Dict			,						lowerCAmelCase__		: Tuple			,						lowerCAmelCase__		: Optional[Any]			,						lowerCAmelCase__		: Optional[Any]			,						lowerCAmelCase__		: Optional[Any] = None			,						)    ->      str:
			UpperCAmelCase					      =  self._prepare_inputs(lowercase__    )

			UpperCAmelCase					      =  {
			    "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					      =  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"]:
							UpperCAmelCase					      =  self._pad_tensors_to_max_len(lowercase__			,						gen_kwargs["max_length"]    )

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

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

			UpperCAmelCase					      =  generated_tokens if self.args.predict_with_generate else logits

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

			return (loss, logits, labels)


	def _UpperCamelCase	(						self		: List[Any]			,						lowerCAmelCase__		: Optional[int]			,						lowerCAmelCase__		: Any    )    ->      Tuple:
			UpperCAmelCase					      =  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					      =  pad_token_id * torch.ones(
			    (tensor.shape[0], max_length)			,						dtype=tensor.dtype			,						device=tensor.device    )
			UpperCAmelCase					      =  tensor
			return padded_tensor






import json
import os
import unittest

from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast
from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, require_torch
from transformers.utils import cached_property

from ...test_tokenization_common import TokenizerTesterMixin






@require_tokenizers
class 						__magic_name__    (       _snake_case	,						unittest.TestCase    ):
 UpperCAmelCase							    =						LEDTokenizer
 UpperCAmelCase							    =						LEDTokenizerFast
 UpperCAmelCase							    =						True


 def _UpperCamelCase	(						self		: Tuple    )    ->      Union[str, Any]:
   super().setUp()
   UpperCAmelCase					      =  [
       "l",
       "o",
       "w",
       "e",
       "r",
       "s",
       "t",
       "i",
       "d",
       "n",
       "\u0120",
       "\u0120l",
       "\u0120n",
       "\u0120lo",
       "\u0120low",
       "er",
       "\u0120lowest",
       "\u0120newer",
       "\u0120wider",
       "<unk>",
   ]
   UpperCAmelCase					      =  dict(zip(lowerCAmelCase__			,						range(len(lowerCAmelCase__    )    )    )    )
   UpperCAmelCase					      =  ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
   UpperCAmelCase					      =  {"unk_token": "<unk>"}

   UpperCAmelCase					      =  os.path.join(self.tmpdirname			,						VOCAB_FILES_NAMES["vocab_file"]    )
   UpperCAmelCase					      =  os.path.join(self.tmpdirname			,						VOCAB_FILES_NAMES["merges_file"]    )
   with open(self.vocab_file			,						"w"			,						encoding="utf-8"    ) as fp:
     fp.write(json.dumps(lowerCAmelCase__    ) + "\n"    )
   with open(self.merges_file			,						"w"			,						encoding="utf-8"    ) as fp:
     fp.write("\n".join(lowerCAmelCase__    )    )


 def _UpperCamelCase	(						self		: Union[str, Any]			,						**lowerCAmelCase__		: Optional[int]    )    ->      Optional[int]:
   kwargs.update(self.special_tokens_map    )
   return self.tokenizer_class.from_pretrained(self.tmpdirname			,						**lowerCAmelCase__    )


 def _UpperCamelCase	(						self		: str			,						**lowerCAmelCase__		: str    )    ->      Optional[int]:
   kwargs.update(self.special_tokens_map    )
   return self.rust_tokenizer_class.from_pretrained(self.tmpdirname			,						**lowerCAmelCase__    )


 def _UpperCamelCase	(						self		: List[str]			,						lowerCAmelCase__		: List[Any]    )    ->      List[Any]:
   return "lower newer", "lower newer"


 @cached_property
 def _UpperCamelCase	(						self		: Dict    )    ->      str:
   return LEDTokenizer.from_pretrained("allenai/led-base-16384"    )


 @cached_property
 def _UpperCamelCase	(						self		: int    )    ->      Tuple:
   return LEDTokenizerFast.from_pretrained("allenai/led-base-16384"    )


 @require_torch
 def _UpperCamelCase	(						self		: Tuple    )    ->      List[str]:
   UpperCAmelCase					      =  ["A long paragraph for summarization.", "Another paragraph for summarization."]
   UpperCAmelCase					      =  [0, 2_5_0, 2_5_1, 1_7_8_1_8, 1_3, 3_9_1_8_6, 1_9_3_8, 4, 2]

   for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
     UpperCAmelCase					      =  tokenizer(lowerCAmelCase__			,						max_length=len(lowerCAmelCase__    )			,						padding=lowerCAmelCase__			,						return_tensors="pt"    )
     self.assertIsInstance(lowerCAmelCase__			,						lowerCAmelCase__    )

     self.assertEqual((2, 9)			,						batch.input_ids.shape    )
     self.assertEqual((2, 9)			,						batch.attention_mask.shape    )
     UpperCAmelCase					      =  batch.input_ids.tolist()[0]
     self.assertListEqual(lowerCAmelCase__			,						lowerCAmelCase__    )


 @require_torch
 def _UpperCamelCase	(						self		: Union[str, Any]    )    ->      List[Any]:
   UpperCAmelCase					      =  ["A long paragraph for summarization.", "Another paragraph for summarization."]
   for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
     UpperCAmelCase					      =  tokenizer(lowerCAmelCase__			,						padding=lowerCAmelCase__			,						return_tensors="pt"    )
     self.assertIn("input_ids"			,						lowerCAmelCase__    )
     self.assertIn("attention_mask"			,						lowerCAmelCase__    )
     self.assertNotIn("labels"			,						lowerCAmelCase__    )
     self.assertNotIn("decoder_attention_mask"			,						lowerCAmelCase__    )


 @require_torch
 def _UpperCamelCase	(						self		: int    )    ->      int:
   UpperCAmelCase					      =  [
       "Summary of the text.",
       "Another summary.",
   ]
   for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
     UpperCAmelCase					      =  tokenizer(text_target=lowerCAmelCase__			,						max_length=3_2			,						padding="max_length"			,						return_tensors="pt"    )
     self.assertEqual(3_2			,						targets["input_ids"].shape[1]    )


 @require_torch
 def _UpperCamelCase	(						self		: Any    )    ->      int:
   for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
     UpperCAmelCase					      =  tokenizer(
         ["I am a small frog" * 1_0_2_4, "I am a small frog"]			,						padding=lowerCAmelCase__			,						truncation=lowerCAmelCase__			,						return_tensors="pt"    )
     self.assertIsInstance(lowerCAmelCase__			,						lowerCAmelCase__    )
     self.assertEqual(batch.input_ids.shape			,						(2, 5_1_2_2)    )


 @require_torch
 def _UpperCamelCase	(						self		: Dict    )    ->      Tuple:
   UpperCAmelCase					      =  ["A long paragraph for summarization."]
   UpperCAmelCase					      =  [
       "Summary of the text.",
   ]
   for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
     UpperCAmelCase					      =  tokenizer(lowerCAmelCase__			,						return_tensors="pt"    )
     UpperCAmelCase					      =  tokenizer(text_target=lowerCAmelCase__			,						return_tensors="pt"    )
     UpperCAmelCase					      =  inputs["input_ids"]
     UpperCAmelCase					      =  targets["input_ids"]
     self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item()    )
     self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item()    )
     self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item()    )
     self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item()    )


 @require_torch
 def _UpperCamelCase	(						self		: Optional[int]    )    ->      Optional[Any]:
   for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
     UpperCAmelCase					      =  ["Summary of the text.", "Another summary."]
     UpperCAmelCase					      =  [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]]

     UpperCAmelCase					      =  tokenizer(lowerCAmelCase__			,						padding=lowerCAmelCase__    )
     UpperCAmelCase					      =  [[0] * len(lowerCAmelCase__    ) for x in encoded_output["input_ids"]]
     UpperCAmelCase					      =  tokenizer.pad(lowerCAmelCase__    )
     self.assertSequenceEqual(outputs["global_attention_mask"]			,						lowerCAmelCase__    )


 def _UpperCamelCase	(						self		: List[str]    )    ->      int:
   pass


 def _UpperCamelCase	(						self		: Optional[Any]    )    ->      Union[str, Any]:
   for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
     with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"    ):
       UpperCAmelCase					      =  self.rust_tokenizer_class.from_pretrained(lowerCAmelCase__			,						**lowerCAmelCase__    )
       UpperCAmelCase					      =  self.tokenizer_class.from_pretrained(lowerCAmelCase__			,						**lowerCAmelCase__    )
       UpperCAmelCase					      =  "A, <mask> AllenNLP sentence."
       UpperCAmelCase					      =  tokenizer_r.encode_plus(lowerCAmelCase__			,						add_special_tokens=lowerCAmelCase__			,						return_token_type_ids=lowerCAmelCase__    )
       UpperCAmelCase					      =  tokenizer_p.encode_plus(lowerCAmelCase__			,						add_special_tokens=lowerCAmelCase__			,						return_token_type_ids=lowerCAmelCase__    )
       self.assertEqual(sum(tokens_r["token_type_ids"]    )			,						sum(tokens_p["token_type_ids"]    )    )
       self.assertEqual(
           sum(tokens_r["attention_mask"]    ) / len(tokens_r["attention_mask"]    )			,						sum(tokens_p["attention_mask"]    ) / len(tokens_p["attention_mask"]    )			,						)

       UpperCAmelCase					      =  tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"]    )
       UpperCAmelCase					      =  tokenizer_p.convert_ids_to_tokens(tokens_p["input_ids"]    )
       self.assertSequenceEqual(tokens_p["input_ids"]			,						[0, 2_5_0, 6, 5_0_2_6_4, 3_8_2_3, 4_8_7, 2_1_9_9_2, 3_6_4_5, 4, 2]    )
       self.assertSequenceEqual(tokens_r["input_ids"]			,						[0, 2_5_0, 6, 5_0_2_6_4, 3_8_2_3, 4_8_7, 2_1_9_9_2, 3_6_4_5, 4, 2]    )

       self.assertSequenceEqual(
           lowerCAmelCase__			,						["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"]    )
       self.assertSequenceEqual(
           lowerCAmelCase__			,						["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"]    )



