'''simple docstring'''

from typing import Optional

import torch
import torch.utils.checkpoint
from torch import Tensor, nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import (
    BackboneOutput,
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import (
    add_code_sample_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    logging,
    replace_return_docstrings,
)
from ...utils.backbone_utils import BackboneMixin
from .configuration_resnet import ResNetConfig


__a:			List[Any]	       =       logging.get_logger(__name__)

# General docstring
__a:			List[Any]	       =       """ResNetConfig"""

# Base docstring
__a:			Optional[Any]	       =       """microsoft/resnet-50"""
__a:			Optional[int]	       =       [1, 20_48, 7, 7]

# Image classification docstring
__a:			List[str]	       =       """microsoft/resnet-50"""
__a:			List[Any]	       =       """tiger cat"""

__a:			Optional[Any]	       =       [
    """microsoft/resnet-50""",
    # See all resnet models at https://huggingface.co/models?filter=resnet
]



class       UpperCAmelCase  (						nn.Module ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase = 3     ,       __lowerCAmelCase = 1     ,       __lowerCAmelCase = "relu"			)  ->  Any:
        super().__init__()
        lowercase__    :   Dict						= nn.Convad(
            __lowerCAmelCase     ,       __lowerCAmelCase     ,       kernel_size=__lowerCAmelCase     ,       stride=__lowerCAmelCase     ,       padding=kernel_size // 2     ,       bias=__lowerCAmelCase			)
        lowercase__    :   str						= nn.BatchNormad(__lowerCAmelCase			)
        lowercase__    :   List[str]						= ACTaFN[activation] if activation is not None else nn.Identity()


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  Tensor:
        lowercase__    :   int						= self.convolution(__lowerCAmelCase			)
        lowercase__    :   Any						= self.normalization(__lowerCAmelCase			)
        lowercase__    :   int						= self.activation(__lowerCAmelCase			)
        return hidden_state



class       UpperCAmelCase  (						nn.Module ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase			)  ->  List[Any]:
        super().__init__()
        lowercase__    :   str						= ResNetConvLayer(
            config.num_channels     ,       config.embedding_size     ,       kernel_size=7     ,       stride=2     ,       activation=config.hidden_act			)
        lowercase__    :   Union[str, Any]						= nn.MaxPoolad(kernel_size=3     ,       stride=2     ,       padding=1			)
        lowercase__    :   int						= config.num_channels


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  Tensor:
        lowercase__    :   int						= pixel_values.shape[1]
        if num_channels != self.num_channels:
         raise ValueError(
             '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.'''			)
        lowercase__    :   List[Any]						= self.embedder(__lowerCAmelCase			)
        lowercase__    :   List[str]						= self.pooler(__lowerCAmelCase			)
        return embedding



class       UpperCAmelCase  (						nn.Module ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase = 2			)  ->  Optional[Any]:
        super().__init__()
        lowercase__    :   Dict						= nn.Convad(__lowerCAmelCase     ,       __lowerCAmelCase     ,       kernel_size=1     ,       stride=__lowerCAmelCase     ,       bias=__lowerCAmelCase			)
        lowercase__    :   Any						= nn.BatchNormad(__lowerCAmelCase			)


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  Tensor:
        lowercase__    :   str						= self.convolution(__lowerCAmelCase			)
        lowercase__    :   Optional[int]						= self.normalization(__lowerCAmelCase			)
        return hidden_state



class       UpperCAmelCase  (						nn.Module ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase = 1     ,       __lowerCAmelCase = "relu"			)  ->  Optional[int]:
        super().__init__()
        lowercase__    :   Any						= in_channels != out_channels or stride != 1
        lowercase__    :   Any						= (
            ResNetShortCut(__lowerCAmelCase     ,       __lowerCAmelCase     ,       stride=__lowerCAmelCase			) if should_apply_shortcut else nn.Identity()
        )
        lowercase__    :   Dict						= nn.Sequential(
            ResNetConvLayer(__lowerCAmelCase     ,       __lowerCAmelCase     ,       stride=__lowerCAmelCase			)     ,       ResNetConvLayer(__lowerCAmelCase     ,       __lowerCAmelCase     ,       activation=__lowerCAmelCase			)     ,       )
        lowercase__    :   str						= ACTaFN[activation]


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  Optional[int]:
        lowercase__    :   List[str]						= hidden_state
        lowercase__    :   int						= self.layer(__lowerCAmelCase			)
        lowercase__    :   Tuple						= self.shortcut(__lowerCAmelCase			)
        hidden_state += residual
        lowercase__    :   Tuple						= self.activation(__lowerCAmelCase			)
        return hidden_state



class       UpperCAmelCase  (						nn.Module ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase = 1     ,       __lowerCAmelCase = "relu"     ,       __lowerCAmelCase = 4			)  ->  Tuple:
        super().__init__()
        lowercase__    :   Union[str, Any]						= in_channels != out_channels or stride != 1
        lowercase__    :   Any						= out_channels // reduction
        lowercase__    :   List[Any]						= (
            ResNetShortCut(__lowerCAmelCase     ,       __lowerCAmelCase     ,       stride=__lowerCAmelCase			) if should_apply_shortcut else nn.Identity()
        )
        lowercase__    :   str						= nn.Sequential(
            ResNetConvLayer(__lowerCAmelCase     ,       __lowerCAmelCase     ,       kernel_size=1			)     ,       ResNetConvLayer(__lowerCAmelCase     ,       __lowerCAmelCase     ,       stride=__lowerCAmelCase			)     ,       ResNetConvLayer(__lowerCAmelCase     ,       __lowerCAmelCase     ,       kernel_size=1     ,       activation=__lowerCAmelCase			)     ,       )
        lowercase__    :   int						= ACTaFN[activation]


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  Tuple:
        lowercase__    :   List[str]						= hidden_state
        lowercase__    :   Union[str, Any]						= self.layer(__lowerCAmelCase			)
        lowercase__    :   Dict						= self.shortcut(__lowerCAmelCase			)
        hidden_state += residual
        lowercase__    :   Optional[Any]						= self.activation(__lowerCAmelCase			)
        return hidden_state



class       UpperCAmelCase  (						nn.Module ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase = 2     ,       __lowerCAmelCase = 2     ,       )  ->  Tuple:
        super().__init__()

        lowercase__    :   Optional[Any]						= ResNetBottleNeckLayer if config.layer_type == '''bottleneck''' else ResNetBasicLayer

        lowercase__    :   int						= nn.Sequential(
            # downsampling is done in the first layer with stride of 2
            layer(__lowerCAmelCase     ,       __lowerCAmelCase     ,       stride=__lowerCAmelCase     ,       activation=config.hidden_act			)     ,       *[layer(__lowerCAmelCase     ,       __lowerCAmelCase     ,       activation=config.hidden_act			) for _ in range(depth - 1			)]     ,       )


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  Tensor:
        lowercase__    :   Tuple						= input
        for layer in self.layers:
         lowercase__    :   Optional[Any]						= layer(__lowerCAmelCase			)
        return hidden_state



class       UpperCAmelCase  (						nn.Module ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase			)  ->  Tuple:
        super().__init__()
        lowercase__    :   Optional[int]						= nn.ModuleList([]			)
        # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
        self.stages.append(
            ResNetStage(
                __lowerCAmelCase     ,       config.embedding_size     ,       config.hidden_sizes[0]     ,       stride=2 if config.downsample_in_first_stage else 1     ,       depth=config.depths[0]     ,       )			)
        lowercase__    :   int						= zip(config.hidden_sizes     ,       config.hidden_sizes[1:]			)
        for (in_channels, out_channels), depth in zip(__lowerCAmelCase     ,       config.depths[1:]			):
         self.stages.append(ResNetStage(__lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       depth=__lowerCAmelCase			)			)


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase = False     ,       __lowerCAmelCase = True			)  ->  BaseModelOutputWithNoAttention:
        lowercase__    :   List[Any]						= () if output_hidden_states else None

        for stage_module in self.stages:
         if output_hidden_states:
          lowercase__    :   List[str]						= hidden_states + (hidden_state,)

         lowercase__    :   Optional[Any]						= stage_module(__lowerCAmelCase			)

        if output_hidden_states:
         lowercase__    :   List[str]						= hidden_states + (hidden_state,)

        if not return_dict:
         return tuple(v for v in [hidden_state, hidden_states] if v is not None			)

        return BaseModelOutputWithNoAttention(
            last_hidden_state=__lowerCAmelCase     ,       hidden_states=__lowerCAmelCase     ,       )



class       UpperCAmelCase  (						a__ ):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE 		=   ResNetConfig
       SCREAMING_SNAKE_CASE 		=   "resnet"
       SCREAMING_SNAKE_CASE 		=   "pixel_values"
       SCREAMING_SNAKE_CASE 		=   True

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  Union[str, Any]:
        if isinstance(__lowerCAmelCase     ,       nn.Convad			):
         nn.init.kaiming_normal_(module.weight     ,       mode='''fan_out'''     ,       nonlinearity='''relu'''			)
        elif isinstance(__lowerCAmelCase     ,       (nn.BatchNormad, nn.GroupNorm)			):
         nn.init.constant_(module.weight     ,       1			)
         nn.init.constant_(module.bias     ,       0			)


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase=False			)  ->  str:
        if isinstance(__lowerCAmelCase     ,       __lowerCAmelCase			):
         lowercase__    :   Dict						= value


__a:			str	       =       R"""
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`ResNetConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""

__a:			Union[str, Any]	       =       R"""
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`ConvNextImageProcessor.__call__`] for details.

        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""



@add_start_docstrings(
    "The bare ResNet model outputting raw features without any specific head on top."   ,						a__   ,						)
class       UpperCAmelCase  (						a__ ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase			)  ->  Dict:
        super().__init__(__lowerCAmelCase			)
        lowercase__    :   Dict						= config
        lowercase__    :   Union[str, Any]						= ResNetEmbeddings(__lowerCAmelCase			)
        lowercase__    :   str						= ResNetEncoder(__lowerCAmelCase			)
        lowercase__    :   Dict						= nn.AdaptiveAvgPoolad((1, 1)			)
        # Initialize weights and apply final processing
        self.post_init()


       @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     ,       __lowerCAmelCase = None     ,       __lowerCAmelCase = None			)  ->  BaseModelOutputWithPoolingAndNoAttention:
        lowercase__    :   Dict						= (
            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

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

        lowercase__    :   List[Any]						= self.encoder(
            __lowerCAmelCase     ,       output_hidden_states=__lowerCAmelCase     ,       return_dict=__lowerCAmelCase			)

        lowercase__    :   List[str]						= encoder_outputs[0]

        lowercase__    :   Optional[int]						= self.pooler(__lowerCAmelCase			)

        if not return_dict:
         return (last_hidden_state, pooled_output) + encoder_outputs[1:]

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



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





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase			)  ->  str:
        super().__init__(__lowerCAmelCase			)
        lowercase__    :   int						= config.num_labels
        lowercase__    :   List[str]						= ResNetModel(__lowerCAmelCase			)
        # classification head
        lowercase__    :   Optional[int]						= nn.Sequential(
            nn.Flatten()     ,       nn.Linear(config.hidden_sizes[-1]     ,       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     ,       )  ->  ImageClassifierOutputWithNoAttention:
        lowercase__    :   List[str]						= return_dict if return_dict is not None else self.config.use_return_dict

        lowercase__    :   List[str]						= self.resnet(__lowerCAmelCase     ,       output_hidden_states=__lowerCAmelCase     ,       return_dict=__lowerCAmelCase			)

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

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

        lowercase__    :   int						= None

        if labels is not None:
         if self.config.problem_type is None:
          if self.num_labels == 1:
           lowercase__    :   Tuple						= '''regression'''
          elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
           lowercase__    :   Any						= '''single_label_classification'''
          else:
           lowercase__    :   int						= '''multi_label_classification'''
         if self.config.problem_type == "regression":
          lowercase__    :   int						= MSELoss()
          if self.num_labels == 1:
           lowercase__    :   str						= loss_fct(logits.squeeze()     ,       labels.squeeze()			)
          else:
           lowercase__    :   Any						= loss_fct(__lowerCAmelCase     ,       __lowerCAmelCase			)
         elif self.config.problem_type == "single_label_classification":
          lowercase__    :   Tuple						= CrossEntropyLoss()
          lowercase__    :   str						= loss_fct(logits.view(-1     ,       self.num_labels			)     ,       labels.view(-1			)			)
         elif self.config.problem_type == "multi_label_classification":
          lowercase__    :   Tuple						= BCEWithLogitsLoss()
          lowercase__    :   Any						= loss_fct(__lowerCAmelCase     ,       __lowerCAmelCase			)

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

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



@add_start_docstrings(
    "\n    ResNet backbone, to be used with frameworks like DETR and MaskFormer.\n    "   ,						a__   ,						)
class       UpperCAmelCase  (						a__   ,						a__ ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase			)  ->  List[Any]:
        super().__init__(__lowerCAmelCase			)
        super()._init_backbone(__lowerCAmelCase			)

        lowercase__    :   str						= [config.embedding_size] + config.hidden_sizes
        lowercase__    :   Any						= ResNetEmbeddings(__lowerCAmelCase			)
        lowercase__    :   Optional[int]						= ResNetEncoder(__lowerCAmelCase			)

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


       @add_start_docstrings_to_model_forward(__lowerCAmelCase			)
       @replace_return_docstrings(output_type=__lowerCAmelCase     ,       config_class=_CONFIG_FOR_DOC			)
       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase = None     ,       __lowerCAmelCase = None			)  ->  BackboneOutput:
        lowercase__    :   Union[str, Any]						= return_dict if return_dict is not None else self.config.use_return_dict
        lowercase__    :   int						= (
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )

        lowercase__    :   str						= self.embedder(__lowerCAmelCase			)

        lowercase__    :   List[str]						= self.encoder(__lowerCAmelCase     ,       output_hidden_states=__lowerCAmelCase     ,       return_dict=__lowerCAmelCase			)

        lowercase__    :   Optional[Any]						= outputs.hidden_states

        lowercase__    :   Dict						= ()
        for idx, stage in enumerate(self.stage_names			):
         if stage in self.out_features:
          feature_maps += (hidden_states[idx],)

        if not return_dict:
         lowercase__    :   Optional[int]						= (feature_maps,)
         if output_hidden_states:
          output += (outputs.hidden_states,)
         return output

        return BackboneOutput(
            feature_maps=__lowerCAmelCase     ,       hidden_states=outputs.hidden_states if output_hidden_states else None     ,       attentions=__lowerCAmelCase     ,       )





'''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			)			)

