
"""simple docstring"""



import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    Pipeline,
    ZeroShotClassificationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow

from .test_pipelines_common import ANY


# These 2 model types require different inputs than those of the usual text models.
a					:	Union[str, Any]							=		{'''LayoutLMv2Config''', '''LayoutLMv3Config'''}




@is_pipeline_test
class 		a_						( unittest.TestCase	):
    a      :				List[Any]     =				MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
    a      :				str     =				TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

    if model_mapping is not None:
        a      :				List[Any]     =				{config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
    if tf_model_mapping is not None:
        a      :				List[str]     =				{
            config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
        }







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






        '''simple docstring'''






        _UpperCAmelCase          =   ZeroShotClassificationPipeline(
            model=__UpperCamelCase     ,					tokenizer=__UpperCamelCase     ,					candidate_labels=["""polics""", """health"""]     )
        return classifier, ["Who are you voting for in 2020?", "My stomach hurts."]







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






        '''simple docstring'''






        _UpperCAmelCase          =   classifier("""Who are you voting for in 2020?"""     ,					candidate_labels="""politics"""     )
        self.assertEqual(__UpperCamelCase     ,					{"""sequence""": ANY(__UpperCamelCase     ), """labels""": [ANY(__UpperCamelCase     )], """scores""": [ANY(__UpperCamelCase     )]}     )

        # No kwarg
        _UpperCAmelCase          =   classifier("""Who are you voting for in 2020?"""     ,					["""politics"""]     )
        self.assertEqual(__UpperCamelCase     ,					{"""sequence""": ANY(__UpperCamelCase     ), """labels""": [ANY(__UpperCamelCase     )], """scores""": [ANY(__UpperCamelCase     )]}     )

        _UpperCAmelCase          =   classifier("""Who are you voting for in 2020?"""     ,					candidate_labels=["""politics"""]     )
        self.assertEqual(__UpperCamelCase     ,					{"""sequence""": ANY(__UpperCamelCase     ), """labels""": [ANY(__UpperCamelCase     )], """scores""": [ANY(__UpperCamelCase     )]}     )

        _UpperCAmelCase          =   classifier("""Who are you voting for in 2020?"""     ,					candidate_labels="""politics, public health"""     )
        self.assertEqual(
            __UpperCamelCase     ,					{"""sequence""": ANY(__UpperCamelCase     ), """labels""": [ANY(__UpperCamelCase     ), ANY(__UpperCamelCase     )], """scores""": [ANY(__UpperCamelCase     ), ANY(__UpperCamelCase     )]}     )
        self.assertAlmostEqual(sum(nested_simplify(outputs["""scores"""]     )     )     ,					1.0     )

        _UpperCAmelCase          =   classifier("""Who are you voting for in 2020?"""     ,					candidate_labels=["""politics""", """public health"""]     )
        self.assertEqual(
            __UpperCamelCase     ,					{"""sequence""": ANY(__UpperCamelCase     ), """labels""": [ANY(__UpperCamelCase     ), ANY(__UpperCamelCase     )], """scores""": [ANY(__UpperCamelCase     ), ANY(__UpperCamelCase     )]}     )
        self.assertAlmostEqual(sum(nested_simplify(outputs["""scores"""]     )     )     ,					1.0     )

        _UpperCAmelCase          =   classifier(
            """Who are you voting for in 2020?"""     ,					candidate_labels="""politics"""     ,					hypothesis_template="""This text is about {}"""     )
        self.assertEqual(__UpperCamelCase     ,					{"""sequence""": ANY(__UpperCamelCase     ), """labels""": [ANY(__UpperCamelCase     )], """scores""": [ANY(__UpperCamelCase     )]}     )

        # https://github.com/huggingface/transformers/issues/13846
        _UpperCAmelCase          =   classifier(["""I am happy"""]     ,					["""positive""", """negative"""]     )
        self.assertEqual(
            __UpperCamelCase     ,					[
                {"""sequence""": ANY(__UpperCamelCase     ), """labels""": [ANY(__UpperCamelCase     ), ANY(__UpperCamelCase     )], """scores""": [ANY(__UpperCamelCase     ), ANY(__UpperCamelCase     )]}
                for i in range(1     )
            ]     ,					)
        _UpperCAmelCase          =   classifier(["""I am happy""", """I am sad"""]     ,					["""positive""", """negative"""]     )
        self.assertEqual(
            __UpperCamelCase     ,					[
                {"""sequence""": ANY(__UpperCamelCase     ), """labels""": [ANY(__UpperCamelCase     ), ANY(__UpperCamelCase     )], """scores""": [ANY(__UpperCamelCase     ), ANY(__UpperCamelCase     )]}
                for i in range(2     )
            ]     ,					)

        with self.assertRaises(__UpperCamelCase     ):
            classifier(""""""     ,					candidate_labels="""politics"""     )

        with self.assertRaises(__UpperCamelCase     ):
            classifier(__UpperCamelCase     ,					candidate_labels="""politics"""     )

        with self.assertRaises(__UpperCamelCase     ):
            classifier("""Who are you voting for in 2020?"""     ,					candidate_labels=""""""     )

        with self.assertRaises(__UpperCamelCase     ):
            classifier("""Who are you voting for in 2020?"""     ,					candidate_labels=__UpperCamelCase     )

        with self.assertRaises(__UpperCamelCase     ):
            classifier(
                """Who are you voting for in 2020?"""     ,					candidate_labels="""politics"""     ,					hypothesis_template="""Not formatting template"""     ,					)

        with self.assertRaises(__UpperCamelCase     ):
            classifier(
                """Who are you voting for in 2020?"""     ,					candidate_labels="""politics"""     ,					hypothesis_template=__UpperCamelCase     ,					)

        self.run_entailment_id(__UpperCamelCase     )







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






        '''simple docstring'''






        _UpperCAmelCase          =   zero_shot_classifier.model.config
        _UpperCAmelCase          =   config.labelaid
        _UpperCAmelCase          =   zero_shot_classifier.entailment_id

        _UpperCAmelCase          =   {"""LABEL_0""": 0, """LABEL_1""": 1, """LABEL_2""": 2}
        self.assertEqual(zero_shot_classifier.entailment_id     ,					-1     )

        _UpperCAmelCase          =   {"""entailment""": 0, """neutral""": 1, """contradiction""": 2}
        self.assertEqual(zero_shot_classifier.entailment_id     ,					0     )

        _UpperCAmelCase          =   {"""ENTAIL""": 0, """NON-ENTAIL""": 1}
        self.assertEqual(zero_shot_classifier.entailment_id     ,					0     )

        _UpperCAmelCase          =   {"""ENTAIL""": 2, """NEUTRAL""": 1, """CONTR""": 0}
        self.assertEqual(zero_shot_classifier.entailment_id     ,					2     )

        _UpperCAmelCase          =   original_labelaid
        self.assertEqual(__UpperCamelCase     ,					zero_shot_classifier.entailment_id     )







    @require_torch
    def      _snake_case					(			self			:       Dict     )		->Tuple:






        '''simple docstring'''






        _UpperCAmelCase          =   pipeline(
            """zero-shot-classification"""     ,					model="""sshleifer/tiny-distilbert-base-cased-distilled-squad"""     ,					framework="""pt"""     ,					)
        # There was a regression in 4.10 for this
        # Adding a test so we don't make the mistake again.
        # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499
        zero_shot_classifier(
            """Who are you voting for in 2020?""" * 1_00     ,					candidate_labels=["""politics""", """public health""", """science"""]     )







    @require_torch
    def      _snake_case					(			self			:       Optional[Any]     )		->str:






        '''simple docstring'''






        _UpperCAmelCase          =   pipeline(
            """zero-shot-classification"""     ,					model="""sshleifer/tiny-distilbert-base-cased-distilled-squad"""     ,					framework="""pt"""     ,					)
        _UpperCAmelCase          =   zero_shot_classifier(
            """Who are you voting for in 2020?"""     ,					candidate_labels=["""politics""", """public health""", """science"""]     )

        self.assertEqual(
            nested_simplify(__UpperCamelCase     )     ,					{
                """sequence""": """Who are you voting for in 2020?""",
                """labels""": ["""science""", """public health""", """politics"""],
                """scores""": [0.3_3_3, 0.3_3_3, 0.3_3_3],
            }     ,					)







    @require_tf
    def      _snake_case					(			self			:       Any     )		->int:






        '''simple docstring'''






        _UpperCAmelCase          =   pipeline(
            """zero-shot-classification"""     ,					model="""sshleifer/tiny-distilbert-base-cased-distilled-squad"""     ,					framework="""tf"""     ,					)
        _UpperCAmelCase          =   zero_shot_classifier(
            """Who are you voting for in 2020?"""     ,					candidate_labels=["""politics""", """public health""", """science"""]     )

        self.assertEqual(
            nested_simplify(__UpperCamelCase     )     ,					{
                """sequence""": """Who are you voting for in 2020?""",
                """labels""": ["""science""", """public health""", """politics"""],
                """scores""": [0.3_3_3, 0.3_3_3, 0.3_3_3],
            }     ,					)







    @slow
    @require_torch
    def      _snake_case					(			self			:       Optional[Any]     )		->Any:






        '''simple docstring'''






        _UpperCAmelCase          =   pipeline("""zero-shot-classification"""     ,					model="""roberta-large-mnli"""     ,					framework="""pt"""     )
        _UpperCAmelCase          =   zero_shot_classifier(
            """Who are you voting for in 2020?"""     ,					candidate_labels=["""politics""", """public health""", """science"""]     )

        self.assertEqual(
            nested_simplify(__UpperCamelCase     )     ,					{
                """sequence""": """Who are you voting for in 2020?""",
                """labels""": ["""politics""", """public health""", """science"""],
                """scores""": [0.9_7_6, 0.0_1_5, 0.0_0_9],
            }     ,					)
        _UpperCAmelCase          =   zero_shot_classifier(
            """The dominant sequence transduction models are based on complex recurrent or convolutional neural networks"""
            """ in an encoder-decoder configuration. The best performing models also connect the encoder and decoder"""
            """ through an attention mechanism. We propose a new simple network architecture, the Transformer, based"""
            """ solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two"""
            """ machine translation tasks show these models to be superior in quality while being more parallelizable"""
            """ and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014"""
            """ English-to-German translation task, improving over the existing best results, including ensembles by"""
            """ over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new"""
            """ single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small"""
            """ fraction of the training costs of the best models from the literature. We show that the Transformer"""
            """ generalizes well to other tasks by applying it successfully to English constituency parsing both with"""
            """ large and limited training data."""     ,					candidate_labels=["""machine learning""", """statistics""", """translation""", """vision"""]     ,					multi_label=__UpperCamelCase     ,					)
        self.assertEqual(
            nested_simplify(__UpperCamelCase     )     ,					{
                """sequence""": (
                    """The dominant sequence transduction models are based on complex recurrent or convolutional neural"""
                    """ networks in an encoder-decoder configuration. The best performing models also connect the"""
                    """ encoder and decoder through an attention mechanism. We propose a new simple network"""
                    """ architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence"""
                    """ and convolutions entirely. Experiments on two machine translation tasks show these models to be"""
                    """ superior in quality while being more parallelizable and requiring significantly less time to"""
                    """ train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,"""
                    """ improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014"""
                    """ English-to-French translation task, our model establishes a new single-model state-of-the-art"""
                    """ BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training"""
                    """ costs of the best models from the literature. We show that the Transformer generalizes well to"""
                    """ other tasks by applying it successfully to English constituency parsing both with large and"""
                    """ limited training data."""
                ),
                """labels""": ["""translation""", """machine learning""", """vision""", """statistics"""],
                """scores""": [0.8_1_7, 0.7_1_3, 0.0_1_8, 0.0_1_8],
            }     ,					)







    @slow
    @require_tf
    def      _snake_case					(			self			:       str     )		->Dict:






        '''simple docstring'''






        _UpperCAmelCase          =   pipeline("""zero-shot-classification"""     ,					model="""roberta-large-mnli"""     ,					framework="""tf"""     )
        _UpperCAmelCase          =   zero_shot_classifier(
            """Who are you voting for in 2020?"""     ,					candidate_labels=["""politics""", """public health""", """science"""]     )

        self.assertEqual(
            nested_simplify(__UpperCamelCase     )     ,					{
                """sequence""": """Who are you voting for in 2020?""",
                """labels""": ["""politics""", """public health""", """science"""],
                """scores""": [0.9_7_6, 0.0_1_5, 0.0_0_9],
            }     ,					)
        _UpperCAmelCase          =   zero_shot_classifier(
            """The dominant sequence transduction models are based on complex recurrent or convolutional neural networks"""
            """ in an encoder-decoder configuration. The best performing models also connect the encoder and decoder"""
            """ through an attention mechanism. We propose a new simple network architecture, the Transformer, based"""
            """ solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two"""
            """ machine translation tasks show these models to be superior in quality while being more parallelizable"""
            """ and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014"""
            """ English-to-German translation task, improving over the existing best results, including ensembles by"""
            """ over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new"""
            """ single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small"""
            """ fraction of the training costs of the best models from the literature. We show that the Transformer"""
            """ generalizes well to other tasks by applying it successfully to English constituency parsing both with"""
            """ large and limited training data."""     ,					candidate_labels=["""machine learning""", """statistics""", """translation""", """vision"""]     ,					multi_label=__UpperCamelCase     ,					)
        self.assertEqual(
            nested_simplify(__UpperCamelCase     )     ,					{
                """sequence""": (
                    """The dominant sequence transduction models are based on complex recurrent or convolutional neural"""
                    """ networks in an encoder-decoder configuration. The best performing models also connect the"""
                    """ encoder and decoder through an attention mechanism. We propose a new simple network"""
                    """ architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence"""
                    """ and convolutions entirely. Experiments on two machine translation tasks show these models to be"""
                    """ superior in quality while being more parallelizable and requiring significantly less time to"""
                    """ train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,"""
                    """ improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014"""
                    """ English-to-French translation task, our model establishes a new single-model state-of-the-art"""
                    """ BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training"""
                    """ costs of the best models from the literature. We show that the Transformer generalizes well to"""
                    """ other tasks by applying it successfully to English constituency parsing both with large and"""
                    """ limited training data."""
                ),
                """labels""": ["""translation""", """machine learning""", """vision""", """statistics"""],
                """scores""": [0.8_1_7, 0.7_1_3, 0.0_1_8, 0.0_1_8],
            }     ,					)

"""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			:       Union[str, Any]     ,					__UpperCamelCase			:       Optional[int]     ,					__UpperCamelCase			:       Optional[int]=2     ,					__UpperCamelCase			:       int=32     ,					__UpperCamelCase			:       Tuple=16     ,					__UpperCamelCase			:       Dict=3     ,					__UpperCamelCase			:       Dict=True     ,					__UpperCamelCase			:       Optional[Any]=True     ,					__UpperCamelCase			:       Optional[Any]=32     ,					__UpperCamelCase			:       Any=4     ,					__UpperCamelCase			:       Optional[int]=[0, 1, 2, 3]     ,					__UpperCamelCase			:       str=4     ,					__UpperCamelCase			:       Optional[Any]=37     ,					__UpperCamelCase			:       str="gelu"     ,					__UpperCamelCase			:       Optional[int]=0.1     ,					__UpperCamelCase			:       Any=0.1     ,					__UpperCamelCase			:       Any=0.0_2     ,					__UpperCamelCase			:       Optional[int]=3     ,					__UpperCamelCase			:       int=[1, 3_84, 24, 24]     ,					__UpperCamelCase			:       Union[str, Any]=True     ,					__UpperCamelCase			:       Any=None     ,					)		->Optional[Any]:






        '''simple docstring'''






        _UpperCAmelCase          =   parent
        _UpperCAmelCase          =   batch_size
        _UpperCAmelCase          =   image_size
        _UpperCAmelCase          =   patch_size
        _UpperCAmelCase          =   num_channels
        _UpperCAmelCase          =   is_training
        _UpperCAmelCase          =   use_labels
        _UpperCAmelCase          =   hidden_size
        _UpperCAmelCase          =   num_hidden_layers
        _UpperCAmelCase          =   backbone_out_indices
        _UpperCAmelCase          =   num_attention_heads
        _UpperCAmelCase          =   intermediate_size
        _UpperCAmelCase          =   hidden_act
        _UpperCAmelCase          =   hidden_dropout_prob
        _UpperCAmelCase          =   attention_probs_dropout_prob
        _UpperCAmelCase          =   initializer_range
        _UpperCAmelCase          =   num_labels
        _UpperCAmelCase          =   backbone_featmap_shape
        _UpperCAmelCase          =   scope
        _UpperCAmelCase          =   is_hybrid
        # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
        _UpperCAmelCase          =   (image_size // patch_size) ** 2
        _UpperCAmelCase          =   num_patches + 1







    def      _snake_case					(			self			:       str     )		->int:






        '''simple docstring'''






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

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

        _UpperCAmelCase          =   self.get_config()

        return config, pixel_values, labels







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






        '''simple docstring'''






        _UpperCAmelCase          =   {
            """global_padding""": """same""",
            """layer_type""": """bottleneck""",
            """depths""": [3, 4, 9],
            """out_features""": ["""stage1""", """stage2""", """stage3"""],
            """embedding_dynamic_padding""": True,
            """hidden_sizes""": [96, 1_92, 3_84, 7_68],
            """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=__UpperCamelCase     ,					initializer_range=self.initializer_range     ,					is_hybrid=self.is_hybrid     ,					backbone_config=__UpperCamelCase     ,					backbone_featmap_shape=self.backbone_featmap_shape     ,					)







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






        '''simple docstring'''






        _UpperCAmelCase          =   DPTModel(config=__UpperCamelCase     )
        model.to(__UpperCamelCase     )
        model.eval()
        _UpperCAmelCase          =   model(__UpperCamelCase     )
        self.parent.assertEqual(result.last_hidden_state.shape     ,					(self.batch_size, self.seq_length, self.hidden_size)     )







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






        '''simple docstring'''






        _UpperCAmelCase          =   self.num_labels
        _UpperCAmelCase          =   DPTForDepthEstimation(__UpperCamelCase     )
        model.to(__UpperCamelCase     )
        model.eval()
        _UpperCAmelCase          =   model(__UpperCamelCase     )
        self.parent.assertEqual(result.predicted_depth.shape     ,					(self.batch_size, self.image_size, self.image_size)     )







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






        '''simple docstring'''






        _UpperCAmelCase          =   self.num_labels
        _UpperCAmelCase          =   DPTForSemanticSegmentation(__UpperCamelCase     )
        model.to(__UpperCamelCase     )
        model.eval()
        _UpperCAmelCase          =   model(__UpperCamelCase     ,					labels=__UpperCamelCase     )
        self.parent.assertEqual(
            result.logits.shape     ,					(self.batch_size, self.num_labels, self.image_size, self.image_size)     )







    def      _snake_case					(			self			:       Tuple     )		->Any:






        '''simple docstring'''






        _UpperCAmelCase          =   self.prepare_config_and_inputs()
        _UpperCAmelCase    ,_UpperCAmelCase    ,_UpperCAmelCase          =   config_and_inputs
        _UpperCAmelCase          =   {"""pixel_values""": pixel_values}
        return config, inputs_dict







@require_torch
class 		a_						( _UpperCAmelCase     ,						_UpperCAmelCase     ,						unittest.TestCase	):
    a      :				Dict     =				(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
    a      :				int     =				(
        {
            'depth-estimation': DPTForDepthEstimation,
            'feature-extraction': DPTModel,
            'image-segmentation': DPTForSemanticSegmentation,
        }
        if is_torch_available()
        else {}
    )

    a      :				str     =				False
    a      :				List[str]     =				False
    a      :				Dict     =				False







    def      _snake_case					(			self			:       Any     )		->Any:






        '''simple docstring'''






        _UpperCAmelCase          =   DPTModelTester(self     )
        _UpperCAmelCase          =   ConfigTester(self     ,					config_class=__UpperCamelCase     ,					has_text_modality=__UpperCamelCase     ,					hidden_size=37     )







    def      _snake_case					(			self			:       Optional[int]     )		->Any:






        '''simple docstring'''






        self.config_tester.run_common_tests()







    @unittest.skip(reason="""DPT does not use inputs_embeds"""     )
    def      _snake_case					(			self			:       Tuple     )		->Tuple:






        '''simple docstring'''






        pass







    def      _snake_case					(			self			:       int     )		->Any:






        '''simple docstring'''






        _UpperCAmelCase    ,_UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs_for_common()

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







    def      _snake_case					(			self			:       Optional[int]     )		->Optional[Any]:






        '''simple docstring'''






        _UpperCAmelCase    ,_UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs_for_common()

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

            _UpperCAmelCase          =   ["""pixel_values"""]
            self.assertListEqual(arg_names[:1]     ,					__UpperCamelCase     )







    def      _snake_case					(			self			:       Optional[Any]     )		->Dict:






        '''simple docstring'''






        _UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__UpperCamelCase     )







    def      _snake_case					(			self			:       str     )		->int:






        '''simple docstring'''






        _UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_depth_estimation(*__UpperCamelCase     )







    def      _snake_case					(			self			:       Any     )		->Tuple:






        '''simple docstring'''






        _UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_semantic_segmentation(*__UpperCamelCase     )







    def      _snake_case					(			self			:       str     )		->Any:






        '''simple docstring'''






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

            _UpperCAmelCase    ,_UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs_for_common()
            _UpperCAmelCase          =   True

            if model_class in get_values(__UpperCamelCase     ):
                continue

            _UpperCAmelCase          =   model_class(__UpperCamelCase     )
            model.to(__UpperCamelCase     )
            model.train()
            _UpperCAmelCase          =   self._prepare_for_class(__UpperCamelCase     ,					__UpperCamelCase     ,					return_labels=__UpperCamelCase     )
            _UpperCAmelCase          =   model(**__UpperCamelCase     ).loss
            loss.backward()







    def      _snake_case					(			self			:       List[str]     )		->Dict:






        '''simple docstring'''






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

            _UpperCAmelCase    ,_UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs_for_common()
            _UpperCAmelCase          =   False
            _UpperCAmelCase          =   True

            if model_class in get_values(__UpperCamelCase     ) or not model_class.supports_gradient_checkpointing:
                continue
            _UpperCAmelCase          =   model_class(__UpperCamelCase     )
            model.to(__UpperCamelCase     )
            model.gradient_checkpointing_enable()
            model.train()
            _UpperCAmelCase          =   self._prepare_for_class(__UpperCamelCase     ,					__UpperCamelCase     ,					return_labels=__UpperCamelCase     )
            _UpperCAmelCase          =   model(**__UpperCamelCase     ).loss
            loss.backward()







    def      _snake_case					(			self			:       Tuple     )		->List[str]:






        '''simple docstring'''






        _UpperCAmelCase    ,_UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs_for_common()

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






        '''simple docstring'''






        pass







    @slow
    def      _snake_case					(			self			:       Optional[int]     )		->List[Any]:






        '''simple docstring'''






        for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
            _UpperCAmelCase          =   DPTModel.from_pretrained(__UpperCamelCase     )
            self.assertIsNotNone(__UpperCamelCase     )







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






        '''simple docstring'''






        _UpperCAmelCase    ,_UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs_for_common()
        _UpperCAmelCase          =   """add"""
        with self.assertRaises(__UpperCamelCase     ):
            _UpperCAmelCase          =   DPTForDepthEstimation(__UpperCamelCase     )







def  _UpperCamelCase	(						)    ->  int:





    """simple docstring"""

    _UpperCAmelCase          =   Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""      )
    return image







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







    def      _snake_case					(			self			:       Any     )		->Optional[Any]:






        '''simple docstring'''






        _UpperCAmelCase          =   DPTImageProcessor.from_pretrained("""Intel/dpt-hybrid-midas"""     )
        _UpperCAmelCase          =   DPTForDepthEstimation.from_pretrained("""Intel/dpt-hybrid-midas"""     ).to(__UpperCamelCase     )

        _UpperCAmelCase          =   prepare_img()
        _UpperCAmelCase          =   image_processor(images=__UpperCamelCase     ,					return_tensors="""pt"""     ).to(__UpperCamelCase     )

        # forward pass
        with torch.no_grad():
            _UpperCAmelCase          =   model(**__UpperCamelCase     )
            _UpperCAmelCase          =   outputs.predicted_depth

        # verify the predicted depth
        _UpperCAmelCase          =   torch.Size((1, 3_84, 3_84)     )
        self.assertEqual(predicted_depth.shape     ,					__UpperCamelCase     )

        _UpperCAmelCase          =   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(__UpperCamelCase     )

        self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 1_00     ,					__UpperCamelCase     ,					atol=1e-4     )     )