


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 			SCREAMING_SNAKE_CASE__  (    __SCREAMING_SNAKE_CASE      ):
      def __init__(	self    :	Dict					)		->      Dict:
             a_ :		Union[str, Any]							=  []
      def 	SCREAMING_SNAKE_CASE							(	self    :	str					,							SCREAMING_SNAKE_CASE__    :	int					,							SCREAMING_SNAKE_CASE__    :	int					,							SCREAMING_SNAKE_CASE__    :	List[str]					,							**SCREAMING_SNAKE_CASE__    :	Tuple					)		->      int:
             self.events.append('on_init_end'					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Tuple					,							SCREAMING_SNAKE_CASE__    :	Union[str, Any]					,							SCREAMING_SNAKE_CASE__    :	Optional[int]					,							SCREAMING_SNAKE_CASE__    :	Optional[Any]					,							**SCREAMING_SNAKE_CASE__    :	Union[str, Any]					)		->      Union[str, Any]:
             self.events.append('on_train_begin'					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Union[str, Any]					,							SCREAMING_SNAKE_CASE__    :	Any					,							SCREAMING_SNAKE_CASE__    :	Optional[Any]					,							SCREAMING_SNAKE_CASE__    :	Tuple					,							**SCREAMING_SNAKE_CASE__    :	Dict					)		->      str:
             self.events.append('on_train_end'					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	List[Any]					,							SCREAMING_SNAKE_CASE__    :	Any					,							SCREAMING_SNAKE_CASE__    :	Any					,							SCREAMING_SNAKE_CASE__    :	Dict					,							**SCREAMING_SNAKE_CASE__    :	Optional[Any]					)		->      str:
             self.events.append('on_epoch_begin'					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Dict					,							SCREAMING_SNAKE_CASE__    :	Optional[Any]					,							SCREAMING_SNAKE_CASE__    :	List[str]					,							SCREAMING_SNAKE_CASE__    :	Optional[Any]					,							**SCREAMING_SNAKE_CASE__    :	Optional[Any]					)		->      List[Any]:
             self.events.append('on_epoch_end'					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Dict					,							SCREAMING_SNAKE_CASE__    :	Any					,							SCREAMING_SNAKE_CASE__    :	int					,							SCREAMING_SNAKE_CASE__    :	Optional[int]					,							**SCREAMING_SNAKE_CASE__    :	int					)		->      List[Any]:
             self.events.append('on_step_begin'					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	str					,							SCREAMING_SNAKE_CASE__    :	Optional[int]					,							SCREAMING_SNAKE_CASE__    :	Optional[int]					,							SCREAMING_SNAKE_CASE__    :	int					,							**SCREAMING_SNAKE_CASE__    :	Union[str, Any]					)		->      List[str]:
             self.events.append('on_step_end'					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Dict					,							SCREAMING_SNAKE_CASE__    :	Any					,							SCREAMING_SNAKE_CASE__    :	int					,							SCREAMING_SNAKE_CASE__    :	Any					,							**SCREAMING_SNAKE_CASE__    :	int					)		->      List[Any]:
             self.events.append('on_evaluate'					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Any					,							SCREAMING_SNAKE_CASE__    :	str					,							SCREAMING_SNAKE_CASE__    :	List[Any]					,							SCREAMING_SNAKE_CASE__    :	Optional[Any]					,							**SCREAMING_SNAKE_CASE__    :	str					)		->      str:
             self.events.append('on_predict'					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[int]					,							SCREAMING_SNAKE_CASE__    :	Any					,							SCREAMING_SNAKE_CASE__    :	List[Any]					,							SCREAMING_SNAKE_CASE__    :	List[str]					,							**SCREAMING_SNAKE_CASE__    :	str					)		->      List[Any]:
             self.events.append('on_save'					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	List[Any]					,							SCREAMING_SNAKE_CASE__    :	Tuple					,							SCREAMING_SNAKE_CASE__    :	List[Any]					,							SCREAMING_SNAKE_CASE__    :	str					,							**SCREAMING_SNAKE_CASE__    :	str					)		->      Tuple:
             self.events.append('on_log'					)

      def 	SCREAMING_SNAKE_CASE							(	self    :	List[str]					,							SCREAMING_SNAKE_CASE__    :	Any					,							SCREAMING_SNAKE_CASE__    :	str					,							SCREAMING_SNAKE_CASE__    :	Optional[Any]					,							**SCREAMING_SNAKE_CASE__    :	str					)		->      Optional[Any]:
             self.events.append('on_prediction_step'					)
@require_torch
class 			SCREAMING_SNAKE_CASE__  (    unittest.TestCase      ):
      def 	SCREAMING_SNAKE_CASE							(	self    :	int					)		->      Optional[int]:
             a_ :		Union[str, Any]							=  tempfile.mkdtemp()
      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[Any]					)		->      str:
             shutil.rmtree(self.output_dir					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Tuple					,							SCREAMING_SNAKE_CASE__    :	Union[str, Any]=0					,							SCREAMING_SNAKE_CASE__    :	Any=0					,							SCREAMING_SNAKE_CASE__    :	Dict=6_4					,							SCREAMING_SNAKE_CASE__    :	Optional[Any]=6_4					,							SCREAMING_SNAKE_CASE__    :	List[str]=None					,							SCREAMING_SNAKE_CASE__    :	Tuple=False					,							**SCREAMING_SNAKE_CASE__    :	Union[str, Any]					)		->      Tuple:
             a_ :		int							=  RegressionDataset(length=_SCREAMING_SNAKE_CASE					)
             a_ :		int							=  RegressionDataset(length=_SCREAMING_SNAKE_CASE					)
             a_ :		str							=  RegressionModelConfig(a=_SCREAMING_SNAKE_CASE					,							b=_SCREAMING_SNAKE_CASE					)
             a_ :		Dict							=  RegressionPreTrainedModel(_SCREAMING_SNAKE_CASE					)

             a_ :		List[Any]							=  TrainingArguments(self.output_dir					,							disable_tqdm=_SCREAMING_SNAKE_CASE					,							report_to=[]					,							**_SCREAMING_SNAKE_CASE					)
             return Trainer(
                 _SCREAMING_SNAKE_CASE					,							_SCREAMING_SNAKE_CASE					,							train_dataset=_SCREAMING_SNAKE_CASE					,							eval_dataset=_SCREAMING_SNAKE_CASE					,							callbacks=_SCREAMING_SNAKE_CASE					,							)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Tuple					,							SCREAMING_SNAKE_CASE__    :	int					,							SCREAMING_SNAKE_CASE__    :	List[Any]					)		->      Dict:
             self.assertEqual(len(_SCREAMING_SNAKE_CASE					)					,							len(_SCREAMING_SNAKE_CASE					)					)

             # Order doesn't matter
             a_ :		Dict							=  sorted(_SCREAMING_SNAKE_CASE					,							key=lambda SCREAMING_SNAKE_CASE__					: cb.__name__ if isinstance(_SCREAMING_SNAKE_CASE					,							_SCREAMING_SNAKE_CASE					) else cb.__class__.__name__					)
             a_ :		Any							=  sorted(_SCREAMING_SNAKE_CASE					,							key=lambda SCREAMING_SNAKE_CASE__					: cb.__name__ if isinstance(_SCREAMING_SNAKE_CASE					,							_SCREAMING_SNAKE_CASE					) else cb.__class__.__name__					)

             for cba, cba in zip(_SCREAMING_SNAKE_CASE					,							_SCREAMING_SNAKE_CASE					):
                    if isinstance(_SCREAMING_SNAKE_CASE					,							_SCREAMING_SNAKE_CASE					) and isinstance(_SCREAMING_SNAKE_CASE					,							_SCREAMING_SNAKE_CASE					):
                           self.assertEqual(_SCREAMING_SNAKE_CASE					,							_SCREAMING_SNAKE_CASE					)
                    elif isinstance(_SCREAMING_SNAKE_CASE					,							_SCREAMING_SNAKE_CASE					) and not isinstance(_SCREAMING_SNAKE_CASE					,							_SCREAMING_SNAKE_CASE					):
                           self.assertEqual(_SCREAMING_SNAKE_CASE					,							cba.__class__					)
                    elif not isinstance(_SCREAMING_SNAKE_CASE					,							_SCREAMING_SNAKE_CASE					) and isinstance(_SCREAMING_SNAKE_CASE					,							_SCREAMING_SNAKE_CASE					):
                           self.assertEqual(cba.__class__					,							_SCREAMING_SNAKE_CASE					)
                    else:
                           self.assertEqual(_SCREAMING_SNAKE_CASE					,							_SCREAMING_SNAKE_CASE					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	str					,							SCREAMING_SNAKE_CASE__    :	str					)		->      Tuple:
             a_ :		Tuple							=  ["on_init_end", "on_train_begin"]
             a_ :		List[Any]							=  0
             a_ :		List[str]							=  len(trainer.get_eval_dataloader()					)
             a_ :		Dict							=  ["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(_SCREAMING_SNAKE_CASE					):
                           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 	SCREAMING_SNAKE_CASE							(	self    :	Union[str, Any]					)		->      List[Any]:
             a_ :		Optional[Any]							=  self.get_trainer()
             a_ :		Dict							=  DEFAULT_CALLBACKS.copy() + [ProgressCallback]
             self.check_callbacks_equality(trainer.callback_handler.callbacks					,							_SCREAMING_SNAKE_CASE					)

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

             # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback
             a_ :		Any							=  self.get_trainer(disable_tqdm=_SCREAMING_SNAKE_CASE					)
             a_ :		List[str]							=  DEFAULT_CALLBACKS.copy() + [PrinterCallback]
             self.check_callbacks_equality(trainer.callback_handler.callbacks					,							_SCREAMING_SNAKE_CASE					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	List[Any]					)		->      Optional[Any]:
             a_ :		Union[str, Any]							=  DEFAULT_CALLBACKS.copy() + [ProgressCallback]
             a_ :		List[str]							=  self.get_trainer()

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

             a_ :		int							=  self.get_trainer()
             a_ :		List[Any]							=  trainer.pop_callback(_SCREAMING_SNAKE_CASE					)
             self.assertEqual(cb.__class__					,							_SCREAMING_SNAKE_CASE					)
             self.check_callbacks_equality(trainer.callback_handler.callbacks					,							_SCREAMING_SNAKE_CASE					)

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

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

             a_ :		Optional[int]							=  self.get_trainer()
             a_ :		List[Any]							=  trainer.callback_handler.callbacks[0]
             a_ :		Optional[Any]							=  trainer.pop_callback(_SCREAMING_SNAKE_CASE					)
             self.assertEqual(_SCREAMING_SNAKE_CASE					,							_SCREAMING_SNAKE_CASE					)
             self.check_callbacks_equality(trainer.callback_handler.callbacks					,							_SCREAMING_SNAKE_CASE					)

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

      def 	SCREAMING_SNAKE_CASE							(	self    :	Any					)		->      List[str]:
             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=_SCREAMING_SNAKE_CASE					)

             a_ :		str							=  self.get_trainer(callbacks=[MyTestTrainerCallback]					)
             trainer.train()
             a_ :		Union[str, Any]							=  trainer.callback_handler.callbacks[-2].events
             self.assertEqual(_SCREAMING_SNAKE_CASE					,							self.get_expected_events(_SCREAMING_SNAKE_CASE					)					)

             # Independent log/save/eval
             a_ :		Optional[int]							=  self.get_trainer(callbacks=[MyTestTrainerCallback]					,							logging_steps=5					)
             trainer.train()
             a_ :		Optional[int]							=  trainer.callback_handler.callbacks[-2].events
             self.assertEqual(_SCREAMING_SNAKE_CASE					,							self.get_expected_events(_SCREAMING_SNAKE_CASE					)					)

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

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

             a_ :		List[Any]							=  self.get_trainer(callbacks=[MyTestTrainerCallback]					,							evaluation_strategy='epoch'					)
             trainer.train()
             a_ :		Tuple							=  trainer.callback_handler.callbacks[-2].events
             self.assertEqual(_SCREAMING_SNAKE_CASE					,							self.get_expected_events(_SCREAMING_SNAKE_CASE					)					)

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

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








import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch


if is_torch_available():
   import torch

   from transformers.activations import gelu_new, gelu_python, get_activation
@require_torch
class 			SCREAMING_SNAKE_CASE__  (    unittest.TestCase      ):
      def 	SCREAMING_SNAKE_CASE							(	self    :	Dict					)		->      List[str]:
             a_ :		List[str]							=  torch.tensor([-1_0_0, -1, -0.1, 0, 0.1, 1.0, 1_0_0]					)
             a_ :		Union[str, Any]							=  get_activation('gelu'					)
             self.assertTrue(torch.allclose(gelu_python(SCREAMING_SNAKE_CASE__					)					,							torch_builtin(SCREAMING_SNAKE_CASE__					)					)					)
             self.assertFalse(torch.allclose(gelu_python(SCREAMING_SNAKE_CASE__					)					,							gelu_new(SCREAMING_SNAKE_CASE__					)					)					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Union[str, Any]					)		->      Any:
             a_ :		List[str]							=  torch.tensor([-1_0_0, -1, -0.1, 0, 0.1, 1.0, 1_0_0]					)
             a_ :		Union[str, Any]							=  get_activation('gelu'					)
             a_ :		str							=  get_activation('gelu_10'					)

             a_ :		Tuple							=  torch_builtin(SCREAMING_SNAKE_CASE__					)
             a_ :		str							=  geluaa(SCREAMING_SNAKE_CASE__					)

             a_ :		List[Any]							=  torch.where(y_gelu_aa < 10.0					,							1					,							0					)

             self.assertTrue(torch.max(SCREAMING_SNAKE_CASE__					).item() == 10.0					)
             self.assertTrue(torch.allclose(y_gelu * clipped_mask					,							y_gelu_aa * clipped_mask					)					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Dict					)		->      List[Any]:
             get_activation('gelu'					)
             get_activation('gelu_10'					)
             get_activation('gelu_fast'					)
             get_activation('gelu_new'					)
             get_activation('gelu_python'					)
             get_activation('gelu_pytorch_tanh'					)
             get_activation('linear'					)
             get_activation('mish'					)
             get_activation('quick_gelu'					)
             get_activation('relu'					)
             get_activation('sigmoid'					)
             get_activation('silu'					)
             get_activation('swish'					)
             get_activation('tanh'					)
             with self.assertRaises(SCREAMING_SNAKE_CASE__					):
                    get_activation('bogus'					)
             with self.assertRaises(SCREAMING_SNAKE_CASE__					):
                    get_activation(SCREAMING_SNAKE_CASE__					)

      def 	SCREAMING_SNAKE_CASE							(	self    :	str					)		->      str:
             a_ :		Any							=  get_activation('gelu'					)
             a_ :		Any							=  1
             a_ :		int							=  get_activation('gelu'					)
             self.assertEqual(acta.a					,							1					)
             with self.assertRaises(SCREAMING_SNAKE_CASE__					):
                    a_ :		Tuple							=  acta.a


