



import inspect
import unittest
from math import floor

from transformers import CvtConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch

     from transformers import CvtForImageClassification, CvtModel
     from transformers.models.cvt.modeling_cvt import CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor






class SCREAMING_SNAKE_CASE__     (		SCREAMING_SNAKE_CASE__    ):




    '''simple docstring'''






    def 			_lowerCAmelCase					(       self		):
        A :       Optional[int]          =   self.config_class(**self.inputs_dict		)
        self.parent.assertTrue(hasattr(lowerCamelCase__,		"""embed_dim"""		)		)
        self.parent.assertTrue(hasattr(lowerCamelCase__,		"""num_heads"""		)		)






class SCREAMING_SNAKE_CASE__     :




    '''simple docstring'''






    def __init__(       self,		lowerCamelCase__,		lowerCamelCase__=13,		lowerCamelCase__=64,		lowerCamelCase__=3,		lowerCamelCase__=[16, 48, 96],		lowerCamelCase__=[1, 3, 6],		lowerCamelCase__=[1, 2, 10],		lowerCamelCase__=[7, 3, 3],		lowerCamelCase__=[4, 2, 2],		lowerCamelCase__=[2, 1, 1],		lowerCamelCase__=[2, 2, 2],		lowerCamelCase__=[False, False, True],		lowerCamelCase__=[0.0, 0.0, 0.0],		lowerCamelCase__=0.02,		lowerCamelCase__=1e-12,		lowerCamelCase__=True,		lowerCamelCase__=True,		lowerCamelCase__=2,		):
        A :       Any          =   parent
        A :       Union[str, Any]          =   batch_size
        A :       List[str]          =   image_size
        A :       Optional[Any]          =   patch_sizes
        A :       List[Any]          =   patch_stride
        A :       List[Any]          =   patch_padding
        A :       Dict          =   is_training
        A :       List[Any]          =   use_labels
        A :       Optional[int]          =   num_labels
        A :       List[str]          =   num_channels
        A :       Optional[Any]          =   embed_dim
        A :       Optional[int]          =   num_heads
        A :       Optional[Any]          =   stride_kv
        A :       List[str]          =   depth
        A :       str          =   cls_token
        A :       List[Any]          =   attention_drop_rate
        A :       Any          =   initializer_range
        A :       str          =   layer_norm_eps






    def 			_lowerCAmelCase					(       self		):
        A :       Optional[Any]          =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

        A :       int          =   self.get_config()
        return config, pixel_values, labels






    def 			_lowerCAmelCase					(       self		):
        return CvtConfig(
            image_size=self.image_size,		num_labels=self.num_labels,		num_channels=self.num_channels,		embed_dim=self.embed_dim,		num_heads=self.num_heads,		patch_sizes=self.patch_sizes,		patch_padding=self.patch_padding,		patch_stride=self.patch_stride,		stride_kv=self.stride_kv,		depth=self.depth,		cls_token=self.cls_token,		attention_drop_rate=self.attention_drop_rate,		initializer_range=self.initializer_range,		)






    def 			_lowerCAmelCase					(       self,		lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__		):
        A :       Optional[int]          =   CvtModel(config=lowerCamelCase__		)
        model.to(lowerCamelCase__		)
        model.eval()
        A :       Tuple          =   model(lowerCamelCase__		)
        A :       Union[str, Any]          =   (self.image_size, self.image_size)
        A     ,							A :       Union[str, Any]          =   image_size[0], image_size[1]
        for i in range(len(self.depth		)		):
            A :       Any          =   floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1		)
            A :       Optional[int]          =   floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1		)
        self.parent.assertEqual(result.last_hidden_state.shape,		(self.batch_size, self.embed_dim[-1], height, width)		)






    def 			_lowerCAmelCase					(       self,		lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__		):
        A :       List[Any]          =   self.num_labels
        A :       Optional[int]          =   CvtForImageClassification(lowerCamelCase__		)
        model.to(lowerCamelCase__		)
        model.eval()
        A :       Union[str, Any]          =   model(lowerCamelCase__,		labels=lowerCamelCase__		)
        self.parent.assertEqual(result.logits.shape,		(self.batch_size, self.num_labels)		)






    def 			_lowerCAmelCase					(       self		):
        A :       str          =   self.prepare_config_and_inputs()
        A     ,							A     ,							A :       List[str]          =   config_and_inputs
        A :       int          =   {"""pixel_values""": pixel_values}
        return config, inputs_dict






@require_torch
class SCREAMING_SNAKE_CASE__     (		SCREAMING_SNAKE_CASE__ ,						SCREAMING_SNAKE_CASE__ ,						unittest.TestCase    ):




    '''simple docstring'''






    __lowerCamelCase			: Tuple					=      (CvtModel, CvtForImageClassification) if is_torch_available() else ()
    __lowerCamelCase			: Dict					=      (
        {"feature-extraction": CvtModel, "image-classification": CvtForImageClassification}
        if is_torch_available()
        else {}
    )

    __lowerCamelCase			: Optional[int]					=      False
    __lowerCamelCase			: Tuple					=      False
    __lowerCamelCase			: Tuple					=      False
    __lowerCamelCase			: Any					=      False
    __lowerCamelCase			: List[str]					=      False






    def 			_lowerCAmelCase					(       self		):
        A :       List[str]          =   CvtModelTester(self		)
        A :       Optional[Any]          =   ConfigTester(self,		config_class=lowerCamelCase__,		has_text_modality=lowerCamelCase__,		hidden_size=37		)






    def 			_lowerCAmelCase					(       self		):
        self.create_and_test_config_common_properties()
        self.config_tester.create_and_test_config_to_json_string()
        self.config_tester.create_and_test_config_to_json_file()
        self.config_tester.create_and_test_config_from_and_save_pretrained()
        self.config_tester.create_and_test_config_with_num_labels()
        self.config_tester.check_config_can_be_init_without_params()
        self.config_tester.check_config_arguments_init()






    def 			_lowerCAmelCase					(       self		):
        return






    @unittest.skip(reason="""Cvt does not output attentions"""		)
    def 			_lowerCAmelCase					(       self		):
        pass






    @unittest.skip(reason="""Cvt does not use inputs_embeds"""		)
    def 			_lowerCAmelCase					(       self		):
        pass






    @unittest.skip(reason="""Cvt does not support input and output embeddings"""		)
    def 			_lowerCAmelCase					(       self		):
        pass






    def 			_lowerCAmelCase					(       self		):
        A     ,							A :       Tuple          =   self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            A :       Optional[int]          =   model_class(lowerCamelCase__		)
            A :       List[Any]          =   inspect.signature(model.forward		)
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            A :       Optional[Any]          =   [*signature.parameters.keys()]

            A :       int          =   ["""pixel_values"""]
            self.assertListEqual(arg_names[:1],		lowerCamelCase__		)






    def 			_lowerCAmelCase					(       self		):
        A :       Union[str, Any]          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowerCamelCase__		)






    def 			_lowerCAmelCase					(       self		):
        def check_hidden_states_output(lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__		):
            A :       Dict          =   model_class(lowerCamelCase__		)
            model.to(lowerCamelCase__		)
            model.eval()

            with torch.no_grad():
                A :       Any          =   model(**self._prepare_for_class(lowerCamelCase__,		lowerCamelCase__		)		)

            A :       Optional[int]          =   outputs.hidden_states

            A :       Dict          =   len(self.model_tester.depth		)
            self.assertEqual(len(lowerCamelCase__		),		lowerCamelCase__		)

            # verify the first hidden states (first block)
            self.assertListEqual(
                list(hidden_states[0].shape[-3:]		),		[
                    self.model_tester.embed_dim[0],
                    self.model_tester.image_size // 4,
                    self.model_tester.image_size // 4,
                ],		)

        A     ,							A :       Tuple          =   self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            A :       List[str]          =   True
            check_hidden_states_output(lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__		)

            # check that output_hidden_states also work using config
            del inputs_dict["output_hidden_states"]
            A :       Optional[int]          =   True

            check_hidden_states_output(lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__		)






    def 			_lowerCAmelCase					(       self		):
        A :       Optional[int]          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__		)






    @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""		)
    def 			_lowerCAmelCase					(       self		):
        pass






    @slow
    def 			_lowerCAmelCase					(       self		):
        for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            A :       List[Any]          =   CvtModel.from_pretrained(lowerCamelCase__		)
            self.assertIsNotNone(lowerCamelCase__		)




def 	__UpperCamelCase	(  )       ->  str:



    """simple docstring"""






    A :       Optional[Any]          =   Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""		)
    return image






@require_torch
@require_vision
class SCREAMING_SNAKE_CASE__     (		unittest.TestCase    ):




    '''simple docstring'''






    @cached_property
    def 			_lowerCAmelCase					(       self		):
        return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)






    @slow
    def 			_lowerCAmelCase					(       self		):
        A :       Optional[int]          =   CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]		).to(lowerCamelCase__		)

        A :       Dict          =   self.default_image_processor
        A :       Tuple          =   prepare_img()
        A :       str          =   image_processor(images=lowerCamelCase__,		return_tensors="""pt"""		).to(lowerCamelCase__		)

        # forward pass
        with torch.no_grad():
            A :       Any          =   model(**lowerCamelCase__		)

        # verify the logits
        A :       Dict          =   torch.Size((1, 1000)		)
        self.assertEqual(outputs.logits.shape,		lowerCamelCase__		)

        A :       List[Any]          =   torch.tensor([0.9285, 0.9015, -0.3150]		).to(lowerCamelCase__		)

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







def 	__UpperCamelCase	(  _lowerCAmelCase = 100_0000		)       ->  int:



    """simple docstring"""






    A :       str          =   limit + 1
    A :       Tuple          =   [0] * limit
    for first_term in range(1      ,     _lowerCAmelCase		):
        for n in range(_lowerCAmelCase      ,     _lowerCAmelCase      ,     _lowerCAmelCase		):
            A :       Any          =   first_term + n / first_term
            if common_difference % 4:  # d must be divisble by 4
                continue
            else:
                common_difference /= 4
                if (
                    first_term > common_difference
                    and first_term < 4 * common_difference
                ):  # since x,y,z are positive integers
                    frequency[n] += 1  # so z>0 and a>d ,also 4d<a

    A :       Optional[int]          =   sum(1 for x in frequency[1:limit] if x == 10		)

    return count


if __name__ == "__main__":
     print(F"""{solution() = }""")


