'''simple docstring'''

from typing import Optional, Tuple, Union

import tensorflow as tf

from ...activations_tf import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_tf_outputs import (
    TFBaseModelOutputWithNoAttention,
    TFBaseModelOutputWithPoolingAndNoAttention,
    TFSequenceClassifierOutput,
)
from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs
from ...tf_utils import shape_list
from ...utils import logging
from .configuration_regnet import RegNetConfig


__a:			Tuple	       =       logging.get_logger(__name__)

# General docstring
__a:			str	       =       """RegNetConfig"""

# Base docstring
__a:			str	       =       """facebook/regnet-y-040"""
__a:			List[Any]	       =       [1, 10_88, 7, 7]

# Image classification docstring
__a:			Tuple	       =       """facebook/regnet-y-040"""
__a:			int	       =       """tabby, tabby cat"""

__a:			List[Any]	       =       [
    """facebook/regnet-y-040""",
    # See all regnet models at https://huggingface.co/models?filter=regnet
]



class       UpperCAmelCase  (						tf.keras.layers.Layer ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase = 3     ,       __lowerCAmelCase = 1     ,       __lowerCAmelCase = 1     ,       __lowerCAmelCase = "relu"     ,       **__lowerCAmelCase     ,       )  ->  Dict:
        super().__init__(**__lowerCAmelCase			)
        # The padding and conv has been verified in
        # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb
        lowercase__    :   List[Any]						= tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2			)
        lowercase__    :   str						= tf.keras.layers.ConvaD(
            filters=__lowerCAmelCase     ,       kernel_size=__lowerCAmelCase     ,       strides=__lowerCAmelCase     ,       padding='''VALID'''     ,       groups=__lowerCAmelCase     ,       use_bias=__lowerCAmelCase     ,       name='''convolution'''     ,       )
        lowercase__    :   Optional[Any]						= tf.keras.layers.BatchNormalization(epsilon=1E-5     ,       momentum=0.9     ,       name='''normalization'''			)
        lowercase__    :   List[Any]						= ACTaFN[activation] if activation is not None else tf.identity


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  List[Any]:
        lowercase__    :   Optional[Any]						= self.convolution(self.padding(__lowerCAmelCase			)			)
        lowercase__    :   Any						= self.normalization(__lowerCAmelCase			)
        lowercase__    :   Tuple						= self.activation(__lowerCAmelCase			)
        return hidden_state



class       UpperCAmelCase  (						tf.keras.layers.Layer ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       **__lowerCAmelCase			)  ->  Optional[Any]:
        super().__init__(**__lowerCAmelCase			)
        lowercase__    :   Union[str, Any]						= config.num_channels
        lowercase__    :   Tuple						= TFRegNetConvLayer(
            out_channels=config.embedding_size     ,       kernel_size=3     ,       stride=2     ,       activation=config.hidden_act     ,       name='''embedder'''     ,       )


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  str:
        lowercase__    :   Tuple						= shape_list(__lowerCAmelCase			)[1]
        if tf.executing_eagerly() and 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.'''			)

        # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format.
        # So change the input format from `NCHW` to `NHWC`.
        # shape = (batch_size, in_height, in_width, in_channels=num_channels)
        lowercase__    :   List[Any]						= tf.transpose(__lowerCAmelCase     ,       perm=(0, 2, 3, 1)			)
        lowercase__    :   List[Any]						= self.embedder(__lowerCAmelCase			)
        return hidden_state



class       UpperCAmelCase  (						tf.keras.layers.Layer ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase = 2     ,       **__lowerCAmelCase			)  ->  List[Any]:
        super().__init__(**__lowerCAmelCase			)
        lowercase__    :   Optional[Any]						= tf.keras.layers.ConvaD(
            filters=__lowerCAmelCase     ,       kernel_size=1     ,       strides=__lowerCAmelCase     ,       use_bias=__lowerCAmelCase     ,       name='''convolution'''			)
        lowercase__    :   Optional[Any]						= tf.keras.layers.BatchNormalization(epsilon=1E-5     ,       momentum=0.9     ,       name='''normalization'''			)


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase = False			)  ->  tf.Tensor:
        return self.normalization(self.convolution(__lowerCAmelCase			)     ,       training=__lowerCAmelCase			)



class       UpperCAmelCase  (						tf.keras.layers.Layer ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       **__lowerCAmelCase			)  ->  Optional[int]:
        super().__init__(**__lowerCAmelCase			)
        lowercase__    :   Optional[Any]						= tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowerCAmelCase     ,       name='''pooler'''			)
        lowercase__    :   Optional[int]						= [
            tf.keras.layers.ConvaD(filters=__lowerCAmelCase     ,       kernel_size=1     ,       activation='''relu'''     ,       name='''attention.0'''			),
            tf.keras.layers.ConvaD(filters=__lowerCAmelCase     ,       kernel_size=1     ,       activation='''sigmoid'''     ,       name='''attention.2'''			),
        ]


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  Dict:
        # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels]
        lowercase__    :   Optional[int]						= self.pooler(__lowerCAmelCase			)
        for layer_module in self.attention:
         lowercase__    :   Union[str, Any]						= layer_module(__lowerCAmelCase			)
        lowercase__    :   int						= hidden_state * pooled
        return hidden_state



class       UpperCAmelCase  (						tf.keras.layers.Layer ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase = 1     ,       **__lowerCAmelCase			)  ->  Optional[Any]:
        super().__init__(**__lowerCAmelCase			)
        lowercase__    :   str						= in_channels != out_channels or stride != 1
        lowercase__    :   int						= max(1     ,       out_channels // config.groups_width			)
        lowercase__    :   Union[str, Any]						= (
            TFRegNetShortCut(__lowerCAmelCase     ,       stride=__lowerCAmelCase     ,       name='''shortcut'''			)
            if should_apply_shortcut
            else tf.keras.layers.Activation('''linear'''     ,       name='''shortcut'''			)
        )
        # `self.layers` instead of `self.layer` because that is a reserved argument.
        lowercase__    :   Union[str, Any]						= [
            TFRegNetConvLayer(__lowerCAmelCase     ,       kernel_size=1     ,       activation=config.hidden_act     ,       name='''layer.0'''			),
            TFRegNetConvLayer(
                __lowerCAmelCase     ,       stride=__lowerCAmelCase     ,       groups=__lowerCAmelCase     ,       activation=config.hidden_act     ,       name='''layer.1'''			),
            TFRegNetConvLayer(__lowerCAmelCase     ,       kernel_size=1     ,       activation=__lowerCAmelCase     ,       name='''layer.2'''			),
        ]
        lowercase__    :   int						= ACTaFN[config.hidden_act]


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  Union[str, Any]:
        lowercase__    :   List[Any]						= hidden_state
        for layer_module in self.layers:
         lowercase__    :   int						= layer_module(__lowerCAmelCase			)
        lowercase__    :   str						= self.shortcut(__lowerCAmelCase			)
        hidden_state += residual
        lowercase__    :   Optional[int]						= self.activation(__lowerCAmelCase			)
        return hidden_state



class       UpperCAmelCase  (						tf.keras.layers.Layer ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase = 1     ,       **__lowerCAmelCase			)  ->  Tuple:
        super().__init__(**__lowerCAmelCase			)
        lowercase__    :   List[str]						= in_channels != out_channels or stride != 1
        lowercase__    :   int						= max(1     ,       out_channels // config.groups_width			)
        lowercase__    :   List[str]						= (
            TFRegNetShortCut(__lowerCAmelCase     ,       stride=__lowerCAmelCase     ,       name='''shortcut'''			)
            if should_apply_shortcut
            else tf.keras.layers.Activation('''linear'''     ,       name='''shortcut'''			)
        )
        lowercase__    :   Optional[int]						= [
            TFRegNetConvLayer(__lowerCAmelCase     ,       kernel_size=1     ,       activation=config.hidden_act     ,       name='''layer.0'''			),
            TFRegNetConvLayer(
                __lowerCAmelCase     ,       stride=__lowerCAmelCase     ,       groups=__lowerCAmelCase     ,       activation=config.hidden_act     ,       name='''layer.1'''			),
            TFRegNetSELayer(__lowerCAmelCase     ,       reduced_channels=int(round(in_channels / 4			)			)     ,       name='''layer.2'''			),
            TFRegNetConvLayer(__lowerCAmelCase     ,       kernel_size=1     ,       activation=__lowerCAmelCase     ,       name='''layer.3'''			),
        ]
        lowercase__    :   int						= ACTaFN[config.hidden_act]


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  str:
        lowercase__    :   Optional[int]						= hidden_state
        for layer_module in self.layers:
         lowercase__    :   Dict						= layer_module(__lowerCAmelCase			)
        lowercase__    :   Any						= self.shortcut(__lowerCAmelCase			)
        hidden_state += residual
        lowercase__    :   str						= self.activation(__lowerCAmelCase			)
        return hidden_state



class       UpperCAmelCase  (						tf.keras.layers.Layer ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase = 2     ,       __lowerCAmelCase = 2     ,       **__lowerCAmelCase			)  ->  Optional[int]:
        super().__init__(**__lowerCAmelCase			)

        lowercase__    :   Optional[int]						= TFRegNetXLayer if config.layer_type == '''x''' else TFRegNetYLayer
        lowercase__    :   List[str]						= [
            # downsampling is done in the first layer with stride of 2
            layer(__lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       stride=__lowerCAmelCase     ,       name='''layers.0'''			),
            *[layer(__lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       name=F"""layers.{i+1}"""			) for i in range(depth - 1			)],
        ]


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  List[str]:
        for layer_module in self.layers:
         lowercase__    :   int						= layer_module(__lowerCAmelCase			)
        return hidden_state



class       UpperCAmelCase  (						tf.keras.layers.Layer ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       **__lowerCAmelCase			)  ->  Dict:
        super().__init__(**__lowerCAmelCase			)
        lowercase__    :   Optional[int]						= []
        # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
        self.stages.append(
            TFRegNetStage(
                __lowerCAmelCase     ,       config.embedding_size     ,       config.hidden_sizes[0]     ,       stride=2 if config.downsample_in_first_stage else 1     ,       depth=config.depths[0]     ,       name='''stages.0'''     ,       )			)
        lowercase__    :   int						= zip(config.hidden_sizes     ,       config.hidden_sizes[1:]			)
        for i, ((in_channels, out_channels), depth) in enumerate(zip(__lowerCAmelCase     ,       config.depths[1:]			)			):
         self.stages.append(TFRegNetStage(__lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       depth=__lowerCAmelCase     ,       name=F"""stages.{i+1}"""			)			)


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase = False     ,       __lowerCAmelCase = True			)  ->  TFBaseModelOutputWithNoAttention:
        lowercase__    :   Dict						= () if output_hidden_states else None

        for stage_module in self.stages:
         if output_hidden_states:
          lowercase__    :   Dict						= hidden_states + (hidden_state,)

         lowercase__    :   str						= stage_module(__lowerCAmelCase			)

        if output_hidden_states:
         lowercase__    :   Optional[int]						= hidden_states + (hidden_state,)

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

        return TFBaseModelOutputWithNoAttention(last_hidden_state=__lowerCAmelCase     ,       hidden_states=__lowerCAmelCase			)



@keras_serializable
class       UpperCAmelCase  (						tf.keras.layers.Layer ):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE 		=   RegNetConfig

       def __init__(						self     ,       __lowerCAmelCase     ,       **__lowerCAmelCase			)  ->  Optional[Any]:
        super().__init__(**__lowerCAmelCase			)
        lowercase__    :   List[Any]						= config
        lowercase__    :   Optional[Any]						= TFRegNetEmbeddings(__lowerCAmelCase     ,       name='''embedder'''			)
        lowercase__    :   Dict						= TFRegNetEncoder(__lowerCAmelCase     ,       name='''encoder'''			)
        lowercase__    :   Optional[Any]						= tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowerCAmelCase     ,       name='''pooler'''			)


       @unpack_inputs
       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase = None     ,       __lowerCAmelCase = None     ,       __lowerCAmelCase = False     ,       )  ->  TFBaseModelOutputWithPoolingAndNoAttention:
        lowercase__    :   Union[str, Any]						= (
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        lowercase__    :   str						= return_dict if return_dict is not None else self.config.use_return_dict

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

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

        lowercase__    :   Any						= encoder_outputs[0]
        lowercase__    :   Dict						= self.pooler(__lowerCAmelCase			)

        # Change to NCHW output format have uniformity in the modules
        lowercase__    :   Any						= tf.transpose(__lowerCAmelCase     ,       perm=(0, 3, 1, 2)			)
        lowercase__    :   Optional[Any]						= tf.transpose(__lowerCAmelCase     ,       perm=(0, 3, 1, 2)			)

        # Change the other hidden state outputs to NCHW as well
        if output_hidden_states:
         lowercase__    :   int						= tuple([tf.transpose(__lowerCAmelCase     ,       perm=(0, 3, 1, 2)			) for h in encoder_outputs[1]]			)

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

        return TFBaseModelOutputWithPoolingAndNoAttention(
            last_hidden_state=__lowerCAmelCase     ,       pooler_output=__lowerCAmelCase     ,       hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states     ,       )



class       UpperCAmelCase  (						a__ ):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE 		=   RegNetConfig
       SCREAMING_SNAKE_CASE 		=   "regnet"
       SCREAMING_SNAKE_CASE 		=   "pixel_values"

       @property
       def _lowerCAmelCase(						self			)  ->  Optional[int]:
        return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224)     ,       dtype=tf.floataa			)}


__a:			List[Any]	       =       R"""
    Parameters:
    This model is a Tensorflow
    [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a
    regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and
    behavior.
        config ([`RegNetConfig`]): 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 [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
"""

__a:			Optional[Any]	       =       R"""
    Args:
        pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`ConveNextImageProcessor.__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 RegNet model outputting raw features without any specific head on top."   ,						a__   ,						)
class       UpperCAmelCase  (						a__ ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       *__lowerCAmelCase     ,       **__lowerCAmelCase			)  ->  List[Any]:
        super().__init__(__lowerCAmelCase     ,       *__lowerCAmelCase     ,       **__lowerCAmelCase			)
        lowercase__    :   Optional[int]						= TFRegNetMainLayer(__lowerCAmelCase     ,       name='''regnet'''			)


       @unpack_inputs
       @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     ,       __lowerCAmelCase=False     ,       )  ->  Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]:
        lowercase__    :   Tuple						= (
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        lowercase__    :   int						= return_dict if return_dict is not None else self.config.use_return_dict

        lowercase__    :   Any						= self.regnet(
            pixel_values=__lowerCAmelCase     ,       output_hidden_states=__lowerCAmelCase     ,       return_dict=__lowerCAmelCase     ,       training=__lowerCAmelCase     ,       )
        if not return_dict:
         return (outputs[0],) + outputs[1:]

        return TFBaseModelOutputWithPoolingAndNoAttention(
            last_hidden_state=outputs.last_hidden_state     ,       pooler_output=outputs.pooler_output     ,       hidden_states=outputs.hidden_states     ,       )



@add_start_docstrings(
    "\n    RegNet 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__   ,						a__ ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       *__lowerCAmelCase     ,       **__lowerCAmelCase			)  ->  Optional[Any]:
        super().__init__(__lowerCAmelCase     ,       *__lowerCAmelCase     ,       **__lowerCAmelCase			)
        lowercase__    :   Any						= config.num_labels
        lowercase__    :   Any						= TFRegNetMainLayer(__lowerCAmelCase     ,       name='''regnet'''			)
        # classification head
        lowercase__    :   str						= [
            tf.keras.layers.Flatten(),
            tf.keras.layers.Dense(config.num_labels     ,       name='''classifier.1'''			) if config.num_labels > 0 else tf.identity,
        ]


       @unpack_inputs
       @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     ,       __lowerCAmelCase=False     ,       )  ->  Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:
        lowercase__    :   Dict						= (
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        lowercase__    :   Optional[int]						= return_dict if return_dict is not None else self.config.use_return_dict

        lowercase__    :   str						= self.regnet(
            __lowerCAmelCase     ,       output_hidden_states=__lowerCAmelCase     ,       return_dict=__lowerCAmelCase     ,       training=__lowerCAmelCase			)

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

        lowercase__    :   List[Any]						= self.classifier[0](__lowerCAmelCase			)
        lowercase__    :   str						= self.classifier[1](__lowerCAmelCase			)

        lowercase__    :   str						= None if labels is None else self.hf_compute_loss(labels=__lowerCAmelCase     ,       logits=__lowerCAmelCase			)

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

        return TFSequenceClassifierOutput(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			)			)

