"""simple docstring"""






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 				_A		( __lowercase			):

      def        A__ (		self		):







            """simple docstring"""



            lowercase														=			self.config_class(**self.inputs_dict		)
            self.parent.assertTrue(hasattr(__lowerCAmelCase	, """embed_dim"""		)		)
            self.parent.assertTrue(hasattr(__lowerCAmelCase	, """num_heads"""		)		)






class 				_A		:

      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.0_2	, __lowerCAmelCase=1E-12	, __lowerCAmelCase=True	, __lowerCAmelCase=True	, __lowerCAmelCase=2	, ):







            """simple docstring"""



            lowercase														=			parent
            lowercase														=			batch_size
            lowercase														=			image_size
            lowercase														=			patch_sizes
            lowercase														=			patch_stride
            lowercase														=			patch_padding
            lowercase														=			is_training
            lowercase														=			use_labels
            lowercase														=			num_labels
            lowercase														=			num_channels
            lowercase														=			embed_dim
            lowercase														=			num_heads
            lowercase														=			stride_kv
            lowercase														=			depth
            lowercase														=			cls_token
            lowercase														=			attention_drop_rate
            lowercase														=			initializer_range
            lowercase														=			layer_norm_eps

      def        A__ (		self		):







            """simple docstring"""



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

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

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

      def        A__ (		self		):







            """simple docstring"""



            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        A__ (		self	, __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase		):







            """simple docstring"""



            lowercase														=			CvtModel(config=__lowerCAmelCase		)
            model.to(__lowerCAmelCase		)
            model.eval()
            lowercase														=			model(__lowerCAmelCase		)
            lowercase														=			(self.image_size, self.image_size)
            lowercase														=			image_size[0], image_size[1]
            for i in range(len(self.depth		)		):
                  lowercase														=			floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1		)
                  lowercase														=			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        A__ (		self	, __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase		):







            """simple docstring"""



            lowercase														=			self.num_labels
            lowercase														=			CvtForImageClassification(__lowerCAmelCase		)
            model.to(__lowerCAmelCase		)
            model.eval()
            lowercase														=			model(__lowerCAmelCase	, labels=__lowerCAmelCase		)
            self.parent.assertEqual(result.logits.shape	, (self.batch_size, self.num_labels)		)







      def        A__ (		self		):







            """simple docstring"""



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






@require_torch
class 				_A		( __lowercase						,					__lowercase						,					unittest.TestCase			):
      snake_case__    :     str													=			(CvtModel, CvtForImageClassification) if is_torch_available() else ()
      snake_case__    :     List[Any]													=			(
          {'feature-extraction': CvtModel, 'image-classification': CvtForImageClassification}
          if is_torch_available()
          else {}
      )

      snake_case__    :     Optional[Any]													=			False
      snake_case__    :     int													=			False
      snake_case__    :     Optional[int]													=			False
      snake_case__    :     Dict													=			False
      snake_case__    :     str													=			False

      def        A__ (		self		):







            """simple docstring"""



            lowercase														=			CvtModelTester(self		)
            lowercase														=			ConfigTester(self	, config_class=__lowerCAmelCase	, has_text_modality=__lowerCAmelCase	, hidden_size=37		)

      def        A__ (		self		):







            """simple docstring"""



            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        A__ (		self		):







            """simple docstring"""



            return

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







            """simple docstring"""



            pass

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







            """simple docstring"""



            pass

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







            """simple docstring"""



            pass

      def        A__ (		self		):







            """simple docstring"""



            lowercase														=			self.model_tester.prepare_config_and_inputs_for_common()

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

                  lowercase														=			["pixel_values"]
                  self.assertListEqual(arg_names[:1]	, __lowerCAmelCase		)

      def        A__ (		self		):







            """simple docstring"""



            lowercase														=			self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*__lowerCAmelCase		)

      def        A__ (		self		):







            """simple docstring"""



            def check_hidden_states_output(__lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase		):
                  lowercase														=			model_class(__lowerCAmelCase		)
                  model.to(__lowerCAmelCase		)
                  model.eval()

                  with torch.no_grad():
                        lowercase														=			model(**self._prepare_for_class(__lowerCAmelCase	, __lowerCAmelCase		)		)

                  lowercase														=			outputs.hidden_states

                  lowercase														=			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,
                      ]	, )

            lowercase														=			self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                  lowercase														=			True
                  check_hidden_states_output(__lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase		)

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

                  check_hidden_states_output(__lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase		)

      def        A__ (		self		):







            """simple docstring"""



            lowercase														=			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        A__ (		self		):







            """simple docstring"""



            pass







      @slow
      def        A__ (		self		):







            """simple docstring"""



            for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  lowercase														=			CvtModel.from_pretrained(__lowerCAmelCase		)
                  self.assertIsNotNone(__lowerCAmelCase		)






def     UpperCAmelCase__ (       )				->					List[Any]:
      '''simple docstring'''


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






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

      @cached_property
      def        A__ (		self		):







            """simple docstring"""



            return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)







      @slow
      def        A__ (		self		):







            """simple docstring"""



            lowercase														=			CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]		).to(__lowerCAmelCase		)

            lowercase														=			self.default_image_processor
            lowercase														=			prepare_img()
            lowercase														=			image_processor(images=__lowerCAmelCase	, return_tensors="""pt"""		).to(__lowerCAmelCase		)

            # forward pass
            with torch.no_grad():
                  lowercase														=			model(**__lowerCAmelCase		)

            # verify the logits
            lowercase														=			torch.Size((1, 1000)		)
            self.assertEqual(outputs.logits.shape	, __lowerCAmelCase		)

            lowercase														=			torch.tensor([0.9_2_8_5, 0.9_0_1_5, -0.3_1_5_0]		).to(__lowerCAmelCase		)

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







"""simple docstring"""






import contextlib
import os
import sqlitea

import pytest

from datasets import Dataset, Features, Value
from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter

from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy


def     UpperCAmelCase__ (       lowerCAmelCase__  :int      ,	lowerCAmelCase__  :Tuple	)				->					Union[str, Any]:
      '''simple docstring'''


      assert isinstance(lowerCAmelCase__      ,	lowerCAmelCase__	)
      assert dataset.num_rows == 4
      assert dataset.num_columns == 3
      assert dataset.column_names == ["col_1", "col_2", "col_3"]
      for feature, expected_dtype in expected_features.items():
            assert dataset.features[feature].dtype == expected_dtype


@require_sqlalchemy
@pytest.mark.parametrize("""keep_in_memory"""      ,	[False, True]	)
def     UpperCAmelCase__ (       lowerCAmelCase__  :Dict      ,	lowerCAmelCase__  :Optional[Any]      ,	lowerCAmelCase__  :str      ,	lowerCAmelCase__  :List[str]	)				->					int:
      '''simple docstring'''


      lowercase														=			tmp_path / """cache"""
      lowercase														=			{"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
      with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
            lowercase														=			SqlDatasetReader(
                """dataset"""      ,	"""sqlite:///""" + sqlite_path      ,	cache_dir=lowerCAmelCase__      ,	keep_in_memory=lowerCAmelCase__	).read()
      _check_sql_dataset(lowerCAmelCase__      ,	lowerCAmelCase__	)


@require_sqlalchemy
@pytest.mark.parametrize(
    """features"""      ,	[
        None,
        {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""},
        {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""},
        {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""},
        {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""},
    ]      ,	)
def     UpperCAmelCase__ (       lowerCAmelCase__  :int      ,	lowerCAmelCase__  :Union[str, Any]      ,	lowerCAmelCase__  :List[Any]      ,	lowerCAmelCase__  :Union[str, Any]	)				->					Optional[int]:
      '''simple docstring'''


      lowercase														=			tmp_path / """cache"""
      lowercase														=			{"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
      lowercase														=			features.copy() if features else default_expected_features
      lowercase														=			(
          Features({feature: Value(lowerCAmelCase__	) for feature, dtype in features.items()}	) if features is not None else None
      )
      lowercase														=			SqlDatasetReader("""dataset"""      ,	"""sqlite:///""" + sqlite_path      ,	features=lowerCAmelCase__      ,	cache_dir=lowerCAmelCase__	).read()
      _check_sql_dataset(lowerCAmelCase__      ,	lowerCAmelCase__	)


def     UpperCAmelCase__ (       lowerCAmelCase__  :Any	)				->					Optional[int]:
      '''simple docstring'''


      with contextlib.closing(sqlitea.connect(lowerCAmelCase__	)	) as con:
            lowercase														=			con.cursor()
            cur.execute("""SELECT * FROM dataset"""	)
            for row in cur:
                  yield row


@require_sqlalchemy
def     UpperCAmelCase__ (       lowerCAmelCase__  :Tuple      ,	lowerCAmelCase__  :str      ,	lowerCAmelCase__  :int	)				->					List[Any]:
      '''simple docstring'''


      lowercase														=			tmp_path / """cache"""
      lowercase														=			os.path.join(lowerCAmelCase__      ,	"""tmp.sql"""	)
      lowercase														=			SqlDatasetReader("""dataset"""      ,	"""sqlite:///""" + sqlite_path      ,	cache_dir=lowerCAmelCase__	).read()
      SqlDatasetWriter(lowerCAmelCase__      ,	"""dataset"""      ,	"""sqlite:///""" + output_sqlite_path      ,	num_proc=1	).write()

      lowercase														=			iter_sql_file(lowerCAmelCase__	)
      lowercase														=			iter_sql_file(lowerCAmelCase__	)

      for rowa, rowa in zip(lowerCAmelCase__      ,	lowerCAmelCase__	):
            assert rowa == rowa


@require_sqlalchemy
def     UpperCAmelCase__ (       lowerCAmelCase__  :str      ,	lowerCAmelCase__  :Optional[Any]      ,	lowerCAmelCase__  :Optional[int]	)				->					Optional[int]:
      '''simple docstring'''


      lowercase														=			tmp_path / """cache"""
      lowercase														=			os.path.join(lowerCAmelCase__      ,	"""tmp.sql"""	)
      lowercase														=			SqlDatasetReader("""dataset"""      ,	"""sqlite:///""" + sqlite_path      ,	cache_dir=lowerCAmelCase__	).read()
      SqlDatasetWriter(lowerCAmelCase__      ,	"""dataset"""      ,	"""sqlite:///""" + output_sqlite_path      ,	num_proc=2	).write()

      lowercase														=			iter_sql_file(lowerCAmelCase__	)
      lowercase														=			iter_sql_file(lowerCAmelCase__	)

      for rowa, rowa in zip(lowerCAmelCase__      ,	lowerCAmelCase__	):
            assert rowa == rowa






@require_sqlalchemy
def     UpperCAmelCase__ (       lowerCAmelCase__  :Dict      ,	lowerCAmelCase__  :Dict      ,	lowerCAmelCase__  :Tuple	)				->					Any:
      '''simple docstring'''


      lowercase														=			tmp_path / """cache"""
      lowercase														=			os.path.join(lowerCAmelCase__      ,	"""tmp.sql"""	)
      lowercase														=			SqlDatasetReader("""dataset"""      ,	"""sqlite:///""" + sqlite_path      ,	cache_dir=lowerCAmelCase__	).read()
      with pytest.raises(lowerCAmelCase__	):
            SqlDatasetWriter(lowerCAmelCase__      ,	"""dataset"""      ,	"""sqlite:///""" + output_sqlite_path      ,	num_proc=0	).write()



