






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




							def __init__(							self:    List[str]					):
														lowerCamelCase__ :     Any	  =	[]




							def 		lowerCamelCase_    (							self:    str      ,							UpperCamelCase__:    Optional[int]      ,							UpperCamelCase__:    Optional[Any]      ,							UpperCamelCase__:    Dict      ,							**UpperCamelCase__:    List[str]					):
														self.events.append("""on_init_end"""					)




							def 		lowerCamelCase_    (							self:    str      ,							UpperCamelCase__:    int      ,							UpperCamelCase__:    int      ,							UpperCamelCase__:    Optional[int]      ,							**UpperCamelCase__:    Optional[Any]					):
														self.events.append("""on_train_begin"""					)




							def 		lowerCamelCase_    (							self:    List[str]      ,							UpperCamelCase__:    str      ,							UpperCamelCase__:    List[str]      ,							UpperCamelCase__:    List[str]      ,							**UpperCamelCase__:    Any					):
														self.events.append("""on_train_end"""					)




							def 		lowerCamelCase_    (							self:    int      ,							UpperCamelCase__:    Dict      ,							UpperCamelCase__:    Optional[int]      ,							UpperCamelCase__:    str      ,							**UpperCamelCase__:    Dict					):
														self.events.append("""on_epoch_begin"""					)




							def 		lowerCamelCase_    (							self:    List[Any]      ,							UpperCamelCase__:    str      ,							UpperCamelCase__:    Optional[int]      ,							UpperCamelCase__:    Tuple      ,							**UpperCamelCase__:    Dict					):
														self.events.append("""on_epoch_end"""					)




							def 		lowerCamelCase_    (							self:    Optional[Any]      ,							UpperCamelCase__:    Any      ,							UpperCamelCase__:    Union[str, Any]      ,							UpperCamelCase__:    Optional[int]      ,							**UpperCamelCase__:    Union[str, Any]					):
														self.events.append("""on_step_begin"""					)




							def 		lowerCamelCase_    (							self:    Optional[int]      ,							UpperCamelCase__:    Optional[Any]      ,							UpperCamelCase__:    str      ,							UpperCamelCase__:    List[Any]      ,							**UpperCamelCase__:    List[str]					):
														self.events.append("""on_step_end"""					)




							def 		lowerCamelCase_    (							self:    List[str]      ,							UpperCamelCase__:    str      ,							UpperCamelCase__:    Optional[Any]      ,							UpperCamelCase__:    Dict      ,							**UpperCamelCase__:    List[str]					):
														self.events.append("""on_evaluate"""					)




							def 		lowerCamelCase_    (							self:    Optional[int]      ,							UpperCamelCase__:    Tuple      ,							UpperCamelCase__:    List[Any]      ,							UpperCamelCase__:    str      ,							**UpperCamelCase__:    Optional[int]					):
														self.events.append("""on_predict"""					)




							def 		lowerCamelCase_    (							self:    Tuple      ,							UpperCamelCase__:    int      ,							UpperCamelCase__:    str      ,							UpperCamelCase__:    Union[str, Any]      ,							**UpperCamelCase__:    str					):
														self.events.append("""on_save"""					)




							def 		lowerCamelCase_    (							self:    Optional[Any]      ,							UpperCamelCase__:    List[str]      ,							UpperCamelCase__:    Any      ,							UpperCamelCase__:    List[str]      ,							**UpperCamelCase__:    List[str]					):
														self.events.append("""on_log"""					)




							def 		lowerCamelCase_    (							self:    Optional[int]      ,							UpperCamelCase__:    List[str]      ,							UpperCamelCase__:    Optional[Any]      ,							UpperCamelCase__:    str      ,							**UpperCamelCase__:    Tuple					):
														self.events.append("""on_prediction_step"""					)



@require_torch
class _lowercase     (    unittest.TestCase		):




							def 		lowerCamelCase_    (							self:    List[Any]					):
														lowerCamelCase__ :     Union[str, Any]	  =	tempfile.mkdtemp()




							def 		lowerCamelCase_    (							self:    List[str]					):
														shutil.rmtree(self.output_dir					)




							def 		lowerCamelCase_    (							self:    Any      ,							UpperCamelCase__:    Any=0      ,							UpperCamelCase__:    str=0      ,							UpperCamelCase__:    Optional[Any]=64      ,							UpperCamelCase__:    Optional[int]=64      ,							UpperCamelCase__:    Tuple=None      ,							UpperCamelCase__:    Dict=False      ,							**UpperCamelCase__:    List[Any]					):
														lowerCamelCase__ :     Union[str, Any]	  =	RegressionDataset(length=__UpperCAmelCase					)
														lowerCamelCase__ :     Optional[int]	  =	RegressionDataset(length=__UpperCAmelCase					)
														lowerCamelCase__ :     Any	  =	RegressionModelConfig(a=__UpperCAmelCase      ,							b=__UpperCAmelCase					)
														lowerCamelCase__ :     List[Any]	  =	RegressionPreTrainedModel(__UpperCAmelCase					)

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




							def 		lowerCamelCase_    (							self:    int      ,							UpperCamelCase__:    Optional[int]      ,							UpperCamelCase__:    List[str]					):
														self.assertEqual(len(__UpperCAmelCase					)      ,							len(__UpperCAmelCase					)					)

														# Order doesn't matter
														lowerCamelCase__ :     str	  =	sorted(__UpperCAmelCase      ,							key=lambda UpperCamelCase__					: cb.__name__ if isinstance(__UpperCAmelCase      ,							__UpperCAmelCase					) else cb.__class__.__name__					)
														lowerCamelCase__ :     int	  =	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 		lowerCamelCase_    (							self:    int      ,							UpperCamelCase__:    int					):
														lowerCamelCase__ :     Any	  =	["""on_init_end""", """on_train_begin"""]
														lowerCamelCase__ :     Optional[int]	  =	0
														lowerCamelCase__ :     Dict	  =	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(__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 		lowerCamelCase_    (							self:    Optional[Any]					):
														lowerCamelCase__ :     str	  =	self.get_trainer()
														lowerCamelCase__ :     Dict	  =	DEFAULT_CALLBACKS.copy() + [ProgressCallback]
														self.check_callbacks_equality(trainer.callback_handler.callbacks      ,							__UpperCAmelCase					)

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




							def 		lowerCamelCase_    (							self:    Tuple					):
														lowerCamelCase__ :     Union[str, Any]	  =	DEFAULT_CALLBACKS.copy() + [ProgressCallback]
														lowerCamelCase__ :     Any	  =	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					)

														lowerCamelCase__ :     Optional[int]	  =	self.get_trainer()
														lowerCamelCase__ :     Union[str, Any]	  =	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
														lowerCamelCase__ :     int	  =	self.get_trainer()
														lowerCamelCase__ :     Dict	  =	trainer.callback_handler.callbacks[0]
														trainer.remove_callback(__UpperCAmelCase					)
														expected_callbacks.remove(__UpperCAmelCase					)
														self.check_callbacks_equality(trainer.callback_handler.callbacks      ,							__UpperCAmelCase					)

														lowerCamelCase__ :     Optional[int]	  =	self.get_trainer()
														lowerCamelCase__ :     Optional[int]	  =	trainer.callback_handler.callbacks[0]
														lowerCamelCase__ :     List[Any]	  =	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 		lowerCamelCase_    (							self:    Tuple					):
														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					)

														lowerCamelCase__ :     Dict	  =	self.get_trainer(callbacks=[MyTestTrainerCallback]					)
														trainer.train()
														lowerCamelCase__ :     str	  =	trainer.callback_handler.callbacks[-2].events
														self.assertEqual(__UpperCAmelCase      ,							self.get_expected_events(__UpperCAmelCase					)					)

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

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

														lowerCamelCase__ :     List[Any]	  =	self.get_trainer(callbacks=[MyTestTrainerCallback]      ,							eval_steps=5      ,							evaluation_strategy="""steps"""					)
														trainer.train()
														lowerCamelCase__ :     Dict	  =	trainer.callback_handler.callbacks[-2].events
														self.assertEqual(__UpperCAmelCase      ,							self.get_expected_events(__UpperCAmelCase					)					)

														lowerCamelCase__ :     int	  =	self.get_trainer(callbacks=[MyTestTrainerCallback]      ,							evaluation_strategy="""epoch"""					)
														trainer.train()
														lowerCamelCase__ :     int	  =	trainer.callback_handler.callbacks[-2].events
														self.assertEqual(__UpperCAmelCase      ,							self.get_expected_events(__UpperCAmelCase					)					)

														# A bit of everything
														lowerCamelCase__ :     Union[str, Any]	  =	self.get_trainer(
														    callbacks=[MyTestTrainerCallback]      ,							logging_steps=3      ,							save_steps=10      ,							eval_steps=5      ,							evaluation_strategy="""steps"""      ,							)
														trainer.train()
														lowerCamelCase__ :     Tuple	  =	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:
																					lowerCamelCase__ :     Optional[Any]	  =	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 import CONFIG_MAPPING


_A     :      Union[str, Any]   					=logging.get_logger(__name__)

_A     :      List[Any]   					={
    '''SenseTime/deformable-detr''': '''https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json''',
    # See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr
}

class _lowercase     (    _lowercase		):
							a    				=	"""deformable_detr"""
							a    				=	{
							    """hidden_size""": """d_model""",
							    """num_attention_heads""": """encoder_attention_heads""",
							}




							def __init__(							self:    Optional[int]      ,							UpperCamelCase__:    Tuple=True      ,							UpperCamelCase__:    Tuple=None      ,							UpperCamelCase__:    List[str]=3      ,							UpperCamelCase__:    Any=300      ,							UpperCamelCase__:    Optional[int]=1_024      ,							UpperCamelCase__:    int=6      ,							UpperCamelCase__:    str=1_024      ,							UpperCamelCase__:    Optional[Any]=8      ,							UpperCamelCase__:    Optional[Any]=6      ,							UpperCamelCase__:    Union[str, Any]=1_024      ,							UpperCamelCase__:    Tuple=8      ,							UpperCamelCase__:    str=0.0      ,							UpperCamelCase__:    Tuple=True      ,							UpperCamelCase__:    Any="relu"      ,							UpperCamelCase__:    Any=256      ,							UpperCamelCase__:    List[Any]=0.1      ,							UpperCamelCase__:    Optional[int]=0.0      ,							UpperCamelCase__:    Any=0.0      ,							UpperCamelCase__:    List[str]=0.02      ,							UpperCamelCase__:    str=1.0      ,							UpperCamelCase__:    Any=True      ,							UpperCamelCase__:    List[Any]=False      ,							UpperCamelCase__:    str="sine"      ,							UpperCamelCase__:    Optional[Any]="resnet50"      ,							UpperCamelCase__:    Optional[int]=True      ,							UpperCamelCase__:    Optional[int]=False      ,							UpperCamelCase__:    List[Any]=4      ,							UpperCamelCase__:    Any=4      ,							UpperCamelCase__:    int=4      ,							UpperCamelCase__:    int=False      ,							UpperCamelCase__:    Optional[Any]=300      ,							UpperCamelCase__:    str=False      ,							UpperCamelCase__:    int=1      ,							UpperCamelCase__:    Tuple=5      ,							UpperCamelCase__:    List[Any]=2      ,							UpperCamelCase__:    Optional[int]=1      ,							UpperCamelCase__:    int=1      ,							UpperCamelCase__:    Tuple=5      ,							UpperCamelCase__:    str=2      ,							UpperCamelCase__:    str=0.1      ,							UpperCamelCase__:    List[str]=0.25      ,							UpperCamelCase__:    Any=False      ,							**UpperCamelCase__:    Optional[Any]      ,							):
														if backbone_config is not None and use_timm_backbone:
																					raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`."""					)

														if not use_timm_backbone:
																					if backbone_config is None:
																												logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone."""					)
																												lowerCamelCase__ :     Union[str, Any]	  =	CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""]					)
																					elif isinstance(UpperCamelCase__      ,							UpperCamelCase__					):
																												lowerCamelCase__ :     Tuple	  =	backbone_config.get("""model_type"""					)
																												lowerCamelCase__ :     Dict	  =	CONFIG_MAPPING[backbone_model_type]
																												lowerCamelCase__ :     Optional[Any]	  =	config_class.from_dict(UpperCamelCase__					)
														lowerCamelCase__ :     Tuple	  =	use_timm_backbone
														lowerCamelCase__ :     Tuple	  =	backbone_config
														lowerCamelCase__ :     Union[str, Any]	  =	num_channels
														lowerCamelCase__ :     str	  =	num_queries
														lowerCamelCase__ :     int	  =	max_position_embeddings
														lowerCamelCase__ :     str	  =	d_model
														lowerCamelCase__ :     Dict	  =	encoder_ffn_dim
														lowerCamelCase__ :     Union[str, Any]	  =	encoder_layers
														lowerCamelCase__ :     int	  =	encoder_attention_heads
														lowerCamelCase__ :     str	  =	decoder_ffn_dim
														lowerCamelCase__ :     Optional[Any]	  =	decoder_layers
														lowerCamelCase__ :     Optional[int]	  =	decoder_attention_heads
														lowerCamelCase__ :     int	  =	dropout
														lowerCamelCase__ :     Optional[Any]	  =	attention_dropout
														lowerCamelCase__ :     List[Any]	  =	activation_dropout
														lowerCamelCase__ :     List[Any]	  =	activation_function
														lowerCamelCase__ :     int	  =	init_std
														lowerCamelCase__ :     Dict	  =	init_xavier_std
														lowerCamelCase__ :     Tuple	  =	encoder_layerdrop
														lowerCamelCase__ :     str	  =	auxiliary_loss
														lowerCamelCase__ :     int	  =	position_embedding_type
														lowerCamelCase__ :     Tuple	  =	backbone
														lowerCamelCase__ :     Tuple	  =	use_pretrained_backbone
														lowerCamelCase__ :     Optional[int]	  =	dilation
														# deformable attributes
														lowerCamelCase__ :     Optional[int]	  =	num_feature_levels
														lowerCamelCase__ :     Tuple	  =	encoder_n_points
														lowerCamelCase__ :     Tuple	  =	decoder_n_points
														lowerCamelCase__ :     Dict	  =	two_stage
														lowerCamelCase__ :     int	  =	two_stage_num_proposals
														lowerCamelCase__ :     Any	  =	with_box_refine
														if two_stage is True and with_box_refine is False:
																					raise ValueError("""If two_stage is True, with_box_refine must be True."""					)
														# Hungarian matcher
														lowerCamelCase__ :     Optional[int]	  =	class_cost
														lowerCamelCase__ :     List[str]	  =	bbox_cost
														lowerCamelCase__ :     Any	  =	giou_cost
														# Loss coefficients
														lowerCamelCase__ :     Union[str, Any]	  =	mask_loss_coefficient
														lowerCamelCase__ :     Tuple	  =	dice_loss_coefficient
														lowerCamelCase__ :     int	  =	bbox_loss_coefficient
														lowerCamelCase__ :     Optional[Any]	  =	giou_loss_coefficient
														lowerCamelCase__ :     Dict	  =	eos_coefficient
														lowerCamelCase__ :     Any	  =	focal_alpha
														lowerCamelCase__ :     Optional[Any]	  =	disable_custom_kernels
														super().__init__(is_encoder_decoder=UpperCamelCase__      ,							**UpperCamelCase__					)




							@property
							def 		lowerCamelCase_    (							self:    Dict					):
														return self.encoder_attention_heads




							@property
							def 		lowerCamelCase_    (							self:    Any					):
														return self.d_model




							def 		lowerCamelCase_    (							self:    List[str]					):
														lowerCamelCase__ :     Optional[int]	  =	copy.deepcopy(self.__dict__					)
														if self.backbone_config is not None:
																					lowerCamelCase__ :     int	  =	self.backbone_config.to_dict()
														lowerCamelCase__ :     int	  =	self.__class__.model_type
														return output

