


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     _lowerCamelCase					(   _UpperCamelCase     ):




       """simple docstring"""



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




         '''simple docstring'''





         A_ :							int							=   []



       def 			_snake_case			( self							,			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE							,			**_SCREAMING_SNAKE_CASE						)->Any:




         '''simple docstring'''





         self.events.append('''on_init_end'''						)



       def 			_snake_case			( self							,			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE							,			**_SCREAMING_SNAKE_CASE						)->List[Any]:




         '''simple docstring'''





         self.events.append('''on_train_begin'''						)



       def 			_snake_case			( self							,			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE							,			**_SCREAMING_SNAKE_CASE						)->Optional[Any]:




         '''simple docstring'''





         self.events.append('''on_train_end'''						)



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




         '''simple docstring'''





         self.events.append('''on_epoch_begin'''						)



       def 			_snake_case			( self							,			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE							,			**_SCREAMING_SNAKE_CASE						)->Tuple:




         '''simple docstring'''





         self.events.append('''on_epoch_end'''						)



       def 			_snake_case			( self							,			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE							,			**_SCREAMING_SNAKE_CASE						)->Dict:




         '''simple docstring'''





         self.events.append('''on_step_begin'''						)



       def 			_snake_case			( self							,			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE							,			**_SCREAMING_SNAKE_CASE						)->Optional[int]:




         '''simple docstring'''





         self.events.append('''on_step_end'''						)



       def 			_snake_case			( self							,			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE							,			**_SCREAMING_SNAKE_CASE						)->Optional[int]:




         '''simple docstring'''





         self.events.append('''on_evaluate'''						)



       def 			_snake_case			( self							,			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE							,			**_SCREAMING_SNAKE_CASE						)->Dict:




         '''simple docstring'''





         self.events.append('''on_predict'''						)



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




         '''simple docstring'''





         self.events.append('''on_save'''						)



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




         '''simple docstring'''





         self.events.append('''on_log'''						)







       def 			_snake_case			( self							,			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE							,			**_SCREAMING_SNAKE_CASE						)->Dict:




         '''simple docstring'''





         self.events.append('''on_prediction_step'''						)






@require_torch
class     _lowerCamelCase					(   unittest.TestCase     ):




       """simple docstring"""



       def 			_snake_case			( self						)->Optional[Any]:




         '''simple docstring'''





         A_ :							Any							=   tempfile.mkdtemp()



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




         '''simple docstring'''





         shutil.rmtree(self.output_dir						)



       def 			_snake_case			( self							,			_SCREAMING_SNAKE_CASE=0							,			_SCREAMING_SNAKE_CASE=0							,			_SCREAMING_SNAKE_CASE=64							,			_SCREAMING_SNAKE_CASE=64							,			_SCREAMING_SNAKE_CASE=None							,			_SCREAMING_SNAKE_CASE=False							,			**_SCREAMING_SNAKE_CASE						)->Dict:




         '''simple docstring'''





         A_ :							Dict							=   RegressionDataset(length=lowerCamelCase_						)
         A_ :							Dict							=   RegressionDataset(length=lowerCamelCase_						)
         A_ :							List[Any]							=   RegressionModelConfig(a=lowerCamelCase_							,			b=lowerCamelCase_						)
         A_ :							List[str]							=   RegressionPreTrainedModel(lowerCamelCase_						)

         A_ :							Tuple							=   TrainingArguments(self.output_dir							,			disable_tqdm=lowerCamelCase_							,			report_to=[]							,			**lowerCamelCase_						)
         return Trainer(
             lowerCamelCase_							,			lowerCamelCase_							,			train_dataset=lowerCamelCase_							,			eval_dataset=lowerCamelCase_							,			callbacks=lowerCamelCase_							,			)



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




         '''simple docstring'''





         self.assertEqual(len(lowerCamelCase_						)							,			len(lowerCamelCase_						)						)

         # Order doesn't matter
         A_ :							str							=   sorted(lowerCamelCase_							,			key=lambda _SCREAMING_SNAKE_CASE						: cb.__name__ if isinstance(lowerCamelCase_							,			lowerCamelCase_						) else cb.__class__.__name__						)
         A_ :							str							=   sorted(lowerCamelCase_							,			key=lambda _SCREAMING_SNAKE_CASE						: cb.__name__ if isinstance(lowerCamelCase_							,			lowerCamelCase_						) else cb.__class__.__name__						)

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



       def 			_snake_case			( self							,			_SCREAMING_SNAKE_CASE						)->Any:




         '''simple docstring'''





         A_ :							Any							=   ['on_init_end', 'on_train_begin']
         A_ :							List[str]							=   0
         A_ :							int							=   len(trainer.get_eval_dataloader()						)
         A_ :							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(lowerCamelCase_						):
             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 			_snake_case			( self						)->Optional[int]:




         '''simple docstring'''





         A_ :							Optional[Any]							=   self.get_trainer()
         A_ :							List[str]							=   DEFAULT_CALLBACKS.copy() + [ProgressCallback]
         self.check_callbacks_equality(trainer.callback_handler.callbacks							,			lowerCamelCase_						)

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

         # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback
         A_ :							Dict							=   self.get_trainer(disable_tqdm=lowerCamelCase_						)
         A_ :							Any							=   DEFAULT_CALLBACKS.copy() + [PrinterCallback]
         self.check_callbacks_equality(trainer.callback_handler.callbacks							,			lowerCamelCase_						)



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




         '''simple docstring'''





         A_ :							Union[str, Any]							=   DEFAULT_CALLBACKS.copy() + [ProgressCallback]
         A_ :							Optional[int]							=   self.get_trainer()

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

         A_ :							Dict							=   self.get_trainer()
         A_ :							Dict							=   trainer.pop_callback(lowerCamelCase_						)
         self.assertEqual(cb.__class__							,			lowerCamelCase_						)
         self.check_callbacks_equality(trainer.callback_handler.callbacks							,			lowerCamelCase_						)

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

         # We can also add, pop, or remove by instance
         A_ :							Union[str, Any]							=   self.get_trainer()
         A_ :							Dict							=   trainer.callback_handler.callbacks[0]
         trainer.remove_callback(lowerCamelCase_						)
         expected_callbacks.remove(lowerCamelCase_						)
         self.check_callbacks_equality(trainer.callback_handler.callbacks							,			lowerCamelCase_						)

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

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







       def 			_snake_case			( self						)->Optional[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=lowerCamelCase_						)

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

         # Independent log/save/eval
         A_ :							List[str]							=   self.get_trainer(callbacks=[MyTestTrainerCallback]							,			logging_steps=5						)
         trainer.train()
         A_ :							Tuple							=   trainer.callback_handler.callbacks[-2].events
         self.assertEqual(lowerCamelCase_							,			self.get_expected_events(lowerCamelCase_						)						)

         A_ :							Union[str, Any]							=   self.get_trainer(callbacks=[MyTestTrainerCallback]							,			save_steps=5						)
         trainer.train()
         A_ :							Optional[Any]							=   trainer.callback_handler.callbacks[-2].events
         self.assertEqual(lowerCamelCase_							,			self.get_expected_events(lowerCamelCase_						)						)

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

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

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

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











from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


__UpperCamelCase:	Optional[int] = logging.get_logger(__name__)

__UpperCamelCase:	Optional[int] = {
    """google/mobilenet_v1_1.0_224""": """https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json""",
    """google/mobilenet_v1_0.75_192""": """https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json""",
    # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
}


class       __lowerCAmelCase					(       _UpperCamelCase      ):


	'''simple docstring'''





	_A													=				"mobilenet_v1"

	def __init__(						self:						Dict,					lowerCamelCase_:						Any=3,					lowerCamelCase_:						Dict=224,					lowerCamelCase_:						int=1.0,					lowerCamelCase_:						List[Any]=8,					lowerCamelCase_:						int="relu6",					lowerCamelCase_:						Optional[int]=True,					lowerCamelCase_:						Any=0.9_9_9,					lowerCamelCase_:						List[str]=0.0_2,					lowerCamelCase_:						Optional[int]=0.0_0_1,					**lowerCamelCase_:						Tuple,					):
			super().__init__(**lowerCamelCase_			)

			if depth_multiplier <= 0:
					raise ValueError('depth_multiplier must be greater than zero.'			)

			lowercase__					:      Optional[int]      =		num_channels
			lowercase__					:      List[Any]      =		image_size
			lowercase__					:      str      =		depth_multiplier
			lowercase__					:      Optional[Any]      =		min_depth
			lowercase__					:      int      =		hidden_act
			lowercase__					:      Dict      =		tf_padding
			lowercase__					:      Optional[Any]      =		classifier_dropout_prob
			lowercase__					:      int      =		initializer_range
			lowercase__					:      Any      =		layer_norm_eps


class       __lowerCAmelCase					(       _UpperCamelCase      ):


	'''simple docstring'''





	_A													=				version.parse("1.11"      )

	@property
	def    snake_case__(						self:						Optional[int]			):
			return OrderedDict([('pixel_values', {0: 'batch'})]			)

	@property
	def    snake_case__(						self:						Dict			):
			if self.task == "image-classification":
					return OrderedDict([('logits', {0: 'batch'})]			)
			else:
					return OrderedDict([('last_hidden_state', {0: 'batch'}), ('pooler_output', {0: 'batch'})]			)





	@property
	def    snake_case__(						self:						List[Any]			):
			return 1E-4


