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     lowerCAmelCase_     :







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







							def  UpperCamelCase_						(   self      :     Union[str, Any]		):
												_UpperCamelCase			     =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

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







							def  UpperCamelCase_						(   self      :     int		):
												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=_A ,			initializer_range=self.initializer_range ,			out_features=self.out_features ,			out_indices=self.out_indices ,			num_labels=self.num_labels ,			)







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







							def  UpperCamelCase_						(   self      :     List[str] ,			_A      :     Union[str, Any] ,			_A      :     Dict ,			_A      :     Any		):
												_UpperCamelCase			     =     ConvNextBackbone(config=_A		)
												model.to(_A		)
												model.eval()
												_UpperCamelCase			     =     model(_A		)

												# 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			     =     None
												_UpperCamelCase			     =     ConvNextBackbone(config=_A		)
												model.to(_A		)
												model.eval()
												_UpperCamelCase			     =     model(_A		)

												# 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  UpperCamelCase_						(   self      :     Tuple		):
												_UpperCamelCase			     =     self.prepare_config_and_inputs()
												_UpperCamelCase     ,    _UpperCamelCase     ,    _UpperCamelCase			     =     config_and_inputs
												_UpperCamelCase			     =     {'''pixel_values''': pixel_values}
												return config, inputs_dict




@require_torch
class     lowerCAmelCase_     (       __lowercase,  __lowercase,  unittest.TestCase ):
							UpperCAmelCase				   =     (
							    (
							        ConvNextModel,
							        ConvNextForImageClassification,
							        ConvNextBackbone,
							    )
							    if is_torch_available()
							    else ()
							)
							UpperCAmelCase				   =     (
							    {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification}
							    if is_torch_available()
							    else {}
							)

							UpperCAmelCase				   =     True
							UpperCAmelCase				   =     False
							UpperCAmelCase				   =     False
							UpperCAmelCase				   =     False
							UpperCAmelCase				   =     False







							def  UpperCamelCase_						(   self      :     Union[str, Any]		):
												_UpperCamelCase			     =     ConvNextModelTester(self		)
												_UpperCamelCase			     =     ConfigTester(self ,			config_class=_A ,			has_text_modality=_A ,			hidden_size=37		)







							def  UpperCamelCase_						(   self      :     str		):
												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  UpperCamelCase_						(   self      :     str		):
												return







							@unittest.skip(reason='''ConvNext does not use inputs_embeds'''		)
							def  UpperCamelCase_						(   self      :     Union[str, Any]		):
												pass







							@unittest.skip(reason='''ConvNext does not support input and output embeddings'''		)
							def  UpperCamelCase_						(   self      :     Optional[Any]		):
												pass







							@unittest.skip(reason='''ConvNext does not use feedforward chunking'''		)
							def  UpperCamelCase_						(   self      :     Optional[int]		):
												pass







							def  UpperCamelCase_						(   self      :     List[str]		):
												_UpperCamelCase     ,    _UpperCamelCase			     =     self.model_tester.prepare_config_and_inputs_for_common()

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

																	_UpperCamelCase			     =     ['''pixel_values''']
																	self.assertListEqual(arg_names[:1] ,			_A		)







							def  UpperCamelCase_						(   self      :     Optional[Any]		):
												_UpperCamelCase			     =     self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*_A		)







							def  UpperCamelCase_						(   self      :     int		):
												_UpperCamelCase			     =     self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_backbone(*_A		)







							def  UpperCamelCase_						(   self      :     List[str]		):
												def check_hidden_states_output(_A      :     int ,			_A      :     Optional[int] ,			_A      :     Dict		):
																	_UpperCamelCase			     =     model_class(_A		)
																	model.to(_A		)
																	model.eval()

																	with torch.no_grad():
																						_UpperCamelCase			     =     model(**self._prepare_for_class(_A ,			_A		)		)

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

																	_UpperCamelCase			     =     self.model_tester.num_stages
																	self.assertEqual(len(_A		) ,			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			     =     self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																	_UpperCamelCase			     =     True
																	check_hidden_states_output(_A ,			_A ,			_A		)

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

																	check_hidden_states_output(_A ,			_A ,			_A		)







							def  UpperCamelCase_						(   self      :     Dict		):
												_UpperCamelCase			     =     self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*_A		)







							@slow
							def  UpperCamelCase_						(   self      :     List[str]		):
												for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	_UpperCamelCase			     =     ConvNextModel.from_pretrained(_A		)
																	self.assertIsNotNone(_A		)




def 					_snake_case	(  ):
					_UpperCamelCase			     =     Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
					return image
@require_torch
@require_vision
class     lowerCAmelCase_     (       unittest.TestCase ):







							@cached_property
							def  UpperCamelCase_						(   self      :     int		):
												return AutoImageProcessor.from_pretrained('''facebook/convnext-tiny-224'''		) if is_vision_available() else None







							@slow
							def  UpperCamelCase_						(   self      :     List[str]		):
												_UpperCamelCase			     =     ConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''		).to(_A		)

												_UpperCamelCase			     =     self.default_image_processor
												_UpperCamelCase			     =     prepare_img()
												_UpperCamelCase			     =     image_processor(images=_A ,			return_tensors='''pt'''		).to(_A		)

												# forward pass
												with torch.no_grad():
																	_UpperCamelCase			     =     model(**_A		)

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

												_UpperCamelCase			     =     torch.tensor([-0.0260, -0.4739, 0.1911]		).to(_A		)

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




@require_torch
class     lowerCAmelCase_     (       unittest.TestCase,  __lowercase ):
							UpperCAmelCase				   =     (ConvNextBackbone,) if is_torch_available() else ()
							UpperCAmelCase				   =     ConvNextConfig

							UpperCAmelCase				   =     False







							def  UpperCamelCase_						(   self      :     Dict		):
												_UpperCamelCase			     =     ConvNextModelTester(self		)


import torch
import torch.nn as nn
from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel

from ...utils import logging


UpperCamelCase_						:     int	       =							logging.get_logger(__name__)



def 		UpperCamelCase     (       _UpperCAmelCase  :   Optional[int] ,			_UpperCAmelCase  :   Dict  )   ->			Any:






						'''simple docstring'''

						_lowercase       :	List[Any]           =   nn.functional.normalize(_UpperCAmelCase  )
						_lowercase       :	List[str]           =   nn.functional.normalize(_UpperCAmelCase  )
						return torch.mm(_UpperCAmelCase ,			normalized_text_embeds.t()  )




class   __lowercase						(						__snake_case       ):
	_A       =   CLIPConfig

	_A       =   ["CLIPEncoderLayer"]






	def __init__(self				: List[str]      ,	snake_case				: CLIPConfig    ) ->			Optional[int]:
							super().__init__(snake_case    )

							_lowercase       :	Tuple           =   CLIPVisionModel(config.vision_config    )
							_lowercase       :	Any           =   nn.Linear(config.vision_config.hidden_size      ,	config.projection_dim      ,	bias=snake_case    )

							_lowercase       :	int           =   nn.Parameter(torch.ones(17      ,	config.projection_dim    )      ,	requires_grad=snake_case    )
							_lowercase       :	str           =   nn.Parameter(torch.ones(3      ,	config.projection_dim    )      ,	requires_grad=snake_case    )

							_lowercase       :	Any           =   nn.Parameter(torch.ones(17    )      ,	requires_grad=snake_case    )
							_lowercase       :	Dict           =   nn.Parameter(torch.ones(3    )      ,	requires_grad=snake_case    )






	@torch.no_grad()
	def       _a(self				: int      ,	snake_case				: Tuple      ,	snake_case				: Optional[Any]    ) ->			Union[str, Any]:
							_lowercase       :	str           =   self.vision_model(snake_case    )[1]  # pooled_output
							_lowercase       :	List[Any]           =   self.visual_projection(snake_case    )

							# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
							_lowercase       :	str           =   cosine_distance(snake_case      ,	self.special_care_embeds    ).cpu().float().numpy()
							_lowercase       :	Optional[int]           =   cosine_distance(snake_case      ,	self.concept_embeds    ).cpu().float().numpy()

							_lowercase       :	List[str]           =   []
							_lowercase       :	int           =   image_embeds.shape[0]
							for i in range(snake_case    ):
													_lowercase       :	int           =   {"special_scores": {}, "special_care": [], "concept_scores": {}, "bad_concepts": []}

													# increase this value to create a stronger `nfsw` filter
													# at the cost of increasing the possibility of filtering benign images
													_lowercase       :	Optional[int]           =   0.0

													for concept_idx in range(len(special_cos_dist[0]    )    ):
																			_lowercase       :	Union[str, Any]           =   special_cos_dist[i][concept_idx]
																			_lowercase       :	Optional[int]           =   self.special_care_embeds_weights[concept_idx].item()
																			_lowercase       :	Optional[int]           =   round(concept_cos - concept_threshold + adjustment      ,	3    )
																			if result_img["special_scores"][concept_idx] > 0:
																									result_img["special_care"].append({concept_idx, result_img["special_scores"][concept_idx]}    )
																									_lowercase       :	Union[str, Any]           =   0.01

													for concept_idx in range(len(cos_dist[0]    )    ):
																			_lowercase       :	Tuple           =   cos_dist[i][concept_idx]
																			_lowercase       :	Union[str, Any]           =   self.concept_embeds_weights[concept_idx].item()
																			_lowercase       :	str           =   round(concept_cos - concept_threshold + adjustment      ,	3    )
																			if result_img["concept_scores"][concept_idx] > 0:
																									result_img["bad_concepts"].append(snake_case    )

													result.append(snake_case    )

							_lowercase       :	Dict           =   [len(res["bad_concepts"]    ) > 0 for res in result]

							return images, has_nsfw_concepts






	@torch.no_grad()
	def       _a(self				: str      ,	snake_case				: torch.FloatTensor      ,	snake_case				: torch.FloatTensor    ) ->			List[str]:
							_lowercase       :	Dict           =   self.vision_model(snake_case    )[1]  # pooled_output
							_lowercase       :	Any           =   self.visual_projection(snake_case    )

							_lowercase       :	Optional[Any]           =   cosine_distance(snake_case      ,	self.special_care_embeds    )
							_lowercase       :	Optional[Any]           =   cosine_distance(snake_case      ,	self.concept_embeds    )

							# increase this value to create a stronger `nsfw` filter
							# at the cost of increasing the possibility of filtering benign images
							_lowercase       :	Optional[int]           =   0.0

							_lowercase       :	Optional[int]           =   special_cos_dist - self.special_care_embeds_weights + adjustment
							# special_scores = special_scores.round(decimals=3)
							_lowercase       :	List[str]           =   torch.any(special_scores > 0      ,	dim=1    )
							_lowercase       :	List[Any]           =   special_care * 0.01
							_lowercase       :	Optional[Any]           =   special_adjustment.unsqueeze(1    ).expand(-1      ,	cos_dist.shape[1]    )

							_lowercase       :	Any           =   (cos_dist - self.concept_embeds_weights) + special_adjustment
							# concept_scores = concept_scores.round(decimals=3)
							_lowercase       :	List[Any]           =   torch.any(concept_scores > 0      ,	dim=1    )

							return images, has_nsfw_concepts




