






"""simple docstring"""
import argparse
import glob
import logging
import os
import sys
import time
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Tuple

import numpy as np
import pytorch_lightning as pl
import torch
from callbacks import SeqaSeqLoggingCallback, get_checkpoint_callback, get_early_stopping_callback
from torch import nn
from torch.utils.data import DataLoader

from transformers import MBartTokenizer, TaForConditionalGeneration
from transformers.models.bart.modeling_bart import shift_tokens_right
from utils import (
    ROUGE_KEYS,
    LegacySeqaSeqDataset,
    SeqaSeqDataset,
    assert_all_frozen,
    calculate_bleu,
    calculate_rouge,
    check_output_dir,
    flatten_list,
    freeze_embeds,
    freeze_params,
    get_git_info,
    label_smoothed_nll_loss,
    lmap,
    pickle_save,
    save_git_info,
    save_json,
    use_task_specific_params,
)


# need the parent dir module
sys.path.insert(2, str(Path(__file__).resolve().parents[1]))
from lightning_base import BaseTransformer, add_generic_args, generic_train  # noqa


snake_case : List[Any]     		=		logging.getLogger(__name__)



class        UpperCamelCase__ (				a_):







    """simple docstring"""
    __UpperCAmelCase           = """summarization"""
    __UpperCAmelCase           = ["""loss"""]
    __UpperCAmelCase           = ROUGE_KEYS
    __UpperCAmelCase           = """rouge2"""







    def __init__(		self :	Optional[Any]				,    UpperCamelCase_ :	Optional[int]				,    **UpperCamelCase_ :	Tuple ):





           '''simple docstring'''

           if hparams.sortish_sampler and hparams.gpus > 1:
                  __magic_name__      				=    False
           elif hparams.max_tokens_per_batch is not None:
                  if hparams.gpus > 1:
                         raise NotImplementedError('Dynamic Batch size does not work for multi-gpu training' )
                  if hparams.sortish_sampler:
                         raise ValueError('--sortish_sampler and --max_tokens_per_batch may not be used simultaneously' )

           super().__init__(UpperCamelCase_				,    num_labels=UpperCamelCase_				,    mode=self.mode				,    **UpperCamelCase_ )
           use_task_specific_params(self.model				,    'summarization' )
           save_git_info(self.hparams.output_dir )
           __magic_name__      				=    Path(self.output_dir ) / 'metrics.json'
           __magic_name__      				=    Path(self.output_dir ) / 'hparams.pkl'
           pickle_save(self.hparams				,    self.hparams_save_path )
           __magic_name__      				=    0
           __magic_name__      				=    defaultdict(UpperCamelCase_ )
           __magic_name__      				=    self.config.model_type
           __magic_name__      				=    self.config.tgt_vocab_size if self.model_type == 'fsmt' else self.config.vocab_size

           __magic_name__      				=    {
               "data_dir": self.hparams.data_dir,
               "max_source_length": self.hparams.max_source_length,
               "prefix": self.model.config.prefix or "",
           }
           __magic_name__      				=    {
               'train': self.hparams.n_train,
               'val': self.hparams.n_val,
               'test': self.hparams.n_test,
           }
           __magic_name__      				=    {k: v if v >= 0 else None for k, v in n_observations_per_split.items()}

           __magic_name__      				=    {
               'train': self.hparams.max_target_length,
               'val': self.hparams.val_max_target_length,
               'test': self.hparams.test_max_target_length,
           }
           assert self.target_lens["train"] <= self.target_lens["val"], f"""target_lens: {self.target_lens}"""
           assert self.target_lens["train"] <= self.target_lens["test"], f"""target_lens: {self.target_lens}"""
           if self.hparams.freeze_embeds:
                  freeze_embeds(self.model )
           if self.hparams.freeze_encoder:
                  freeze_params(self.model.get_encoder() )
                  assert_all_frozen(self.model.get_encoder() )

           __magic_name__      				=    get_git_info()['repo_sha']
           __magic_name__      				=    hparams.num_workers
           __magic_name__      				=    None  # default to config
           if self.model.config.decoder_start_token_id is None and isinstance(self.tokenizer				,    UpperCamelCase_ ):
                  __magic_name__      				=    self.tokenizer.lang_code_to_id[hparams.tgt_lang]
                  __magic_name__      				=    self.decoder_start_token_id
           __magic_name__      				=    (
               SeqaSeqDataset if hasattr(self.tokenizer				,    'prepare_seq2seq_batch' ) else LegacySeqaSeqDataset
           )
           __magic_name__      				=    False
           __magic_name__      				=    self.model.config.num_beams if self.hparams.eval_beams is None else self.hparams.eval_beams
           if self.hparams.eval_max_gen_length is not None:
                  __magic_name__      				=    self.hparams.eval_max_gen_length
           else:
                  __magic_name__      				=    self.model.config.max_length
           __magic_name__      				=    self.default_val_metric if self.hparams.val_metric is None else self.hparams.val_metric







    def 				a__			(		self :	Dict				,    UpperCamelCase_ :	Dict[str, torch.Tensor] ):





           '''simple docstring'''

           __magic_name__      				=    {
               k: self.tokenizer.batch_decode(v.tolist() ) if 'mask' not in k else v.shape for k, v in batch.items()
           }
           save_json(UpperCamelCase_				,    Path(self.output_dir ) / 'text_batch.json' )
           save_json({k: v.tolist() for k, v in batch.items()}				,    Path(self.output_dir ) / 'tok_batch.json' )

           __magic_name__      				=    True
           return readable_batch







    def 				a__			(		self :	Union[str, Any]				,    UpperCamelCase_ :	str				,    **UpperCamelCase_ :	Optional[int] ):





           '''simple docstring'''

           return self.model(UpperCamelCase_				,    **UpperCamelCase_ )







    def 				a__			(		self :	int				,    UpperCamelCase_ :	List[int] ):





           '''simple docstring'''

           __magic_name__      				=    self.tokenizer.batch_decode(
               UpperCamelCase_				,    skip_special_tokens=UpperCamelCase_				,    clean_up_tokenization_spaces=UpperCamelCase_ )
           return lmap(str.strip				,    UpperCamelCase_ )







    def 				a__			(		self :	List[str]				,    UpperCamelCase_ :	dict ):





           '''simple docstring'''

           __magic_name__      				=    self.tokenizer.pad_token_id
           __magic_name__				,  __magic_name__      				=    batch['input_ids'], batch['attention_mask']
           __magic_name__      				=    batch['labels']
           if isinstance(self.model				,    UpperCamelCase_ ):
                  __magic_name__      				=    self.model._shift_right(UpperCamelCase_ )
           else:
                  __magic_name__      				=    shift_tokens_right(UpperCamelCase_				,    UpperCamelCase_ )
           if not self.already_saved_batch:  # This would be slightly better if it only happened on rank zero
                  __magic_name__      				=    decoder_input_ids
                  self.save_readable_batch(UpperCamelCase_ )

           __magic_name__      				=    self(UpperCamelCase_				,    attention_mask=UpperCamelCase_				,    decoder_input_ids=UpperCamelCase_				,    use_cache=UpperCamelCase_ )
           __magic_name__      				=    outputs['logits']
           if self.hparams.label_smoothing == 0:
                  # Same behavior as modeling_bart.py, besides ignoring pad_token_id
                  __magic_name__      				=    nn.CrossEntropyLoss(ignore_index=UpperCamelCase_ )

                  assert lm_logits.shape[-1] == self.vocab_size
                  __magic_name__      				=    ce_loss_fct(lm_logits.view(-1				,    lm_logits.shape[-1] )				,    tgt_ids.view(-1 ) )
           else:
                  __magic_name__      				=    nn.functional.log_softmax(UpperCamelCase_				,    dim=-1 )
                  __magic_name__				,  __magic_name__      				=    label_smoothed_nll_loss(
                      UpperCamelCase_				,    UpperCamelCase_				,    self.hparams.label_smoothing				,    ignore_index=UpperCamelCase_ )
           return (loss,)







    @property
    def 				a__			(		self :	List[str] ):





           '''simple docstring'''

           return self.tokenizer.pad_token_id







    def 				a__			(		self :	Optional[Any]				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	Dict ):





           '''simple docstring'''

           __magic_name__      				=    self._step(UpperCamelCase_ )

           __magic_name__      				=    dict(zip(self.loss_names				,    UpperCamelCase_ ) )
           # tokens per batch
           __magic_name__      				=    batch['input_ids'].ne(self.pad ).sum() + batch['labels'].ne(self.pad ).sum()
           __magic_name__      				=    batch['input_ids'].shape[0]
           __magic_name__      				=    batch['input_ids'].eq(self.pad ).sum()
           __magic_name__      				=    batch['input_ids'].eq(self.pad ).float().mean()
           # TODO(SS): make a wandb summary metric for this
           return {"loss": loss_tensors[0], "log": logs}







    def 				a__			(		self :	Dict				,    UpperCamelCase_ :	str				,    UpperCamelCase_ :	Optional[int] ):





           '''simple docstring'''

           return self._generative_step(UpperCamelCase_ )







    def 				a__			(		self :	Union[str, Any]				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	Optional[int]="val" ):





           '''simple docstring'''

           self.step_count += 1
           __magic_name__      				=    {k: torch.stack([x[k] for x in outputs] ).mean() for k in self.loss_names}
           __magic_name__      				=    losses['loss']
           __magic_name__      				=    {
               k: np.array([x[k] for x in outputs] ).mean() for k in self.metric_names + ['gen_time', 'gen_len']
           }
           __magic_name__      				=    (
               generative_metrics[self.val_metric] if self.val_metric in generative_metrics else losses[self.val_metric]
           )
           __magic_name__      				=    torch.tensor(UpperCamelCase_ ).type_as(UpperCamelCase_ )
           generative_metrics.update({k: v.item() for k, v in losses.items()} )
           losses.update(UpperCamelCase_ )
           __magic_name__      				=    {f"""{prefix}_avg_{k}""": x for k, x in losses.items()}
           __magic_name__      				=    self.step_count
           self.metrics[prefix].append(UpperCamelCase_ )  # callback writes this to self.metrics_save_path
           __magic_name__      				=    flatten_list([x['preds'] for x in outputs] )
           return {
               "log": all_metrics,
               "preds": preds,
               f"""{prefix}_loss""": loss,
               f"""{prefix}_{self.val_metric}""": metric_tensor,
           }







    def 				a__			(		self :	str				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	Union[str, Any] ):





           '''simple docstring'''

           return calculate_rouge(UpperCamelCase_				,    UpperCamelCase_ )







    def 				a__			(		self :	Tuple				,    UpperCamelCase_ :	dict ):





           '''simple docstring'''

           __magic_name__      				=    time.time()

           # parser.add_argument('--eval_max_gen_length', type=int, default=None, help='never generate more than n tokens')
           __magic_name__      				=    self.model.generate(
               batch['input_ids']				,    attention_mask=batch['attention_mask']				,    use_cache=UpperCamelCase_				,    decoder_start_token_id=self.decoder_start_token_id				,    num_beams=self.eval_beams				,    max_length=self.eval_max_length				,    )
           __magic_name__      				=    (time.time() - ta) / batch['input_ids'].shape[0]
           __magic_name__      				=    self.ids_to_clean_text(UpperCamelCase_ )
           __magic_name__      				=    self.ids_to_clean_text(batch['labels'] )
           __magic_name__      				=    self._step(UpperCamelCase_ )
           __magic_name__      				=    dict(zip(self.loss_names				,    UpperCamelCase_ ) )
           __magic_name__      				=    self.calc_generative_metrics(UpperCamelCase_				,    UpperCamelCase_ )
           __magic_name__      				=    np.mean(lmap(UpperCamelCase_				,    UpperCamelCase_ ) )
           base_metrics.update(gen_time=UpperCamelCase_				,    gen_len=UpperCamelCase_				,    preds=UpperCamelCase_				,    target=UpperCamelCase_				,    **UpperCamelCase_ )
           return base_metrics







    def 				a__			(		self :	Tuple				,    UpperCamelCase_ :	Tuple				,    UpperCamelCase_ :	str ):





           '''simple docstring'''

           return self._generative_step(UpperCamelCase_ )







    def 				a__			(		self :	Union[str, Any]				,    UpperCamelCase_ :	Union[str, Any] ):





           '''simple docstring'''

           return self.validation_epoch_end(UpperCamelCase_				,    prefix='test' )







    def 				a__			(		self :	Union[str, Any]				,    UpperCamelCase_ :	List[Any] ):





           '''simple docstring'''

           __magic_name__      				=    self.n_obs[type_path]
           __magic_name__      				=    self.target_lens[type_path]
           __magic_name__      				=    self.dataset_class(
               self.tokenizer				,    type_path=UpperCamelCase_				,    n_obs=UpperCamelCase_				,    max_target_length=UpperCamelCase_				,    **self.dataset_kwargs				,    )
           return dataset







    def 				a__			(		self :	int				,    UpperCamelCase_ :	str				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	bool = False ):





           '''simple docstring'''

           __magic_name__      				=    self.get_dataset(UpperCamelCase_ )

           if self.hparams.sortish_sampler and type_path != "test" and type_path != "val":
                  __magic_name__      				=    dataset.make_sortish_sampler(UpperCamelCase_				,    distributed=self.hparams.gpus > 1 )
                  return DataLoader(
                      UpperCamelCase_				,    batch_size=UpperCamelCase_				,    collate_fn=dataset.collate_fn				,    shuffle=UpperCamelCase_				,    num_workers=self.num_workers				,    sampler=UpperCamelCase_				,    )

           elif self.hparams.max_tokens_per_batch is not None and type_path != "test" and type_path != "val":
                  __magic_name__      				=    dataset.make_dynamic_sampler(
                      self.hparams.max_tokens_per_batch				,    distributed=self.hparams.gpus > 1 )
                  return DataLoader(
                      UpperCamelCase_				,    batch_sampler=UpperCamelCase_				,    collate_fn=dataset.collate_fn				,    num_workers=self.num_workers				,    )
           else:
                  return DataLoader(
                      UpperCamelCase_				,    batch_size=UpperCamelCase_				,    collate_fn=dataset.collate_fn				,    shuffle=UpperCamelCase_				,    num_workers=self.num_workers				,    sampler=UpperCamelCase_				,    )







    def 				a__			(		self :	Union[str, Any] ):





           '''simple docstring'''

           __magic_name__      				=    self.get_dataloader('train'				,    batch_size=self.hparams.train_batch_size				,    shuffle=UpperCamelCase_ )
           return dataloader







    def 				a__			(		self :	List[Any] ):





           '''simple docstring'''

           return self.get_dataloader('val'				,    batch_size=self.hparams.eval_batch_size )







    def 				a__			(		self :	str ):





           '''simple docstring'''

           return self.get_dataloader('test'				,    batch_size=self.hparams.eval_batch_size )







    @staticmethod
    def 				a__			(		UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	Tuple ):





           '''simple docstring'''

           BaseTransformer.add_model_specific_args(UpperCamelCase_				,    UpperCamelCase_ )
           add_generic_args(UpperCamelCase_				,    UpperCamelCase_ )
           parser.add_argument(
               '--max_source_length'				,    default=1_0_2_4				,    type=UpperCamelCase_				,    help=(
                   'The maximum total input sequence length after tokenization. Sequences longer '
                   'than this will be truncated, sequences shorter will be padded.'
               )				,    )
           parser.add_argument(
               '--max_target_length'				,    default=5_6				,    type=UpperCamelCase_				,    help=(
                   'The maximum total input sequence length after tokenization. Sequences longer '
                   'than this will be truncated, sequences shorter will be padded.'
               )				,    )
           parser.add_argument(
               '--val_max_target_length'				,    default=1_4_2				,    type=UpperCamelCase_				,    help=(
                   'The maximum total input sequence length after tokenization. Sequences longer '
                   'than this will be truncated, sequences shorter will be padded.'
               )				,    )
           parser.add_argument(
               '--test_max_target_length'				,    default=1_4_2				,    type=UpperCamelCase_				,    help=(
                   'The maximum total input sequence length after tokenization. Sequences longer '
                   'than this will be truncated, sequences shorter will be padded.'
               )				,    )
           parser.add_argument('--freeze_encoder'				,    action='store_true' )
           parser.add_argument('--freeze_embeds'				,    action='store_true' )
           parser.add_argument('--sortish_sampler'				,    action='store_true'				,    default=UpperCamelCase_ )
           parser.add_argument('--overwrite_output_dir'				,    action='store_true'				,    default=UpperCamelCase_ )
           parser.add_argument('--max_tokens_per_batch'				,    type=UpperCamelCase_				,    default=UpperCamelCase_ )
           parser.add_argument('--logger_name'				,    type=UpperCamelCase_				,    choices=['default', 'wandb', 'wandb_shared']				,    default='default' )
           parser.add_argument('--n_train'				,    type=UpperCamelCase_				,    default=-1				,    required=UpperCamelCase_				,    help='# examples. -1 means use all.' )
           parser.add_argument('--n_val'				,    type=UpperCamelCase_				,    default=5_0_0				,    required=UpperCamelCase_				,    help='# examples. -1 means use all.' )
           parser.add_argument('--n_test'				,    type=UpperCamelCase_				,    default=-1				,    required=UpperCamelCase_				,    help='# examples. -1 means use all.' )
           parser.add_argument(
               '--task'				,    type=UpperCamelCase_				,    default='summarization'				,    required=UpperCamelCase_				,    help='# examples. -1 means use all.' )
           parser.add_argument('--label_smoothing'				,    type=UpperCamelCase_				,    default=0.0				,    required=UpperCamelCase_ )
           parser.add_argument('--src_lang'				,    type=UpperCamelCase_				,    default=''				,    required=UpperCamelCase_ )
           parser.add_argument('--tgt_lang'				,    type=UpperCamelCase_				,    default=''				,    required=UpperCamelCase_ )
           parser.add_argument('--eval_beams'				,    type=UpperCamelCase_				,    default=UpperCamelCase_				,    required=UpperCamelCase_ )
           parser.add_argument(
               '--val_metric'				,    type=UpperCamelCase_				,    default=UpperCamelCase_				,    required=UpperCamelCase_				,    choices=['bleu', 'rouge2', 'loss', None] )
           parser.add_argument('--eval_max_gen_length'				,    type=UpperCamelCase_				,    default=UpperCamelCase_				,    help='never generate more than n tokens' )
           parser.add_argument('--save_top_k'				,    type=UpperCamelCase_				,    default=1				,    required=UpperCamelCase_				,    help='How many checkpoints to save' )
           parser.add_argument(
               '--early_stopping_patience'				,    type=UpperCamelCase_				,    default=-1				,    required=UpperCamelCase_				,    help=(
                   '-1 means never early stop. early_stopping_patience is measured in validation checks, not epochs. So'
                   ' val_check_interval will effect it.'
               )				,    )
           return parser



class        UpperCamelCase__ (				a_):







    """simple docstring"""
    __UpperCAmelCase           = """translation"""
    __UpperCAmelCase           = ["""loss"""]
    __UpperCAmelCase           = ["""bleu"""]
    __UpperCAmelCase           = """bleu"""







    def __init__(		self :	Union[str, Any]				,    UpperCamelCase_ :	List[str]				,    **UpperCamelCase_ :	Optional[int] ):





           '''simple docstring'''

           super().__init__(UpperCamelCase_				,    **UpperCamelCase_ )
           __magic_name__      				=    hparams.src_lang
           __magic_name__      				=    hparams.tgt_lang







    def 				a__			(		self :	str				,    UpperCamelCase_ :	Union[str, Any]				,    UpperCamelCase_ :	Any ):





           '''simple docstring'''

           return calculate_bleu(UpperCamelCase_				,    UpperCamelCase_ )


def 							A						(				__snake_case: Tuple ,     __snake_case: int=None  )    ->		SummarizationModule:

       """simple docstring"""





       Path(args.output_dir  ).mkdir(exist_ok=__snake_case  )
       check_output_dir(__snake_case ,     expected_items=3  )

       if model is None:
              if "summarization" in args.task:
                     __magic_name__      				=    SummarizationModule(__snake_case  )
              else:
                     __magic_name__      				=    TranslationModule(__snake_case  )
       __magic_name__      				=    Path(args.data_dir  ).name
       if (
           args.logger_name == "default"
           or args.fast_dev_run
           or str(args.output_dir  ).startswith('/tmp'  )
           or str(args.output_dir  ).startswith('/var'  )
       ):
              __magic_name__      				=    True  # don't pollute wandb logs unnecessarily
       elif args.logger_name == "wandb":
              from pytorch_lightning.loggers import WandbLogger

              __magic_name__      				=    os.environ.get('WANDB_PROJECT' ,     __snake_case  )
              __magic_name__      				=    WandbLogger(name=model.output_dir.name ,     project=__snake_case  )

       elif args.logger_name == "wandb_shared":
              from pytorch_lightning.loggers import WandbLogger

              __magic_name__      				=    WandbLogger(name=model.output_dir.name ,     project=F"""hf_{dataset}"""  )

       if args.early_stopping_patience >= 0:
              __magic_name__      				=    get_early_stopping_callback(model.val_metric ,     args.early_stopping_patience  )
       else:
              __magic_name__      				=    False

       __magic_name__      				=    args.val_metric == 'loss'
       __magic_name__      				=    generic_train(
           __snake_case ,     __snake_case ,     logging_callback=SeqaSeqLoggingCallback() ,     checkpoint_callback=get_checkpoint_callback(
               args.output_dir ,     model.val_metric ,     args.save_top_k ,     __snake_case  ) ,     early_stopping_callback=__snake_case ,     logger=__snake_case ,     )
       pickle_save(model.hparams ,     model.output_dir / 'hparams.pkl'  )
       if not args.do_predict:
              return model

       __magic_name__      				=    ''
       __magic_name__      				=    sorted(glob.glob(os.path.join(args.output_dir ,     '*.ckpt'  ) ,     recursive=__snake_case  )  )
       if checkpoints:
              __magic_name__      				=    checkpoints[-1]
              __magic_name__      				=    checkpoints[-1]
       trainer.logger.log_hyperparams(model.hparams  )

       # test() without a model tests using the best checkpoint automatically
       trainer.test()
       return model


if __name__ == "__main__":
 snake_case : Optional[Any]     		=		argparse.ArgumentParser()
 snake_case : Optional[Any]     		=		pl.Trainer.add_argparse_args(parser)
 snake_case : List[str]     		=		SummarizationModule.add_model_specific_args(parser, os.getcwd())

 snake_case : List[str]     		=		parser.parse_args()

 main(args)







"""simple docstring"""
import shutil
import tempfile
import unittest
from unittest.mock import patch

from transformers import (
    DefaultFlowCallback,
    IntervalStrategy,
    PrinterCallback,
    ProgressCallback,
    Trainer,
    TrainerCallback,
    TrainingArguments,
    is_torch_available,
)
from transformers.testing_utils import require_torch


if is_torch_available():
 from transformers.trainer import DEFAULT_CALLBACKS

 from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel



class        UpperCamelCase__ (				a_):







    """simple docstring"""







    def __init__(		self :	Union[str, Any] ):





           '''simple docstring'''

           __magic_name__      				=    []







    def 				a__			(		self :	Tuple				,    UpperCamelCase_ :	Dict				,    UpperCamelCase_ :	Union[str, Any]				,    UpperCamelCase_ :	int				,    **UpperCamelCase_ :	int ):





           '''simple docstring'''

           self.events.append('on_init_end' )







    def 				a__			(		self :	Any				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	str				,    UpperCamelCase_ :	List[str]				,    **UpperCamelCase_ :	str ):





           '''simple docstring'''

           self.events.append('on_train_begin' )







    def 				a__			(		self :	str				,    UpperCamelCase_ :	Tuple				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	Optional[int]				,    **UpperCamelCase_ :	Dict ):





           '''simple docstring'''

           self.events.append('on_train_end' )







    def 				a__			(		self :	List[str]				,    UpperCamelCase_ :	Tuple				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	Tuple				,    **UpperCamelCase_ :	Optional[Any] ):





           '''simple docstring'''

           self.events.append('on_epoch_begin' )







    def 				a__			(		self :	Optional[int]				,    UpperCamelCase_ :	List[Any]				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	Tuple				,    **UpperCamelCase_ :	List[Any] ):





           '''simple docstring'''

           self.events.append('on_epoch_end' )







    def 				a__			(		self :	Union[str, Any]				,    UpperCamelCase_ :	Union[str, Any]				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	Union[str, Any]				,    **UpperCamelCase_ :	Optional[Any] ):





           '''simple docstring'''

           self.events.append('on_step_begin' )







    def 				a__			(		self :	List[str]				,    UpperCamelCase_ :	Optional[Any]				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	Any				,    **UpperCamelCase_ :	List[Any] ):





           '''simple docstring'''

           self.events.append('on_step_end' )







    def 				a__			(		self :	List[Any]				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	Tuple				,    **UpperCamelCase_ :	Dict ):





           '''simple docstring'''

           self.events.append('on_evaluate' )







    def 				a__			(		self :	str				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	Dict				,    **UpperCamelCase_ :	Any ):





           '''simple docstring'''

           self.events.append('on_predict' )







    def 				a__			(		self :	Any				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	Union[str, Any]				,    UpperCamelCase_ :	str				,    **UpperCamelCase_ :	Optional[int] ):





           '''simple docstring'''

           self.events.append('on_save' )







    def 				a__			(		self :	Optional[Any]				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	str				,    UpperCamelCase_ :	Union[str, Any]				,    **UpperCamelCase_ :	Optional[int] ):





           '''simple docstring'''

           self.events.append('on_log' )







    def 				a__			(		self :	List[Any]				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	List[Any]				,    UpperCamelCase_ :	str				,    **UpperCamelCase_ :	List[Any] ):





           '''simple docstring'''

           self.events.append('on_prediction_step' )



@require_torch
class        UpperCamelCase__ (				unittest.TestCase):







    """simple docstring"""







    def 				a__			(		self :	Optional[Any] ):





           '''simple docstring'''

           __magic_name__      				=    tempfile.mkdtemp()







    def 				a__			(		self :	List[Any] ):





           '''simple docstring'''

           shutil.rmtree(self.output_dir )







    def 				a__			(		self :	List[str]				,    UpperCamelCase_ :	Optional[int]=0				,    UpperCamelCase_ :	List[Any]=0				,    UpperCamelCase_ :	Optional[int]=6_4				,    UpperCamelCase_ :	Optional[int]=6_4				,    UpperCamelCase_ :	List[Any]=None				,    UpperCamelCase_ :	Optional[Any]=False				,    **UpperCamelCase_ :	str ):





           '''simple docstring'''

           __magic_name__      				=    RegressionDataset(length=UpperCamelCase_ )
           __magic_name__      				=    RegressionDataset(length=UpperCamelCase_ )
           __magic_name__      				=    RegressionModelConfig(a=UpperCamelCase_				,    b=UpperCamelCase_ )
           __magic_name__      				=    RegressionPreTrainedModel(UpperCamelCase_ )

           __magic_name__      				=    TrainingArguments(self.output_dir				,    disable_tqdm=UpperCamelCase_				,    report_to=[]				,    **UpperCamelCase_ )
           return Trainer(
               UpperCamelCase_				,    UpperCamelCase_				,    train_dataset=UpperCamelCase_				,    eval_dataset=UpperCamelCase_				,    callbacks=UpperCamelCase_				,    )







    def 				a__			(		self :	Optional[int]				,    UpperCamelCase_ :	str				,    UpperCamelCase_ :	Dict ):





           '''simple docstring'''

           self.assertEqual(len(UpperCamelCase_ )				,    len(UpperCamelCase_ ) )

           # Order doesn't matter
           __magic_name__      				=    sorted(UpperCamelCase_				,    key=lambda UpperCamelCase_ : cb.__name__ if isinstance(UpperCamelCase_				,    UpperCamelCase_ ) else cb.__class__.__name__ )
           __magic_name__      				=    sorted(UpperCamelCase_				,    key=lambda UpperCamelCase_ : cb.__name__ if isinstance(UpperCamelCase_				,    UpperCamelCase_ ) else cb.__class__.__name__ )

           for cba, cba in zip(UpperCamelCase_				,    UpperCamelCase_ ):
                  if isinstance(UpperCamelCase_				,    UpperCamelCase_ ) and isinstance(UpperCamelCase_				,    UpperCamelCase_ ):
                         self.assertEqual(UpperCamelCase_				,    UpperCamelCase_ )
                  elif isinstance(UpperCamelCase_				,    UpperCamelCase_ ) and not isinstance(UpperCamelCase_				,    UpperCamelCase_ ):
                         self.assertEqual(UpperCamelCase_				,    cba.__class__ )
                  elif not isinstance(UpperCamelCase_				,    UpperCamelCase_ ) and isinstance(UpperCamelCase_				,    UpperCamelCase_ ):
                         self.assertEqual(cba.__class__				,    UpperCamelCase_ )
                  else:
                         self.assertEqual(UpperCamelCase_				,    UpperCamelCase_ )







    def 				a__			(		self :	Union[str, Any]				,    UpperCamelCase_ :	Any ):





           '''simple docstring'''

           __magic_name__      				=    ['on_init_end', 'on_train_begin']
           __magic_name__      				=    0
           __magic_name__      				=    len(trainer.get_eval_dataloader() )
           __magic_name__      				=    ['on_prediction_step'] * len(trainer.get_eval_dataloader() ) + ['on_log', 'on_evaluate']
           for _ in range(trainer.state.num_train_epochs ):
                  expected_events.append('on_epoch_begin' )
                  for _ in range(UpperCamelCase_ ):
                         step += 1
                         expected_events += ["on_step_begin", "on_step_end"]
                         if step % trainer.args.logging_steps == 0:
                                expected_events.append('on_log' )
                         if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0:
                                expected_events += evaluation_events.copy()
                         if step % trainer.args.save_steps == 0:
                                expected_events.append('on_save' )
                  expected_events.append('on_epoch_end' )
                  if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH:
                         expected_events += evaluation_events.copy()
           expected_events += ["on_log", "on_train_end"]
           return expected_events







    def 				a__			(		self :	List[Any] ):





           '''simple docstring'''

           __magic_name__      				=    self.get_trainer()
           __magic_name__      				=    DEFAULT_CALLBACKS.copy() + [ProgressCallback]
           self.check_callbacks_equality(trainer.callback_handler.callbacks				,    UpperCamelCase_ )

           # Callbacks passed at init are added to the default callbacks
           __magic_name__      				=    self.get_trainer(callbacks=[MyTestTrainerCallback] )
           expected_callbacks.append(UpperCamelCase_ )
           self.check_callbacks_equality(trainer.callback_handler.callbacks				,    UpperCamelCase_ )

           # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback
           __magic_name__      				=    self.get_trainer(disable_tqdm=UpperCamelCase_ )
           __magic_name__      				=    DEFAULT_CALLBACKS.copy() + [PrinterCallback]
           self.check_callbacks_equality(trainer.callback_handler.callbacks				,    UpperCamelCase_ )







    def 				a__			(		self :	List[str] ):





           '''simple docstring'''

           __magic_name__      				=    DEFAULT_CALLBACKS.copy() + [ProgressCallback]
           __magic_name__      				=    self.get_trainer()

           # We can add, pop, or remove by class name
           trainer.remove_callback(UpperCamelCase_ )
           expected_callbacks.remove(UpperCamelCase_ )
           self.check_callbacks_equality(trainer.callback_handler.callbacks				,    UpperCamelCase_ )

           __magic_name__      				=    self.get_trainer()
           __magic_name__      				=    trainer.pop_callback(UpperCamelCase_ )
           self.assertEqual(cb.__class__				,    UpperCamelCase_ )
           self.check_callbacks_equality(trainer.callback_handler.callbacks				,    UpperCamelCase_ )

           trainer.add_callback(UpperCamelCase_ )
           expected_callbacks.insert(0				,    UpperCamelCase_ )
           self.check_callbacks_equality(trainer.callback_handler.callbacks				,    UpperCamelCase_ )

           # We can also add, pop, or remove by instance
           __magic_name__      				=    self.get_trainer()
           __magic_name__      				=    trainer.callback_handler.callbacks[0]
           trainer.remove_callback(UpperCamelCase_ )
           expected_callbacks.remove(UpperCamelCase_ )
           self.check_callbacks_equality(trainer.callback_handler.callbacks				,    UpperCamelCase_ )

           __magic_name__      				=    self.get_trainer()
           __magic_name__      				=    trainer.callback_handler.callbacks[0]
           __magic_name__      				=    trainer.pop_callback(UpperCamelCase_ )
           self.assertEqual(UpperCamelCase_				,    UpperCamelCase_ )
           self.check_callbacks_equality(trainer.callback_handler.callbacks				,    UpperCamelCase_ )

           trainer.add_callback(UpperCamelCase_ )
           expected_callbacks.insert(0				,    UpperCamelCase_ )
           self.check_callbacks_equality(trainer.callback_handler.callbacks				,    UpperCamelCase_ )







    def 				a__			(		self :	Any ):





           '''simple docstring'''

           import warnings

           # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested
           warnings.simplefilter(action='ignore'				,    category=UpperCamelCase_ )

           __magic_name__      				=    self.get_trainer(callbacks=[MyTestTrainerCallback] )
           trainer.train()
           __magic_name__      				=    trainer.callback_handler.callbacks[-2].events
           self.assertEqual(UpperCamelCase_				,    self.get_expected_events(UpperCamelCase_ ) )

           # Independent log/save/eval
           __magic_name__      				=    self.get_trainer(callbacks=[MyTestTrainerCallback]				,    logging_steps=5 )
           trainer.train()
           __magic_name__      				=    trainer.callback_handler.callbacks[-2].events
           self.assertEqual(UpperCamelCase_				,    self.get_expected_events(UpperCamelCase_ ) )

           __magic_name__      				=    self.get_trainer(callbacks=[MyTestTrainerCallback]				,    save_steps=5 )
           trainer.train()
           __magic_name__      				=    trainer.callback_handler.callbacks[-2].events
           self.assertEqual(UpperCamelCase_				,    self.get_expected_events(UpperCamelCase_ ) )

           __magic_name__      				=    self.get_trainer(callbacks=[MyTestTrainerCallback]				,    eval_steps=5				,    evaluation_strategy='steps' )
           trainer.train()
           __magic_name__      				=    trainer.callback_handler.callbacks[-2].events
           self.assertEqual(UpperCamelCase_				,    self.get_expected_events(UpperCamelCase_ ) )

           __magic_name__      				=    self.get_trainer(callbacks=[MyTestTrainerCallback]				,    evaluation_strategy='epoch' )
           trainer.train()
           __magic_name__      				=    trainer.callback_handler.callbacks[-2].events
           self.assertEqual(UpperCamelCase_				,    self.get_expected_events(UpperCamelCase_ ) )

           # A bit of everything
           __magic_name__      				=    self.get_trainer(
               callbacks=[MyTestTrainerCallback]				,    logging_steps=3				,    save_steps=1_0				,    eval_steps=5				,    evaluation_strategy='steps'				,    )
           trainer.train()
           __magic_name__      				=    trainer.callback_handler.callbacks[-2].events
           self.assertEqual(UpperCamelCase_				,    self.get_expected_events(UpperCamelCase_ ) )

           # warning should be emitted for duplicated callbacks
           with patch('transformers.trainer_callback.logger.warning' ) as warn_mock:
                  __magic_name__      				=    self.get_trainer(
                      callbacks=[MyTestTrainerCallback, MyTestTrainerCallback]				,    )
                  assert str(UpperCamelCase_ ) in warn_mock.call_args[0][0]