



'''simple docstring'''

from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
    import tensorflow as tf

    from transformers import TFCvtForImageClassification, TFCvtModel
    from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor

class __snake_case(				_lowerCAmelCase ):


      '''simple docstring'''



      def     __snake_case   ( self				)     ->     Tuple:
       lowerCAmelCase   =     self.config_class(**self.inputs_dict				)
       self.parent.assertTrue(hasattr(_snake_case     ,	"""embed_dim"""				)				)
       self.parent.assertTrue(hasattr(_snake_case     ,	"""num_heads"""				)				)







class __snake_case:


      '''simple docstring'''



      def __init__( self     ,	A_     ,	A_=13     ,	A_=64     ,	A_=3     ,	A_=[16, 48, 96]     ,	A_=[1, 3, 6]     ,	A_=[1, 2, 10]     ,	A_=[7, 3, 3]     ,	A_=[4, 2, 2]     ,	A_=[2, 1, 1]     ,	A_=[2, 2, 2]     ,	A_=[False, False, True]     ,	A_=[0.0, 0.0, 0.0]     ,	A_=0.0_2     ,	A_=1e-12     ,	A_=True     ,	A_=True     ,	A_=2     ,	)     ->     int:
       lowerCAmelCase   =     parent
       lowerCAmelCase   =     batch_size
       lowerCAmelCase   =     image_size
       lowerCAmelCase   =     patch_sizes
       lowerCAmelCase   =     patch_stride
       lowerCAmelCase   =     patch_padding
       lowerCAmelCase   =     is_training
       lowerCAmelCase   =     use_labels
       lowerCAmelCase   =     num_labels
       lowerCAmelCase   =     num_channels
       lowerCAmelCase   =     embed_dim
       lowerCAmelCase   =     num_heads
       lowerCAmelCase   =     stride_kv
       lowerCAmelCase   =     depth
       lowerCAmelCase   =     cls_token
       lowerCAmelCase   =     attention_drop_rate
       lowerCAmelCase   =     initializer_range
       lowerCAmelCase   =     layer_norm_eps


      def     __snake_case   ( self				)     ->     Optional[int]:
       lowerCAmelCase   =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

       lowerCAmelCase   =     None
       if self.use_labels:
        # create a random int32 tensor of given shape
        lowerCAmelCase   =     ids_tensor([self.batch_size]     ,	self.num_labels				)

       lowerCAmelCase   =     self.get_config()
       return config, pixel_values, labels


      def     __snake_case   ( self				)     ->     Tuple:
       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     __snake_case   ( self     ,	A_     ,	A_     ,	A_				)     ->     int:
       lowerCAmelCase   =     TFCvtModel(config=_snake_case				)
       lowerCAmelCase   =     model(_snake_case     ,	training=_snake_case				)
       lowerCAmelCase   =     (self.image_size, self.image_size)
       lowerCAmelCase,       lowerCAmelCase   =     image_size[0], image_size[1]
       for i in range(len(self.depth				)				):
        lowerCAmelCase   =     floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1				)
        lowerCAmelCase   =     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     __snake_case   ( self     ,	A_     ,	A_     ,	A_				)     ->     List[Any]:
       lowerCAmelCase   =     self.num_labels
       lowerCAmelCase   =     TFCvtForImageClassification(_snake_case				)
       lowerCAmelCase   =     model(_snake_case     ,	labels=_snake_case     ,	training=_snake_case				)
       self.parent.assertEqual(result.logits.shape     ,	(self.batch_size, self.num_labels)				)




      def     __snake_case   ( self				)     ->     Optional[Any]:
       lowerCAmelCase   =     self.prepare_config_and_inputs()
       lowerCAmelCase,       lowerCAmelCase,       lowerCAmelCase   =     config_and_inputs
       lowerCAmelCase   =     {"""pixel_values""": pixel_values}
       return config, inputs_dict







@require_tf
class __snake_case(				_lowerCAmelCase		,							_lowerCAmelCase		,							unittest.TestCase ):


      '''simple docstring'''



      UpperCAmelCase							:   int									=		(TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
      UpperCAmelCase							:   List[str]									=		(
          {"feature-extraction": TFCvtModel, "image-classification": TFCvtForImageClassification}
          if is_tf_available()
          else {}
      )
      UpperCAmelCase							:   Optional[Any]									=		False
      UpperCAmelCase							:   Dict									=		False
      UpperCAmelCase							:   Optional[Any]									=		False
      UpperCAmelCase							:   List[Any]									=		False
      UpperCAmelCase							:   Any									=		False


      def     __snake_case   ( self				)     ->     Any:
       lowerCAmelCase   =     TFCvtModelTester(self				)
       lowerCAmelCase   =     TFCvtConfigTester(self     ,	config_class=_snake_case     ,	has_text_modality=_snake_case     ,	hidden_size=37				)


      def     __snake_case   ( self				)     ->     Optional[int]:
       self.config_tester.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()


      @unittest.skip(reason="""Cvt does not output attentions"""				)
      def     __snake_case   ( self				)     ->     Tuple:
       pass


      @unittest.skip(reason="""Cvt does not use inputs_embeds"""				)
      def     __snake_case   ( self				)     ->     Union[str, Any]:
       pass


      @unittest.skip(reason="""Cvt does not support input and output embeddings"""				)
      def     __snake_case   ( self				)     ->     Optional[Any]:
       pass


      @unittest.skipIf(
          not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""				)				) == 0     ,	reason="""TF does not support backprop for grouped convolutions on CPU."""     ,	)
      def     __snake_case   ( self				)     ->     int:
       super().test_dataset_conversion()


      @unittest.skipIf(
          not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""				)				) == 0     ,	reason="""TF does not support backprop for grouped convolutions on CPU."""     ,	)
      @slow
      def     __snake_case   ( self				)     ->     Optional[int]:
       super().test_keras_fit()


      @unittest.skip(reason="""Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8"""				)
      def     __snake_case   ( self				)     ->     Tuple:
       lowerCAmelCase   =     tf.keras.mixed_precision.Policy("""mixed_float16"""				)
       tf.keras.mixed_precision.set_global_policy(_snake_case				)
       super().test_keras_fit()
       tf.keras.mixed_precision.set_global_policy("""float32"""				)


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

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

        lowerCAmelCase   =     ["""pixel_values"""]
        self.assertListEqual(arg_names[:1]     ,	_snake_case				)


      def     __snake_case   ( self				)     ->     Dict:




       def check_hidden_states_output(A_     ,	A_     ,	A_				):
        lowerCAmelCase   =     model_class(_snake_case				)

        lowerCAmelCase   =     model(**self._prepare_for_class(_snake_case     ,	_snake_case				)				)
        lowerCAmelCase   =     outputs.hidden_states

        lowerCAmelCase   =     len(self.model_tester.depth				)
        self.assertEqual(len(_snake_case				)     ,	_snake_case				)

        # 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,
            ]     ,	)

       lowerCAmelCase,       lowerCAmelCase   =     self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        lowerCAmelCase   =     True
        check_hidden_states_output(_snake_case     ,	_snake_case     ,	_snake_case				)

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        lowerCAmelCase   =     True

        check_hidden_states_output(_snake_case     ,	_snake_case     ,	_snake_case				)


      def     __snake_case   ( self				)     ->     Dict:
       lowerCAmelCase   =     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_snake_case				)


      def     __snake_case   ( self				)     ->     List[Any]:
       lowerCAmelCase   =     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_snake_case				)




      @slow
      def     __snake_case   ( self				)     ->     Union[str, Any]:




       for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        lowerCAmelCase   =     TFCvtModel.from_pretrained(_snake_case				)
        self.assertIsNotNone(_snake_case				)







def 		_snake_case		( )      ->						Optional[int]:







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





@require_tf
@require_vision
class __snake_case(				unittest.TestCase ):


      '''simple docstring'''



      @cached_property
      def     __snake_case   ( self				)     ->     Union[str, Any]:
       return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)




      @slow
      def     __snake_case   ( self				)     ->     List[Any]:
       lowerCAmelCase   =     TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)

       lowerCAmelCase   =     self.default_image_processor
       lowerCAmelCase   =     prepare_img()
       lowerCAmelCase   =     image_processor(images=_snake_case     ,	return_tensors="""tf"""				)

       # forward pass
       lowerCAmelCase   =     model(**_snake_case				)

       # verify the logits
       lowerCAmelCase   =     tf.TensorShape((1, 1000)				)
       self.assertEqual(outputs.logits.shape     ,	_snake_case				)

       lowerCAmelCase   =     tf.constant([0.9_2_8_5, 0.9_0_1_5, -0.3_1_5_0]				)
       self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()     ,	_snake_case     ,	atol=1e-4				)				)




'''simple docstring'''

import unittest

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


if is_torch_available():
				import torch

				from transformers import AutoModelForImageClassification

if is_vision_available():
				from transformers import AutoImageProcessor

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


						'''simple docstring'''



						@slow
						def     __snake_case   ( self				)     ->     List[str]:
							lowerCAmelCase   =     AutoImageProcessor.from_pretrained("""microsoft/dit-base-finetuned-rvlcdip"""				)
							lowerCAmelCase   =     AutoModelForImageClassification.from_pretrained("""microsoft/dit-base-finetuned-rvlcdip"""				)
							model.to(A_				)

							from datasets import load_dataset

							lowerCAmelCase   =     load_dataset("""nielsr/rvlcdip-demo"""				)

							lowerCAmelCase   =     dataset["""train"""][0]["""image"""].convert("""RGB"""				)

							lowerCAmelCase   =     image_processor(A_     ,	return_tensors="""pt"""				).to(A_				)

							# forward pass
							with torch.no_grad():
								lowerCAmelCase   =     model(**A_				)
								lowerCAmelCase   =     outputs.logits

							lowerCAmelCase   =     torch.Size((1, 16)				)
							self.assertEqual(logits.shape     ,	A_				)

							lowerCAmelCase   =     torch.tensor(
							    [-0.4_1_5_8, -0.4_0_9_2, -0.4_3_4_7]     ,	device=A_     ,	dtype=torch.float     ,	)
							self.assertTrue(torch.allclose(logits[0, :3]     ,	A_     ,	atol=1e-4				)				)