

from .hash_table import HashTable
from .number_theory.prime_numbers import is_prime, next_prime
class    A_				( UpperCAmelCase__  ):


    '''simple docstring'''






    def __init__(self       , *lowercase__       , **lowercase__					)       -> List[Any]:
        super().__init__(*lowercase__       , **lowercase__					)


    def        lowerCAmelCase_  (self       , lowercase__       , lowercase__					)       -> List[str]:
        __UpperCAmelCase			   =     (
            next_prime(value % self.size_table					)
            if not is_prime(value % self.size_table					)
            else value % self.size_table
        )  # gt = bigger than
        return next_prime_gt - (data % next_prime_gt)


    def        lowerCAmelCase_  (self       , lowercase__       , lowercase__       , lowercase__					)       -> List[Any]:
        return (increment * self.__hash_function_a(lowercase__       , lowercase__					)) % self.size_table






    def        lowerCAmelCase_  (self       , lowercase__       , lowercase__=None					)       -> Any:
        __UpperCAmelCase			   =     1
        __UpperCAmelCase			   =     self.hash_function(lowercase__					)

        while self.values[new_key] is not None and self.values[new_key] != key:
            __UpperCAmelCase			   =     (
                self.__hash_double_function(lowercase__       , lowercase__       , lowercase__					)
                if self.balanced_factor() >= self.lim_charge
                else None
            )
            if new_key is None:
                break
            else:
                i += 1

        return new_key







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_				:


    '''simple docstring'''






    def __init__(self       , lowercase__       , lowercase__=2       , lowercase__=32       , lowercase__=16       , lowercase__=3       , lowercase__=True       , lowercase__=True       , lowercase__=32       , lowercase__=4       , lowercase__=[0, 1, 2, 3]       , lowercase__=4       , lowercase__=37       , lowercase__="gelu"       , lowercase__=0.1       , lowercase__=0.1       , lowercase__=0.02       , lowercase__=3       , lowercase__=False       , lowercase__=None       , )       -> Any:
        __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			   =     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        lowerCAmelCase_  (self					)       -> List[str]:
        __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        lowerCAmelCase_  (self					)       -> str:
        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=lowercase__       , initializer_range=self.initializer_range       , is_hybrid=self.is_hybrid       , )


    def        lowerCAmelCase_  (self       , lowercase__       , lowercase__       , lowercase__					)       -> Any:
        __UpperCAmelCase			   =     DPTModel(config=lowercase__					)
        model.to(lowercase__					)
        model.eval()
        __UpperCAmelCase			   =     model(lowercase__					)
        self.parent.assertEqual(result.last_hidden_state.shape       , (self.batch_size, self.seq_length, self.hidden_size)					)


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


    def        lowerCAmelCase_  (self       , lowercase__       , lowercase__       , lowercase__					)       -> str:
        __UpperCAmelCase			   =     self.num_labels
        __UpperCAmelCase			   =     DPTForSemanticSegmentation(lowercase__					)
        model.to(lowercase__					)
        model.eval()
        __UpperCAmelCase			   =     model(lowercase__       , labels=lowercase__					)
        self.parent.assertEqual(
            result.logits.shape       , (self.batch_size, self.num_labels, self.image_size, self.image_size)					)






    def        lowerCAmelCase_  (self					)       -> Union[str, Any]:
        __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_				( _a	,       _a	,       unittest.TestCase  ):


    '''simple docstring'''






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

    a__       							=    False
    a__       							=    False
    a__       							=    False


    def        lowerCAmelCase_  (self					)       -> Tuple:
        __UpperCAmelCase			   =     DPTModelTester(self					)
        __UpperCAmelCase			   =     ConfigTester(self       , config_class=lowercase__       , has_text_modality=lowercase__       , hidden_size=37					)


    def        lowerCAmelCase_  (self					)       -> Dict:
        self.config_tester.run_common_tests()


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


    def        lowerCAmelCase_  (self					)       -> Any:
        __UpperCAmelCase   ,       __UpperCAmelCase			   =     self.model_tester.prepare_config_and_inputs_for_common()

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


    def        lowerCAmelCase_  (self					)       -> int:
        __UpperCAmelCase   ,       __UpperCAmelCase			   =     self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            __UpperCAmelCase			   =     model_class(lowercase__					)
            __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]       , lowercase__					)


    def        lowerCAmelCase_  (self					)       -> Optional[int]:
        __UpperCAmelCase			   =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowercase__					)


    def        lowerCAmelCase_  (self					)       -> Optional[Any]:
        __UpperCAmelCase			   =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_depth_estimation(*lowercase__					)


    def        lowerCAmelCase_  (self					)       -> int:
        __UpperCAmelCase			   =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_semantic_segmentation(*lowercase__					)


    def        lowerCAmelCase_  (self					)       -> Any:
        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(lowercase__					):
                continue

            __UpperCAmelCase			   =     model_class(lowercase__					)
            model.to(lowercase__					)
            model.train()
            __UpperCAmelCase			   =     self._prepare_for_class(lowercase__       , lowercase__       , return_labels=lowercase__					)
            __UpperCAmelCase			   =     model(**lowercase__					).loss
            loss.backward()


    def        lowerCAmelCase_  (self					)       -> Tuple:
        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(lowercase__					) or not model_class.supports_gradient_checkpointing:
                continue
            __UpperCAmelCase			   =     model_class(lowercase__					)
            model.to(lowercase__					)
            model.gradient_checkpointing_enable()
            model.train()
            __UpperCAmelCase			   =     self._prepare_for_class(lowercase__       , lowercase__       , return_labels=lowercase__					)
            __UpperCAmelCase			   =     model(**lowercase__					).loss
            loss.backward()


    def        lowerCAmelCase_  (self					)       -> Union[str, Any]:
        __UpperCAmelCase   ,       __UpperCAmelCase			   =     self.model_tester.prepare_config_and_inputs_for_common()

        __UpperCAmelCase			   =     _config_zero_init(lowercase__					)
        for model_class in self.all_model_classes:
            __UpperCAmelCase			   =     model_class(config=lowercase__					)
            # 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        lowerCAmelCase_  (self					)       -> int:
        pass






    @slow
    def        lowerCAmelCase_  (self					)       -> List[str]:
        for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            __UpperCAmelCase			   =     DPTModel.from_pretrained(lowercase__					)
            self.assertIsNotNone(lowercase__					)






def  __a    (				) ->       Any:






    '''simple docstring'''
    __UpperCAmelCase			   =     Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
    return image
@require_torch
@require_vision
@slow
class    A_				( unittest.TestCase  ):


    '''simple docstring'''






    def        lowerCAmelCase_  (self					)       -> Any:
        __UpperCAmelCase			   =     DPTImageProcessor.from_pretrained('''Intel/dpt-large'''					)
        __UpperCAmelCase			   =     DPTForDepthEstimation.from_pretrained('''Intel/dpt-large'''					).to(lowercase__					)

        __UpperCAmelCase			   =     prepare_img()
        __UpperCAmelCase			   =     image_processor(images=lowercase__       , return_tensors='''pt'''					).to(lowercase__					)

        # forward pass
        with torch.no_grad():
            __UpperCAmelCase			   =     model(**lowercase__					)
            __UpperCAmelCase			   =     outputs.predicted_depth

        # verify the predicted depth
        __UpperCAmelCase			   =     torch.Size((1, 384, 384)					)
        self.assertEqual(predicted_depth.shape       , lowercase__					)

        __UpperCAmelCase			   =     torch.tensor(
            [[6.3199, 6.3629, 6.4148], [6.3850, 6.3615, 6.4166], [6.3519, 6.3176, 6.3575]]					).to(lowercase__					)

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


    def        lowerCAmelCase_  (self					)       -> Tuple:
        __UpperCAmelCase			   =     DPTImageProcessor.from_pretrained('''Intel/dpt-large-ade'''					)
        __UpperCAmelCase			   =     DPTForSemanticSegmentation.from_pretrained('''Intel/dpt-large-ade'''					).to(lowercase__					)

        __UpperCAmelCase			   =     prepare_img()
        __UpperCAmelCase			   =     image_processor(images=lowercase__       , return_tensors='''pt'''					).to(lowercase__					)

        # forward pass
        with torch.no_grad():
            __UpperCAmelCase			   =     model(**lowercase__					)

        # verify the logits
        __UpperCAmelCase			   =     torch.Size((1, 150, 480, 480)					)
        self.assertEqual(outputs.logits.shape       , lowercase__					)

        __UpperCAmelCase			   =     torch.tensor(
            [[4.0480, 4.2420, 4.4360], [4.3124, 4.5693, 4.8261], [4.5768, 4.8965, 5.2163]]					).to(lowercase__					)

        self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]       , lowercase__       , atol=1E-4					)					)






    def        lowerCAmelCase_  (self					)       -> str:
        __UpperCAmelCase			   =     DPTImageProcessor.from_pretrained('''Intel/dpt-large-ade'''					)
        __UpperCAmelCase			   =     DPTForSemanticSegmentation.from_pretrained('''Intel/dpt-large-ade'''					).to(lowercase__					)

        __UpperCAmelCase			   =     prepare_img()
        __UpperCAmelCase			   =     image_processor(images=lowercase__       , return_tensors='''pt'''					).to(lowercase__					)

        # forward pass
        with torch.no_grad():
            __UpperCAmelCase			   =     model(**lowercase__					)

        __UpperCAmelCase			   =     outputs.logits.detach().cpu()

        __UpperCAmelCase			   =     image_processor.post_process_semantic_segmentation(outputs=lowercase__       , target_sizes=[(500, 300)]					)
        __UpperCAmelCase			   =     torch.Size((500, 300)					)
        self.assertEqual(segmentation[0].shape       , lowercase__					)

        __UpperCAmelCase			   =     image_processor.post_process_semantic_segmentation(outputs=lowercase__					)
        __UpperCAmelCase			   =     torch.Size((480, 480)					)
        self.assertEqual(segmentation[0].shape       , lowercase__					)




