




"""simple docstring"""






import collections.abc
from typing import Optional, Tuple, Union

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

from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithNoAttention, 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_poolformer import PoolFormerConfig


UpperCamelCase__						=			logging.get_logger(__name__)

# General docstring
UpperCamelCase__						=			'''PoolFormerConfig'''

# Base docstring
UpperCamelCase__						=			'''sail/poolformer_s12'''
UpperCamelCase__						=			[1, 5_1_2, 7, 7]

# Image classification docstring
UpperCamelCase__						=			'''sail/poolformer_s12'''
UpperCamelCase__						=			'''tabby, tabby cat'''

UpperCamelCase__						=			[
    '''sail/poolformer_s12''',
    # See all PoolFormer models at https://huggingface.co/models?filter=poolformer
]





def 							UpperCAmelCase		(		snake_case			:					int      ,       snake_case			:					Tuple = 0.0      ,       snake_case			:					Optional[Any] = False    ):
					if drop_prob == 0.0 or not training:
										return input
					_lowerCAmelCase:List[str]									=  1 - drop_prob
					_lowerCAmelCase:Optional[int]									=  (input.shape[0],) + (1,) * (input.ndim - 1)  # work with diff dim tensors, not just 2D ConvNets
					_lowerCAmelCase:str									=  keep_prob + torch.rand(snake_case_      ,       dtype=input.dtype      ,       device=input.device    )
					random_tensor.floor_()  # binarize
					_lowerCAmelCase:List[str]									=  input.div(snake_case_    ) * random_tensor
					return output




class   a__			(       nn.Module  ):





						def __init__(							self      :	Optional[Any]     ,a__      :	Dict = None)						->       None:




											"""simple docstring"""







											super().__init__()
											_lowerCAmelCase:List[str]									=  drop_prob





						def       __UpperCamelCase     (							self      :	Union[str, Any]     ,a__      :	Any)						->       torch.Tensor:




											"""simple docstring"""







											return drop_path(_a     ,self.drop_prob     ,self.training)







						def       __UpperCamelCase     (							self      :	Dict)						->       str:




											"""simple docstring"""







											return "p={}".format(self.drop_prob)




class   a__			(       nn.Module  ):





						def __init__(							self      :	Dict     ,a__      :	str     ,a__      :	int     ,a__      :	List[str]     ,a__      :	int     ,a__      :	Union[str, Any]     ,a__      :	Optional[Any]=None)						->       List[str]:




											"""simple docstring"""







											super().__init__()
											_lowerCAmelCase:int									=  patch_size if isinstance(_a     ,collections.abc.Iterable) else (patch_size, patch_size)
											_lowerCAmelCase:Optional[Any]									=  stride if isinstance(_a     ,collections.abc.Iterable) else (stride, stride)
											_lowerCAmelCase:Dict									=  padding if isinstance(_a     ,collections.abc.Iterable) else (padding, padding)

											_lowerCAmelCase:Optional[Any]									=  nn.Convad(_a     ,_a     ,kernel_size=_a     ,stride=_a     ,padding=_a)
											_lowerCAmelCase:str									=  norm_layer(_a) if norm_layer else nn.Identity()







						def       __UpperCamelCase     (							self      :	Dict     ,a__      :	List[str])						->       List[Any]:




											"""simple docstring"""







											_lowerCAmelCase:Any									=  self.projection(_a)
											_lowerCAmelCase:List[Any]									=  self.norm(_a)
											return embeddings




class   a__			(       nn.GroupNorm  ):





						def __init__(							self      :	Union[str, Any]     ,a__      :	Union[str, Any]     ,**a__      :	Optional[int])						->       List[Any]:




											"""simple docstring"""







											super().__init__(1     ,_a     ,**_a)




class   a__			(       nn.Module  ):





						def __init__(							self      :	int     ,a__      :	Optional[Any])						->       int:




											"""simple docstring"""







											super().__init__()
											_lowerCAmelCase:Union[str, Any]									=  nn.AvgPoolad(_a     ,stride=1     ,padding=pool_size // 2     ,count_include_pad=_a)







						def       __UpperCamelCase     (							self      :	Union[str, Any]     ,a__      :	Any)						->       Tuple:




											"""simple docstring"""







											return self.pool(_a) - hidden_states




class   a__			(       nn.Module  ):





						def __init__(							self      :	List[Any]     ,a__      :	Dict     ,a__      :	Dict     ,a__      :	Any     ,a__      :	List[str])						->       int:




											"""simple docstring"""







											super().__init__()
											_lowerCAmelCase:Tuple									=  nn.Convad(_a     ,_a     ,1)
											_lowerCAmelCase:Tuple									=  nn.Convad(_a     ,_a     ,1)
											_lowerCAmelCase:Any									=  PoolFormerDropPath(_a)
											if isinstance(config.hidden_act     ,_a):
																_lowerCAmelCase:Optional[int]									=  ACTaFN[config.hidden_act]
											else:
																_lowerCAmelCase:Optional[Any]									=  config.hidden_act







						def       __UpperCamelCase     (							self      :	Optional[Any]     ,a__      :	Optional[int])						->       Any:




											"""simple docstring"""







											_lowerCAmelCase:Tuple									=  self.conva(_a)
											_lowerCAmelCase:int									=  self.act_fn(_a)
											_lowerCAmelCase:List[str]									=  self.drop(_a)
											_lowerCAmelCase:Union[str, Any]									=  self.conva(_a)
											_lowerCAmelCase:Optional[int]									=  self.drop(_a)

											return hidden_states




class   a__			(       nn.Module  ):





						def __init__(							self      :	Union[str, Any]     ,a__      :	str     ,a__      :	str     ,a__      :	Dict     ,a__      :	Union[str, Any]     ,a__      :	Optional[int]     ,a__      :	Any)						->       Union[str, Any]:




											"""simple docstring"""







											super().__init__()
											_lowerCAmelCase:List[str]									=  PoolFormerPooling(_a)
											_lowerCAmelCase:int									=  PoolFormerOutput(_a     ,_a     ,_a     ,_a)
											_lowerCAmelCase:Optional[Any]									=  PoolFormerGroupNorm(_a)
											_lowerCAmelCase:Optional[Any]									=  PoolFormerGroupNorm(_a)

											# Useful for training neural nets
											_lowerCAmelCase:List[Any]									=  PoolFormerDropPath(_a) if drop_path > 0.0 else nn.Identity()
											_lowerCAmelCase:List[str]									=  config.use_layer_scale
											if config.use_layer_scale:
																_lowerCAmelCase:Tuple									=  nn.Parameter(
																    config.layer_scale_init_value * torch.ones((_a))     ,requires_grad=_a)
																_lowerCAmelCase:Tuple									=  nn.Parameter(
																    config.layer_scale_init_value * torch.ones((_a))     ,requires_grad=_a)







						def       __UpperCamelCase     (							self      :	List[str]     ,a__      :	Dict)						->       Union[str, Any]:




											"""simple docstring"""







											if self.use_layer_scale:
																_lowerCAmelCase:Optional[Any]									=  self.pooling(self.before_norm(_a))
																_lowerCAmelCase:Union[str, Any]									=  self.layer_scale_a.unsqueeze(-1).unsqueeze(-1) * pooling_output
																# First residual connection
																_lowerCAmelCase:Union[str, Any]									=  hidden_states + self.drop_path(_a)
																_lowerCAmelCase:List[Any]									=  ()

																_lowerCAmelCase:List[str]									=  self.output(self.after_norm(_a))
																_lowerCAmelCase:Optional[Any]									=  self.layer_scale_a.unsqueeze(-1).unsqueeze(-1) * layer_output
																# Second residual connection
																_lowerCAmelCase:List[Any]									=  hidden_states + self.drop_path(_a)

																_lowerCAmelCase:Union[str, Any]									=  (output,) + outputs
																return outputs

											else:
																_lowerCAmelCase:int									=  self.drop_path(self.pooling(self.before_norm(_a)))
																# First residual connection
																_lowerCAmelCase:int									=  pooling_output + hidden_states
																_lowerCAmelCase:Dict									=  ()

																# Second residual connection inside the PoolFormerOutput block
																_lowerCAmelCase:int									=  self.drop_path(self.output(self.after_norm(_a)))
																_lowerCAmelCase:Union[str, Any]									=  hidden_states + layer_output

																_lowerCAmelCase:Dict									=  (output,) + outputs
																return outputs




class   a__			(       nn.Module  ):





						def __init__(							self      :	Any     ,a__      :	Optional[Any])						->       Optional[int]:




											"""simple docstring"""







											super().__init__()
											_lowerCAmelCase:Union[str, Any]									=  config
											# stochastic depth decay rule
											_lowerCAmelCase:Union[str, Any]									=  [x.item() for x in torch.linspace(0     ,config.drop_path_rate     ,sum(config.depths))]

											# patch embeddings
											_lowerCAmelCase:Optional[Any]									=  []
											for i in range(config.num_encoder_blocks):
																embeddings.append(
																    PoolFormerEmbeddings(
																        patch_size=config.patch_sizes[i]     ,stride=config.strides[i]     ,padding=config.padding[i]     ,num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1]     ,hidden_size=config.hidden_sizes[i]     ,))
											_lowerCAmelCase:Optional[int]									=  nn.ModuleList(_a)

											# Transformer blocks
											_lowerCAmelCase:Optional[Any]									=  []
											_lowerCAmelCase:Tuple									=  0
											for i in range(config.num_encoder_blocks):
																# each block consists of layers
																_lowerCAmelCase:List[Any]									=  []
																if i != 0:
																					cur += config.depths[i - 1]
																for j in range(config.depths[i]):
																					layers.append(
																					    PoolFormerLayer(
																					        _a     ,num_channels=config.hidden_sizes[i]     ,pool_size=config.pool_size     ,hidden_size=config.hidden_sizes[i]     ,intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio)     ,drop_path=dpr[cur + j]     ,))
																blocks.append(nn.ModuleList(_a))

											_lowerCAmelCase:List[Any]									=  nn.ModuleList(_a)







						def       __UpperCamelCase     (							self      :	Tuple     ,a__      :	int     ,a__      :	Optional[int]=False     ,a__      :	Optional[int]=True)						->       Tuple:




											"""simple docstring"""







											_lowerCAmelCase:Tuple									=  () if output_hidden_states else None

											_lowerCAmelCase:List[str]									=  pixel_values
											for idx, layers in enumerate(zip(self.patch_embeddings     ,self.block)):
																_lowerCAmelCase:Union[str, Any]									=  layers
																# Get patch embeddings from hidden_states
																_lowerCAmelCase:str									=  embedding_layer(_a)
																# Send the embeddings through the blocks
																for _, blk in enumerate(_a):
																					_lowerCAmelCase:Optional[Any]									=  blk(_a)
																					_lowerCAmelCase:List[str]									=  layer_outputs[0]

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

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

											return BaseModelOutputWithNoAttention(last_hidden_state=_a     ,hidden_states=_a)




class   a__			(       UpperCamelCase__  ):
						snake_case__             = PoolFormerConfig
						snake_case__             = '''poolformer'''
						snake_case__             = '''pixel_values'''
						snake_case__             = True





						def       __UpperCamelCase     (							self      :	Union[str, Any]     ,a__      :	Optional[int])						->       Tuple:




											"""simple docstring"""







											if isinstance(_a     ,(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(_a     ,nn.LayerNorm):
																module.bias.data.zero_()
																module.weight.data.fill_(1.0)







						def       __UpperCamelCase     (							self      :	Dict     ,a__      :	Union[str, Any]     ,a__      :	Optional[int]=False)						->       Union[str, Any]:




											"""simple docstring"""







											if isinstance(_a     ,_a):
																_lowerCAmelCase:List[str]									=  value



UpperCamelCase__						=			r'''\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n    it 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 ([`PoolFormerConfig`]): 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'''

UpperCamelCase__						=			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            [`PoolFormerImageProcessor.__call__`] for details.\n'''




@add_start_docstrings(
    '''The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.'''					,	UpperCamelCase__					,	)
class   a__			(       UpperCamelCase__  ):





						def __init__(							self      :	Union[str, Any]     ,a__      :	List[Any])						->       List[str]:




											"""simple docstring"""







											super().__init__(_a)
											_lowerCAmelCase:Any									=  config

											_lowerCAmelCase:Union[str, Any]									=  PoolFormerEncoder(_a)

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





						def       __UpperCamelCase     (							self      :	List[Any])						->       str:




											"""simple docstring"""







											return self.embeddings.patch_embeddings







						@add_start_docstrings_to_model_forward(_a)
						@add_code_sample_docstrings(
						    checkpoint=_CHECKPOINT_FOR_DOC     ,output_type=_a     ,config_class=_CONFIG_FOR_DOC     ,modality='''vision'''     ,expected_output=_EXPECTED_OUTPUT_SHAPE     ,)
						def       __UpperCamelCase     (							self      :	List[Any]     ,a__      :	Optional[Any] = None     ,a__      :	List[Any] = None     ,a__      :	Optional[int] = None     ,)						->       Union[Tuple, BaseModelOutputWithNoAttention]:




											"""simple docstring"""







											_lowerCAmelCase:Optional[int]									=  (
											    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
											)
											_lowerCAmelCase:List[str]									=  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''')

											_lowerCAmelCase:Any									=  self.encoder(
											    _a     ,output_hidden_states=_a     ,return_dict=_a     ,)
											_lowerCAmelCase:Optional[int]									=  encoder_outputs[0]

											if not return_dict:
																return (sequence_output, None) + encoder_outputs[1:]

											return BaseModelOutputWithNoAttention(
											    last_hidden_state=_a     ,hidden_states=encoder_outputs.hidden_states     ,)




class   a__			(       nn.Module  ):





						def __init__(							self      :	Tuple     ,a__      :	Dict)						->       Tuple:




											"""simple docstring"""







											super().__init__()
											_lowerCAmelCase:List[str]									=  nn.Linear(config.hidden_size     ,config.hidden_size)







						def       __UpperCamelCase     (							self      :	Tuple     ,a__      :	Tuple)						->       Tuple:




											"""simple docstring"""







											_lowerCAmelCase:str									=  self.dense(_a)
											return output




@add_start_docstrings(
    '''\n    PoolFormer Model transformer with an image classification head on top\n    '''					,	UpperCamelCase__					,	)
class   a__			(       UpperCamelCase__  ):





						def __init__(							self      :	Any     ,a__      :	str)						->       List[Any]:




											"""simple docstring"""







											super().__init__(_a)
											_lowerCAmelCase:Tuple									=  config.num_labels
											_lowerCAmelCase:Optional[Any]									=  PoolFormerModel(_a)

											# Final norm
											_lowerCAmelCase:Optional[int]									=  PoolFormerGroupNorm(config.hidden_sizes[-1])
											# Classifier head
											_lowerCAmelCase:str									=  (
											    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(_a)
						@add_code_sample_docstrings(
						    checkpoint=_IMAGE_CLASS_CHECKPOINT     ,output_type=_a     ,config_class=_CONFIG_FOR_DOC     ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT     ,)
						def       __UpperCamelCase     (							self      :	int     ,a__      :	Tuple = None     ,a__      :	Union[str, Any] = None     ,a__      :	Optional[Any] = None     ,a__      :	Optional[Any] = None     ,)						->       Union[Tuple, ImageClassifierOutputWithNoAttention]:




											"""simple docstring"""







											_lowerCAmelCase:Optional[Any]									=  return_dict if return_dict is not None else self.config.use_return_dict

											_lowerCAmelCase:Optional[Any]									=  self.poolformer(
											    _a     ,output_hidden_states=_a     ,return_dict=_a     ,)

											_lowerCAmelCase:Tuple									=  outputs[0]

											_lowerCAmelCase:Any									=  self.classifier(self.norm(_a).mean([-2, -1]))

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

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

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

											return ImageClassifierOutputWithNoAttention(loss=_a     ,logits=_a     ,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   a__			:





						def __init__(							self      :	List[str]     ,a__      :	List[Any]     ,a__      :	List[str]=2     ,a__      :	Optional[Any]=32     ,a__      :	int=16     ,a__      :	Dict=3     ,a__      :	Optional[int]=True     ,a__      :	int=True     ,a__      :	Optional[Any]=32     ,a__      :	str=4     ,a__      :	Tuple=[0, 1, 2, 3]     ,a__      :	Any=4     ,a__      :	int=37     ,a__      :	int="gelu"     ,a__      :	Optional[int]=0.1     ,a__      :	List[Any]=0.1     ,a__      :	Optional[Any]=0.02     ,a__      :	str=3     ,a__      :	str=[1, 384, 24, 24]     ,a__      :	Optional[Any]=True     ,a__      :	Tuple=None     ,)						->       Optional[Any]:




											"""simple docstring"""







											_lowerCAmelCase:Optional[Any]									=  parent
											_lowerCAmelCase:Union[str, Any]									=  batch_size
											_lowerCAmelCase:List[Any]									=  image_size
											_lowerCAmelCase:int									=  patch_size
											_lowerCAmelCase:Optional[int]									=  num_channels
											_lowerCAmelCase:List[str]									=  is_training
											_lowerCAmelCase:int									=  use_labels
											_lowerCAmelCase:Any									=  hidden_size
											_lowerCAmelCase:Any									=  num_hidden_layers
											_lowerCAmelCase:List[Any]									=  backbone_out_indices
											_lowerCAmelCase:int									=  num_attention_heads
											_lowerCAmelCase:Tuple									=  intermediate_size
											_lowerCAmelCase:int									=  hidden_act
											_lowerCAmelCase:Optional[int]									=  hidden_dropout_prob
											_lowerCAmelCase:Union[str, Any]									=  attention_probs_dropout_prob
											_lowerCAmelCase:Any									=  initializer_range
											_lowerCAmelCase:int									=  num_labels
											_lowerCAmelCase:Optional[int]									=  backbone_featmap_shape
											_lowerCAmelCase:List[str]									=  scope
											_lowerCAmelCase:Union[str, Any]									=  is_hybrid
											# sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
											_lowerCAmelCase:Any									=  (image_size // patch_size) ** 2
											_lowerCAmelCase:Tuple									=  num_patches + 1





						def       __UpperCamelCase     (							self      :	Tuple)						->       Dict:




											"""simple docstring"""







											_lowerCAmelCase:List[str]									=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

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

											return config, pixel_values, labels





						def       __UpperCamelCase     (							self      :	Union[str, Any])						->       Dict:




											"""simple docstring"""







											_lowerCAmelCase:Optional[int]									=  {
											    '''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=a__     ,initializer_range=self.initializer_range     ,is_hybrid=self.is_hybrid     ,backbone_config=a__     ,backbone_featmap_shape=self.backbone_featmap_shape     ,)





						def       __UpperCamelCase     (							self      :	int     ,a__      :	Tuple     ,a__      :	Tuple     ,a__      :	Tuple)						->       Dict:




											"""simple docstring"""







											_lowerCAmelCase:Dict									=  DPTModel(config=a__)
											model.to(a__)
											model.eval()
											_lowerCAmelCase:Optional[Any]									=  model(a__)
											self.parent.assertEqual(result.last_hidden_state.shape     ,(self.batch_size, self.seq_length, self.hidden_size))





						def       __UpperCamelCase     (							self      :	str     ,a__      :	Optional[int]     ,a__      :	Union[str, Any]     ,a__      :	int)						->       Optional[int]:




											"""simple docstring"""







											_lowerCAmelCase:Tuple									=  self.num_labels
											_lowerCAmelCase:List[Any]									=  DPTForDepthEstimation(a__)
											model.to(a__)
											model.eval()
											_lowerCAmelCase:int									=  model(a__)
											self.parent.assertEqual(result.predicted_depth.shape     ,(self.batch_size, self.image_size, self.image_size))





						def       __UpperCamelCase     (							self      :	Union[str, Any]     ,a__      :	Dict     ,a__      :	List[Any]     ,a__      :	str)						->       Optional[int]:




											"""simple docstring"""







											_lowerCAmelCase:Dict									=  self.num_labels
											_lowerCAmelCase:str									=  DPTForSemanticSegmentation(a__)
											model.to(a__)
											model.eval()
											_lowerCAmelCase:int									=  model(a__     ,labels=a__)
											self.parent.assertEqual(
											    result.logits.shape     ,(self.batch_size, self.num_labels, self.image_size, self.image_size))







						def       __UpperCamelCase     (							self      :	Optional[int])						->       List[str]:




											"""simple docstring"""







											_lowerCAmelCase:List[str]									=  self.prepare_config_and_inputs()
											_lowerCAmelCase							,   _lowerCAmelCase							,   _lowerCAmelCase:Any									=  config_and_inputs
											_lowerCAmelCase:Union[str, Any]									=  {'''pixel_values''': pixel_values}
											return config, inputs_dict




@require_torch
class   a__			(       UpperCamelCase_					,	UpperCamelCase_					,	unittest.TestCase  ):
						snake_case__             = (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
						snake_case__             = (
						    {
						        '''depth-estimation''': DPTForDepthEstimation,
						        '''feature-extraction''': DPTModel,
						        '''image-segmentation''': DPTForSemanticSegmentation,
						    }
						    if is_torch_available()
						    else {}
						)

						snake_case__             = False
						snake_case__             = False
						snake_case__             = False





						def       __UpperCamelCase     (							self      :	Optional[Any])						->       List[str]:




											"""simple docstring"""







											_lowerCAmelCase:List[str]									=  DPTModelTester(self)
											_lowerCAmelCase:List[str]									=  ConfigTester(self     ,config_class=a__     ,has_text_modality=a__     ,hidden_size=37)





						def       __UpperCamelCase     (							self      :	str)						->       Optional[int]:




											"""simple docstring"""







											self.config_tester.run_common_tests()





						@unittest.skip(reason='''DPT does not use inputs_embeds''')
						def       __UpperCamelCase     (							self      :	Optional[int])						->       Dict:




											"""simple docstring"""







											pass





						def       __UpperCamelCase     (							self      :	Optional[Any])						->       List[Any]:




											"""simple docstring"""







											_lowerCAmelCase							,   _lowerCAmelCase:Union[str, Any]									=  self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																_lowerCAmelCase:Union[str, Any]									=  model_class(a__)
																self.assertIsInstance(model.get_input_embeddings()     ,(nn.Module))
																_lowerCAmelCase:Optional[int]									=  model.get_output_embeddings()
																self.assertTrue(x is None or isinstance(a__     ,nn.Linear))





						def       __UpperCamelCase     (							self      :	Dict)						->       int:




											"""simple docstring"""







											_lowerCAmelCase							,   _lowerCAmelCase:Any									=  self.model_tester.prepare_config_and_inputs_for_common()

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

																_lowerCAmelCase:Any									=  ['''pixel_values''']
																self.assertListEqual(arg_names[:1]     ,a__)





						def       __UpperCamelCase     (							self      :	Tuple)						->       int:




											"""simple docstring"""







											_lowerCAmelCase:Optional[Any]									=  self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*a__)





						def       __UpperCamelCase     (							self      :	Dict)						->       int:




											"""simple docstring"""







											_lowerCAmelCase:Dict									=  self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_depth_estimation(*a__)





						def       __UpperCamelCase     (							self      :	Optional[Any])						->       Union[str, Any]:




											"""simple docstring"""







											_lowerCAmelCase:Union[str, Any]									=  self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_semantic_segmentation(*a__)





						def       __UpperCamelCase     (							self      :	List[Any])						->       List[str]:




											"""simple docstring"""







											for model_class in self.all_model_classes:
																if model_class.__name__ == "DPTForDepthEstimation":
																					continue

																_lowerCAmelCase							,   _lowerCAmelCase:Dict									=  self.model_tester.prepare_config_and_inputs_for_common()
																_lowerCAmelCase:Union[str, Any]									=  True

																if model_class in get_values(a__):
																					continue

																_lowerCAmelCase:Union[str, Any]									=  model_class(a__)
																model.to(a__)
																model.train()
																_lowerCAmelCase:Optional[int]									=  self._prepare_for_class(a__     ,a__     ,return_labels=a__)
																_lowerCAmelCase:Union[str, Any]									=  model(**a__).loss
																loss.backward()





						def       __UpperCamelCase     (							self      :	Optional[Any])						->       List[str]:




											"""simple docstring"""







											for model_class in self.all_model_classes:
																if model_class.__name__ == "DPTForDepthEstimation":
																					continue

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

																if model_class in get_values(a__) or not model_class.supports_gradient_checkpointing:
																					continue
																_lowerCAmelCase:Dict									=  model_class(a__)
																model.to(a__)
																model.gradient_checkpointing_enable()
																model.train()
																_lowerCAmelCase:Any									=  self._prepare_for_class(a__     ,a__     ,return_labels=a__)
																_lowerCAmelCase:Tuple									=  model(**a__).loss
																loss.backward()





						def       __UpperCamelCase     (							self      :	Any)						->       int:




											"""simple docstring"""







											_lowerCAmelCase							,   _lowerCAmelCase:Optional[Any]									=  self.model_tester.prepare_config_and_inputs_for_common()

											_lowerCAmelCase:Dict									=  _config_zero_init(a__)
											for model_class in self.all_model_classes:
																_lowerCAmelCase:Tuple									=  model_class(config=a__)
																# Skip the check for the backbone
																_lowerCAmelCase:Tuple									=  []
																for name, module in model.named_modules():
																					if module.__class__.__name__ == "DPTViTHybridEmbeddings":
																										_lowerCAmelCase:Tuple									=  [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       __UpperCamelCase     (							self      :	Dict)						->       Any:




											"""simple docstring"""







											pass





						@slow
						def       __UpperCamelCase     (							self      :	List[Any])						->       List[str]:




											"""simple docstring"""







											for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
																_lowerCAmelCase:str									=  DPTModel.from_pretrained(a__)
																self.assertIsNotNone(a__)







						def       __UpperCamelCase     (							self      :	int)						->       Optional[int]:




											"""simple docstring"""







											_lowerCAmelCase							,   _lowerCAmelCase:List[str]									=  self.model_tester.prepare_config_and_inputs_for_common()
											_lowerCAmelCase:Any									=  '''add'''
											with self.assertRaises(a__):
																_lowerCAmelCase:Any									=  DPTForDepthEstimation(a__)





def 							UpperCAmelCase		(		):
					_lowerCAmelCase:Union[str, Any]									=  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''    )
					return image





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





						def       __UpperCamelCase     (							self      :	Optional[int])						->       Union[str, Any]:




											"""simple docstring"""







											_lowerCAmelCase:List[str]									=  DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas''')
											_lowerCAmelCase:Optional[int]									=  DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas''').to(a__)

											_lowerCAmelCase:Tuple									=  prepare_img()
											_lowerCAmelCase:List[str]									=  image_processor(images=a__     ,return_tensors='''pt''').to(a__)

											# forward pass
											with torch.no_grad():
																_lowerCAmelCase:Dict									=  model(**a__)
																_lowerCAmelCase:List[str]									=  outputs.predicted_depth

											# verify the predicted depth
											_lowerCAmelCase:str									=  torch.Size((1, 384, 384))
											self.assertEqual(predicted_depth.shape     ,a__)

											_lowerCAmelCase:Any									=  torch.tensor(
											    [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]]).to(a__)

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






