






import inspect
import unittest

from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
	import torch
	from torch import nn

	from transformers import RegNetForImageClassification, RegNetModel
	from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import AutoImageProcessor






class 						UpperCAmelCase__ :







		def __init__(					self       ,A__       ,A__=3       ,A__=32       ,A__=3       ,A__=10       ,A__=[10, 20, 30, 40]       ,A__=[1, 1, 2, 1]       ,A__=True       ,A__=True       ,A__="relu"       ,A__=3       ,A__=None       ,):
						_A	:				Union[str, Any]   =      parent
						_A	:				Any   =      batch_size
						_A	:				Tuple   =      image_size
						_A	:				Union[str, Any]   =      num_channels
						_A	:				int   =      embeddings_size
						_A	:				Any   =      hidden_sizes
						_A	:				str   =      depths
						_A	:				List[Any]   =      is_training
						_A	:				Dict   =      use_labels
						_A	:				List[str]   =      hidden_act
						_A	:				List[Any]   =      num_labels
						_A	:				Optional[Any]   =      scope
						_A	:				Union[str, Any]   =      len(A__		)







		def  A__      (					self		):
						_A	:				Optional[int]   =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

						_A	:				List[str]   =      None
						if self.use_labels:
										_A	:				str   =      ids_tensor([self.batch_size]       ,self.num_labels		)

						_A	:				Tuple   =      self.get_config()

						return config, pixel_values, labels







		def  A__      (					self		):
						return RegNetConfig(
						    num_channels=self.num_channels       ,embeddings_size=self.embeddings_size       ,hidden_sizes=self.hidden_sizes       ,depths=self.depths       ,hidden_act=self.hidden_act       ,num_labels=self.num_labels       ,)







		def  A__      (					self       ,A__       ,A__       ,A__		):
						_A	:				Union[str, Any]   =      RegNetModel(config=A__		)
						model.to(A__		)
						model.eval()
						_A	:				List[str]   =      model(A__		)
						# expected last hidden states: B, C, H // 32, W // 32
						self.parent.assertEqual(
						    result.last_hidden_state.shape       ,(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)       ,)







		def  A__      (					self       ,A__       ,A__       ,A__		):
						_A	:				Union[str, Any]   =      self.num_labels
						_A	:				Optional[Any]   =      RegNetForImageClassification(A__		)
						model.to(A__		)
						model.eval()
						_A	:				Optional[Any]   =      model(A__       ,labels=A__		)
						self.parent.assertEqual(result.logits.shape       ,(self.batch_size, self.num_labels)		)







		def  A__      (					self		):
						_A	:				List[Any]   =      self.prepare_config_and_inputs()
						_A	:				Optional[Any]   =      config_and_inputs
						_A	:				str   =      {'pixel_values': pixel_values}
						return config, inputs_dict






@require_torch
class 						UpperCAmelCase__ (							_a     ,				_a     ,				unittest.TestCase							):
		__snake_case      :       Optional[Any]     =   (RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
		__snake_case      :       Optional[int]     =   (
		    {"""feature-extraction""": RegNetModel, """image-classification""": RegNetForImageClassification}
		    if is_torch_available()
		    else {}
		)

		__snake_case      :       Union[str, Any]     =   False
		__snake_case      :       List[str]     =   False
		__snake_case      :       Optional[Any]     =   False
		__snake_case      :       List[Any]     =   False







		def  A__      (					self		):
						_A	:				Union[str, Any]   =      RegNetModelTester(self		)
						_A	:				Optional[Any]   =      ConfigTester(self       ,config_class=A__       ,has_text_modality=A__		)







		def  A__      (					self		):
						self.create_and_test_config_common_properties()
						self.config_tester.create_and_test_config_to_json_string()
						self.config_tester.create_and_test_config_to_json_file()
						self.config_tester.create_and_test_config_from_and_save_pretrained()
						self.config_tester.create_and_test_config_with_num_labels()
						self.config_tester.check_config_can_be_init_without_params()
						self.config_tester.check_config_arguments_init()







		def  A__      (					self		):
						return







		@unittest.skip(reason='''RegNet does not use inputs_embeds'''		)
		def  A__      (					self		):
						pass







		@unittest.skip(reason='''RegNet does not support input and output embeddings'''		)
		def  A__      (					self		):
						pass







		def  A__      (					self		):
						_A	:				Union[str, Any]   =      self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
										_A	:				Any   =      model_class(A__		)
										_A	:				Tuple   =      inspect.signature(model.forward		)
										# signature.parameters is an OrderedDict => so arg_names order is deterministic
										_A	:				Any   =      [*signature.parameters.keys()]

										_A	:				Dict   =      ['pixel_values']
										self.assertListEqual(arg_names[:1]       ,A__		)







		def  A__      (					self		):
						_A	:				Tuple   =      self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*A__		)







		def  A__      (					self		):
						_A	:				List[Any]   =      self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
										_A	:				Optional[Any]   =      model_class(config=A__		)
										for name, module in model.named_modules():
														if isinstance(A__       ,(nn.BatchNormad, nn.GroupNorm)		):
																		self.assertTrue(
																		    torch.all(module.weight == 1		)       ,msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""       ,)
																		self.assertTrue(
																		    torch.all(module.bias == 0		)       ,msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""       ,)







		def  A__      (					self		):

						def check_hidden_states_output(A__       ,A__       ,A__		):
										_A	:				str   =      model_class(A__		)
										model.to(A__		)
										model.eval()

										with torch.no_grad():
														_A	:				Any   =      model(**self._prepare_for_class(A__       ,A__		)		)

										_A	:				List[str]   =      outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

										_A	:				int   =      self.model_tester.num_stages
										self.assertEqual(len(A__		)       ,expected_num_stages + 1		)

										# RegNet's feature maps are of shape (batch_size, num_channels, height, width)
										self.assertListEqual(
										    list(hidden_states[0].shape[-2:]		)       ,[self.model_tester.image_size // 2, self.model_tester.image_size // 2]       ,)

						_A	:				Any   =      self.model_tester.prepare_config_and_inputs_for_common()
						_A	:				Any   =      ['basic', 'bottleneck']
						for model_class in self.all_model_classes:
										for layer_type in layers_type:
														_A	:				Dict   =      layer_type
														_A	:				Any   =      True
														check_hidden_states_output(A__       ,A__       ,A__		)

														# check that output_hidden_states also work using config
														del inputs_dict["output_hidden_states"]
														_A	:				str   =      True

														check_hidden_states_output(A__       ,A__       ,A__		)







		def  A__      (					self		):
						_A	:				Union[str, Any]   =      self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*A__		)







		@slow
		def  A__      (					self		):

						for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										_A	:				Optional[Any]   =      RegNetModel.from_pretrained(A__		)
										self.assertIsNotNone(A__		)



def  a__ ()		-> List[str]:
				_A	:				int   =      Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
				return image






@require_torch
@require_vision
class 						UpperCAmelCase__ (							unittest.TestCase							):







		@cached_property
		def  A__      (					self		):
						return (
						    AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)
						    if is_vision_available()
						    else None
						)







		@slow
		def  A__      (					self		):
						_A	:				Dict   =      RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		).to(A__		)

						_A	:				Dict   =      self.default_image_processor
						_A	:				Optional[Any]   =      prepare_img()
						_A	:				List[str]   =      image_processor(images=A__       ,return_tensors='''pt'''		).to(A__		)

						# forward pass
						with torch.no_grad():
										_A	:				Optional[int]   =      model(**A__		)

						# verify the logits
						_A	:				List[str]   =      torch.Size((1, 1000)		)
						self.assertEqual(outputs.logits.shape       ,A__		)

						_A	:				Optional[int]   =      torch.tensor([-0.41_80, -1.50_51, -3.48_36]		).to(A__		)

						self.assertTrue(torch.allclose(outputs.logits[0, :3]       ,A__       ,atol=1E-4		)		)







import copy

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


SCREAMING_SNAKE_CASE			: List[str]				   =					logging.get_logger(__name__)

SCREAMING_SNAKE_CASE			: Any				   =					{
    "ut/deta": "https://huggingface.co/ut/deta/resolve/main/config.json",
}






class _lowerCamelCase(		_a  ):
       lowercase_					:      Any       					=     """deta"""
       lowercase_					:      Union[str, Any]       					=     {
           """hidden_size""": """d_model""",
           """num_attention_heads""": """encoder_attention_heads""",
       }
       def __init__(   self, lowerCamelCase=None, lowerCamelCase=9_00, lowerCamelCase=20_48, lowerCamelCase=6, lowerCamelCase=20_48, lowerCamelCase=8, lowerCamelCase=6, lowerCamelCase=10_24, lowerCamelCase=8, lowerCamelCase=0.0, lowerCamelCase=True, lowerCamelCase="relu", lowerCamelCase=2_56, lowerCamelCase=0.1, lowerCamelCase=0.0, lowerCamelCase=0.0, lowerCamelCase=0.0_2, lowerCamelCase=1.0, lowerCamelCase=True, lowerCamelCase=False, lowerCamelCase="sine", lowerCamelCase=5, lowerCamelCase=4, lowerCamelCase=4, lowerCamelCase=True, lowerCamelCase=3_00, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=1, lowerCamelCase=5, lowerCamelCase=2, lowerCamelCase=1, lowerCamelCase=1, lowerCamelCase=5, lowerCamelCase=2, lowerCamelCase=0.1, lowerCamelCase=0.2_5, **lowerCamelCase, )			->  Any:




           """simple docstring"""

           if backbone_config is None:
               logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.')
               _lowercase			:				List[Any] 						=						CONFIG_MAPPING['resnet'](out_features=['stage2', 'stage3', 'stage4'])
           else:
               if isinstance(lowerCamelCase, lowerCamelCase):
                   _lowercase			:				Dict 						=						backbone_config.pop('model_type')
                   _lowercase			:				int 						=						CONFIG_MAPPING[backbone_model_type]
                   _lowercase			:				Union[str, Any] 						=						config_class.from_dict(lowerCamelCase)

           _lowercase			:				Union[str, Any] 						=						backbone_config
           _lowercase			:				Any 						=						num_queries
           _lowercase			:				Union[str, Any] 						=						max_position_embeddings
           _lowercase			:				Union[str, Any] 						=						d_model
           _lowercase			:				Optional[int] 						=						encoder_ffn_dim
           _lowercase			:				Optional[int] 						=						encoder_layers
           _lowercase			:				Optional[Any] 						=						encoder_attention_heads
           _lowercase			:				Optional[Any] 						=						decoder_ffn_dim
           _lowercase			:				Dict 						=						decoder_layers
           _lowercase			:				Tuple 						=						decoder_attention_heads
           _lowercase			:				Union[str, Any] 						=						dropout
           _lowercase			:				Optional[Any] 						=						attention_dropout
           _lowercase			:				int 						=						activation_dropout
           _lowercase			:				Tuple 						=						activation_function
           _lowercase			:				List[Any] 						=						init_std
           _lowercase			:				Union[str, Any] 						=						init_xavier_std
           _lowercase			:				int 						=						encoder_layerdrop
           _lowercase			:				Optional[int] 						=						auxiliary_loss
           _lowercase			:				Dict 						=						position_embedding_type
           # deformable attributes
           _lowercase			:				Any 						=						num_feature_levels
           _lowercase			:				str 						=						encoder_n_points
           _lowercase			:				Any 						=						decoder_n_points
           _lowercase			:				List[str] 						=						two_stage
           _lowercase			:				Dict 						=						two_stage_num_proposals
           _lowercase			:				Any 						=						with_box_refine
           _lowercase			:				List[Any] 						=						assign_first_stage
           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
           _lowercase			:				List[Any] 						=						class_cost
           _lowercase			:				Optional[int] 						=						bbox_cost
           _lowercase			:				str 						=						giou_cost
           # Loss coefficients
           _lowercase			:				Optional[int] 						=						mask_loss_coefficient
           _lowercase			:				int 						=						dice_loss_coefficient
           _lowercase			:				List[Any] 						=						bbox_loss_coefficient
           _lowercase			:				Optional[Any] 						=						giou_loss_coefficient
           _lowercase			:				str 						=						eos_coefficient
           _lowercase			:				int 						=						focal_alpha
           super().__init__(is_encoder_decoder=lowerCamelCase, **lowerCamelCase)
       @property
       def      UpperCamelCase	(   self)			->  int:




           """simple docstring"""

           return self.encoder_attention_heads
       @property
       def      UpperCamelCase	(   self)			->  int:




           """simple docstring"""

           return self.d_model




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




           """simple docstring"""

           _lowercase			:				int 						=						copy.deepcopy(self.__dict__)
           _lowercase			:				Optional[int] 						=						self.backbone_config.to_dict()
           _lowercase			:				Optional[Any] 						=						self.__class__.model_type
           return output


