


"""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 						_A  :







    """simple docstring"""




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






    def 	__snake_case							(					self				:    List[str]):
      a						:		Optional[int]      							=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

      a						:		Optional[Any]      							=			self.get_config()

      return config, pixel_values, labels






    def 	__snake_case							(					self				:    int):
      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 	__snake_case							(					self				:    List[Any]				, __UpperCAmelCase				:    str				, __UpperCAmelCase				:    Any				, __UpperCAmelCase				:    Dict):
      a						:		int      							=			ConvNextVaModel(config=__UpperCAmelCase)
      model.to(__UpperCAmelCase)
      model.eval()
      a						:		List[str]      							=			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 	__snake_case							(					self				:    int				, __UpperCAmelCase				:    Tuple				, __UpperCAmelCase				:    int				, __UpperCAmelCase				:    Dict):
      a						:		Optional[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 	__snake_case							(					self				:    List[str]				, __UpperCAmelCase				:    Optional[int]				, __UpperCAmelCase				:    List[Any]				, __UpperCAmelCase				:    List[str]):
      a						:		Optional[int]      							=			ConvNextVaBackbone(config=__UpperCAmelCase)
      model.to(__UpperCAmelCase)
      model.eval()
      a						:		List[Any]      							=			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						:		Any      							=			None
      a						:		Optional[int]      							=			ConvNextVaBackbone(config=__UpperCAmelCase)
      model.to(__UpperCAmelCase)
      model.eval()
      a						:		Optional[Any]      							=			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 	__snake_case							(					self				:    Union[str, Any]):
      a						:		str      							=			self.prepare_config_and_inputs()
      a							,		a							,		a						:		Any      							=			config_and_inputs
      a						:		List[Any]      							=			{"pixel_values": pixel_values}
      return config, inputs_dict






    def 	__snake_case							(					self				:    Union[str, Any]):
      a						:		int      							=			self.prepare_config_and_inputs()
      a							,		a							,		a						:		Optional[int]      							=			config_and_inputs
      a						:		Optional[int]      							=			{"pixel_values": pixel_values, "labels": labels}
      return config, inputs_dict






@require_torch
class 						_A  (  _a    ,_a    ,unittest.TestCase  ):







    """simple docstring"""




    UpperCAmelCase       :							Tuple	=       (
        (
            ConvNextVaModel,
            ConvNextVaForImageClassification,
            ConvNextVaBackbone,
        )
        if is_torch_available()
        else ()
    )
    UpperCAmelCase       :							Optional[int]	=       (
        {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification}
        if is_torch_available()
        else {}
    )

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






    def 	__snake_case							(					self				:    List[str]):
      a						:		Tuple      							=			ConvNextVaModelTester(self)
      a						:		str      							=			ConfigTester(self				, config_class=__UpperCAmelCase				, has_text_modality=__UpperCAmelCase				, hidden_size=37)






    def 	__snake_case							(					self				:    str):
      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 	__snake_case							(					self				:    Any):
      return






    @unittest.skip(reason="ConvNextV2 does not use inputs_embeds")
    def 	__snake_case							(					self				:    Optional[int]):
      pass






    @unittest.skip(reason="ConvNextV2 does not support input and output embeddings")
    def 	__snake_case							(					self				:    int):
      pass






    @unittest.skip(reason="ConvNextV2 does not use feedforward chunking")
    def 	__snake_case							(					self				:    str):
      pass






    def 	__snake_case							(					self				:    Optional[int]):
      if not self.model_tester.is_training:
        return

      for model_class in self.all_model_classes:
        a							,		a						:		Dict      							=			self.model_tester.prepare_config_and_inputs_with_labels()
        a						:		Tuple      							=			True

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

        a						:		int      							=			model_class(__UpperCAmelCase)
        model.to(__UpperCAmelCase)
        model.train()
        a						:		Dict      							=			self._prepare_for_class(__UpperCAmelCase				, __UpperCAmelCase				, return_labels=__UpperCAmelCase)
        a						:		Optional[int]      							=			model(**__UpperCAmelCase).loss
        loss.backward()






    def 	__snake_case							(					self				:    Dict):
      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						:		Optional[Any]      							=			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						:		Union[str, Any]      							=			self._prepare_for_class(__UpperCAmelCase				, __UpperCAmelCase				, return_labels=__UpperCAmelCase)
        a						:		Optional[int]      							=			model(**__UpperCAmelCase).loss
        loss.backward()






    def 	__snake_case							(					self				:    Dict):
      a							,		a						:		Tuple      							=			self.model_tester.prepare_config_and_inputs_for_common()

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

        a						:		Tuple      							=			["pixel_values"]
        self.assertListEqual(arg_names[:1]				, __UpperCAmelCase)






    def 	__snake_case							(					self				:    Dict):
      a						:		Any      							=			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__UpperCAmelCase)






    def 	__snake_case							(					self				:    Optional[Any]):
      def check_hidden_states_output(__UpperCAmelCase				:    Union[str, Any]				, __UpperCAmelCase				:    Union[str, Any]				, __UpperCAmelCase				:    Optional[int]):
        a						:		Optional[int]      							=			model_class(__UpperCAmelCase)
        model.to(__UpperCAmelCase)
        model.eval()

        with torch.no_grad():
          a						:		Optional[Any]      							=			model(**self._prepare_for_class(__UpperCAmelCase				, __UpperCAmelCase))

        a						:		Tuple      							=			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

        a						:		List[Any]      							=			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						:		Union[str, Any]      							=			self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        a						:		List[Any]      							=			True
        check_hidden_states_output(__UpperCAmelCase				, __UpperCAmelCase				, __UpperCAmelCase)

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

        check_hidden_states_output(__UpperCAmelCase				, __UpperCAmelCase				, __UpperCAmelCase)






    def 	__snake_case							(					self				:    Optional[int]):
      a						:		Union[str, Any]      							=			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase)






    @slow
    def 	__snake_case							(					self				:    Optional[Any]):
      for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        a						:		Tuple      							=			ConvNextVaModel.from_pretrained(__UpperCAmelCase)
        self.assertIsNotNone(__UpperCAmelCase)






def      lowercase			(				)->      List[str]:
  '''simple docstring'''







  a						:		int      							=			Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"       )
  return image







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







    """simple docstring"""




    @cached_property
    def 	__snake_case							(					self				:    Union[str, Any]):
      return AutoImageProcessor.from_pretrained("facebook/convnextv2-tiny-1k-224") if is_vision_available() else None






    @slow
    def 	__snake_case							(					self				:    int):
      a						:		Optional[int]      							=			ConvNextVaForImageClassification.from_pretrained("facebook/convnextv2-tiny-1k-224").to(__UpperCAmelCase)

      a						:		Any      							=			self.default_image_processor
      a						:		Union[str, Any]      							=			prepare_img()
      a						:		List[str]      							=			preprocessor(images=__UpperCAmelCase				, return_tensors="pt").to(__UpperCAmelCase)

      # forward pass
      with torch.no_grad():
        a						:		Any      							=			model(**__UpperCAmelCase)

      # verify the logits
      a						:		str      							=			torch.Size((1, 1000))
      self.assertEqual(outputs.logits.shape				, __UpperCAmelCase)

      a						:		Union[str, Any]      							=			torch.tensor([0.9_996, 0.1_966, -0.4_386]).to(__UpperCAmelCase)
      self.assertTrue(torch.allclose(outputs.logits[0, :3]				, __UpperCAmelCase				, atol=1e-4))








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 							A__		(	__SCREAMING_SNAKE_CASE):
      _UpperCAmelCase				:    Union[str, Any]           =			"""conditional_detr"""
      _UpperCAmelCase				:    Optional[int]           =			["""past_key_values"""]
      _UpperCAmelCase				:    Optional[Any]           =			{
          """hidden_size""": """d_model""",
          """num_attention_heads""": """encoder_attention_heads""",
      }
      def __init__(      self    ,  __magic_name__=True    ,  __magic_name__=None    ,  __magic_name__=3    ,  __magic_name__=3_0_0    ,  __magic_name__=6    ,  __magic_name__=2_0_4_8    ,  __magic_name__=8    ,  __magic_name__=6    ,  __magic_name__=2_0_4_8    ,  __magic_name__=8    ,  __magic_name__=0.0    ,  __magic_name__=0.0    ,  __magic_name__=True    ,  __magic_name__="relu"    ,  __magic_name__=2_5_6    ,  __magic_name__=0.1    ,  __magic_name__=0.0    ,  __magic_name__=0.0    ,  __magic_name__=0.02    ,  __magic_name__=1.0    ,  __magic_name__=False    ,  __magic_name__="sine"    ,  __magic_name__="resnet50"    ,  __magic_name__=True    ,  __magic_name__=False    ,  __magic_name__=2    ,  __magic_name__=5    ,  __magic_name__=2    ,  __magic_name__=1    ,  __magic_name__=1    ,  __magic_name__=2    ,  __magic_name__=5    ,  __magic_name__=2    ,  __magic_name__=0.25    ,  **__magic_name__    ,  ):
       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		:	Optional[int]							=      CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""]      )
        elif isinstance(__magic_name__    ,  __magic_name__      ):
         lowerCamelCase		:	List[Any]							=      backbone_config.get("""model_type"""      )
         lowerCamelCase		:	Dict							=      CONFIG_MAPPING[backbone_model_type]
         lowerCamelCase		:	str							=      config_class.from_dict(__magic_name__      )

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






      def 						UpperCamelCase__							(      self      ):
       lowerCamelCase		:	Optional[int]							=      copy.deepcopy(self.__dict__      )
       if self.backbone_config is not None:
        lowerCamelCase		:	Optional[int]							=      self.backbone_config.to_dict()
       lowerCamelCase		:	Optional[Any]							=      self.__class__.model_type
       return output





class 							A__		(	__SCREAMING_SNAKE_CASE):
      _UpperCAmelCase				:    Any           =			version.parse("""1.11""")
      @property
      def 						UpperCamelCase__							(      self      ):
       return OrderedDict(
           [
               ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
               ("""pixel_mask""", {0: """batch"""}),
           ]      )
      @property
      def 						UpperCamelCase__							(      self      ):
       return 1e-5






      @property
      def 						UpperCamelCase__							(      self      ):
       return 1_2




