

import inspect
import unittest

from transformers import MobileNetVaConfig
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 MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel
       from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from PIL import Image

       from transformers import MobileNetVaImageProcessor

class  __A(						__UpperCAmelCase ):

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						self.config_class(**self.inputs_dict      )
            self.parent.assertTrue(hasattr(_lowerCamelCase,       '''tf_padding'''      )      )
            self.parent.assertTrue(hasattr(_lowerCamelCase,       '''depth_multiplier'''      )      )






class  __A:

     def __init__(      self,       A,       A=13,       A=3,       A=32,       A=0.25,       A=8,       A=8,       A=6,       A=32,       A=True,       A=True,       A=True,       A="relu6",       A=1280,       A=0.1,       A=0.02,       A=True,       A=True,       A=10,       A=None,       ):





            """simple docstring"""

            _UpperCamelCase              =						parent
            _UpperCamelCase              =						batch_size
            _UpperCamelCase              =						num_channels
            _UpperCamelCase              =						image_size
            _UpperCamelCase              =						depth_multiplier
            _UpperCamelCase              =						depth_divisible_by
            _UpperCamelCase              =						min_depth
            _UpperCamelCase              =						expand_ratio
            _UpperCamelCase              =						tf_padding
            _UpperCamelCase              =						output_stride
            _UpperCamelCase              =						first_layer_is_expansion
            _UpperCamelCase              =						finegrained_output
            _UpperCamelCase              =						hidden_act
            _UpperCamelCase              =						last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier      )
            _UpperCamelCase              =						classifier_dropout_prob
            _UpperCamelCase              =						use_labels
            _UpperCamelCase              =						is_training
            _UpperCamelCase              =						num_labels
            _UpperCamelCase              =						initializer_range
            _UpperCamelCase              =						scope

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

            _UpperCamelCase              =						None
            _UpperCamelCase              =						None
            if self.use_labels:
                   _UpperCamelCase              =						ids_tensor([self.batch_size],       self.num_labels      )
                   _UpperCamelCase              =						ids_tensor([self.batch_size, self.image_size, self.image_size],       self.num_labels      )

            _UpperCamelCase              =						self.get_config()

            return config, pixel_values, labels, pixel_labels

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            return MobileNetVaConfig(
                num_channels=self.num_channels,       image_size=self.image_size,       depth_multiplier=self.depth_multiplier,       depth_divisible_by=self.depth_divisible_by,       min_depth=self.min_depth,       expand_ratio=self.expand_ratio,       output_stride=self.output_stride,       first_layer_is_expansion=self.first_layer_is_expansion,       finegrained_output=self.finegrained_output,       hidden_act=self.hidden_act,       tf_padding=self.tf_padding,       classifier_dropout_prob=self.classifier_dropout_prob,       initializer_range=self.initializer_range,       )

     def 	_UpperCamelCase     (      self,       A,       A,       A,       A      ):





            """simple docstring"""

            _UpperCamelCase              =						MobileNetVaModel(config=_lowerCamelCase      )
            model.to(_lowerCamelCase      )
            model.eval()
            _UpperCamelCase              =						model(_lowerCamelCase      )
            self.parent.assertEqual(
                result.last_hidden_state.shape,       (
                    self.batch_size,
                    self.last_hidden_size,
                    self.image_size // self.output_stride,
                    self.image_size // self.output_stride,
                ),       )
            self.parent.assertEqual(
                result.pooler_output.shape,       (self.batch_size, self.last_hidden_size),       )

     def 	_UpperCamelCase     (      self,       A,       A,       A,       A      ):





            """simple docstring"""

            _UpperCamelCase              =						self.num_labels
            _UpperCamelCase              =						MobileNetVaForImageClassification(_lowerCamelCase      )
            model.to(_lowerCamelCase      )
            model.eval()
            _UpperCamelCase              =						model(_lowerCamelCase,       labels=_lowerCamelCase      )
            self.parent.assertEqual(result.logits.shape,       (self.batch_size, self.num_labels)      )

     def 	_UpperCamelCase     (      self,       A,       A,       A,       A      ):





            """simple docstring"""

            _UpperCamelCase              =						self.num_labels
            _UpperCamelCase              =						MobileNetVaForSemanticSegmentation(_lowerCamelCase      )
            model.to(_lowerCamelCase      )
            model.eval()
            _UpperCamelCase              =						model(_lowerCamelCase      )
            self.parent.assertEqual(
                result.logits.shape,       (
                    self.batch_size,
                    self.num_labels,
                    self.image_size // self.output_stride,
                    self.image_size // self.output_stride,
                ),       )
            _UpperCamelCase              =						model(_lowerCamelCase,       labels=_lowerCamelCase      )
            self.parent.assertEqual(
                result.logits.shape,       (
                    self.batch_size,
                    self.num_labels,
                    self.image_size // self.output_stride,
                    self.image_size // self.output_stride,
                ),       )



     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						self.prepare_config_and_inputs()
            _UpperCamelCase       ,		_UpperCamelCase       ,		_UpperCamelCase       ,		_UpperCamelCase              =						config_and_inputs
            _UpperCamelCase              =						{'''pixel_values''': pixel_values}
            return config, inputs_dict






@require_torch
class  __A(						__UpperCAmelCase						,			__UpperCAmelCase						,			unittest.TestCase ):
     __A	  =       (
         (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
         if is_torch_available()
         else ()
     )
     __A	  =       (
         {
             "feature-extraction": MobileNetVaModel,
             "image-classification": MobileNetVaForImageClassification,
             "image-segmentation": MobileNetVaForSemanticSegmentation,
         }
         if is_torch_available()
         else {}
     )

     __A	  =       False
     __A	  =       False
     __A	  =       False
     __A	  =       False

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						MobileNetVaModelTester(self      )
            _UpperCamelCase              =						MobileNetVaConfigTester(self,       config_class=_lowerCamelCase,       has_text_modality=_lowerCamelCase      )

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            self.config_tester.run_common_tests()

     @unittest.skip(reason='''MobileNetV2 does not use inputs_embeds'''      )
     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            pass

     @unittest.skip(reason='''MobileNetV2 does not support input and output embeddings'''      )
     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            pass

     @unittest.skip(reason='''MobileNetV2 does not output attentions'''      )
     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            pass

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase       ,		_UpperCamelCase              =						self.model_tester.prepare_config_and_inputs_for_common()

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

                   _UpperCamelCase              =						['''pixel_values''']
                   self.assertListEqual(arg_names[:1],       _lowerCamelCase      )

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*_lowerCamelCase      )

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            def check_hidden_states_output(A,       A,       A      ):
                   _UpperCamelCase              =						model_class(_lowerCamelCase      )
                   model.to(_lowerCamelCase      )
                   model.eval()

                   with torch.no_grad():
                          _UpperCamelCase              =						model(**self._prepare_for_class(_lowerCamelCase,       _lowerCamelCase      )      )

                   _UpperCamelCase              =						outputs.hidden_states

                   _UpperCamelCase              =						16
                   self.assertEqual(len(_lowerCamelCase      ),       _lowerCamelCase      )

            _UpperCamelCase       ,		_UpperCamelCase              =						self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                   _UpperCamelCase              =						True
                   check_hidden_states_output(_lowerCamelCase,       _lowerCamelCase,       _lowerCamelCase      )

                   # check that output_hidden_states also work using config
                   del inputs_dict["output_hidden_states"]
                   _UpperCamelCase              =						True

                   check_hidden_states_output(_lowerCamelCase,       _lowerCamelCase,       _lowerCamelCase      )

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase      )

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_semantic_segmentation(*_lowerCamelCase      )



     @slow
     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   _UpperCamelCase              =						MobileNetVaModel.from_pretrained(_lowerCamelCase      )
                   self.assertIsNotNone(_lowerCamelCase      )






def     SCREAMING_SNAKE_CASE			(      ):
       _UpperCamelCase              =						Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''					)
       return image

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

     @cached_property
     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            return (
                MobileNetVaImageProcessor.from_pretrained('''google/mobilenet_v2_1.0_224'''      ) if is_vision_available() else None
            )

     @slow
     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v2_1.0_224'''      ).to(_lowerCamelCase      )

            _UpperCamelCase              =						self.default_image_processor
            _UpperCamelCase              =						prepare_img()
            _UpperCamelCase              =						image_processor(images=_lowerCamelCase,       return_tensors='''pt'''      ).to(_lowerCamelCase      )

            # forward pass
            with torch.no_grad():
                   _UpperCamelCase              =						model(**_lowerCamelCase      )

            # verify the logits
            _UpperCamelCase              =						torch.Size((1, 1001)      )
            self.assertEqual(outputs.logits.shape,       _lowerCamelCase      )

            _UpperCamelCase              =						torch.tensor([0.2_445, -1.1_993, 0.1_905]      ).to(_lowerCamelCase      )

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



     @slow
     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						MobileNetVaForSemanticSegmentation.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513'''      )
            _UpperCamelCase              =						model.to(_lowerCamelCase      )

            _UpperCamelCase              =						MobileNetVaImageProcessor.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513'''      )

            _UpperCamelCase              =						prepare_img()
            _UpperCamelCase              =						image_processor(images=_lowerCamelCase,       return_tensors='''pt'''      ).to(_lowerCamelCase      )

            # forward pass
            with torch.no_grad():
                   _UpperCamelCase              =						model(**_lowerCamelCase      )
            _UpperCamelCase              =						outputs.logits

            # verify the logits
            _UpperCamelCase              =						torch.Size((1, 21, 65, 65)      )
            self.assertEqual(logits.shape,       _lowerCamelCase      )

            _UpperCamelCase              =						torch.tensor(
                [
                    [[17.5_790, 17.7_581, 18.3_355], [18.3_257, 18.4_230, 18.8_973], [18.6_169, 18.8_650, 19.2_187]],
                    [[-2.1_595, -2.0_977, -2.3_741], [-2.4_226, -2.3_028, -2.6_835], [-2.7_819, -2.5_991, -2.7_706]],
                    [[4.2_058, 4.8_317, 4.7_638], [4.4_136, 5.0_361, 4.9_383], [4.5_028, 4.9_644, 4.8_734]],
                ],       device=_lowerCamelCase,       )

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













import copy
from collections import OrderedDict
from typing import Dict, Mapping

from packaging import version

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


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

lowercase    : List[Any]    	=  {
    """facebook/detr-resnet-50""": """https://huggingface.co/facebook/detr-resnet-50/resolve/main/config.json""",
    # See all DETR models at https://huggingface.co/models?filter=detr
}

class  __A(						__UpperCAmelCase ):
     __A	  =       "detr"
     __A	  =       ["past_key_values"]
     __A	  =       {
         "hidden_size": "d_model",
         "num_attention_heads": "encoder_attention_heads",
     }

     def __init__(      self,       A=True,       A=None,       A=3,       A=100,       A=6,       A=2048,       A=8,       A=6,       A=2048,       A=8,       A=0.0,       A=0.0,       A=True,       A="relu",       A=256,       A=0.1,       A=0.0,       A=0.0,       A=0.02,       A=1.0,       A=False,       A="sine",       A="resnet50",       A=True,       A=False,       A=1,       A=5,       A=2,       A=1,       A=1,       A=5,       A=2,       A=0.1,       **A,       ):





            """simple docstring"""

            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.'''      )
                          _UpperCamelCase              =						CONFIG_MAPPING['''resnet'''](out_features=['''stage4''']      )
                   elif isinstance(A,       A      ):
                          _UpperCamelCase              =						backbone_config.get('''model_type'''      )
                          _UpperCamelCase              =						CONFIG_MAPPING[backbone_model_type]
                          _UpperCamelCase              =						config_class.from_dict(A      )
                   # set timm attributes to None
                   _UpperCamelCase       ,		_UpperCamelCase       ,		_UpperCamelCase              =						None, None, None

            _UpperCamelCase              =						use_timm_backbone
            _UpperCamelCase              =						backbone_config
            _UpperCamelCase              =						num_channels
            _UpperCamelCase              =						num_queries
            _UpperCamelCase              =						d_model
            _UpperCamelCase              =						encoder_ffn_dim
            _UpperCamelCase              =						encoder_layers
            _UpperCamelCase              =						encoder_attention_heads
            _UpperCamelCase              =						decoder_ffn_dim
            _UpperCamelCase              =						decoder_layers
            _UpperCamelCase              =						decoder_attention_heads
            _UpperCamelCase              =						dropout
            _UpperCamelCase              =						attention_dropout
            _UpperCamelCase              =						activation_dropout
            _UpperCamelCase              =						activation_function
            _UpperCamelCase              =						init_std
            _UpperCamelCase              =						init_xavier_std
            _UpperCamelCase              =						encoder_layerdrop
            _UpperCamelCase              =						decoder_layerdrop
            _UpperCamelCase              =						encoder_layers
            _UpperCamelCase              =						auxiliary_loss
            _UpperCamelCase              =						position_embedding_type
            _UpperCamelCase              =						backbone
            _UpperCamelCase              =						use_pretrained_backbone
            _UpperCamelCase              =						dilation
            # Hungarian matcher
            _UpperCamelCase              =						class_cost
            _UpperCamelCase              =						bbox_cost
            _UpperCamelCase              =						giou_cost
            # Loss coefficients
            _UpperCamelCase              =						mask_loss_coefficient
            _UpperCamelCase              =						dice_loss_coefficient
            _UpperCamelCase              =						bbox_loss_coefficient
            _UpperCamelCase              =						giou_loss_coefficient
            _UpperCamelCase              =						eos_coefficient
            super().__init__(is_encoder_decoder=A,       **A      )

     @property
     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            return self.encoder_attention_heads

     @property
     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            return self.d_model

     @classmethod
     def 	_UpperCamelCase     (      cls,       A,       **A      ):





            """simple docstring"""

            return cls(backbone_config=A,       **A      )



     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						copy.deepcopy(self.__dict__      )
            if output["backbone_config"] is not None:
                   _UpperCamelCase              =						self.backbone_config.to_dict()
            _UpperCamelCase              =						self.__class__.model_type
            return output






class  __A(						__UpperCAmelCase ):
     __A	  =       version.parse("1.11" )

     @property
     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            return OrderedDict(
                [
                    ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
                    ('''pixel_mask''', {0: '''batch'''}),
                ]      )

     @property
     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            return 1E-5



     @property
     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            return 12






