
"""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   __a  (      _lowerCAmelCase	):






       def __init__(  self :							int			)->  Optional[Any]:







              """simple docstring"""
              UpperCamelCase					 =		[]






       def 	_SCREAMING_SNAKE_CASE       (  self :							Dict       ,      UpperCAmelCase_ :							Tuple       ,      UpperCAmelCase_ :							List[str]       ,      UpperCAmelCase_ :							List[str]       ,      **UpperCAmelCase_ :							int			)->  Union[str, Any]:







              """simple docstring"""
              self.events.append("on_init_end"			)






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







              """simple docstring"""
              self.events.append("on_train_begin"			)






       def 	_SCREAMING_SNAKE_CASE       (  self :							Dict       ,      UpperCAmelCase_ :							List[str]       ,      UpperCAmelCase_ :							List[Any]       ,      UpperCAmelCase_ :							Dict       ,      **UpperCAmelCase_ :							Dict			)->  Union[str, Any]:







              """simple docstring"""
              self.events.append("on_train_end"			)






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







              """simple docstring"""
              self.events.append("on_epoch_begin"			)






       def 	_SCREAMING_SNAKE_CASE       (  self :							Tuple       ,      UpperCAmelCase_ :							str       ,      UpperCAmelCase_ :							Dict       ,      UpperCAmelCase_ :							int       ,      **UpperCAmelCase_ :							Optional[int]			)->  List[Any]:







              """simple docstring"""
              self.events.append("on_epoch_end"			)






       def 	_SCREAMING_SNAKE_CASE       (  self :							List[Any]       ,      UpperCAmelCase_ :							str       ,      UpperCAmelCase_ :							Dict       ,      UpperCAmelCase_ :							List[str]       ,      **UpperCAmelCase_ :							Optional[Any]			)->  int:







              """simple docstring"""
              self.events.append("on_step_begin"			)






       def 	_SCREAMING_SNAKE_CASE       (  self :							Any       ,      UpperCAmelCase_ :							Union[str, Any]       ,      UpperCAmelCase_ :							Union[str, Any]       ,      UpperCAmelCase_ :							Union[str, Any]       ,      **UpperCAmelCase_ :							Any			)->  Optional[Any]:







              """simple docstring"""
              self.events.append("on_step_end"			)






       def 	_SCREAMING_SNAKE_CASE       (  self :							List[Any]       ,      UpperCAmelCase_ :							str       ,      UpperCAmelCase_ :							List[str]       ,      UpperCAmelCase_ :							int       ,      **UpperCAmelCase_ :							str			)->  Dict:







              """simple docstring"""
              self.events.append("on_evaluate"			)






       def 	_SCREAMING_SNAKE_CASE       (  self :							int       ,      UpperCAmelCase_ :							Dict       ,      UpperCAmelCase_ :							Tuple       ,      UpperCAmelCase_ :							str       ,      **UpperCAmelCase_ :							List[str]			)->  List[Any]:







              """simple docstring"""
              self.events.append("on_predict"			)






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







              """simple docstring"""
              self.events.append("on_save"			)






       def 	_SCREAMING_SNAKE_CASE       (  self :							Any       ,      UpperCAmelCase_ :							Any       ,      UpperCAmelCase_ :							Optional[Any]       ,      UpperCAmelCase_ :							int       ,      **UpperCAmelCase_ :							Dict			)->  Tuple:







              """simple docstring"""
              self.events.append("on_log"			)






       def 	_SCREAMING_SNAKE_CASE       (  self :							int       ,      UpperCAmelCase_ :							Tuple       ,      UpperCAmelCase_ :							List[Any]       ,      UpperCAmelCase_ :							int       ,      **UpperCAmelCase_ :							Union[str, Any]			)->  Optional[Any]:







              """simple docstring"""
              self.events.append("on_prediction_step"			)





@require_torch
class   __a  (      unittest.TestCase	):






       def 	_SCREAMING_SNAKE_CASE       (  self :							List[str]			)->  Union[str, Any]:







              """simple docstring"""
              UpperCamelCase					 =		tempfile.mkdtemp()






       def 	_SCREAMING_SNAKE_CASE       (  self :							Optional[int]			)->  Any:







              """simple docstring"""
              shutil.rmtree(self.output_dir			)






       def 	_SCREAMING_SNAKE_CASE       (  self :							List[str]       ,      UpperCAmelCase_ :							Optional[int]=0       ,      UpperCAmelCase_ :							Optional[Any]=0       ,      UpperCAmelCase_ :							Optional[Any]=64       ,      UpperCAmelCase_ :							List[str]=64       ,      UpperCAmelCase_ :							List[Any]=None       ,      UpperCAmelCase_ :							str=False       ,      **UpperCAmelCase_ :							str			)->  Optional[Any]:







              """simple docstring"""
              # disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure
              # its set to False since the tests later on depend on its value.
              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 	_SCREAMING_SNAKE_CASE       (  self :							Tuple       ,      UpperCAmelCase_ :							List[Any]       ,      UpperCAmelCase_ :							Union[str, Any]			)->  Optional[int]:







              """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 	_SCREAMING_SNAKE_CASE       (  self :							Optional[int]       ,      UpperCAmelCase_ :							List[Any]			)->  Dict:







              """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 	_SCREAMING_SNAKE_CASE       (  self :							Optional[Any]			)->  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 	_SCREAMING_SNAKE_CASE       (  self :							Optional[Any]			)->  List[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 	_SCREAMING_SNAKE_CASE       (  self :							Optional[Any]			)->  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"""


import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto.configuration_auto import CONFIG_MAPPING


SCREAMING_SNAKE_CASE      =     logging.get_logger(__name__)



class   __a  (      _lowerCAmelCase	):
       UpperCamelCase_		:					Optional[int]   =			'''upernet'''






       def __init__(  self :							int       ,      UpperCAmelCase_ :							Optional[Any]=None       ,      UpperCAmelCase_ :							Any=512       ,      UpperCAmelCase_ :							Union[str, Any]=0.02       ,      UpperCAmelCase_ :							List[Any]=[1, 2, 3, 6]       ,      UpperCAmelCase_ :							List[str]=True       ,      UpperCAmelCase_ :							Union[str, Any]=0.4       ,      UpperCAmelCase_ :							Union[str, Any]=384       ,      UpperCAmelCase_ :							Optional[Any]=256       ,      UpperCAmelCase_ :							Optional[int]=1       ,      UpperCAmelCase_ :							str=False       ,      UpperCAmelCase_ :							Tuple=255       ,      **UpperCAmelCase_ :							str       ,      )->  Tuple:







              """simple docstring"""
              super().__init__(**UpperCAmelCase_			)

              if backbone_config is None:
                     logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone."			)
                     UpperCamelCase					 =		CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"]			)
              elif isinstance(UpperCAmelCase_       ,      UpperCAmelCase_			):
                     UpperCamelCase					 =		backbone_config.get("model_type"			)
                     UpperCamelCase					 =		CONFIG_MAPPING[backbone_model_type]
                     UpperCamelCase					 =		config_class.from_dict(UpperCAmelCase_			)

              UpperCamelCase					 =		backbone_config
              UpperCamelCase					 =		hidden_size
              UpperCamelCase					 =		initializer_range
              UpperCamelCase					 =		pool_scales
              UpperCamelCase					 =		use_auxiliary_head
              UpperCamelCase					 =		auxiliary_loss_weight
              UpperCamelCase					 =		auxiliary_in_channels
              UpperCamelCase					 =		auxiliary_channels
              UpperCamelCase					 =		auxiliary_num_convs
              UpperCamelCase					 =		auxiliary_concat_input
              UpperCamelCase					 =		loss_ignore_index






       def 	_SCREAMING_SNAKE_CASE       (  self :							Optional[int]			)->  Dict:







              """simple docstring"""
              UpperCamelCase					 =		copy.deepcopy(self.__dict__			)
              UpperCamelCase					 =		self.backbone_config.to_dict()
              UpperCamelCase					 =		self.__class__.model_type
              return output





