



'''simple docstring'''

import inspect
import unittest

from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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 transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
							from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor

class 	__magic_name__						:







							def __init__(							self					:       List[str]	,_UpperCAmelCase					:       List[Any]	,_UpperCAmelCase					:       List[str]=13	,_UpperCAmelCase					:       Any=32	,_UpperCAmelCase					:       Union[str, Any]=3	,_UpperCAmelCase					:       Optional[int]=4	,_UpperCAmelCase					:       Optional[Any]=[10, 20, 30, 40]	,_UpperCAmelCase					:       Tuple=[2, 2, 3, 2]	,_UpperCAmelCase					:       Optional[int]=True	,_UpperCAmelCase					:       Optional[int]=True	,_UpperCAmelCase					:       Union[str, Any]=37	,_UpperCAmelCase					:       Optional[int]="gelu"	,_UpperCAmelCase					:       Optional[Any]=10	,_UpperCAmelCase					:       Tuple=0.02	,_UpperCAmelCase					:       Any=["stage2", "stage3", "stage4"]	,_UpperCAmelCase					:       Any=[2, 3, 4]	,_UpperCAmelCase					:       Tuple=None	,):
									_a     :      Optional[Any]        =							parent
									_a     :      List[Any]        =							batch_size
									_a     :      str        =							image_size
									_a     :      Union[str, Any]        =							num_channels
									_a     :      List[Any]        =							num_stages
									_a     :      Dict        =							hidden_sizes
									_a     :      int        =							depths
									_a     :      Tuple        =							is_training
									_a     :      List[str]        =							use_labels
									_a     :      Dict        =							intermediate_size
									_a     :      int        =							hidden_act
									_a     :      int        =							num_labels
									_a     :      Any        =							initializer_range
									_a     :      Tuple        =							out_features
									_a     :      int        =							out_indices
									_a     :      List[Any]        =							scope







							def 							__lowercase			(							self					:       Dict		):
									_a     :      List[Any]        =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

									_a     :      Union[str, Any]        =							None
									if self.use_labels:
											_a     :      Tuple        =							ids_tensor([self.batch_size]	,self.num_labels		)

									_a     :      str        =							self.get_config()

									return config, pixel_values, labels







							def 							__lowercase			(							self					:       Any		):
									return ConvNextVaConfig(
									    num_channels=self.num_channels	,hidden_sizes=self.hidden_sizes	,depths=self.depths	,num_stages=self.num_stages	,hidden_act=self.hidden_act	,is_decoder=_UpperCAmelCase	,initializer_range=self.initializer_range	,out_features=self.out_features	,out_indices=self.out_indices	,num_labels=self.num_labels	,)







							def 							__lowercase			(							self					:       Tuple	,_UpperCAmelCase					:       Any	,_UpperCAmelCase					:       Any	,_UpperCAmelCase					:       Optional[Any]		):
									_a     :      Optional[Any]        =							ConvNextVaModel(config=_UpperCAmelCase		)
									model.to(_UpperCAmelCase		)
									model.eval()
									_a     :      Any        =							model(_UpperCAmelCase		)
									# 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 							__lowercase			(							self					:       Tuple	,_UpperCAmelCase					:       Union[str, Any]	,_UpperCAmelCase					:       List[Any]	,_UpperCAmelCase					:       int		):
									_a     :      List[Any]        =							ConvNextVaForImageClassification(_UpperCAmelCase		)
									model.to(_UpperCAmelCase		)
									model.eval()
									_a     :      List[str]        =							model(_UpperCAmelCase	,labels=_UpperCAmelCase		)
									self.parent.assertEqual(result.logits.shape	,(self.batch_size, self.num_labels)		)







							def 							__lowercase			(							self					:       str	,_UpperCAmelCase					:       List[Any]	,_UpperCAmelCase					:       str	,_UpperCAmelCase					:       Optional[Any]		):
									_a     :      Optional[int]        =							ConvNextVaBackbone(config=_UpperCAmelCase		)
									model.to(_UpperCAmelCase		)
									model.eval()
									_a     :      Dict        =							model(_UpperCAmelCase		)

									# verify hidden states
									self.parent.assertEqual(len(result.feature_maps		)	,len(config.out_features		)		)
									self.parent.assertListEqual(list(result.feature_maps[0].shape		)	,[self.batch_size, self.hidden_sizes[1], 4, 4]		)

									# verify channels
									self.parent.assertEqual(len(model.channels		)	,len(config.out_features		)		)
									self.parent.assertListEqual(model.channels	,config.hidden_sizes[1:]		)

									# verify backbone works with out_features=None
									_a     :      Tuple        =							None
									_a     :      List[Any]        =							ConvNextVaBackbone(config=_UpperCAmelCase		)
									model.to(_UpperCAmelCase		)
									model.eval()
									_a     :      List[str]        =							model(_UpperCAmelCase		)

									# verify feature maps
									self.parent.assertEqual(len(result.feature_maps		)	,1		)
									self.parent.assertListEqual(list(result.feature_maps[0].shape		)	,[self.batch_size, self.hidden_sizes[-1], 1, 1]		)

									# verify channels
									self.parent.assertEqual(len(model.channels		)	,1		)
									self.parent.assertListEqual(model.channels	,[config.hidden_sizes[-1]]		)







							def 							__lowercase			(							self					:       Optional[Any]		):
									_a     :      Any        =							self.prepare_config_and_inputs()
									_a       ,					_a       ,					_a     :      Union[str, Any]        =							config_and_inputs
									_a     :      Any        =							{'pixel_values': pixel_values}
									return config, inputs_dict







							def 							__lowercase			(							self					:       str		):
									_a     :      Tuple        =							self.prepare_config_and_inputs()
									_a       ,					_a       ,					_a     :      Tuple        =							config_and_inputs
									_a     :      List[Any]        =							{'pixel_values': pixel_values, 'labels': labels}
									return config, inputs_dict

@require_torch
class 	__magic_name__						(    _UpperCamelCase			,						_UpperCamelCase			,						unittest.TestCase   ):
							lowerCAmelCase       :    str   				=					(
							    (
							        ConvNextVaModel,
							        ConvNextVaForImageClassification,
							        ConvNextVaBackbone,
							    )
							    if is_torch_available()
							    else ()
							)
							lowerCAmelCase       :    str   				=					(
							    {'feature-extraction': ConvNextVaModel, 'image-classification': ConvNextVaForImageClassification}
							    if is_torch_available()
							    else {}
							)

							lowerCAmelCase       :    int   				=					False
							lowerCAmelCase       :    str   				=					False
							lowerCAmelCase       :    Optional[Any]   				=					False
							lowerCAmelCase       :    List[str]   				=					False
							lowerCAmelCase       :    Optional[int]   				=					False







							def 							__lowercase			(							self					:       List[Any]		):
									_a     :      str        =							ConvNextVaModelTester(self		)
									_a     :      Tuple        =							ConfigTester(self	,config_class=_UpperCAmelCase	,has_text_modality=_UpperCAmelCase	,hidden_size=37		)







							def 							__lowercase			(							self					:       Optional[Any]		):
									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 							__lowercase			(							self					:       str		):
									return







							@unittest.skip(reason='ConvNextV2 does not use inputs_embeds'		)
							def 							__lowercase			(							self					:       List[Any]		):
									pass







							@unittest.skip(reason='ConvNextV2 does not support input and output embeddings'		)
							def 							__lowercase			(							self					:       Optional[int]		):
									pass







							@unittest.skip(reason='ConvNextV2 does not use feedforward chunking'		)
							def 							__lowercase			(							self					:       Any		):
									pass







							def 							__lowercase			(							self					:       List[str]		):
									if not self.model_tester.is_training:
											return

									for model_class in self.all_model_classes:
											_a       ,					_a     :      List[Any]        =							self.model_tester.prepare_config_and_inputs_with_labels()
											_a     :      Any        =							True

											if model_class.__name__ in [
											    *get_values(_UpperCAmelCase		),
											    *get_values(_UpperCAmelCase		),
											]:
													continue

											_a     :      Optional[Any]        =							model_class(_UpperCAmelCase		)
											model.to(_UpperCAmelCase		)
											model.train()
											_a     :      str        =							self._prepare_for_class(_UpperCAmelCase	,_UpperCAmelCase	,return_labels=_UpperCAmelCase		)
											_a     :      Optional[int]        =							model(**_UpperCAmelCase		).loss
											loss.backward()







							def 							__lowercase			(							self					:       str		):
									if not self.model_tester.is_training:
											return

									for model_class in self.all_model_classes:
											_a       ,					_a     :      Optional[Any]        =							self.model_tester.prepare_config_and_inputs_with_labels()
											_a     :      Optional[int]        =							False
											_a     :      Tuple        =							True

											if (
											    model_class.__name__
											    in [*get_values(_UpperCAmelCase		), *get_values(_UpperCAmelCase		)]
											    or not model_class.supports_gradient_checkpointing
											):
													continue

											_a     :      Tuple        =							model_class(_UpperCAmelCase		)
											model.to(_UpperCAmelCase		)
											model.gradient_checkpointing_enable()
											model.train()
											_a     :      Any        =							self._prepare_for_class(_UpperCAmelCase	,_UpperCAmelCase	,return_labels=_UpperCAmelCase		)
											_a     :      List[Any]        =							model(**_UpperCAmelCase		).loss
											loss.backward()







							def 							__lowercase			(							self					:       List[Any]		):
									_a       ,					_a     :      List[Any]        =							self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
											_a     :      int        =							model_class(_UpperCAmelCase		)
											_a     :      Optional[Any]        =							inspect.signature(model.forward		)
											# signature.parameters is an OrderedDict => so arg_names order is deterministic
											_a     :      Dict        =							[*signature.parameters.keys()]

											_a     :      int        =							['pixel_values']
											self.assertListEqual(arg_names[:1]	,_UpperCAmelCase		)







							def 							__lowercase			(							self					:       int		):
									_a     :      Dict        =							self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_UpperCAmelCase		)







							def 							__lowercase			(							self					:       Any		):
									def check_hidden_states_output(_UpperCAmelCase					:       List[Any]	,_UpperCAmelCase					:       Tuple	,_UpperCAmelCase					:       Dict		):
											_a     :      Union[str, Any]        =							model_class(_UpperCAmelCase		)
											model.to(_UpperCAmelCase		)
											model.eval()

											with torch.no_grad():
													_a     :      List[Any]        =							model(**self._prepare_for_class(_UpperCAmelCase	,_UpperCAmelCase		)		)

											_a     :      Any        =							outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

											_a     :      str        =							self.model_tester.num_stages
											self.assertEqual(len(_UpperCAmelCase		)	,expected_num_stages + 1		)

											# ConvNextV2'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 // 4, self.model_tester.image_size // 4]	,)

									_a       ,					_a     :      List[str]        =							self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
											_a     :      int        =							True
											check_hidden_states_output(_UpperCAmelCase	,_UpperCAmelCase	,_UpperCAmelCase		)

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											_a     :      Optional[Any]        =							True

											check_hidden_states_output(_UpperCAmelCase	,_UpperCAmelCase	,_UpperCAmelCase		)







							def 							__lowercase			(							self					:       List[Any]		):
									_a     :      Optional[Any]        =							self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase		)







							@slow
							def 							__lowercase			(							self					:       int		):
									for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											_a     :      Any        =							ConvNextVaModel.from_pretrained(_UpperCAmelCase		)
											self.assertIsNotNone(_UpperCAmelCase		)



def      __lowerCamelCase     (      )			->      List[Any]:
		_a     :      List[Any]        =							Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'  )
		return image

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







							@cached_property
							def 							__lowercase			(							self					:       Optional[Any]		):
									return AutoImageProcessor.from_pretrained('facebook/convnextv2-tiny-1k-224'		) if is_vision_available() else None







							@slow
							def 							__lowercase			(							self					:       Any		):
									_a     :      List[str]        =							ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224'		).to(_UpperCAmelCase		)

									_a     :      Optional[int]        =							self.default_image_processor
									_a     :      str        =							prepare_img()
									_a     :      str        =							preprocessor(images=_UpperCAmelCase	,return_tensors='pt'		).to(_UpperCAmelCase		)

									# forward pass
									with torch.no_grad():
											_a     :      Dict        =							model(**_UpperCAmelCase		)

									# verify the logits
									_a     :      Optional[Any]        =							torch.Size((1, 1000)		)
									self.assertEqual(outputs.logits.shape	,_UpperCAmelCase		)

									_a     :      Optional[Any]        =							torch.tensor([0.99_96, 0.19_66, -0.43_86]		).to(_UpperCAmelCase		)
									self.assertTrue(torch.allclose(outputs.logits[0, :3]	,_UpperCAmelCase	,atol=1E-4		)		)









'''simple docstring'''

import copy
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
from ..auto import CONFIG_MAPPING


__lowerCAmelCase									=   logging.get_logger(__name__)

__lowerCAmelCase									=   {
    '''microsoft/conditional-detr-resnet-50''': (
        '''https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json'''
    ),
}

class 	__magic_name__						(    _UpperCamelCase   ):
							lowerCAmelCase       :    Any   				=					'conditional_detr'
							lowerCAmelCase       :    List[str]   				=					['past_key_values']
							lowerCAmelCase       :    Optional[int]   				=					{
							    'hidden_size': 'd_model',
							    'num_attention_heads': 'encoder_attention_heads',
							}







							def __init__(							self					:       Optional[int]	,_UpperCAmelCase					:       Optional[int]=True	,_UpperCAmelCase					:       Union[str, Any]=None	,_UpperCAmelCase					:       List[Any]=3	,_UpperCAmelCase					:       List[Any]=300	,_UpperCAmelCase					:       Dict=6	,_UpperCAmelCase					:       List[str]=2048	,_UpperCAmelCase					:       Optional[int]=8	,_UpperCAmelCase					:       List[Any]=6	,_UpperCAmelCase					:       Optional[int]=2048	,_UpperCAmelCase					:       Dict=8	,_UpperCAmelCase					:       int=0.0	,_UpperCAmelCase					:       Optional[Any]=0.0	,_UpperCAmelCase					:       Optional[Any]=True	,_UpperCAmelCase					:       str="relu"	,_UpperCAmelCase					:       Tuple=256	,_UpperCAmelCase					:       Optional[int]=0.1	,_UpperCAmelCase					:       str=0.0	,_UpperCAmelCase					:       Optional[int]=0.0	,_UpperCAmelCase					:       Union[str, Any]=0.02	,_UpperCAmelCase					:       List[str]=1.0	,_UpperCAmelCase					:       Any=False	,_UpperCAmelCase					:       int="sine"	,_UpperCAmelCase					:       List[str]="resnet50"	,_UpperCAmelCase					:       Optional[int]=True	,_UpperCAmelCase					:       str=False	,_UpperCAmelCase					:       str=2	,_UpperCAmelCase					:       int=5	,_UpperCAmelCase					:       Optional[int]=2	,_UpperCAmelCase					:       str=1	,_UpperCAmelCase					:       Union[str, Any]=1	,_UpperCAmelCase					:       List[str]=2	,_UpperCAmelCase					:       Union[str, Any]=5	,_UpperCAmelCase					:       List[Any]=2	,_UpperCAmelCase					:       Optional[int]=0.25	,**_UpperCAmelCase					:       Tuple	,):
									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.'		)
													_a     :      Optional[Any]        =							CONFIG_MAPPING['resnet'](out_features=['stage4']		)
											elif isinstance(_UpperCAmelCase	,_UpperCAmelCase		):
													_a     :      str        =							backbone_config.get('model_type'		)
													_a     :      Union[str, Any]        =							CONFIG_MAPPING[backbone_model_type]
													_a     :      List[Any]        =							config_class.from_dict(_UpperCAmelCase		)

									_a     :      Tuple        =							use_timm_backbone
									_a     :      Union[str, Any]        =							backbone_config
									_a     :      List[Any]        =							num_channels
									_a     :      Union[str, Any]        =							num_queries
									_a     :      Optional[Any]        =							d_model
									_a     :      Tuple        =							encoder_ffn_dim
									_a     :      Dict        =							encoder_layers
									_a     :      List[str]        =							encoder_attention_heads
									_a     :      Union[str, Any]        =							decoder_ffn_dim
									_a     :      Optional[int]        =							decoder_layers
									_a     :      int        =							decoder_attention_heads
									_a     :      Optional[int]        =							dropout
									_a     :      Tuple        =							attention_dropout
									_a     :      List[Any]        =							activation_dropout
									_a     :      str        =							activation_function
									_a     :      Optional[Any]        =							init_std
									_a     :      Union[str, Any]        =							init_xavier_std
									_a     :      List[Any]        =							encoder_layerdrop
									_a     :      List[Any]        =							decoder_layerdrop
									_a     :      Dict        =							encoder_layers
									_a     :      List[Any]        =							auxiliary_loss
									_a     :      Optional[int]        =							position_embedding_type
									_a     :      List[Any]        =							backbone
									_a     :      Optional[int]        =							use_pretrained_backbone
									_a     :      Optional[int]        =							dilation
									# Hungarian matcher
									_a     :      Tuple        =							class_cost
									_a     :      str        =							bbox_cost
									_a     :      Any        =							giou_cost
									# Loss coefficients
									_a     :      Tuple        =							mask_loss_coefficient
									_a     :      Dict        =							dice_loss_coefficient
									_a     :      Tuple        =							cls_loss_coefficient
									_a     :      Any        =							bbox_loss_coefficient
									_a     :      Dict        =							giou_loss_coefficient
									_a     :      Union[str, Any]        =							focal_alpha
									super().__init__(is_encoder_decoder=_UpperCAmelCase	,**_UpperCAmelCase		)







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







							@property
							def 							__lowercase			(							self					:       str		):
									return self.d_model







							def 							__lowercase			(							self					:       int		):
									_a     :      List[str]        =							copy.deepcopy(self.__dict__		)
									if self.backbone_config is not None:
											_a     :      Dict        =							self.backbone_config.to_dict()
									_a     :      Union[str, Any]        =							self.__class__.model_type
									return output

class 	__magic_name__						(    _UpperCamelCase   ):
							lowerCAmelCase       :    str   				=					version.parse('1.11'   )







							@property
							def 							__lowercase			(							self					:       Dict		):
									return OrderedDict(
									    [
									        ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
									        ('pixel_mask', {0: 'batch'}),
									    ]		)







							@property
							def 							__lowercase			(							self					:       Any		):
									return 1E-5







							@property
							def 							__lowercase			(							self					:       List[Any]		):
									return 12




