'''simple docstring'''

from typing import Optional, Union

import torch
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_mobilenet_va import MobileNetVaConfig


__a:			Any	       =       logging.get_logger(__name__)


# General docstring
__a:			Optional[int]	       =       """MobileNetV1Config"""

# Base docstring
__a:			Any	       =       """google/mobilenet_v1_1.0_224"""
__a:			str	       =       [1, 10_24, 7, 7]

# Image classification docstring
__a:			Any	       =       """google/mobilenet_v1_1.0_224"""
__a:			Any	       =       """tabby, tabby cat"""


__a:			Optional[Any]	       =       [
    """google/mobilenet_v1_1.0_224""",
    """google/mobilenet_v1_0.75_192""",
    # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
]
def       __UpperCamelCase	(       UpperCAmelCase		,					UpperCAmelCase		,					UpperCAmelCase=None					):
 lowercase__    :   Optional[int]						= {}

 if isinstance(_lowerCamelCase		,					_lowerCamelCase					):
  lowercase__    :   List[Any]						= model.mobilenet_va
 else:
  lowercase__    :   int						= model

 lowercase__    :   Optional[int]						= """MobilenetV1/Conv2d_0/"""
 lowercase__    :   str						= backbone.conv_stem.convolution.weight
 lowercase__    :   List[str]						= backbone.conv_stem.normalization.bias
 lowercase__    :   Union[str, Any]						= backbone.conv_stem.normalization.weight
 lowercase__    :   str						= backbone.conv_stem.normalization.running_mean
 lowercase__    :   Any						= backbone.conv_stem.normalization.running_var

 for i in range(13					):
  lowercase__    :   Dict						= i + 1
  lowercase__    :   Dict						= i * 2

  lowercase__    :   List[str]						= backbone.layer[pt_index]
  lowercase__    :   Optional[Any]						= F"""MobilenetV1/Conv2d_{tf_index}_depthwise/"""
  lowercase__    :   Tuple						= pointer.convolution.weight
  lowercase__    :   Optional[Any]						= pointer.normalization.bias
  lowercase__    :   List[str]						= pointer.normalization.weight
  lowercase__    :   str						= pointer.normalization.running_mean
  lowercase__    :   Optional[Any]						= pointer.normalization.running_var

  lowercase__    :   Optional[Any]						= backbone.layer[pt_index + 1]
  lowercase__    :   Union[str, Any]						= F"""MobilenetV1/Conv2d_{tf_index}_pointwise/"""
  lowercase__    :   Dict						= pointer.convolution.weight
  lowercase__    :   str						= pointer.normalization.bias
  lowercase__    :   Tuple						= pointer.normalization.weight
  lowercase__    :   List[Any]						= pointer.normalization.running_mean
  lowercase__    :   List[str]						= pointer.normalization.running_var

 if isinstance(_lowerCamelCase		,					_lowerCamelCase					):
  lowercase__    :   Any						= """MobilenetV1/Logits/Conv2d_1c_1x1/"""
  lowercase__    :   List[Any]						= model.classifier.weight
  lowercase__    :   List[Any]						= model.classifier.bias

 return tf_to_pt_map
def       __UpperCamelCase	(       UpperCAmelCase		,					UpperCAmelCase		,					UpperCAmelCase					):


 try:
  import numpy as np
  import tensorflow as tf
 except ImportError:
  logger.error(
      '''Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see '''
      '''https://www.tensorflow.org/install/ for installation instructions.'''					)
  raise

 # Load weights from TF model
 lowercase__    :   str						= tf.train.list_variables(_lowerCamelCase					)
 lowercase__    :   List[Any]						= {}
 for name, shape in init_vars:
  logger.info(F"""Loading TF weight {name} with shape {shape}"""					)
  lowercase__    :   int						= tf.train.load_variable(_lowerCamelCase		,					_lowerCamelCase					)
  lowercase__    :   int						= array

 # Build TF to PyTorch weights loading map
 lowercase__    :   int						= _build_tf_to_pytorch_map(_lowerCamelCase		,					_lowerCamelCase		,					_lowerCamelCase					)

 for name, pointer in tf_to_pt_map.items():
  logger.info(F"""Importing {name}"""					)
  if name not in tf_weights:
   logger.info(F"""{name} not in tf pre-trained weights, skipping"""					)
   continue

  lowercase__    :   List[Any]						= tf_weights[name]

  if "depthwise_weights" in name:
   logger.info('''Transposing depthwise'''					)
   lowercase__    :   Optional[int]						= np.transpose(_lowerCamelCase		,					(2, 3, 0, 1)					)
  elif "weights" in name:
   logger.info('''Transposing'''					)
   if len(pointer.shape					) == 2:  # copying into linear layer
    lowercase__    :   Union[str, Any]						= array.squeeze().transpose()
   else:
    lowercase__    :   Union[str, Any]						= np.transpose(_lowerCamelCase		,					(3, 2, 0, 1)					)

  if pointer.shape != array.shape:
   raise ValueError(F"""Pointer shape {pointer.shape} and array shape {array.shape} mismatched"""					)

  logger.info(F"""Initialize PyTorch weight {name} {array.shape}"""					)
  lowercase__    :   List[Any]						= torch.from_numpy(_lowerCamelCase					)

  tf_weights.pop(_lowerCamelCase		,					_lowerCamelCase					)
  tf_weights.pop(name + '''/RMSProp'''		,					_lowerCamelCase					)
  tf_weights.pop(name + '''/RMSProp_1'''		,					_lowerCamelCase					)
  tf_weights.pop(name + '''/ExponentialMovingAverage'''		,					_lowerCamelCase					)

 logger.info(F"""Weights not copied to PyTorch model: {', '.join(tf_weights.keys()					)}"""					)
 return model
def       __UpperCamelCase	(       UpperCAmelCase		,					UpperCAmelCase					):
 lowercase__    :   Dict						= features.shape[-2:]
 lowercase__    :   Optional[int]						= conv_layer.stride
 lowercase__    :   Optional[int]						= conv_layer.kernel_size

 if in_height % stride_height == 0:
  lowercase__    :   str						= max(kernel_height - stride_height		,					0					)
 else:
  lowercase__    :   int						= max(kernel_height - (in_height % stride_height)		,					0					)

 if in_width % stride_width == 0:
  lowercase__    :   int						= max(kernel_width - stride_width		,					0					)
 else:
  lowercase__    :   Any						= max(kernel_width - (in_width % stride_width)		,					0					)

 lowercase__    :   Dict						= pad_along_width // 2
 lowercase__    :   str						= pad_along_width - pad_left
 lowercase__    :   Tuple						= pad_along_height // 2
 lowercase__    :   Any						= pad_along_height - pad_top

 lowercase__    :   str						= (pad_left, pad_right, pad_top, pad_bottom)
 return nn.functional.pad(_lowerCamelCase		,					_lowerCamelCase		,					'''constant'''		,					0.0					)



class       UpperCAmelCase  (						nn.Module ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase = 1     ,       __lowerCAmelCase = 1     ,       __lowerCAmelCase = False     ,       __lowerCAmelCase = True     ,       __lowerCAmelCase = True     ,       )  ->  None:
        super().__init__()
        lowercase__    :   Dict						= config

        if in_channels % groups != 0:
         raise ValueError(F"""Input channels ({in_channels}) are not divisible by {groups} groups."""			)
        if out_channels % groups != 0:
         raise ValueError(F"""Output channels ({out_channels}) are not divisible by {groups} groups."""			)

        lowercase__    :   Any						= 0 if config.tf_padding else int((kernel_size - 1) / 2			)

        lowercase__    :   int						= nn.Convad(
            in_channels=__lowerCAmelCase     ,       out_channels=__lowerCAmelCase     ,       kernel_size=__lowerCAmelCase     ,       stride=__lowerCAmelCase     ,       padding=__lowerCAmelCase     ,       groups=__lowerCAmelCase     ,       bias=__lowerCAmelCase     ,       padding_mode='''zeros'''     ,       )

        if use_normalization:
         lowercase__    :   List[str]						= nn.BatchNormad(
             num_features=__lowerCAmelCase     ,       eps=config.layer_norm_eps     ,       momentum=0.9_9_9_7     ,       affine=__lowerCAmelCase     ,       track_running_stats=__lowerCAmelCase     ,       )
        else:
         lowercase__    :   Union[str, Any]						= None

        if use_activation:
         if isinstance(__lowerCAmelCase     ,       __lowerCAmelCase			):
          lowercase__    :   Dict						= ACTaFN[use_activation]
         elif isinstance(config.hidden_act     ,       __lowerCAmelCase			):
          lowercase__    :   List[Any]						= ACTaFN[config.hidden_act]
         else:
          lowercase__    :   Optional[Any]						= config.hidden_act
        else:
         lowercase__    :   str						= None


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  torch.Tensor:

        if self.config.tf_padding:
         lowercase__    :   List[Any]						= apply_tf_padding(__lowerCAmelCase     ,       self.convolution			)
        lowercase__    :   Any						= self.convolution(__lowerCAmelCase			)
        if self.normalization is not None:
         lowercase__    :   Dict						= self.normalization(__lowerCAmelCase			)
        if self.activation is not None:
         lowercase__    :   Union[str, Any]						= self.activation(__lowerCAmelCase			)
        return features



class       UpperCAmelCase  (						__lowercase ):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE 		=   MobileNetVaConfig
       SCREAMING_SNAKE_CASE 		=   load_tf_weights_in_mobilenet_va
       SCREAMING_SNAKE_CASE 		=   '''mobilenet_v1'''
       SCREAMING_SNAKE_CASE 		=   '''pixel_values'''
       SCREAMING_SNAKE_CASE 		=   False

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  None:

        if isinstance(__lowerCAmelCase     ,       (nn.Linear, nn.Convad)			):
         module.weight.data.normal_(mean=0.0     ,       std=self.config.initializer_range			)
         if module.bias is not None:
          module.bias.data.zero_()
        elif isinstance(__lowerCAmelCase     ,       nn.BatchNormad			):
         module.bias.data.zero_()
         module.weight.data.fill_(1.0			)


__a:			Union[str, Any]	       =       R"""\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n"""

__a:			Union[str, Any]	       =       R"""\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`MobileNetV1ImageProcessor.__call__`] for details.\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n"""



@add_start_docstrings(
    "The bare MobileNetV1 model outputting raw hidden-states without any specific head on top."   ,						__lowercase   ,						)
class       UpperCAmelCase  (						__lowercase ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase = True			)  ->  Optional[int]:
        super().__init__(__lowerCAmelCase			)
        lowercase__    :   Any						= config

        lowercase__    :   Optional[int]						= 32
        lowercase__    :   List[str]						= max(int(depth * config.depth_multiplier			)     ,       config.min_depth			)

        lowercase__    :   Dict						= MobileNetVaConvLayer(
            __lowerCAmelCase     ,       in_channels=config.num_channels     ,       out_channels=__lowerCAmelCase     ,       kernel_size=3     ,       stride=2     ,       )

        lowercase__    :   Optional[Any]						= [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

        lowercase__    :   Any						= nn.ModuleList()
        for i in range(13			):
         lowercase__    :   List[str]						= out_channels

         if strides[i] == 2 or i == 0:
          depth *= 2
          lowercase__    :   str						= max(int(depth * config.depth_multiplier			)     ,       config.min_depth			)

         self.layer.append(
             MobileNetVaConvLayer(
                 __lowerCAmelCase     ,       in_channels=__lowerCAmelCase     ,       out_channels=__lowerCAmelCase     ,       kernel_size=3     ,       stride=strides[i]     ,       groups=__lowerCAmelCase     ,       )			)

         self.layer.append(
             MobileNetVaConvLayer(
                 __lowerCAmelCase     ,       in_channels=__lowerCAmelCase     ,       out_channels=__lowerCAmelCase     ,       kernel_size=1     ,       )			)

        lowercase__    :   str						= nn.AdaptiveAvgPoolad((1, 1)			) if add_pooling_layer else None

        # Initialize weights and apply final processing
        self.post_init()

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  int:
        raise NotImplementedError


       @add_start_docstrings_to_model_forward(__lowerCAmelCase			)
       @add_code_sample_docstrings(
           checkpoint=_CHECKPOINT_FOR_DOC     ,       output_type=__lowerCAmelCase     ,       config_class=_CONFIG_FOR_DOC     ,       modality='''vision'''     ,       expected_output=_EXPECTED_OUTPUT_SHAPE     ,       )
       def _lowerCAmelCase(						self     ,       __lowerCAmelCase = None     ,       __lowerCAmelCase = None     ,       __lowerCAmelCase = None     ,       )  ->  Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:
        lowercase__    :   List[str]						= (
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        lowercase__    :   Union[str, Any]						= return_dict if return_dict is not None else self.config.use_return_dict

        if pixel_values is None:
         raise ValueError('''You have to specify pixel_values'''			)

        lowercase__    :   List[Any]						= self.conv_stem(__lowerCAmelCase			)

        lowercase__    :   Union[str, Any]						= () if output_hidden_states else None

        for i, layer_module in enumerate(self.layer			):
         lowercase__    :   List[Any]						= layer_module(__lowerCAmelCase			)

         if output_hidden_states:
          lowercase__    :   Any						= all_hidden_states + (hidden_states,)

        lowercase__    :   List[str]						= hidden_states

        if self.pooler is not None:
         lowercase__    :   Optional[int]						= torch.flatten(self.pooler(__lowerCAmelCase			)     ,       start_dim=1			)
        else:
         lowercase__    :   Union[str, Any]						= None

        if not return_dict:
         return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None			)

        return BaseModelOutputWithPoolingAndNoAttention(
            last_hidden_state=__lowerCAmelCase     ,       pooler_output=__lowerCAmelCase     ,       hidden_states=__lowerCAmelCase     ,       )



@add_start_docstrings(
    "\n    MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    "   ,						__lowercase   ,						)
class       UpperCAmelCase  (						__lowercase ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase			)  ->  None:
        super().__init__(__lowerCAmelCase			)

        lowercase__    :   Union[str, Any]						= config.num_labels
        lowercase__    :   Optional[Any]						= MobileNetVaModel(__lowerCAmelCase			)

        lowercase__    :   str						= self.mobilenet_va.layer[-1].convolution.out_channels

        # Classifier head
        lowercase__    :   str						= nn.Dropout(config.classifier_dropout_prob     ,       inplace=__lowerCAmelCase			)
        lowercase__    :   Dict						= nn.Linear(__lowerCAmelCase     ,       config.num_labels			) if config.num_labels > 0 else nn.Identity()

        # Initialize weights and apply final processing
        self.post_init()


       @add_start_docstrings_to_model_forward(__lowerCAmelCase			)
       @add_code_sample_docstrings(
           checkpoint=_IMAGE_CLASS_CHECKPOINT     ,       output_type=__lowerCAmelCase     ,       config_class=_CONFIG_FOR_DOC     ,       expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT     ,       )
       def _lowerCAmelCase(						self     ,       __lowerCAmelCase = None     ,       __lowerCAmelCase = None     ,       __lowerCAmelCase = None     ,       __lowerCAmelCase = None     ,       )  ->  Union[tuple, ImageClassifierOutputWithNoAttention]:
        lowercase__    :   Tuple						= return_dict if return_dict is not None else self.config.use_return_dict

        lowercase__    :   int						= self.mobilenet_va(__lowerCAmelCase     ,       output_hidden_states=__lowerCAmelCase     ,       return_dict=__lowerCAmelCase			)

        lowercase__    :   Dict						= outputs.pooler_output if return_dict else outputs[1]

        lowercase__    :   Any						= self.classifier(self.dropout(__lowerCAmelCase			)			)

        lowercase__    :   List[str]						= None
        if labels is not None:
         if self.config.problem_type is None:
          if self.num_labels == 1:
           lowercase__    :   Dict						= """regression"""
          elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
           lowercase__    :   List[str]						= """single_label_classification"""
          else:
           lowercase__    :   Tuple						= """multi_label_classification"""

         if self.config.problem_type == "regression":
          lowercase__    :   Optional[Any]						= MSELoss()
          if self.num_labels == 1:
           lowercase__    :   Optional[int]						= loss_fct(logits.squeeze()     ,       labels.squeeze()			)
          else:
           lowercase__    :   Tuple						= loss_fct(__lowerCAmelCase     ,       __lowerCAmelCase			)
         elif self.config.problem_type == "single_label_classification":
          lowercase__    :   Optional[int]						= CrossEntropyLoss()
          lowercase__    :   Tuple						= loss_fct(logits.view(-1     ,       self.num_labels			)     ,       labels.view(-1			)			)
         elif self.config.problem_type == "multi_label_classification":
          lowercase__    :   List[str]						= BCEWithLogitsLoss()
          lowercase__    :   str						= loss_fct(__lowerCAmelCase     ,       __lowerCAmelCase			)

        if not return_dict:
         lowercase__    :   int						= (logits,) + outputs[2:]
         return ((loss,) + output) if loss is not None else output

        return ImageClassifierOutputWithNoAttention(
            loss=__lowerCAmelCase     ,       logits=__lowerCAmelCase     ,       hidden_states=outputs.hidden_states     ,       )





'''simple docstring'''

import inspect
import unittest

from transformers import DPTConfig
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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


if is_torch_available():
  import torch
  from torch import nn

  from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel
  from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import DPTImageProcessor



class       UpperCAmelCase  :





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase=2     ,       __lowerCAmelCase=32     ,       __lowerCAmelCase=16     ,       __lowerCAmelCase=3     ,       __lowerCAmelCase=True     ,       __lowerCAmelCase=True     ,       __lowerCAmelCase=32     ,       __lowerCAmelCase=4     ,       __lowerCAmelCase=[0, 1, 2, 3]     ,       __lowerCAmelCase=4     ,       __lowerCAmelCase=37     ,       __lowerCAmelCase="gelu"     ,       __lowerCAmelCase=0.1     ,       __lowerCAmelCase=0.1     ,       __lowerCAmelCase=0.0_2     ,       __lowerCAmelCase=3     ,       __lowerCAmelCase=[1, 384, 24, 24]     ,       __lowerCAmelCase=True     ,       __lowerCAmelCase=None     ,       )  ->  Dict:
        lowercase__    :   str						= parent
        lowercase__    :   List[Any]						= batch_size
        lowercase__    :   Dict						= image_size
        lowercase__    :   Tuple						= patch_size
        lowercase__    :   str						= num_channels
        lowercase__    :   Dict						= is_training
        lowercase__    :   Optional[int]						= use_labels
        lowercase__    :   List[Any]						= hidden_size
        lowercase__    :   int						= num_hidden_layers
        lowercase__    :   int						= backbone_out_indices
        lowercase__    :   List[str]						= num_attention_heads
        lowercase__    :   Union[str, Any]						= intermediate_size
        lowercase__    :   List[Any]						= hidden_act
        lowercase__    :   str						= hidden_dropout_prob
        lowercase__    :   Tuple						= attention_probs_dropout_prob
        lowercase__    :   List[Any]						= initializer_range
        lowercase__    :   Optional[int]						= num_labels
        lowercase__    :   Optional[int]						= backbone_featmap_shape
        lowercase__    :   int						= scope
        lowercase__    :   List[str]						= is_hybrid
        # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
        lowercase__    :   List[str]						= (image_size // patch_size) ** 2
        lowercase__    :   Tuple						= num_patches + 1

       def _lowerCAmelCase(						self			)  ->  List[str]:
        lowercase__    :   Union[str, Any]						= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

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

        lowercase__    :   Union[str, Any]						= self.get_config()

        return config, pixel_values, labels

       def _lowerCAmelCase(						self			)  ->  Union[str, Any]:
        lowercase__    :   Optional[Any]						= {
            '''global_padding''': '''same''',
            '''layer_type''': '''bottleneck''',
            '''depths''': [3, 4, 9],
            '''out_features''': ['''stage1''', '''stage2''', '''stage3'''],
            '''embedding_dynamic_padding''': True,
            '''hidden_sizes''': [96, 192, 384, 768],
            '''num_groups''': 2,
        }

        return DPTConfig(
            image_size=self.image_size     ,       patch_size=self.patch_size     ,       num_channels=self.num_channels     ,       hidden_size=self.hidden_size     ,       num_hidden_layers=self.num_hidden_layers     ,       backbone_out_indices=self.backbone_out_indices     ,       num_attention_heads=self.num_attention_heads     ,       intermediate_size=self.intermediate_size     ,       hidden_act=self.hidden_act     ,       hidden_dropout_prob=self.hidden_dropout_prob     ,       attention_probs_dropout_prob=self.attention_probs_dropout_prob     ,       is_decoder=__lowerCAmelCase     ,       initializer_range=self.initializer_range     ,       is_hybrid=self.is_hybrid     ,       backbone_config=__lowerCAmelCase     ,       backbone_featmap_shape=self.backbone_featmap_shape     ,       )

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase			)  ->  Union[str, Any]:
        lowercase__    :   Optional[int]						= DPTModel(config=__lowerCAmelCase			)
        model.to(__lowerCAmelCase			)
        model.eval()
        lowercase__    :   Dict						= model(__lowerCAmelCase			)
        self.parent.assertEqual(result.last_hidden_state.shape     ,       (self.batch_size, self.seq_length, self.hidden_size)			)

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase			)  ->  str:
        lowercase__    :   Union[str, Any]						= self.num_labels
        lowercase__    :   str						= DPTForDepthEstimation(__lowerCAmelCase			)
        model.to(__lowerCAmelCase			)
        model.eval()
        lowercase__    :   List[str]						= model(__lowerCAmelCase			)
        self.parent.assertEqual(result.predicted_depth.shape     ,       (self.batch_size, self.image_size, self.image_size)			)

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase			)  ->  List[Any]:
        lowercase__    :   str						= self.num_labels
        lowercase__    :   Tuple						= DPTForSemanticSegmentation(__lowerCAmelCase			)
        model.to(__lowerCAmelCase			)
        model.eval()
        lowercase__    :   Dict						= model(__lowerCAmelCase     ,       labels=__lowerCAmelCase			)
        self.parent.assertEqual(
            result.logits.shape     ,       (self.batch_size, self.num_labels, self.image_size, self.image_size)			)


       def _lowerCAmelCase(						self			)  ->  Optional[int]:
        lowercase__    :   List[str]						= self.prepare_config_and_inputs()
        lowercase__			,							lowercase__			,							lowercase__    :   Dict						= config_and_inputs
        lowercase__    :   Tuple						= {'''pixel_values''': pixel_values}
        return config, inputs_dict



@require_torch
class       UpperCAmelCase  (						a__   ,						a__   ,						unittest.TestCase ):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE 		=   (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
       SCREAMING_SNAKE_CASE 		=   (
           {
               "depth-estimation": DPTForDepthEstimation,
               "feature-extraction": DPTModel,
               "image-segmentation": DPTForSemanticSegmentation,
           }
           if is_torch_available()
           else {}
       )

       SCREAMING_SNAKE_CASE 		=   False
       SCREAMING_SNAKE_CASE 		=   False
       SCREAMING_SNAKE_CASE 		=   False

       def _lowerCAmelCase(						self			)  ->  Union[str, Any]:
        lowercase__    :   str						= DPTModelTester(self			)
        lowercase__    :   int						= ConfigTester(self     ,       config_class=__lowerCAmelCase     ,       has_text_modality=__lowerCAmelCase     ,       hidden_size=37			)

       def _lowerCAmelCase(						self			)  ->  List[Any]:
        self.config_tester.run_common_tests()

       @unittest.skip(reason='''DPT does not use inputs_embeds'''			)
       def _lowerCAmelCase(						self			)  ->  Tuple:
        pass

       def _lowerCAmelCase(						self			)  ->  Optional[Any]:
        lowercase__			,							lowercase__    :   Union[str, Any]						= self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
         lowercase__    :   str						= model_class(__lowerCAmelCase			)
         self.assertIsInstance(model.get_input_embeddings()     ,       (nn.Module)			)
         lowercase__    :   Tuple						= model.get_output_embeddings()
         self.assertTrue(x is None or isinstance(__lowerCAmelCase     ,       nn.Linear			)			)

       def _lowerCAmelCase(						self			)  ->  List[str]:
        lowercase__			,							lowercase__    :   List[Any]						= self.model_tester.prepare_config_and_inputs_for_common()

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

         lowercase__    :   int						= ['''pixel_values''']
         self.assertListEqual(arg_names[:1]     ,       __lowerCAmelCase			)

       def _lowerCAmelCase(						self			)  ->  List[str]:
        lowercase__    :   Any						= self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__lowerCAmelCase			)

       def _lowerCAmelCase(						self			)  ->  Union[str, Any]:
        lowercase__    :   Optional[Any]						= self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_depth_estimation(*__lowerCAmelCase			)

       def _lowerCAmelCase(						self			)  ->  Dict:
        lowercase__    :   List[Any]						= self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_semantic_segmentation(*__lowerCAmelCase			)

       def _lowerCAmelCase(						self			)  ->  Union[str, Any]:
        for model_class in self.all_model_classes:
         if model_class.__name__ == "DPTForDepthEstimation":
          continue

         lowercase__			,							lowercase__    :   str						= self.model_tester.prepare_config_and_inputs_for_common()
         lowercase__    :   Dict						= True

         if model_class in get_values(__lowerCAmelCase			):
          continue

         lowercase__    :   List[str]						= model_class(__lowerCAmelCase			)
         model.to(__lowerCAmelCase			)
         model.train()
         lowercase__    :   Tuple						= self._prepare_for_class(__lowerCAmelCase     ,       __lowerCAmelCase     ,       return_labels=__lowerCAmelCase			)
         lowercase__    :   str						= model(**__lowerCAmelCase			).loss
         loss.backward()

       def _lowerCAmelCase(						self			)  ->  Tuple:
        for model_class in self.all_model_classes:
         if model_class.__name__ == "DPTForDepthEstimation":
          continue

         lowercase__			,							lowercase__    :   Optional[int]						= self.model_tester.prepare_config_and_inputs_for_common()
         lowercase__    :   Any						= False
         lowercase__    :   str						= True

         if model_class in get_values(__lowerCAmelCase			) or not model_class.supports_gradient_checkpointing:
          continue
         lowercase__    :   List[str]						= model_class(__lowerCAmelCase			)
         model.to(__lowerCAmelCase			)
         model.gradient_checkpointing_enable()
         model.train()
         lowercase__    :   str						= self._prepare_for_class(__lowerCAmelCase     ,       __lowerCAmelCase     ,       return_labels=__lowerCAmelCase			)
         lowercase__    :   List[Any]						= model(**__lowerCAmelCase			).loss
         loss.backward()

       def _lowerCAmelCase(						self			)  ->  List[Any]:
        lowercase__			,							lowercase__    :   List[Any]						= self.model_tester.prepare_config_and_inputs_for_common()

        lowercase__    :   Union[str, Any]						= _config_zero_init(__lowerCAmelCase			)
        for model_class in self.all_model_classes:
         lowercase__    :   Dict						= model_class(config=__lowerCAmelCase			)
         # Skip the check for the backbone
         lowercase__    :   Union[str, Any]						= []
         for name, module in model.named_modules():
          if module.__class__.__name__ == "DPTViTHybridEmbeddings":
           lowercase__    :   List[Any]						= [F"""{name}.{key}""" for key in module.state_dict().keys()]
           break

         for name, param in model.named_parameters():
          if param.requires_grad:
           if name in backbone_params:
            continue
           self.assertIn(
               ((param.data.mean() * 1E9).round() / 1E9).item()     ,       [0.0, 1.0]     ,       msg=F"""Parameter {name} of model {model_class} seems not properly initialized"""     ,       )

       @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''			)
       def _lowerCAmelCase(						self			)  ->  List[str]:
        pass

       @slow
       def _lowerCAmelCase(						self			)  ->  List[Any]:
        for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
         lowercase__    :   Dict						= DPTModel.from_pretrained(__lowerCAmelCase			)
         self.assertIsNotNone(__lowerCAmelCase			)


       def _lowerCAmelCase(						self			)  ->  str:
        # We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type
        lowercase__			,							lowercase__    :   Any						= self.model_tester.prepare_config_and_inputs_for_common()
        lowercase__    :   List[str]						= '''add'''
        with self.assertRaises(__lowerCAmelCase			):
         lowercase__    :   Tuple						= DPTForDepthEstimation(__lowerCAmelCase			)


def       __UpperCamelCase	(       ):
 lowercase__    :   Optional[int]						= Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''					)
 return image





@require_torch
@require_vision
@slow
class       UpperCAmelCase  (						unittest.TestCase ):





       '''simple docstring'''



       def _lowerCAmelCase(						self			)  ->  Any:
        lowercase__    :   Optional[int]						= DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas'''			)
        lowercase__    :   List[Any]						= DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas'''			).to(__lowerCAmelCase			)

        lowercase__    :   Optional[Any]						= prepare_img()
        lowercase__    :   Optional[Any]						= image_processor(images=__lowerCAmelCase     ,       return_tensors='''pt'''			).to(__lowerCAmelCase			)

        # forward pass
        with torch.no_grad():
         lowercase__    :   Optional[Any]						= model(**__lowerCAmelCase			)
         lowercase__    :   str						= outputs.predicted_depth

        # verify the predicted depth
        lowercase__    :   Optional[Any]						= torch.Size((1, 384, 384)			)
        self.assertEqual(predicted_depth.shape     ,       __lowerCAmelCase			)

        lowercase__    :   str						= torch.tensor(
            [[[5.6_4_3_7, 5.6_1_4_6, 5.6_5_1_1], [5.4_3_7_1, 5.5_6_4_9, 5.5_9_5_8], [5.5_2_1_5, 5.5_1_8_4, 5.5_2_9_3]]]			).to(__lowerCAmelCase			)

        self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100     ,       __lowerCAmelCase     ,       atol=1E-4			)			)

