






"""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     UpperCamelCase_ :





	def __init__(   self      :				List[Any]			,			lowerCAmelCase_      :				int			,			lowerCAmelCase_      :				List[str]=13			,			lowerCAmelCase_      :				Optional[int]=32			,			lowerCAmelCase_      :				Union[str, Any]=3			,			lowerCAmelCase_      :				str=4			,			lowerCAmelCase_      :				Any=[10, 20, 30, 40]			,			lowerCAmelCase_      :				Tuple=[2, 2, 3, 2]			,			lowerCAmelCase_      :				Dict=True			,			lowerCAmelCase_      :				int=True			,			lowerCAmelCase_      :				Any=37			,			lowerCAmelCase_      :				str="gelu"			,			lowerCAmelCase_      :				Optional[Any]=10			,			lowerCAmelCase_      :				Dict=0.0_2			,			lowerCAmelCase_      :				int=["stage2", "stage3", "stage4"]			,			lowerCAmelCase_      :				Optional[int]=[2, 3, 4]			,			lowerCAmelCase_      :				Tuple=None			,			)		->    int:
				UpperCAmelCase_  :				Tuple      =      parent
				UpperCAmelCase_  :				Union[str, Any]      =      batch_size
				UpperCAmelCase_  :				List[Any]      =      image_size
				UpperCAmelCase_  :				str      =      num_channels
				UpperCAmelCase_  :				List[str]      =      num_stages
				UpperCAmelCase_  :				int      =      hidden_sizes
				UpperCAmelCase_  :				List[str]      =      depths
				UpperCAmelCase_  :				Tuple      =      is_training
				UpperCAmelCase_  :				Optional[int]      =      use_labels
				UpperCAmelCase_  :				Optional[Any]      =      intermediate_size
				UpperCAmelCase_  :				str      =      hidden_act
				UpperCAmelCase_  :				Tuple      =      num_labels
				UpperCAmelCase_  :				List[str]      =      initializer_range
				UpperCAmelCase_  :				str      =      out_features
				UpperCAmelCase_  :				Any      =      out_indices
				UpperCAmelCase_  :				str      =      scope





	def   _SCREAMING_SNAKE_CASE   (   self      :				Optional[Any]		)		->    List[Any]:
				UpperCAmelCase_  :				Union[str, Any]      =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

				UpperCAmelCase_  :				Tuple      =      None
				if self.use_labels:
							UpperCAmelCase_  :				Optional[Any]      =      ids_tensor([self.batch_size]			,			self.num_labels		)

				UpperCAmelCase_  :				str      =      self.get_config()
				return config, pixel_values, labels





	def   _SCREAMING_SNAKE_CASE   (   self      :				Optional[int]		)		->    Dict:
				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   _SCREAMING_SNAKE_CASE   (   self      :				Optional[Any]			,			lowerCAmelCase_      :				List[Any]			,			lowerCAmelCase_      :				Union[str, Any]			,			lowerCAmelCase_      :				Tuple		)		->    str:
				UpperCAmelCase_  :				Dict      =      ConvNextModel(config=lowerCAmelCase_		)
				model.to(lowerCAmelCase_		)
				model.eval()
				UpperCAmelCase_  :				Any      =      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   _SCREAMING_SNAKE_CASE   (   self      :				List[str]			,			lowerCAmelCase_      :				Tuple			,			lowerCAmelCase_      :				Union[str, Any]			,			lowerCAmelCase_      :				Optional[Any]		)		->    str:
				UpperCAmelCase_  :				List[str]      =      ConvNextForImageClassification(lowerCAmelCase_		)
				model.to(lowerCAmelCase_		)
				model.eval()
				UpperCAmelCase_  :				int      =      model(lowerCAmelCase_			,			labels=lowerCAmelCase_		)
				self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.num_labels)		)





	def   _SCREAMING_SNAKE_CASE   (   self      :				Tuple			,			lowerCAmelCase_      :				Any			,			lowerCAmelCase_      :				List[Any]			,			lowerCAmelCase_      :				int		)		->    List[str]:
				UpperCAmelCase_  :				Any      =      ConvNextBackbone(config=lowerCAmelCase_		)
				model.to(lowerCAmelCase_		)
				model.eval()
				UpperCAmelCase_  :				Optional[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
				UpperCAmelCase_  :				Optional[int]      =      None
				UpperCAmelCase_  :				str      =      ConvNextBackbone(config=lowerCAmelCase_		)
				model.to(lowerCAmelCase_		)
				model.eval()
				UpperCAmelCase_  :				Any      =      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   _SCREAMING_SNAKE_CASE   (   self      :				List[Any]		)		->    Dict:
				UpperCAmelCase_  :				Any      =      self.prepare_config_and_inputs()
				UpperCAmelCase_  ,			UpperCAmelCase_  ,			UpperCAmelCase_  :				List[str]      =      config_and_inputs
				UpperCAmelCase_  :				Optional[int]      =      {"pixel_values": pixel_values}
				return config, inputs_dict







@require_torch
class     UpperCamelCase_ (__A       ,		__A       ,		unittest.TestCase  ):
	__magic_name__			   =       (
	    (
	        ConvNextModel,
	        ConvNextForImageClassification,
	        ConvNextBackbone,
	    )
	    if is_torch_available()
	    else ()
	)
	__magic_name__			   =       (
	    {'''feature-extraction''': ConvNextModel, '''image-classification''': ConvNextForImageClassification}
	    if is_torch_available()
	    else {}
	)

	__magic_name__			   =       True
	__magic_name__			   =       False
	__magic_name__			   =       False
	__magic_name__			   =       False
	__magic_name__			   =       False





	def   _SCREAMING_SNAKE_CASE   (   self      :				List[str]		)		->    Optional[Any]:
				UpperCAmelCase_  :				Optional[int]      =      ConvNextModelTester(self		)
				UpperCAmelCase_  :				Any      =      ConfigTester(self			,			config_class=lowerCAmelCase_			,			has_text_modality=lowerCAmelCase_			,			hidden_size=37		)





	def   _SCREAMING_SNAKE_CASE   (   self      :				Optional[int]		)		->    Dict:
				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      :				List[Any]		)		->    Dict:
				return





	@unittest.skip(reason="ConvNext does not use inputs_embeds"		)
	def   _SCREAMING_SNAKE_CASE   (   self      :				Any		)		->    List[Any]:
				pass





	@unittest.skip(reason="ConvNext does not support input and output embeddings"		)
	def   _SCREAMING_SNAKE_CASE   (   self      :				Optional[int]		)		->    Dict:
				pass





	@unittest.skip(reason="ConvNext does not use feedforward chunking"		)
	def   _SCREAMING_SNAKE_CASE   (   self      :				Optional[Any]		)		->    Tuple:
				pass





	def   _SCREAMING_SNAKE_CASE   (   self      :				List[Any]		)		->    Tuple:
				UpperCAmelCase_  ,			UpperCAmelCase_  :				int      =      self.model_tester.prepare_config_and_inputs_for_common()

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

							UpperCAmelCase_  :				List[Any]      =      ["pixel_values"]
							self.assertListEqual(arg_names[:1]			,			lowerCAmelCase_		)





	def   _SCREAMING_SNAKE_CASE   (   self      :				Union[str, Any]		)		->    List[Any]:
				UpperCAmelCase_  :				Optional[int]      =      self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*lowerCAmelCase_		)





	def   _SCREAMING_SNAKE_CASE   (   self      :				Optional[Any]		)		->    Any:
				UpperCAmelCase_  :				str      =      self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_backbone(*lowerCAmelCase_		)





	def   _SCREAMING_SNAKE_CASE   (   self      :				int		)		->    List[str]:
				def check_hidden_states_output(lowerCAmelCase_      :				int			,			lowerCAmelCase_      :				Dict			,			lowerCAmelCase_      :				int		):
							UpperCAmelCase_  :				List[str]      =      model_class(lowerCAmelCase_		)
							model.to(lowerCAmelCase_		)
							model.eval()

							with torch.no_grad():
										UpperCAmelCase_  :				Any      =      model(**self._prepare_for_class(lowerCAmelCase_			,			lowerCAmelCase_		)		)

							UpperCAmelCase_  :				List[Any]      =      outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

							UpperCAmelCase_  :				List[str]      =      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]			,			)

				UpperCAmelCase_  ,			UpperCAmelCase_  :				int      =      self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
							UpperCAmelCase_  :				List[Any]      =      True
							check_hidden_states_output(lowerCAmelCase_			,			lowerCAmelCase_			,			lowerCAmelCase_		)

							# check that output_hidden_states also work using config
							del inputs_dict["output_hidden_states"]
							UpperCAmelCase_  :				Tuple      =      True

							check_hidden_states_output(lowerCAmelCase_			,			lowerCAmelCase_			,			lowerCAmelCase_		)





	def   _SCREAMING_SNAKE_CASE   (   self      :				List[str]		)		->    Union[str, Any]:
				UpperCAmelCase_  :				Tuple      =      self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_		)





	@slow
	def   _SCREAMING_SNAKE_CASE   (   self      :				Any		)		->    List[str]:
				for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							UpperCAmelCase_  :				Optional[Any]      =      ConvNextModel.from_pretrained(lowerCAmelCase_		)
							self.assertIsNotNone(lowerCAmelCase_		)





def        snake_case   (     ):
			UpperCAmelCase_  :				int      =      Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
			return image







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





	@cached_property
	def   _SCREAMING_SNAKE_CASE   (   self      :				List[Any]		)		->    Optional[Any]:
				return AutoImageProcessor.from_pretrained("facebook/convnext-tiny-224"		) if is_vision_available() else None





	@slow
	def   _SCREAMING_SNAKE_CASE   (   self      :				Tuple		)		->    Union[str, Any]:
				UpperCAmelCase_  :				Any      =      ConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"		).to(lowerCAmelCase_		)

				UpperCAmelCase_  :				int      =      self.default_image_processor
				UpperCAmelCase_  :				str      =      prepare_img()
				UpperCAmelCase_  :				Optional[Any]      =      image_processor(images=lowerCAmelCase_			,			return_tensors="pt"		).to(lowerCAmelCase_		)

				# forward pass
				with torch.no_grad():
							UpperCAmelCase_  :				Optional[Any]      =      model(**lowerCAmelCase_		)

				# verify the logits
				UpperCAmelCase_  :				Optional[Any]      =      torch.Size((1, 1_000)		)
				self.assertEqual(outputs.logits.shape			,			lowerCAmelCase_		)

				UpperCAmelCase_  :				Union[str, Any]      =      torch.tensor([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1]		).to(lowerCAmelCase_		)

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







@require_torch
class     UpperCamelCase_ (unittest.TestCase       ,		__A  ):
	__magic_name__			   =       (ConvNextBackbone,) if is_torch_available() else ()
	__magic_name__			   =       ConvNextConfig

	__magic_name__			   =       False





	def   _SCREAMING_SNAKE_CASE   (   self      :				List[Any]		)		->    Union[str, Any]:
				UpperCAmelCase_  :				Optional[int]      =      ConvNextModelTester(self		)











"""simple docstring"""
from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
    is_vision_available,
)


lowerCamelCase_       			=   {
    '''configuration_clip''': [
        '''CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''CLIPConfig''',
        '''CLIPOnnxConfig''',
        '''CLIPTextConfig''',
        '''CLIPVisionConfig''',
    ],
    '''processing_clip''': ['''CLIPProcessor'''],
    '''tokenization_clip''': ['''CLIPTokenizer'''],
}

try:
			if not is_tokenizers_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			lowerCamelCase_       			=   ['''CLIPTokenizerFast''']

try:
			if not is_vision_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			lowerCamelCase_       			=   ['''CLIPFeatureExtractor''']
			lowerCamelCase_       			=   ['''CLIPImageProcessor''']

try:
			if not is_torch_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			lowerCamelCase_       			=   [
			    '''CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',
			    '''CLIPModel''',
			    '''CLIPPreTrainedModel''',
			    '''CLIPTextModel''',
			    '''CLIPTextModelWithProjection''',
			    '''CLIPVisionModel''',
			    '''CLIPVisionModelWithProjection''',
			]

try:
			if not is_tf_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			lowerCamelCase_       			=   [
			    '''TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',
			    '''TFCLIPModel''',
			    '''TFCLIPPreTrainedModel''',
			    '''TFCLIPTextModel''',
			    '''TFCLIPVisionModel''',
			]

try:
			if not is_flax_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			lowerCamelCase_       			=   [
			    '''FlaxCLIPModel''',
			    '''FlaxCLIPPreTrainedModel''',
			    '''FlaxCLIPTextModel''',
			    '''FlaxCLIPTextPreTrainedModel''',
			    '''FlaxCLIPVisionModel''',
			    '''FlaxCLIPVisionPreTrainedModel''',
			]


if TYPE_CHECKING:
			from .configuration_clip import (
			    CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
			    CLIPConfig,
			    CLIPOnnxConfig,
			    CLIPTextConfig,
			    CLIPVisionConfig,
			)
			from .processing_clip import CLIPProcessor
			from .tokenization_clip import CLIPTokenizer

			try:
						if not is_tokenizers_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .tokenization_clip_fast import CLIPTokenizerFast

			try:
						if not is_vision_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .feature_extraction_clip import CLIPFeatureExtractor
						from .image_processing_clip import CLIPImageProcessor

			try:
						if not is_torch_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_clip import (
						    CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
						    CLIPModel,
						    CLIPPreTrainedModel,
						    CLIPTextModel,
						    CLIPTextModelWithProjection,
						    CLIPVisionModel,
						    CLIPVisionModelWithProjection,
						)

			try:
						if not is_tf_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_tf_clip import (
						    TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
						    TFCLIPModel,
						    TFCLIPPreTrainedModel,
						    TFCLIPTextModel,
						    TFCLIPVisionModel,
						)

			try:
						if not is_flax_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_flax_clip import (
						    FlaxCLIPModel,
						    FlaxCLIPPreTrainedModel,
						    FlaxCLIPTextModel,
						    FlaxCLIPTextPreTrainedModel,
						    FlaxCLIPVisionModel,
						    FlaxCLIPVisionPreTrainedModel,
						)


else:
			import sys

			lowerCamelCase_       			=   _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)



