


import copy
import tempfile
import unittest

from transformers import MaMaaaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from transformers.utils import cached_property

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer
 from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder




def       a_ (       SCREAMING_SNAKE_CASE__   : List[str]						,     SCREAMING_SNAKE_CASE__   : str						,     SCREAMING_SNAKE_CASE__   : Tuple						,     SCREAMING_SNAKE_CASE__   : Union[str, Any]=None						,     SCREAMING_SNAKE_CASE__   : str=None						,     SCREAMING_SNAKE_CASE__   : Optional[int]=None						,     SCREAMING_SNAKE_CASE__   : str=None						,     SCREAMING_SNAKE_CASE__   : str=None						,     ):
       '''simple docstring'''





       if attention_mask is None:
              _lowerCamelCase			:						List[str]            =input_ids.ne(config.pad_token_id	)
       if decoder_attention_mask is None:
              _lowerCamelCase			:						List[Any]            =decoder_input_ids.ne(config.pad_token_id	)
       if head_mask is None:
              _lowerCamelCase			:						List[str]            =torch.ones(config.encoder_layers						,     config.encoder_attention_heads						,     device=SCREAMING_SNAKE_CASE__	)
       if decoder_head_mask is None:
              _lowerCamelCase			:						Optional[Any]            =torch.ones(config.decoder_layers						,     config.decoder_attention_heads						,     device=SCREAMING_SNAKE_CASE__	)
       if cross_attn_head_mask is None:
              _lowerCamelCase			:						Union[str, Any]            =torch.ones(config.decoder_layers						,     config.decoder_attention_heads						,     device=SCREAMING_SNAKE_CASE__	)
       return {
           "input_ids": input_ids,
           "decoder_input_ids": decoder_input_ids,
           "attention_mask": attention_mask,
           "decoder_attention_mask": attention_mask,
           "head_mask": head_mask,
           "decoder_head_mask": decoder_head_mask,
           "cross_attn_head_mask": cross_attn_head_mask,
       }




class A    :






      def __init__(   self		:	str     ,  lowercase_		:	Optional[Any]     ,  lowercase_		:	int=13     ,  lowercase_		:	Tuple=7     ,  lowercase_		:	List[str]=True     ,  lowercase_		:	int=False     ,  lowercase_		:	Tuple=99     ,  lowercase_		:	Optional[Any]=16     ,  lowercase_		:	List[str]=2     ,  lowercase_		:	Union[str, Any]=4     ,  lowercase_		:	str=4     ,  lowercase_		:	int="relu"     ,  lowercase_		:	Any=0.1     ,  lowercase_		:	Optional[Any]=0.1     ,  lowercase_		:	Optional[Any]=0.0     ,  lowercase_		:	str=0.0     ,  lowercase_		:	List[str]=20     ,  lowercase_		:	Any=2     ,  lowercase_		:	Tuple=1     ,  lowercase_		:	List[str]=0     ,  )   ->		int:
             """simple docstring"""




             _lowerCamelCase			:						Optional[int]            =parent
             _lowerCamelCase			:						Any            =batch_size
             _lowerCamelCase			:						List[str]            =seq_length
             _lowerCamelCase			:						Optional[Any]            =is_training
             _lowerCamelCase			:						str            =use_labels
             _lowerCamelCase			:						Union[str, Any]            =vocab_size
             _lowerCamelCase			:						Union[str, Any]            =hidden_size
             _lowerCamelCase			:						int            =num_hidden_layers
             _lowerCamelCase			:						Any            =num_attention_heads
             _lowerCamelCase			:						Optional[int]            =intermediate_size
             _lowerCamelCase			:						List[Any]            =hidden_act
             _lowerCamelCase			:						str            =hidden_dropout_prob
             _lowerCamelCase			:						Dict            =attention_probs_dropout_prob
             _lowerCamelCase			:						Dict            =encoder_layerdrop
             _lowerCamelCase			:						Tuple            =decoder_layerdrop
             _lowerCamelCase			:						List[Any]            =max_position_embeddings
             _lowerCamelCase			:						Optional[int]            =eos_token_id
             _lowerCamelCase			:						Dict            =pad_token_id
             _lowerCamelCase			:						Dict            =bos_token_id






      def 			lowerCamelCase			(   self		:	Union[str, Any]					)   ->		Dict:
             """simple docstring"""




             _lowerCamelCase			:						List[Any]            =ids_tensor([self.batch_size, self.seq_length]     ,  self.vocab_size					)
             _lowerCamelCase			:						Optional[int]            =self.eos_token_id  # Eos Token
             _lowerCamelCase			:						List[str]            =ids_tensor([self.batch_size, self.seq_length]     ,  self.vocab_size					)

             # we need to clamp the input ids here to avoid having pad token in between
             # this is because for M2M100 the position_ids are prepared such that
             # all pad tokens have pos id = 2 and rest are between 2..seq_length
             # and the seq_length here is seq_length - num_pad_tokens
             # but when using past, there is no way of knowing if the past input ids had
             # pad tokens in them, which results in incorrect seq_lenth and which in turn results in
             # position_ids being off by num_pad_tokens in past input
             _lowerCamelCase			:						Tuple            =input_ids.clamp(self.pad_token_id + 1					)
             _lowerCamelCase			:						int            =decoder_input_ids.clamp(self.pad_token_id + 1					)

             _lowerCamelCase			:						Any            =self.get_config()
             _lowerCamelCase			:						Dict            =prepare_mam_aaa_inputs_dict(lowercase_     ,  lowercase_     ,  lowercase_					)
             return config, inputs_dict






      def 			lowerCamelCase			(   self		:	List[Any]					)   ->		List[str]:
             """simple docstring"""




             return MaMaaaConfig(
                 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     ,  encoder_layerdrop=self.encoder_layerdrop     ,  decoder_layerdrop=self.decoder_layerdrop     ,  max_position_embeddings=self.max_position_embeddings     ,  eos_token_id=self.eos_token_id     ,  bos_token_id=self.bos_token_id     ,  pad_token_id=self.pad_token_id     ,  )






      def 			lowerCamelCase			(   self		:	Optional[int]					)   ->		Optional[int]:
             """simple docstring"""




             _lowerCamelCase      ,	_lowerCamelCase			:						Any            =self.prepare_config_and_inputs()
             return config, inputs_dict






      def 			lowerCamelCase			(   self		:	Optional[Any]     ,  lowercase_		:	Optional[Any]     ,  lowercase_		:	Union[str, Any]					)   ->		Any:
             """simple docstring"""




             _lowerCamelCase			:						Dict            =MaMaaaModel(config=lowercase_					).get_decoder().to(lowercase_					).eval()
             _lowerCamelCase			:						int            =inputs_dict['input_ids']
             _lowerCamelCase			:						Optional[int]            =inputs_dict['attention_mask']
             _lowerCamelCase			:						Optional[int]            =inputs_dict['head_mask']

             # first forward pass
             _lowerCamelCase			:						Union[str, Any]            =model(lowercase_     ,  attention_mask=lowercase_     ,  head_mask=lowercase_     ,  use_cache=lowercase_					)

             _lowerCamelCase      ,	_lowerCamelCase			:						Optional[Any]            =outputs.to_tuple()

             # create hypothetical multiple next token and extent to next_input_ids
             _lowerCamelCase			:						Optional[Any]            =ids_tensor((self.batch_size, 3)     ,  config.vocab_size					)
             _lowerCamelCase			:						Dict            =ids_tensor((self.batch_size, 3)     ,  2					)

             # append to next input_ids and
             _lowerCamelCase			:						Union[str, Any]            =torch.cat([input_ids, next_tokens]     ,  dim=-1					)
             _lowerCamelCase			:						int            =torch.cat([attention_mask, next_attn_mask]     ,  dim=-1					)

             _lowerCamelCase			:						int            =model(lowercase_     ,  attention_mask=lowercase_					)['last_hidden_state']
             _lowerCamelCase			:						str            =model(lowercase_     ,  attention_mask=lowercase_     ,  past_key_values=lowercase_					)[
                 'last_hidden_state'
             ]

             # select random slice
             _lowerCamelCase			:						List[Any]            =ids_tensor((1,)     ,  output_from_past.shape[-1]					).item()
             _lowerCamelCase			:						Any            =output_from_no_past[:, -3:, random_slice_idx].detach()
             _lowerCamelCase			:						Dict            =output_from_past[:, :, random_slice_idx].detach()

             self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]					)

             # test that outputs are equal for slice
             self.parent.assertTrue(torch.allclose(lowercase_     ,  lowercase_     ,  atol=1E-2					)					)






      def 			lowerCamelCase			(   self		:	Any     ,  lowercase_		:	Optional[Any]     ,  lowercase_		:	List[Any]					)   ->		List[str]:
             """simple docstring"""




             _lowerCamelCase			:						Optional[Any]            =MaMaaaModel(config=lowercase_					).to(lowercase_					).eval()
             _lowerCamelCase			:						Dict            =model(**lowercase_					)

             _lowerCamelCase			:						List[Any]            =outputs.encoder_last_hidden_state
             _lowerCamelCase			:						Tuple            =outputs.last_hidden_state

             with tempfile.TemporaryDirectory() as tmpdirname:
                    _lowerCamelCase			:						Optional[Any]            =model.get_encoder()
                    encoder.save_pretrained(lowercase_					)
                    _lowerCamelCase			:						str            =MaMaaaEncoder.from_pretrained(lowercase_					).to(lowercase_					)

             _lowerCamelCase			:						List[Any]            =encoder(inputs_dict['input_ids']     ,  attention_mask=inputs_dict['attention_mask']					)[
                 0
             ]

             self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3					)

             with tempfile.TemporaryDirectory() as tmpdirname:
                    _lowerCamelCase			:						int            =model.get_decoder()
                    decoder.save_pretrained(lowercase_					)
                    _lowerCamelCase			:						Any            =MaMaaaDecoder.from_pretrained(lowercase_					).to(lowercase_					)

             _lowerCamelCase			:						Optional[int]            =decoder(
                 input_ids=inputs_dict['decoder_input_ids']     ,  attention_mask=inputs_dict['decoder_attention_mask']     ,  encoder_hidden_states=lowercase_     ,  encoder_attention_mask=inputs_dict['attention_mask']     ,  )[0]

             self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3					)




@require_torch
class A    (  UpperCamelCase_       ,				UpperCamelCase_       ,				UpperCamelCase_       ,				unittest.TestCase	):
      UpperCamelCase__				:    Tuple =(
          (
              MaMaaaModel,
              MaMaaaForConditionalGeneration,
          )
          if is_torch_available()
          else ()
      )
      UpperCamelCase__				:    List[Any] =(MaMaaaForConditionalGeneration,) if is_torch_available() else ()
      UpperCamelCase__				:    str =(
          {
              'conversational': MaMaaaForConditionalGeneration,
              'feature-extraction': MaMaaaModel,
              'summarization': MaMaaaForConditionalGeneration,
              'text2text-generation': MaMaaaForConditionalGeneration,
              'translation': MaMaaaForConditionalGeneration,
          }
          if is_torch_available()
          else {}
      )
      UpperCamelCase__				:    Optional[Any] =True
      UpperCamelCase__				:    str =True
      UpperCamelCase__				:    str =False
      UpperCamelCase__				:    Dict =False






      def 			lowerCamelCase			(   self		:	Any     ,  lowercase_		:	Optional[int]     ,  lowercase_		:	str     ,  lowercase_		:	Union[str, Any]     ,  lowercase_		:	List[Any]     ,  lowercase_		:	Optional[int]					)   ->		str:
             """simple docstring"""




             if pipeline_test_casse_name == "TranslationPipelineTests":
                    # Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`.
                    # `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer.
                    return True

             return False






      def 			lowerCamelCase			(   self		:	Dict					)   ->		Any:
             """simple docstring"""




             _lowerCamelCase			:						Tuple            =MaMaaaModelTester(self					)
             _lowerCamelCase			:						Optional[int]            =ConfigTester(self     ,  config_class=lowercase_					)






      def 			lowerCamelCase			(   self		:	int					)   ->		List[Any]:
             """simple docstring"""




             self.config_tester.run_common_tests()






      def 			lowerCamelCase			(   self		:	List[Any]					)   ->		Any:
             """simple docstring"""




             _lowerCamelCase      ,	_lowerCamelCase			:						str            =self.model_tester.prepare_config_and_inputs()
             for model_class in self.all_model_classes:
                    _lowerCamelCase			:						Optional[int]            =model_class(lowercase_					)

                    with tempfile.TemporaryDirectory() as tmpdirname:
                           model.save_pretrained(lowercase_					)
                           _lowerCamelCase      ,	_lowerCamelCase			:						int            =model_class.from_pretrained(lowercase_     ,  output_loading_info=lowercase_					)
                    self.assertEqual(info['missing_keys']     ,  []					)






      def 			lowerCamelCase			(   self		:	Union[str, Any]					)   ->		str:
             """simple docstring"""




             _lowerCamelCase			:						Any            =self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_decoder_model_past_large_inputs(*lowercase_					)






      def 			lowerCamelCase			(   self		:	int					)   ->		Dict:
             """simple docstring"""




             _lowerCamelCase			:						Union[str, Any]            =self.model_tester.prepare_config_and_inputs_for_common()
             self.model_tester.check_encoder_decoder_model_standalone(*lowercase_					)






      def 			lowerCamelCase			(   self		:	Any					)   ->		Tuple:
             """simple docstring"""




             _lowerCamelCase      ,	_lowerCamelCase			:						Union[str, Any]            =self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
                    _lowerCamelCase			:						str            =model_class(lowercase_					)
                    model.to(lowercase_					)
                    model.eval()

                    _lowerCamelCase			:						Tuple            =copy.deepcopy(self._prepare_for_class(lowercase_     ,  lowercase_					)					)

                    if not self.is_encoder_decoder:
                           _lowerCamelCase			:						Tuple            =inputs['input_ids']
                           del inputs["input_ids"]
                    else:
                           _lowerCamelCase			:						int            =inputs['input_ids']
                           _lowerCamelCase			:						Optional[Any]            =inputs.get('decoder_input_ids'     ,  lowercase_					)
                           del inputs["input_ids"]
                           inputs.pop('decoder_input_ids'     ,  lowercase_					)

                    _lowerCamelCase			:						str            =model.get_input_embeddings()
                    if not self.is_encoder_decoder:
                           _lowerCamelCase			:						List[str]            =wte(lowercase_					)
                    else:
                           _lowerCamelCase			:						Any            =wte(lowercase_					)
                           _lowerCamelCase			:						Any            =wte(lowercase_					)

                    with torch.no_grad():
                           model(**lowercase_					)[0]






      def 			lowerCamelCase			(   self		:	Tuple					)   ->		Any:
             """simple docstring"""




             _lowerCamelCase      ,	_lowerCamelCase			:						Any            =self.model_tester.prepare_config_and_inputs()
             _lowerCamelCase			:						Any            =input_dict['input_ids']
             _lowerCamelCase			:						Union[str, Any]            =input_ids.ne(1					).to(lowercase_					)
             _lowerCamelCase			:						Any            =MaMaaaForConditionalGeneration(lowercase_					).eval().to(lowercase_					)
             if torch_device == "cuda":
                    model.half()
             model.generate(lowercase_     ,  attention_mask=lowercase_					)
             model.generate(num_beams=4     ,  do_sample=lowercase_     ,  early_stopping=lowercase_     ,  num_return_sequences=3					)




def       a_ (       SCREAMING_SNAKE_CASE__   : str	):
       '''simple docstring'''





       return torch.tensor(SCREAMING_SNAKE_CASE__						,     dtype=torch.long						,     device=SCREAMING_SNAKE_CASE__	)


lowerCamelCase		   =			1e-4




@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class A    (  unittest.TestCase	):






      @cached_property
      def 			lowerCamelCase			(   self		:	Optional[int]					)   ->		Union[str, Any]:
             """simple docstring"""




             return MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'					)






      def 			lowerCamelCase			(   self		:	Optional[Any]					)   ->		Optional[int]:
             """simple docstring"""




             _lowerCamelCase			:						str            =MaMaaaModel.from_pretrained('facebook/m2m100_418M'					).to(lowercase_					)
             _lowerCamelCase			:						List[Any]            =_long_tensor([[12_8028, 98, 12, 3_0527, 2732, 159, 7755, 6_1904, 3_9144, 38, 2]]					)
             _lowerCamelCase			:						List[Any]            =_long_tensor([[2, 12_8028, 98, 12, 3_0527, 2732, 159, 7755, 6_1904, 3_9144, 38]]					)
             _lowerCamelCase			:						List[str]            =prepare_mam_aaa_inputs_dict(model.config     ,  lowercase_     ,  lowercase_					)
             with torch.no_grad():
                    _lowerCamelCase			:						Tuple            =model(**lowercase_					)[0]
             _lowerCamelCase			:						str            =torch.Size((1, 11, 1024)					)
             self.assertEqual(output.shape     ,  lowercase_					)
             # change to expected output here
             _lowerCamelCase			:						Tuple            =torch.tensor(
                 [[-0.7780, -0.1676, 0.1038], [-6.7556, -1.3992, 0.0567], [-7.5383, -0.5920, -0.2779]]     ,  device=lowercase_					)
             self.assertTrue(torch.allclose(output[:, :3, :3]     ,  lowercase_     ,  atol=lowercase_					)					)






      def 			lowerCamelCase			(   self		:	List[str]					)   ->		str:
             """simple docstring"""




             _lowerCamelCase			:						str            =MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'					).to(lowercase_					)

             # change to intended input
             _lowerCamelCase			:						str            =_long_tensor([[12_8028, 98, 12, 3_0527, 2732, 159, 7755, 6_1904, 3_9144, 38, 2]]					)
             _lowerCamelCase			:						List[str]            =_long_tensor([[2, 12_8028, 98, 12, 3_0527, 2732, 159, 7755, 6_1904, 3_9144, 38]]					)
             _lowerCamelCase			:						int            =prepare_mam_aaa_inputs_dict(model.config     ,  lowercase_     ,  lowercase_					)
             with torch.no_grad():
                    _lowerCamelCase			:						List[Any]            =model(**lowercase_					)[0]
             _lowerCamelCase			:						List[str]            =torch.Size((1, 11, model.config.vocab_size)					)
             self.assertEqual(output.shape     ,  lowercase_					)
             # change to expected output here
             _lowerCamelCase			:						Union[str, Any]            =torch.tensor(
                 [[-1.0448, -1.0411, 3.7992], [-3.2191, -3.2386, -1.3451], [-3.6210, -3.5993, 0.4925]]     ,  device=lowercase_					)
             self.assertTrue(torch.allclose(output[:, :3, :3]     ,  lowercase_     ,  atol=lowercase_					)					)






      def 			lowerCamelCase			(   self		:	Optional[int]					)   ->		Any:
             """simple docstring"""




             _lowerCamelCase			:						Union[str, Any]            =MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'					).to(lowercase_					)
             _lowerCamelCase			:						int            =MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'     ,  src_lang='fr'     ,  tgt_lang='en'					)

             _lowerCamelCase			:						Union[str, Any]            =[
                 'L\'affaire NSA souligne l\'absence totale de débat sur le renseignement',
                 'Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.',
                 'Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent'
                 ' Fabius convoque l\'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de'
                 ' l\'ampleur de la surveillance américaine sur l\'ensemble des communications en France.',
             ]

             # The below article tests that we don't add any hypotheses outside of the top n_beams
             _lowerCamelCase			:						List[str]            =tokenizer(lowercase_     ,  padding=lowercase_     ,  return_tensors='pt'					)

             _lowerCamelCase			:						int            =model.generate(
                 input_ids=dct['input_ids'].to(lowercase_					)     ,  attention_mask=dct['attention_mask'].to(lowercase_					)     ,  num_beams=5     ,  forced_bos_token_id=tokenizer.get_lang_id('en'					)     ,  )

             _lowerCamelCase			:						Any            =[
                 'The NSA case highlights the total absence of intelligence debate',
                 'I think there are two levels of response from the French government.',
                 'When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S.'
                 ' Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all'
                 ' communications in France.',
             ]

             _lowerCamelCase			:						List[str]            =tokenizer.batch_decode(
                 hypotheses_batch.tolist()     ,  clean_up_tokenization_spaces=lowercase_     ,  skip_special_tokens=lowercase_					)
             assert generated == expected_en






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 A    (  UpperCamelCase_	):






      def __init__(   self		:	str					)   ->		Union[str, Any]:
             """simple docstring"""




             _lowerCamelCase			:						Optional[Any]            =[]






      def 			lowerCamelCase			(   self		:	Dict     ,  lowercase_		:	List[Any]     ,  lowercase_		:	Optional[Any]     ,  lowercase_		:	Optional[int]     ,  **lowercase_		:	List[Any]					)   ->		List[Any]:
             """simple docstring"""




             self.events.append('on_init_end'					)






      def 			lowerCamelCase			(   self		:	int     ,  lowercase_		:	Tuple     ,  lowercase_		:	Any     ,  lowercase_		:	Optional[Any]     ,  **lowercase_		:	Any					)   ->		Union[str, Any]:
             """simple docstring"""




             self.events.append('on_train_begin'					)






      def 			lowerCamelCase			(   self		:	Optional[int]     ,  lowercase_		:	Dict     ,  lowercase_		:	Dict     ,  lowercase_		:	Tuple     ,  **lowercase_		:	str					)   ->		Optional[Any]:
             """simple docstring"""




             self.events.append('on_train_end'					)






      def 			lowerCamelCase			(   self		:	Optional[Any]     ,  lowercase_		:	str     ,  lowercase_		:	Dict     ,  lowercase_		:	int     ,  **lowercase_		:	List[str]					)   ->		Dict:
             """simple docstring"""




             self.events.append('on_epoch_begin'					)






      def 			lowerCamelCase			(   self		:	Dict     ,  lowercase_		:	Any     ,  lowercase_		:	Dict     ,  lowercase_		:	List[Any]     ,  **lowercase_		:	Dict					)   ->		Optional[Any]:
             """simple docstring"""




             self.events.append('on_epoch_end'					)






      def 			lowerCamelCase			(   self		:	List[str]     ,  lowercase_		:	List[Any]     ,  lowercase_		:	Optional[Any]     ,  lowercase_		:	Any     ,  **lowercase_		:	Dict					)   ->		Tuple:
             """simple docstring"""




             self.events.append('on_step_begin'					)






      def 			lowerCamelCase			(   self		:	List[str]     ,  lowercase_		:	Dict     ,  lowercase_		:	str     ,  lowercase_		:	Optional[Any]     ,  **lowercase_		:	Optional[int]					)   ->		Tuple:
             """simple docstring"""




             self.events.append('on_step_end'					)






      def 			lowerCamelCase			(   self		:	Tuple     ,  lowercase_		:	int     ,  lowercase_		:	List[Any]     ,  lowercase_		:	Union[str, Any]     ,  **lowercase_		:	List[Any]					)   ->		Any:
             """simple docstring"""




             self.events.append('on_evaluate'					)






      def 			lowerCamelCase			(   self		:	Tuple     ,  lowercase_		:	Union[str, Any]     ,  lowercase_		:	Dict     ,  lowercase_		:	List[str]     ,  **lowercase_		:	Dict					)   ->		Dict:
             """simple docstring"""




             self.events.append('on_predict'					)






      def 			lowerCamelCase			(   self		:	Union[str, Any]     ,  lowercase_		:	List[str]     ,  lowercase_		:	Optional[int]     ,  lowercase_		:	List[Any]     ,  **lowercase_		:	Optional[int]					)   ->		Any:
             """simple docstring"""




             self.events.append('on_save'					)






      def 			lowerCamelCase			(   self		:	str     ,  lowercase_		:	List[Any]     ,  lowercase_		:	Any     ,  lowercase_		:	Optional[int]     ,  **lowercase_		:	Optional[int]					)   ->		List[str]:
             """simple docstring"""




             self.events.append('on_log'					)






      def 			lowerCamelCase			(   self		:	Any     ,  lowercase_		:	List[Any]     ,  lowercase_		:	int     ,  lowercase_		:	List[Any]     ,  **lowercase_		:	str					)   ->		List[Any]:
             """simple docstring"""




             self.events.append('on_prediction_step'					)




@require_torch
class A    (  unittest.TestCase	):






      def 			lowerCamelCase			(   self		:	List[Any]					)   ->		Union[str, Any]:
             """simple docstring"""




             _lowerCamelCase			:						Dict            =tempfile.mkdtemp()






      def 			lowerCamelCase			(   self		:	Union[str, Any]					)   ->		int:
             """simple docstring"""




             shutil.rmtree(self.output_dir					)






      def 			lowerCamelCase			(   self		:	Optional[Any]     ,  lowercase_		:	Optional[int]=0     ,  lowercase_		:	int=0     ,  lowercase_		:	Dict=64     ,  lowercase_		:	List[str]=64     ,  lowercase_		:	int=None     ,  lowercase_		:	Tuple=False     ,  **lowercase_		:	Dict					)   ->		Optional[int]:
             """simple docstring"""




             _lowerCamelCase			:						int            =RegressionDataset(length=lowercase_					)
             _lowerCamelCase			:						Optional[Any]            =RegressionDataset(length=lowercase_					)
             _lowerCamelCase			:						str            =RegressionModelConfig(a=lowercase_     ,  b=lowercase_					)
             _lowerCamelCase			:						Optional[Any]            =RegressionPreTrainedModel(lowercase_					)

             _lowerCamelCase			:						str            =TrainingArguments(self.output_dir     ,  disable_tqdm=lowercase_     ,  report_to=[]     ,  **lowercase_					)
             return Trainer(
                 lowercase_     ,  lowercase_     ,  train_dataset=lowercase_     ,  eval_dataset=lowercase_     ,  callbacks=lowercase_     ,  )






      def 			lowerCamelCase			(   self		:	List[str]     ,  lowercase_		:	int     ,  lowercase_		:	int					)   ->		str:
             """simple docstring"""




             self.assertEqual(len(lowercase_					)     ,  len(lowercase_					)					)

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

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






      def 			lowerCamelCase			(   self		:	Dict     ,  lowercase_		:	List[str]					)   ->		str:
             """simple docstring"""




             _lowerCamelCase			:						List[Any]            =['on_init_end', 'on_train_begin']
             _lowerCamelCase			:						Dict            =0
             _lowerCamelCase			:						str            =len(trainer.get_eval_dataloader()					)
             _lowerCamelCase			:						List[Any]            =['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(lowercase_					):
                           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 			lowerCamelCase			(   self		:	Optional[Any]					)   ->		List[str]:
             """simple docstring"""




             _lowerCamelCase			:						Any            =self.get_trainer()
             _lowerCamelCase			:						Optional[Any]            =DEFAULT_CALLBACKS.copy() + [ProgressCallback]
             self.check_callbacks_equality(trainer.callback_handler.callbacks     ,  lowercase_					)

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

             # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback
             _lowerCamelCase			:						List[str]            =self.get_trainer(disable_tqdm=lowercase_					)
             _lowerCamelCase			:						Tuple            =DEFAULT_CALLBACKS.copy() + [PrinterCallback]
             self.check_callbacks_equality(trainer.callback_handler.callbacks     ,  lowercase_					)






      def 			lowerCamelCase			(   self		:	str					)   ->		Optional[Any]:
             """simple docstring"""




             _lowerCamelCase			:						int            =DEFAULT_CALLBACKS.copy() + [ProgressCallback]
             _lowerCamelCase			:						List[str]            =self.get_trainer()

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

             _lowerCamelCase			:						Tuple            =self.get_trainer()
             _lowerCamelCase			:						Dict            =trainer.pop_callback(lowercase_					)
             self.assertEqual(cb.__class__     ,  lowercase_					)
             self.check_callbacks_equality(trainer.callback_handler.callbacks     ,  lowercase_					)

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

             # We can also add, pop, or remove by instance
             _lowerCamelCase			:						Optional[int]            =self.get_trainer()
             _lowerCamelCase			:						Any            =trainer.callback_handler.callbacks[0]
             trainer.remove_callback(lowercase_					)
             expected_callbacks.remove(lowercase_					)
             self.check_callbacks_equality(trainer.callback_handler.callbacks     ,  lowercase_					)

             _lowerCamelCase			:						Any            =self.get_trainer()
             _lowerCamelCase			:						Optional[int]            =trainer.callback_handler.callbacks[0]
             _lowerCamelCase			:						Dict            =trainer.pop_callback(lowercase_					)
             self.assertEqual(lowercase_     ,  lowercase_					)
             self.check_callbacks_equality(trainer.callback_handler.callbacks     ,  lowercase_					)

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






      def 			lowerCamelCase			(   self		:	Tuple					)   ->		Union[str, 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=lowercase_					)

             _lowerCamelCase			:						str            =self.get_trainer(callbacks=[MyTestTrainerCallback]					)
             trainer.train()
             _lowerCamelCase			:						List[Any]            =trainer.callback_handler.callbacks[-2].events
             self.assertEqual(lowercase_     ,  self.get_expected_events(lowercase_					)					)

             # Independent log/save/eval
             _lowerCamelCase			:						str            =self.get_trainer(callbacks=[MyTestTrainerCallback]     ,  logging_steps=5					)
             trainer.train()
             _lowerCamelCase			:						Union[str, Any]            =trainer.callback_handler.callbacks[-2].events
             self.assertEqual(lowercase_     ,  self.get_expected_events(lowercase_					)					)

             _lowerCamelCase			:						int            =self.get_trainer(callbacks=[MyTestTrainerCallback]     ,  save_steps=5					)
             trainer.train()
             _lowerCamelCase			:						Optional[Any]            =trainer.callback_handler.callbacks[-2].events
             self.assertEqual(lowercase_     ,  self.get_expected_events(lowercase_					)					)

             _lowerCamelCase			:						str            =self.get_trainer(callbacks=[MyTestTrainerCallback]     ,  eval_steps=5     ,  evaluation_strategy='steps'					)
             trainer.train()
             _lowerCamelCase			:						Any            =trainer.callback_handler.callbacks[-2].events
             self.assertEqual(lowercase_     ,  self.get_expected_events(lowercase_					)					)

             _lowerCamelCase			:						Optional[int]            =self.get_trainer(callbacks=[MyTestTrainerCallback]     ,  evaluation_strategy='epoch'					)
             trainer.train()
             _lowerCamelCase			:						Optional[int]            =trainer.callback_handler.callbacks[-2].events
             self.assertEqual(lowercase_     ,  self.get_expected_events(lowercase_					)					)

             # A bit of everything
             _lowerCamelCase			:						Optional[Any]            =self.get_trainer(
                 callbacks=[MyTestTrainerCallback]     ,  logging_steps=3     ,  save_steps=10     ,  eval_steps=5     ,  evaluation_strategy='steps'     ,  )
             trainer.train()
             _lowerCamelCase			:						List[str]            =trainer.callback_handler.callbacks[-2].events
             self.assertEqual(lowercase_     ,  self.get_expected_events(lowercase_					)					)

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


