"""simple docstring"""



from __future__ import annotations

import unittest

from transformers import BlenderbotConfig, BlenderbotTokenizer, is_tf_available
from transformers.testing_utils import require_tf, require_tokenizers, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
       import tensorflow as tf

       from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotForConditionalGeneration, TFBlenderbotModel



@require_tf
class      _A	:




    """simple docstring"""




    UpperCamelCase_	:					Optional[Any]							=					BlenderbotConfig
    UpperCamelCase_	:					List[Any]							=					{}
    UpperCamelCase_	:					int							=					'''gelu'''
    def __init__(		self							:     Any	,      A_							:     str	,      A_							:     Any=13	,      A_							:     List[str]=7	,      A_							:     Any=True	,      A_							:     Optional[Any]=False	,      A_							:     Tuple=99	,      A_							:     Optional[int]=32	,      A_							:     str=2	,      A_							:     Dict=4	,      A_							:     Dict=37	,      A_							:     Tuple=0.1	,      A_							:     Optional[int]=0.1	,      A_							:     Optional[Any]=20	,      A_							:     Optional[int]=2	,      A_							:     Union[str, Any]=1	,      A_							:     int=0	,      )    ->       Tuple:
         __snake_case				=							parent
         __snake_case				=							batch_size
         __snake_case				=							seq_length
         __snake_case				=							is_training
         __snake_case				=							use_labels
         __snake_case				=							vocab_size
         __snake_case				=							hidden_size
         __snake_case				=							num_hidden_layers
         __snake_case				=							num_attention_heads
         __snake_case				=							intermediate_size

         __snake_case				=							hidden_dropout_prob
         __snake_case				=							attention_probs_dropout_prob
         __snake_case				=							max_position_embeddings
         __snake_case				=							eos_token_id
         __snake_case				=							pad_token_id
         __snake_case				=							bos_token_id
    def  lowercase					(		self							:     Any    )    ->       Optional[Any]:
         __snake_case				=							ids_tensor([self.batch_size, self.seq_length - 1]	,      self.vocab_size    )
         __snake_case				=							tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size    )	,      1    )
         __snake_case				=							tf.concat([input_ids, eos_tensor]	,      axis=1    )

         __snake_case				=							ids_tensor([self.batch_size, self.seq_length]	,      self.vocab_size    )

         __snake_case				=							self.config_cls(
             vocab_size=self.vocab_size	,      d_model=self.hidden_size	,      encoder_layers=self.num_hidden_layers	,      decoder_layers=self.num_hidden_layers	,      encoder_attention_heads=self.num_attention_heads	,      decoder_attention_heads=self.num_attention_heads	,      encoder_ffn_dim=self.intermediate_size	,      decoder_ffn_dim=self.intermediate_size	,      dropout=self.hidden_dropout_prob	,      attention_dropout=self.attention_probs_dropout_prob	,      max_position_embeddings=self.max_position_embeddings	,      eos_token_ids=[2]	,      bos_token_id=self.bos_token_id	,      pad_token_id=self.pad_token_id	,      decoder_start_token_id=self.pad_token_id	,      **self.config_updates	,      )
         __snake_case				=							prepare_blenderbot_inputs_dict(A_	,      A_	,      A_    )
         return config, inputs_dict







    def  lowercase					(		self							:     Any	,      A_							:     int	,      A_							:     Tuple    )    ->       List[Any]:
         __snake_case				=							TFBlenderbotModel(config=A_    ).get_decoder()
         __snake_case				=							inputs_dict['''input_ids''']

         __snake_case				=							input_ids[:1, :]
         __snake_case				=							inputs_dict['''attention_mask'''][:1, :]
         __snake_case				=							inputs_dict['''head_mask''']
         __snake_case				=							1

         # first forward pass
         __snake_case				=							model(A_	,      attention_mask=A_	,      head_mask=A_	,      use_cache=A_    )

         __snake_case		,	__snake_case				=							outputs.to_tuple()

         # create hypothetical next token and extent to next_input_ids
         __snake_case				=							ids_tensor((self.batch_size, 3)	,      config.vocab_size    )
         __snake_case				=							tf.cast(ids_tensor((self.batch_size, 3)	,      2    )	,      tf.inta    )

         # append to next input_ids and
         __snake_case				=							tf.concat([input_ids, next_tokens]	,      axis=-1    )
         __snake_case				=							tf.concat([attention_mask, next_attn_mask]	,      axis=-1    )

         __snake_case				=							model(A_	,      attention_mask=A_    )[0]
         __snake_case				=							model(A_	,      attention_mask=A_	,      past_key_values=A_    )[0]

         self.parent.assertEqual(next_tokens.shape[1]	,      output_from_past.shape[1]    )

         # select random slice
         __snake_case				=							int(ids_tensor((1,)	,      output_from_past.shape[-1]    )    )
         __snake_case				=							output_from_no_past[:, -3:, random_slice_idx]
         __snake_case				=							output_from_past[:, :, random_slice_idx]

         # test that outputs are equal for slice
         tf.debugging.assert_near(A_	,      A_	,      rtol=1E-3    )






def    SCREAMING_SNAKE_CASE       (     snake_case,      snake_case,      snake_case,      snake_case=None,      snake_case=None,      snake_case=None,      snake_case=None,      snake_case=None,      ):
     if attention_mask is None:
          __snake_case				=							tf.cast(tf.math.not_equal(snake_case,      config.pad_token_id),      tf.inta)
     if decoder_attention_mask is None:
          __snake_case				=							tf.concat(
              [
                  tf.ones(decoder_input_ids[:, :1].shape,      dtype=tf.inta),
                  tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:],      config.pad_token_id),      tf.inta),
              ],      axis=-1,      )
     if head_mask is None:
          __snake_case				=							tf.ones((config.encoder_layers, config.encoder_attention_heads))
     if decoder_head_mask is None:
          __snake_case				=							tf.ones((config.decoder_layers, config.decoder_attention_heads))
     if cross_attn_head_mask is None:
          __snake_case				=							tf.ones((config.decoder_layers, config.decoder_attention_heads))
     return {
         "input_ids": input_ids,
         "decoder_input_ids": decoder_input_ids,
         "attention_mask": attention_mask,
         "decoder_attention_mask": decoder_attention_mask,
         "head_mask": head_mask,
         "decoder_head_mask": decoder_head_mask,
         "cross_attn_head_mask": cross_attn_head_mask,
     }



@require_tf
class      _A	(						_UpperCAmelCase							, _UpperCAmelCase							, unittest.TestCase					):




    """simple docstring"""




    UpperCamelCase_	:					List[str]							=					(TFBlenderbotForConditionalGeneration, TFBlenderbotModel) if is_tf_available() else ()
    UpperCamelCase_	:					Optional[int]							=					(TFBlenderbotForConditionalGeneration,) if is_tf_available() else ()
    UpperCamelCase_	:					Optional[Any]							=					(
        {
            '''conversational''': TFBlenderbotForConditionalGeneration,
            '''feature-extraction''': TFBlenderbotModel,
            '''summarization''': TFBlenderbotForConditionalGeneration,
            '''text2text-generation''': TFBlenderbotForConditionalGeneration,
            '''translation''': TFBlenderbotForConditionalGeneration,
        }
        if is_tf_available()
        else {}
    )
    UpperCamelCase_	:					Optional[Any]							=					True
    UpperCamelCase_	:					Any							=					False
    UpperCamelCase_	:					Optional[Any]							=					False
    def  lowercase					(		self							:     str    )    ->       List[str]:
         __snake_case				=							TFBlenderbotModelTester(self    )
         __snake_case				=							ConfigTester(self	,      config_class=A_    )
    def  lowercase					(		self							:     List[Any]    )    ->       str:
         self.config_tester.run_common_tests()







    def  lowercase					(		self							:     List[str]    )    ->       Tuple:
         __snake_case				=							self.model_tester.prepare_config_and_inputs_for_common()
         self.model_tester.check_decoder_model_past_large_inputs(*A_    )






@require_tokenizers
@require_tf
class      _A	(						unittest.TestCase					):




    """simple docstring"""




    UpperCamelCase_	:					Optional[Any]							=					['''My friends are cool but they eat too many carbs.''']
    UpperCamelCase_	:					Any							=					'''facebook/blenderbot-400M-distill'''
    @cached_property
    def  lowercase					(		self							:     str    )    ->       Optional[int]:
         return BlenderbotTokenizer.from_pretrained(self.model_name    )
    @cached_property
    def  lowercase					(		self							:     Tuple    )    ->       List[str]:
         __snake_case				=							TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name    )
         return model







    @slow
    def  lowercase					(		self							:     List[Any]    )    ->       str:
         __snake_case				=							self.tokenizer(self.src_text	,      return_tensors='''tf'''    )
         __snake_case				=							self.model.generate(
             model_inputs.input_ids	,      )
         __snake_case				=							self.tokenizer.batch_decode(generated_ids.numpy()	,      skip_special_tokens=A_    )[0]
         assert (
             generated_words
             == " That's unfortunate. Are they trying to lose weight or are they just trying to be healthier?"
         )
"""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[int]														=							logging.get_logger(__name__)

__lowercase		:		Optional[int]														=							{
    "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      _A	(						_UpperCAmelCase					):




    """simple docstring"""




    def __init__(		self							:     str	,      A_							:     Optional[Any]=None	,      A_							:     Union[str, Any]=None	,      *A_							:     List[Any]	,      **A_							:     Union[str, Any]    )    ->       List[Any]:
         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__}"
              )
              __snake_case				=							self.model.config
         else:
              __snake_case				=							config

         __snake_case				=							data_args
         __snake_case				=							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:
              __snake_case				=							torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id    )
         else:
              # dynamically import label_smoothed_nll_loss
              from utils import label_smoothed_nll_loss

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

         if self.lr_scheduler is None:
              __snake_case				=							self._get_lr_scheduler(A_    )
         else:  # ignoring --lr_scheduler
              logger.warning('''scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.'''    )
    def  lowercase					(		self							:     Any	,      A_							:     Dict    )    ->       Dict:
         __snake_case				=							arg_to_scheduler[self.args.lr_scheduler]
         if self.args.lr_scheduler == "constant":
              __snake_case				=							schedule_func(self.optimizer    )
         elif self.args.lr_scheduler == "constant_w_warmup":
              __snake_case				=							schedule_func(self.optimizer	,      num_warmup_steps=self.args.warmup_steps    )
         else:
              __snake_case				=							schedule_func(
                  self.optimizer	,      num_warmup_steps=self.args.warmup_steps	,      num_training_steps=A_    )
         return scheduler
    def  lowercase					(		self							:     List[Any]    )    ->       Optional[torch.utils.data.Sampler]:
         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  lowercase					(		self							:     List[Any]	,      A_							:     str	,      A_							:     str	,      A_							:     List[str]    )    ->       Dict:
         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
                   __snake_case				=							model(**A_	,      use_cache=A_    )[0]
                   __snake_case				=							self.loss_fn(logits.view(-1	,      logits.shape[-1]    )	,      labels.view(-1    )    )
              else:
                   # compute usual loss via models
                   __snake_case		,	__snake_case				=							model(**A_	,      labels=A_	,      use_cache=A_    )[:2]
         else:
              # compute label smoothed loss
              __snake_case				=							model(**A_	,      use_cache=A_    )[0]
              __snake_case				=							torch.nn.functional.log_softmax(A_	,      dim=-1    )
              __snake_case		,	__snake_case				=							self.loss_fn(A_	,      A_	,      self.args.label_smoothing	,      ignore_index=self.config.pad_token_id    )
         return loss, logits
    def  lowercase					(		self							:     int	,      A_							:     Tuple	,      A_							:     List[str]    )    ->       List[Any]:
         __snake_case				=							inputs.pop('''labels'''    )
         __snake_case		,	__snake_case				=							self._compute_loss(A_	,      A_	,      A_    )
         return loss
    def  lowercase					(		self							:     Union[str, Any]	,      A_							:     nn.Module	,      A_							:     Dict[str, Union[torch.Tensor, Any]]	,      A_							:     bool	,      A_							:     Optional[List[str]] = None	,      )    ->       Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]:
         __snake_case				=							self._prepare_inputs(A_    )

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

         __snake_case				=							inputs.pop('''labels'''    )
         with torch.no_grad():
              # compute loss on predict data
              __snake_case		,	__snake_case				=							self._compute_loss(A_	,      A_	,      A_    )

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

         __snake_case				=							generated_tokens if self.args.predict_with_generate else logits

         if labels.shape[-1] < gen_kwargs["max_length"]:
              __snake_case				=							self._pad_tensors_to_max_len(A_	,      gen_kwargs['''max_length''']    )

         return (loss, logits, labels)







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

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