



'''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 						a__  :


	def __init__(self			:			Tuple,       __UpperCAmelCase			:			Tuple,       __UpperCAmelCase			:			List[str]=13,       __UpperCAmelCase			:			List[str]=32,       __UpperCAmelCase			:			Any=3,       __UpperCAmelCase			:			Dict=4,       __UpperCAmelCase			:			str=[10, 20, 30, 40],       __UpperCAmelCase			:			List[str]=[2, 2, 3, 2],       __UpperCAmelCase			:			Dict=True,       __UpperCAmelCase			:			int=True,       __UpperCAmelCase			:			List[str]=37,       __UpperCAmelCase			:			Optional[Any]="gelu",       __UpperCAmelCase			:			Tuple=10,       __UpperCAmelCase			:			Tuple=0.02,       __UpperCAmelCase			:			Dict=["stage2", "stage3", "stage4"],       __UpperCAmelCase			:			Tuple=[2, 3, 4],       __UpperCAmelCase			:			Dict=None,       )  ->      Union[str, Any]:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE	:    Any          =			parent
					SCREAMING_SNAKE_CASE	:    Optional[int]          =			batch_size
					SCREAMING_SNAKE_CASE	:    List[str]          =			image_size
					SCREAMING_SNAKE_CASE	:    Union[str, Any]          =			num_channels
					SCREAMING_SNAKE_CASE	:    Dict          =			num_stages
					SCREAMING_SNAKE_CASE	:    Tuple          =			hidden_sizes
					SCREAMING_SNAKE_CASE	:    Optional[Any]          =			depths
					SCREAMING_SNAKE_CASE	:    List[Any]          =			is_training
					SCREAMING_SNAKE_CASE	:    List[Any]          =			use_labels
					SCREAMING_SNAKE_CASE	:    List[str]          =			intermediate_size
					SCREAMING_SNAKE_CASE	:    Union[str, Any]          =			hidden_act
					SCREAMING_SNAKE_CASE	:    Union[str, Any]          =			num_labels
					SCREAMING_SNAKE_CASE	:    List[str]          =			initializer_range
					SCREAMING_SNAKE_CASE	:    Tuple          =			out_features
					SCREAMING_SNAKE_CASE	:    List[Any]          =			out_indices
					SCREAMING_SNAKE_CASE	:    Any          =			scope


	def 					lowercase__	(self			:			Optional[int]   )  ->      int:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE	:    Optional[Any]          =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

					SCREAMING_SNAKE_CASE	:    Any          =			None
					if self.use_labels:
									SCREAMING_SNAKE_CASE	:    List[Any]          =			ids_tensor([self.batch_size],       self.num_labels   )

					SCREAMING_SNAKE_CASE	:    Optional[int]          =			self.get_config()
					return config, pixel_values, labels


	def 					lowercase__	(self			:			str   )  ->      Dict:

					"""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=lowerCamelCase__,       initializer_range=self.initializer_range,       out_features=self.out_features,       out_indices=self.out_indices,       num_labels=self.num_labels,       )


	def 					lowercase__	(self			:			Optional[Any],       __UpperCAmelCase			:			Tuple,       __UpperCAmelCase			:			int,       __UpperCAmelCase			:			int   )  ->      Optional[int]:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE	:    List[Any]          =			ConvNextModel(config=lowerCamelCase__   )
					model.to(lowerCamelCase__   )
					model.eval()
					SCREAMING_SNAKE_CASE	:    str          =			model(lowerCamelCase__   )
					# 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 					lowercase__	(self			:			Optional[int],       __UpperCAmelCase			:			Dict,       __UpperCAmelCase			:			Optional[int],       __UpperCAmelCase			:			Optional[int]   )  ->      Optional[Any]:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE	:    List[str]          =			ConvNextForImageClassification(lowerCamelCase__   )
					model.to(lowerCamelCase__   )
					model.eval()
					SCREAMING_SNAKE_CASE	:    List[Any]          =			model(lowerCamelCase__,       labels=lowerCamelCase__   )
					self.parent.assertEqual(result.logits.shape,       (self.batch_size, self.num_labels)   )


	def 					lowercase__	(self			:			int,       __UpperCAmelCase			:			Optional[Any],       __UpperCAmelCase			:			Any,       __UpperCAmelCase			:			List[Any]   )  ->      Dict:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE	:    List[str]          =			ConvNextBackbone(config=lowerCamelCase__   )
					model.to(lowerCamelCase__   )
					model.eval()
					SCREAMING_SNAKE_CASE	:    int          =			model(lowerCamelCase__   )

					# 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
					SCREAMING_SNAKE_CASE	:    Optional[int]          =			None
					SCREAMING_SNAKE_CASE	:    Union[str, Any]          =			ConvNextBackbone(config=lowerCamelCase__   )
					model.to(lowerCamelCase__   )
					model.eval()
					SCREAMING_SNAKE_CASE	:    int          =			model(lowerCamelCase__   )

					# 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 					lowercase__	(self			:			List[str]   )  ->      Optional[int]:

					"""simple docstring"""

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



@require_torch
class 						a__  (					UpperCAmelCase__,      UpperCAmelCase__,      unittest.TestCase						):
	__magic_name__		:     Optional[Any]						     =  (
	    (
	        ConvNextModel,
	        ConvNextForImageClassification,
	        ConvNextBackbone,
	    )
	    if is_torch_available()
	    else ()
	)
	__magic_name__		:     Dict						     =  (
	    {'feature-extraction': ConvNextModel, 'image-classification': ConvNextForImageClassification}
	    if is_torch_available()
	    else {}
	)

	__magic_name__		:     Any						     =  True
	__magic_name__		:     List[str]						     =  False
	__magic_name__		:     Optional[Any]						     =  False
	__magic_name__		:     List[str]						     =  False
	__magic_name__		:     Optional[Any]						     =  False


	def 					lowercase__	(self			:			Union[str, Any]   )  ->      Optional[int]:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE	:    Any          =			ConvNextModelTester(self   )
					SCREAMING_SNAKE_CASE	:    str          =			ConfigTester(self,       config_class=lowerCamelCase__,       has_text_modality=lowerCamelCase__,       hidden_size=37   )


	def 					lowercase__	(self			:			Optional[int]   )  ->      Dict:

					"""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 					lowercase__	(self			:			int   )  ->      List[str]:

					"""simple docstring"""

					return


	@unittest.skip(reason='''ConvNext does not use inputs_embeds'''   )
	def 					lowercase__	(self			:			int   )  ->      Dict:

					"""simple docstring"""

					pass


	@unittest.skip(reason='''ConvNext does not support input and output embeddings'''   )
	def 					lowercase__	(self			:			List[Any]   )  ->      Union[str, Any]:

					"""simple docstring"""

					pass


	@unittest.skip(reason='''ConvNext does not use feedforward chunking'''   )
	def 					lowercase__	(self			:			Optional[int]   )  ->      Optional[Any]:

					"""simple docstring"""

					pass


	def 					lowercase__	(self			:			Any   )  ->      Tuple:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE	:    Union[str, Any]          =			self.model_tester.prepare_config_and_inputs_for_common()

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

									SCREAMING_SNAKE_CASE	:    List[str]          =			["pixel_values"]
									self.assertListEqual(arg_names[:1],       lowerCamelCase__   )


	def 					lowercase__	(self			:			Tuple   )  ->      int:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE	:    Dict          =			self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*lowerCamelCase__   )


	def 					lowercase__	(self			:			Optional[int]   )  ->      List[str]:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE	:    Any          =			self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_backbone(*lowerCamelCase__   )


	def 					lowercase__	(self			:			List[Any]   )  ->      Optional[Any]:

					"""simple docstring"""

					def check_hidden_states_output(__UpperCAmelCase			:			Any,       __UpperCAmelCase			:			Optional[Any],       __UpperCAmelCase			:			Optional[int]   ):
									SCREAMING_SNAKE_CASE	:    List[str]          =			model_class(lowerCamelCase__   )
									model.to(lowerCamelCase__   )
									model.eval()

									with torch.no_grad():
													SCREAMING_SNAKE_CASE	:    int          =			model(**self._prepare_for_class(lowerCamelCase__,       lowerCamelCase__   )   )

									SCREAMING_SNAKE_CASE	:    Tuple          =			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

									SCREAMING_SNAKE_CASE	:    Optional[int]          =			self.model_tester.num_stages
									self.assertEqual(len(lowerCamelCase__   ),       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],       )

					SCREAMING_SNAKE_CASE	:    str          =			self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
									SCREAMING_SNAKE_CASE	:    Optional[int]          =			True
									check_hidden_states_output(lowerCamelCase__,       lowerCamelCase__,       lowerCamelCase__   )

									# check that output_hidden_states also work using config
									del inputs_dict["output_hidden_states"]
									SCREAMING_SNAKE_CASE	:    Union[str, Any]          =			True

									check_hidden_states_output(lowerCamelCase__,       lowerCamelCase__,       lowerCamelCase__   )


	def 					lowercase__	(self			:			Any   )  ->      List[str]:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE	:    Tuple          =			self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__   )






	@slow
	def 					lowercase__	(self			:			Any   )  ->      int:

					"""simple docstring"""

					for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									SCREAMING_SNAKE_CASE	:    Union[str, Any]          =			ConvNextModel.from_pretrained(lowerCamelCase__   )
									self.assertIsNotNone(lowerCamelCase__   )






def    __lowercase	():
				SCREAMING_SNAKE_CASE	:    List[Any]          =			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''							)
				return image


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


	@cached_property
	def 					lowercase__	(self			:			Any   )  ->      Optional[Any]:

					"""simple docstring"""

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






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

					"""simple docstring"""

					SCREAMING_SNAKE_CASE	:    Optional[Any]          =			ConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''   ).to(lowerCamelCase__   )

					SCREAMING_SNAKE_CASE	:    Optional[Any]          =			self.default_image_processor
					SCREAMING_SNAKE_CASE	:    Tuple          =			prepare_img()
					SCREAMING_SNAKE_CASE	:    List[str]          =			image_processor(images=lowerCamelCase__,       return_tensors='''pt'''   ).to(lowerCamelCase__   )

					# forward pass
					with torch.no_grad():
									SCREAMING_SNAKE_CASE	:    Tuple          =			model(**lowerCamelCase__   )

					# verify the logits
					SCREAMING_SNAKE_CASE	:    Optional[Any]          =			torch.Size((1, 1000)   )
					self.assertEqual(outputs.logits.shape,       lowerCamelCase__   )

					SCREAMING_SNAKE_CASE	:    Tuple          =			torch.tensor([-0.0260, -0.4739, 0.1911]   ).to(lowerCamelCase__   )

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



@require_torch
class 						a__  (					unittest.TestCase,      UpperCAmelCase__						):
	__magic_name__		:     Union[str, Any]						     =  (ConvNextBackbone,) if is_torch_available() else ()
	__magic_name__		:     List[Any]						     =  ConvNextConfig

	__magic_name__		:     Optional[int]						     =  False


	def 					lowercase__	(self			:			Optional[Any]   )  ->      Optional[Any]:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE	:    Union[str, Any]          =			ConvNextModelTester(self   )





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							,				lowercase					):
   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							,				lowercase							,				lowercase							,				lowercase					):
   lowerCAmelCase_:							Any       =	tmp_path / "cache"
   lowerCAmelCase_:							int       =	{"col_1": "string", "col_2": "int64", "col_3": "float64"}
   with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
      lowerCAmelCase_:							Optional[int]       =	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							,				lowercase							,				lowercase							,				lowercase					):
   lowerCAmelCase_:							List[str]       =	tmp_path / "cache"
   lowerCAmelCase_:							int       =	{"col_1": "string", "col_2": "int64", "col_3": "float64"}
   lowerCAmelCase_:							List[str]       =	features.copy() if features else default_expected_features
   lowerCAmelCase_:							Any       =	(
       Features({feature: Value(lowercase					) for feature, dtype in features.items()}					) if features is not None else None
   )
   lowerCAmelCase_:							int       =	SqlDatasetReader("dataset"							,				"sqlite:///" + sqlite_path							,				features=lowercase							,				cache_dir=lowercase					).read()
   _check_sql_dataset(lowercase							,				lowercase					)
def 		snake_case__	(		lowercase					):
   with contextlib.closing(sqlitea.connect(lowercase					)					) as con:
      lowerCAmelCase_:							Any       =	con.cursor()
      cur.execute("SELECT * FROM dataset"					)
      for row in cur:
         yield row
@require_sqlalchemy
def 		snake_case__	(		lowercase							,				lowercase							,				lowercase					):
   lowerCAmelCase_:							Optional[int]       =	tmp_path / "cache"
   lowerCAmelCase_:							Optional[Any]       =	os.path.join(lowercase							,				"tmp.sql"					)
   lowerCAmelCase_:							str       =	SqlDatasetReader("dataset"							,				"sqlite:///" + sqlite_path							,				cache_dir=lowercase					).read()
   SqlDatasetWriter(lowercase							,				"dataset"							,				"sqlite:///" + output_sqlite_path							,				num_proc=1					).write()

   lowerCAmelCase_:							Union[str, Any]       =	iter_sql_file(lowercase					)
   lowerCAmelCase_:							str       =	iter_sql_file(lowercase					)

   for rowa, rowa in zip(lowercase							,				lowercase					):
      assert rowa == rowa
@require_sqlalchemy
def 		snake_case__	(		lowercase							,				lowercase							,				lowercase					):
   lowerCAmelCase_:							str       =	tmp_path / "cache"
   lowerCAmelCase_:							Optional[int]       =	os.path.join(lowercase							,				"tmp.sql"					)
   lowerCAmelCase_:							Optional[Any]       =	SqlDatasetReader("dataset"							,				"sqlite:///" + sqlite_path							,				cache_dir=lowercase					).read()
   SqlDatasetWriter(lowercase							,				"dataset"							,				"sqlite:///" + output_sqlite_path							,				num_proc=2					).write()

   lowerCAmelCase_:							Optional[Any]       =	iter_sql_file(lowercase					)
   lowerCAmelCase_:							Optional[int]       =	iter_sql_file(lowercase					)

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







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