



"""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    lowercase__     (					SCREAMING_SNAKE_CASE   ):







       '''simple docstring'''


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


             '''simple docstring'''




             UpperCAmelCase_    				=							[]



       def   lowercase__       (							self    :						Optional[int]	,       _UpperCAmelCase    :						Union[str, Any]	,       _UpperCAmelCase    :						Dict	,       _UpperCAmelCase    :						Dict	,       **_UpperCAmelCase    :						Optional[Any]					)				->		Optional[Any]:


             '''simple docstring'''




             self.events.append("on_init_end"					)



       def   lowercase__       (							self    :						int	,       _UpperCAmelCase    :						Tuple	,       _UpperCAmelCase    :						Optional[int]	,       _UpperCAmelCase    :						List[str]	,       **_UpperCAmelCase    :						Optional[Any]					)				->		str:


             '''simple docstring'''




             self.events.append("on_train_begin"					)



       def   lowercase__       (							self    :						Tuple	,       _UpperCAmelCase    :						Optional[int]	,       _UpperCAmelCase    :						Optional[int]	,       _UpperCAmelCase    :						Optional[int]	,       **_UpperCAmelCase    :						Tuple					)				->		Any:


             '''simple docstring'''




             self.events.append("on_train_end"					)



       def   lowercase__       (							self    :						Union[str, Any]	,       _UpperCAmelCase    :						List[str]	,       _UpperCAmelCase    :						Optional[Any]	,       _UpperCAmelCase    :						List[Any]	,       **_UpperCAmelCase    :						List[Any]					)				->		Optional[int]:


             '''simple docstring'''




             self.events.append("on_epoch_begin"					)



       def   lowercase__       (							self    :						int	,       _UpperCAmelCase    :						Dict	,       _UpperCAmelCase    :						List[str]	,       _UpperCAmelCase    :						Optional[int]	,       **_UpperCAmelCase    :						List[str]					)				->		Optional[int]:


             '''simple docstring'''




             self.events.append("on_epoch_end"					)



       def   lowercase__       (							self    :						List[str]	,       _UpperCAmelCase    :						Any	,       _UpperCAmelCase    :						str	,       _UpperCAmelCase    :						List[str]	,       **_UpperCAmelCase    :						Tuple					)				->		Optional[Any]:


             '''simple docstring'''




             self.events.append("on_step_begin"					)



       def   lowercase__       (							self    :						List[Any]	,       _UpperCAmelCase    :						List[Any]	,       _UpperCAmelCase    :						Dict	,       _UpperCAmelCase    :						Optional[Any]	,       **_UpperCAmelCase    :						int					)				->		Tuple:


             '''simple docstring'''




             self.events.append("on_step_end"					)



       def   lowercase__       (							self    :						Any	,       _UpperCAmelCase    :						List[str]	,       _UpperCAmelCase    :						List[Any]	,       _UpperCAmelCase    :						Optional[Any]	,       **_UpperCAmelCase    :						str					)				->		Any:


             '''simple docstring'''




             self.events.append("on_evaluate"					)



       def   lowercase__       (							self    :						Any	,       _UpperCAmelCase    :						Optional[Any]	,       _UpperCAmelCase    :						List[str]	,       _UpperCAmelCase    :						Union[str, Any]	,       **_UpperCAmelCase    :						str					)				->		List[str]:


             '''simple docstring'''




             self.events.append("on_predict"					)



       def   lowercase__       (							self    :						List[str]	,       _UpperCAmelCase    :						str	,       _UpperCAmelCase    :						List[Any]	,       _UpperCAmelCase    :						Optional[Any]	,       **_UpperCAmelCase    :						Any					)				->		List[Any]:


             '''simple docstring'''




             self.events.append("on_save"					)



       def   lowercase__       (							self    :						Any	,       _UpperCAmelCase    :						Optional[Any]	,       _UpperCAmelCase    :						Any	,       _UpperCAmelCase    :						Union[str, Any]	,       **_UpperCAmelCase    :						str					)				->		List[str]:


             '''simple docstring'''




             self.events.append("on_log"					)







       def   lowercase__       (							self    :						List[str]	,       _UpperCAmelCase    :						Union[str, Any]	,       _UpperCAmelCase    :						Optional[int]	,       _UpperCAmelCase    :						Any	,       **_UpperCAmelCase    :						Any					)				->		Optional[int]:


             '''simple docstring'''




             self.events.append("on_prediction_step"					)



@require_torch
class    lowercase__     (					unittest.TestCase   ):







       '''simple docstring'''


       def   lowercase__       (							self    :						Union[str, Any]					)				->		Tuple:


             '''simple docstring'''




             UpperCAmelCase_    				=							tempfile.mkdtemp()



       def   lowercase__       (							self    :						List[str]					)				->		str:


             '''simple docstring'''




             shutil.rmtree(self.output_dir					)



       def   lowercase__       (							self    :						Union[str, Any]	,       _UpperCAmelCase    :						str=0	,       _UpperCAmelCase    :						List[str]=0	,       _UpperCAmelCase    :						Any=64	,       _UpperCAmelCase    :						Dict=64	,       _UpperCAmelCase    :						str=None	,       _UpperCAmelCase    :						Dict=False	,       **_UpperCAmelCase    :						Tuple					)				->		Dict:


             '''simple docstring'''




             UpperCAmelCase_    				=							RegressionDataset(length=_UpperCAmelCase					)
             UpperCAmelCase_    				=							RegressionDataset(length=_UpperCAmelCase					)
             UpperCAmelCase_    				=							RegressionModelConfig(a=_UpperCAmelCase	,       b=_UpperCAmelCase					)
             UpperCAmelCase_    				=							RegressionPreTrainedModel(_UpperCAmelCase					)

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



       def   lowercase__       (							self    :						Dict	,       _UpperCAmelCase    :						Tuple	,       _UpperCAmelCase    :						Tuple					)				->		Optional[Any]:


             '''simple docstring'''




             self.assertEqual(len(_UpperCAmelCase					)	,       len(_UpperCAmelCase					)					)

             # Order doesn't matter
             UpperCAmelCase_    				=							sorted(_UpperCAmelCase	,       key=lambda _UpperCAmelCase					: cb.__name__ if isinstance(_UpperCAmelCase	,       _UpperCAmelCase					) else cb.__class__.__name__					)
             UpperCAmelCase_    				=							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   lowercase__       (							self    :						Union[str, Any]	,       _UpperCAmelCase    :						Dict					)				->		Optional[Any]:


             '''simple docstring'''




             UpperCAmelCase_    				=							["on_init_end", "on_train_begin"]
             UpperCAmelCase_    				=							0
             UpperCAmelCase_    				=							len(trainer.get_eval_dataloader()					)
             UpperCAmelCase_    				=							["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   lowercase__       (							self    :						List[str]					)				->		Optional[Any]:


             '''simple docstring'''




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

             # Callbacks passed at init are added to the default callbacks
             UpperCAmelCase_    				=							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
             UpperCAmelCase_    				=							self.get_trainer(disable_tqdm=_UpperCAmelCase					)
             UpperCAmelCase_    				=							DEFAULT_CALLBACKS.copy() + [PrinterCallback]
             self.check_callbacks_equality(trainer.callback_handler.callbacks	,       _UpperCAmelCase					)



       def   lowercase__       (							self    :						Tuple					)				->		str:


             '''simple docstring'''




             UpperCAmelCase_    				=							DEFAULT_CALLBACKS.copy() + [ProgressCallback]
             UpperCAmelCase_    				=							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					)

             UpperCAmelCase_    				=							self.get_trainer()
             UpperCAmelCase_    				=							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
             UpperCAmelCase_    				=							self.get_trainer()
             UpperCAmelCase_    				=							trainer.callback_handler.callbacks[0]
             trainer.remove_callback(_UpperCAmelCase					)
             expected_callbacks.remove(_UpperCAmelCase					)
             self.check_callbacks_equality(trainer.callback_handler.callbacks	,       _UpperCAmelCase					)

             UpperCAmelCase_    				=							self.get_trainer()
             UpperCAmelCase_    				=							trainer.callback_handler.callbacks[0]
             UpperCAmelCase_    				=							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   lowercase__       (							self    :						Tuple					)				->		str:


             '''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					)

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

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

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

             UpperCAmelCase_    				=							self.get_trainer(callbacks=[MyTestTrainerCallback]	,       eval_steps=5	,       evaluation_strategy="steps"					)
             trainer.train()
             UpperCAmelCase_    				=							trainer.callback_handler.callbacks[-2].events
             self.assertEqual(_UpperCAmelCase	,       self.get_expected_events(_UpperCAmelCase					)					)

             UpperCAmelCase_    				=							self.get_trainer(callbacks=[MyTestTrainerCallback]	,       evaluation_strategy="epoch"					)
             trainer.train()
             UpperCAmelCase_    				=							trainer.callback_handler.callbacks[-2].events
             self.assertEqual(_UpperCAmelCase	,       self.get_expected_events(_UpperCAmelCase					)					)

             # A bit of everything
             UpperCAmelCase_    				=							self.get_trainer(
                 callbacks=[MyTestTrainerCallback]	,       logging_steps=3	,       save_steps=10	,       eval_steps=5	,       evaluation_strategy="steps"	,       )
             trainer.train()
             UpperCAmelCase_    				=							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:
                   UpperCAmelCase_    				=							self.get_trainer(
                       callbacks=[MyTestTrainerCallback, MyTestTrainerCallback]	,       )
                   assert str(_UpperCAmelCase					) in warn_mock.call_args[0][0]









"""simple docstring"""





from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


lowerCamelCase      =		{
    """configuration_swinv2""": ["""SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Swinv2Config"""],
}


try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowerCamelCase      =		[
      """SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST""",
      """Swinv2ForImageClassification""",
      """Swinv2ForMaskedImageModeling""",
      """Swinv2Model""",
      """Swinv2PreTrainedModel""",
  ]


if TYPE_CHECKING:
  from .configuration_swinva import SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinvaConfig

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_swinva import (
        SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST,
        SwinvaForImageClassification,
        SwinvaForMaskedImageModeling,
        SwinvaModel,
        SwinvaPreTrainedModel,
    )


else:
  import sys

  lowerCamelCase      =		_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)




