




'''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      __snake_case       (   lowercase   :							Any			, lowercase   :							int  ):
					assert isinstance(lowercase			, lowercase  )
					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      __snake_case       (   lowercase   :							Any			, lowercase   :							Dict			, lowercase   :							List[str]			, lowercase   :							Union[str, Any]  ):
					snake_case_	=      tmp_path / "cache"
					snake_case_	=      {"col_1": "string", "col_2": "int64", "col_3": "float64"}
					with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
										snake_case_	=      SqlDatasetReader(
										    "dataset"			, "sqlite:///" + sqlite_path			, cache_dir=lowercase			, keep_in_memory=lowercase  ).read()
					_check_sql_dataset(lowercase			, lowercase  )
@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      __snake_case       (   lowercase   :							Union[str, Any]			, lowercase   :							Union[str, Any]			, lowercase   :							List[Any]			, lowercase   :							Optional[Any]  ):
					snake_case_	=      tmp_path / "cache"
					snake_case_	=      {"col_1": "string", "col_2": "int64", "col_3": "float64"}
					snake_case_	=      features.copy() if features else default_expected_features
					snake_case_	=      (
					    Features({feature: Value(lowercase  ) for feature, dtype in features.items()}  ) if features is not None else None
					)
					snake_case_	=      SqlDatasetReader("dataset"			, "sqlite:///" + sqlite_path			, features=lowercase			, cache_dir=lowercase  ).read()
					_check_sql_dataset(lowercase			, lowercase  )
def      __snake_case       (   lowercase   :							Tuple  ):


					with contextlib.closing(sqlitea.connect(lowercase  )  ) as con:
										snake_case_	=      con.cursor()
										cur.execute("SELECT * FROM dataset"  )
										for row in cur:
															yield row
@require_sqlalchemy
def      __snake_case       (   lowercase   :							Optional[int]			, lowercase   :							Optional[int]			, lowercase   :							List[str]  ):
					snake_case_	=      tmp_path / "cache"
					snake_case_	=      os.path.join(lowercase			, "tmp.sql"  )
					snake_case_	=      SqlDatasetReader("dataset"			, "sqlite:///" + sqlite_path			, cache_dir=lowercase  ).read()
					SqlDatasetWriter(lowercase			, "dataset"			, "sqlite:///" + output_sqlite_path			, num_proc=1  ).write()

					snake_case_	=      iter_sql_file(lowercase  )
					snake_case_	=      iter_sql_file(lowercase  )

					for rowa, rowa in zip(lowercase			, lowercase  ):
										assert rowa == rowa
@require_sqlalchemy
def      __snake_case       (   lowercase   :							Dict			, lowercase   :							Tuple			, lowercase   :							Dict  ):
					snake_case_	=      tmp_path / "cache"
					snake_case_	=      os.path.join(lowercase			, "tmp.sql"  )
					snake_case_	=      SqlDatasetReader("dataset"			, "sqlite:///" + sqlite_path			, cache_dir=lowercase  ).read()
					SqlDatasetWriter(lowercase			, "dataset"			, "sqlite:///" + output_sqlite_path			, num_proc=2  ).write()

					snake_case_	=      iter_sql_file(lowercase  )
					snake_case_	=      iter_sql_file(lowercase  )

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





@require_sqlalchemy
def      __snake_case       (   lowercase   :							Any			, lowercase   :							Optional[int]			, lowercase   :							Any  ):
					snake_case_	=      tmp_path / "cache"
					snake_case_	=      os.path.join(lowercase			, "tmp.sql"  )
					snake_case_	=      SqlDatasetReader("dataset"			, "sqlite:///" + sqlite_path			, cache_dir=lowercase  ).read()
					with pytest.raises(lowercase  ):
										SqlDatasetWriter(lowercase			, "dataset"			, "sqlite:///" + output_sqlite_path			, num_proc=0  ).write()








'''simple docstring'''



import inspect
import unittest

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

from ...test_backbone_common import BackboneTesterMixin
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 ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
     from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor



class 				_snake_case					:

  def __init__(				self      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE=13      , _SCREAMING_SNAKE_CASE=32      , _SCREAMING_SNAKE_CASE=3      , _SCREAMING_SNAKE_CASE=4      , _SCREAMING_SNAKE_CASE=[10, 20, 30, 40]      , _SCREAMING_SNAKE_CASE=[2, 2, 3, 2]      , _SCREAMING_SNAKE_CASE=True      , _SCREAMING_SNAKE_CASE=True      , _SCREAMING_SNAKE_CASE=37      , _SCREAMING_SNAKE_CASE="gelu"      , _SCREAMING_SNAKE_CASE=10      , _SCREAMING_SNAKE_CASE=0.02      , _SCREAMING_SNAKE_CASE=["stage2", "stage3", "stage4"]      , _SCREAMING_SNAKE_CASE=[2, 3, 4]      , _SCREAMING_SNAKE_CASE=None      , ):





      '''simple docstring'''

      lowerCAmelCase 						=							parent
      lowerCAmelCase 						=							batch_size
      lowerCAmelCase 						=							image_size
      lowerCAmelCase 						=							num_channels
      lowerCAmelCase 						=							num_stages
      lowerCAmelCase 						=							hidden_sizes
      lowerCAmelCase 						=							depths
      lowerCAmelCase 						=							is_training
      lowerCAmelCase 						=							use_labels
      lowerCAmelCase 						=							intermediate_size
      lowerCAmelCase 						=							hidden_act
      lowerCAmelCase 						=							num_labels
      lowerCAmelCase 						=							initializer_range
      lowerCAmelCase 						=							out_features
      lowerCAmelCase 						=							out_indices
      lowerCAmelCase 						=							scope

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

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

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

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

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      return ConvNextConfig(
          num_channels=self.num_channels      , hidden_sizes=self.hidden_sizes      , depths=self.depths      , num_stages=self.num_stages      , hidden_act=self.hidden_act      , is_decoder=_SCREAMING_SNAKE_CASE      , initializer_range=self.initializer_range      , out_features=self.out_features      , out_indices=self.out_indices      , num_labels=self.num_labels      , )

  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      lowerCAmelCase 						=							ConvNextModel(config=_SCREAMING_SNAKE_CASE	)
      model.to(_SCREAMING_SNAKE_CASE	)
      model.eval()
      lowerCAmelCase 						=							model(_SCREAMING_SNAKE_CASE	)
      # expected last hidden states: B, C, H // 32, W // 32
      self.parent.assertEqual(
          result.last_hidden_state.shape      , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)      , )

  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      lowerCAmelCase 						=							ConvNextForImageClassification(_SCREAMING_SNAKE_CASE	)
      model.to(_SCREAMING_SNAKE_CASE	)
      model.eval()
      lowerCAmelCase 						=							model(_SCREAMING_SNAKE_CASE      , labels=_SCREAMING_SNAKE_CASE	)
      self.parent.assertEqual(result.logits.shape      , (self.batch_size, self.num_labels)	)

  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      lowerCAmelCase 						=							ConvNextBackbone(config=_SCREAMING_SNAKE_CASE	)
      model.to(_SCREAMING_SNAKE_CASE	)
      model.eval()
      lowerCAmelCase 						=							model(_SCREAMING_SNAKE_CASE	)

      # verify hidden states
      self.parent.assertEqual(len(result.feature_maps	)      , len(config.out_features	)	)
      self.parent.assertListEqual(list(result.feature_maps[0].shape	)      , [self.batch_size, self.hidden_sizes[1], 4, 4]	)

      # verify channels
      self.parent.assertEqual(len(model.channels	)      , len(config.out_features	)	)
      self.parent.assertListEqual(model.channels      , config.hidden_sizes[1:]	)

      # verify backbone works with out_features=None
      lowerCAmelCase 						=							None
      lowerCAmelCase 						=							ConvNextBackbone(config=_SCREAMING_SNAKE_CASE	)
      model.to(_SCREAMING_SNAKE_CASE	)
      model.eval()
      lowerCAmelCase 						=							model(_SCREAMING_SNAKE_CASE	)

      # verify feature maps
      self.parent.assertEqual(len(result.feature_maps	)      , 1	)
      self.parent.assertListEqual(list(result.feature_maps[0].shape	)      , [self.batch_size, self.hidden_sizes[-1], 1, 1]	)

      # verify channels
      self.parent.assertEqual(len(model.channels	)      , 1	)
      self.parent.assertListEqual(model.channels      , [config.hidden_sizes[-1]]	)


  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							self.prepare_config_and_inputs()
      lowerCAmelCase						,   lowerCAmelCase						,   lowerCAmelCase 						=							config_and_inputs
      lowerCAmelCase 						=							{'pixel_values': pixel_values}
      return config, inputs_dict



@require_torch
class 				_snake_case					(   a_     , a_     , unittest.TestCase			):
  SCREAMING_SNAKE_CASE			:       List[Any]				=     (
      (
          ConvNextModel,
          ConvNextForImageClassification,
          ConvNextBackbone,
      )
      if is_torch_available()
      else ()
  )
  SCREAMING_SNAKE_CASE			:       int				=     (
      {'''feature-extraction''': ConvNextModel, '''image-classification''': ConvNextForImageClassification}
      if is_torch_available()
      else {}
  )

  SCREAMING_SNAKE_CASE			:       Tuple				=     True
  SCREAMING_SNAKE_CASE			:       Union[str, Any]				=     False
  SCREAMING_SNAKE_CASE			:       Tuple				=     False
  SCREAMING_SNAKE_CASE			:       List[str]				=     False
  SCREAMING_SNAKE_CASE			:       Optional[int]				=     False

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							ConvNextModelTester(self	)
      lowerCAmelCase 						=							ConfigTester(self      , config_class=_SCREAMING_SNAKE_CASE      , has_text_modality=_SCREAMING_SNAKE_CASE      , hidden_size=37	)

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





      '''simple docstring'''

      return

  @unittest.skip(reason='ConvNext does not use inputs_embeds'	)
  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      pass

  @unittest.skip(reason='ConvNext does not support input and output embeddings'	)
  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      pass

  @unittest.skip(reason='ConvNext does not use feedforward chunking'	)
  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      pass

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase						,   lowerCAmelCase 						=							self.model_tester.prepare_config_and_inputs_for_common()

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

          lowerCAmelCase 						=							['pixel_values']
          self.assertListEqual(arg_names[:1]      , _SCREAMING_SNAKE_CASE	)

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE	)

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_backbone(*_SCREAMING_SNAKE_CASE	)

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      def check_hidden_states_output(_SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	):
          lowerCAmelCase 						=							model_class(_SCREAMING_SNAKE_CASE	)
          model.to(_SCREAMING_SNAKE_CASE	)
          model.eval()

          with torch.no_grad():
              lowerCAmelCase 						=							model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	)	)

          lowerCAmelCase 						=							outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

          lowerCAmelCase 						=							self.model_tester.num_stages
          self.assertEqual(len(_SCREAMING_SNAKE_CASE	)      , expected_num_stages + 1	)

          # ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
          self.assertListEqual(
              list(hidden_states[0].shape[-2:]	)      , [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(_SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	)

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

          check_hidden_states_output(_SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	)

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE	)


  @slow
  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowerCAmelCase 						=							ConvNextModel.from_pretrained(_SCREAMING_SNAKE_CASE	)
          self.assertIsNotNone(_SCREAMING_SNAKE_CASE	)



def       snake_case   (	) ->  List[str]:


    """simple docstring"""


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



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

  @cached_property
  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      return AutoImageProcessor.from_pretrained('facebook/convnext-tiny-224'	) if is_vision_available() else None


  @slow
  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'	).to(_SCREAMING_SNAKE_CASE	)

      lowerCAmelCase 						=							self.default_image_processor
      lowerCAmelCase 						=							prepare_img()
      lowerCAmelCase 						=							image_processor(images=_SCREAMING_SNAKE_CASE      , return_tensors='pt'	).to(_SCREAMING_SNAKE_CASE	)

      # forward pass
      with torch.no_grad():
          lowerCAmelCase 						=							model(**_SCREAMING_SNAKE_CASE	)

      # verify the logits
      lowerCAmelCase 						=							torch.Size((1, 10_00)	)
      self.assertEqual(outputs.logits.shape      , _SCREAMING_SNAKE_CASE	)

      lowerCAmelCase 						=							torch.tensor([-0.0_260, -0.4_739, 0.1_911]	).to(_SCREAMING_SNAKE_CASE	)

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



@require_torch
class 				_snake_case					(   unittest.TestCase     , a_			):
  SCREAMING_SNAKE_CASE			:       Dict				=     (ConvNextBackbone,) if is_torch_available() else ()
  SCREAMING_SNAKE_CASE			:       Tuple				=     ConvNextConfig

  SCREAMING_SNAKE_CASE			:       Dict				=     False

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							ConvNextModelTester(self	)





