






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

from ...utils import logging


__magic_name__:					str							=     logging.get_logger(__name__)

def    UpperCamelCase						(	_A,   _A			):






						"""simple docstring"""







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





class 	snake_case__ (							_lowerCAmelCase				):
	lowercase__						:					List[str]											=   CLIPConfig

	lowercase__						:					Dict											=   ['''CLIPEncoderLayer''']
	def __init__(    self      ,       lowerCAmelCase__			)							->				Any:
							super().__init__(lowerCAmelCase__			)

							__magic_name__      :       Tuple       						= CLIPVisionModel(config.vision_config			)
							__magic_name__      :       Optional[int]       						= nn.Linear(config.vision_config.hidden_size      ,       config.projection_dim      ,       bias=lowerCAmelCase__			)

							__magic_name__      :       str       						= nn.Parameter(torch.ones(17      ,       config.projection_dim			)      ,       requires_grad=lowerCAmelCase__			)
							__magic_name__      :       str       						= nn.Parameter(torch.ones(3      ,       config.projection_dim			)      ,       requires_grad=lowerCAmelCase__			)

							__magic_name__      :       Tuple       						= nn.Parameter(torch.ones(17			)      ,       requires_grad=lowerCAmelCase__			)
							__magic_name__      :       Optional[Any]       						= nn.Parameter(torch.ones(3			)      ,       requires_grad=lowerCAmelCase__			)
	@torch.no_grad()
	def       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				List[str]:
							__magic_name__      :       Any       						= self.vision_model(lowerCAmelCase__			)[1]  # pooled_output
							__magic_name__      :       Any       						= self.visual_projection(lowerCAmelCase__			)

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

							__magic_name__      :       Dict       						= []
							__magic_name__      :       Union[str, Any]       						= image_embeds.shape[0]
							for i in range(lowerCAmelCase__			):
													__magic_name__      :       Union[str, Any]       						= {"""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
													__magic_name__      :       List[str]       						= 0.0

													for concept_idx in range(len(special_cos_dist[0]			)			):
																			__magic_name__      :       Dict       						= special_cos_dist[i][concept_idx]
																			__magic_name__      :       Dict       						= self.special_care_embeds_weights[concept_idx].item()
																			__magic_name__      :       Optional[Any]       						= 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]}			)
																									__magic_name__      :       Any       						= 0.0_1

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

													result.append(lowerCAmelCase__			)

							__magic_name__      :       Any       						= [len(res["""bad_concepts"""]			) > 0 for res in result]

							return images, has_nsfw_concepts







	@torch.no_grad()
	def       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				List[Any]:
							__magic_name__      :       Dict       						= self.vision_model(lowerCAmelCase__			)[1]  # pooled_output
							__magic_name__      :       Any       						= self.visual_projection(lowerCAmelCase__			)

							__magic_name__      :       Tuple       						= cosine_distance(lowerCAmelCase__      ,       self.special_care_embeds			)
							__magic_name__      :       Union[str, Any]       						= cosine_distance(lowerCAmelCase__      ,       self.concept_embeds			)

							# increase this value to create a stronger `nsfw` filter
							# at the cost of increasing the possibility of filtering benign images
							__magic_name__      :       Any       						= 0.0

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

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

							return images, has_nsfw_concepts








from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import DeiTConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
		import tensorflow as tf

		from transformers import (
		    TFDeiTForImageClassification,
		    TFDeiTForImageClassificationWithTeacher,
		    TFDeiTForMaskedImageModeling,
		    TFDeiTModel,
		)
		from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import DeiTImageProcessor





class 	snake_case__ :
	def __init__(    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__=13      ,       lowerCAmelCase__=30      ,       lowerCAmelCase__=2      ,       lowerCAmelCase__=3      ,       lowerCAmelCase__=True      ,       lowerCAmelCase__=True      ,       lowerCAmelCase__=32      ,       lowerCAmelCase__=2      ,       lowerCAmelCase__=4      ,       lowerCAmelCase__=37      ,       lowerCAmelCase__="gelu"      ,       lowerCAmelCase__=0.1      ,       lowerCAmelCase__=0.1      ,       lowerCAmelCase__=10      ,       lowerCAmelCase__=0.0_2      ,       lowerCAmelCase__=3      ,       lowerCAmelCase__=None      ,       lowerCAmelCase__=2      ,       )							->				Optional[Any]:
							__magic_name__      :       Optional[Any]       						= parent
							__magic_name__      :       List[str]       						= batch_size
							__magic_name__      :       Union[str, Any]       						= image_size
							__magic_name__      :       Optional[Any]       						= patch_size
							__magic_name__      :       Union[str, Any]       						= num_channels
							__magic_name__      :       Union[str, Any]       						= is_training
							__magic_name__      :       Union[str, Any]       						= use_labels
							__magic_name__      :       Tuple       						= hidden_size
							__magic_name__      :       List[str]       						= num_hidden_layers
							__magic_name__      :       Optional[Any]       						= num_attention_heads
							__magic_name__      :       Tuple       						= intermediate_size
							__magic_name__      :       Union[str, Any]       						= hidden_act
							__magic_name__      :       str       						= hidden_dropout_prob
							__magic_name__      :       List[str]       						= attention_probs_dropout_prob
							__magic_name__      :       Tuple       						= type_sequence_label_size
							__magic_name__      :       Any       						= initializer_range
							__magic_name__      :       str       						= scope
							__magic_name__      :       str       						= encoder_stride

							# in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
							__magic_name__      :       Dict       						= (image_size // patch_size) ** 2
							__magic_name__      :       int       						= num_patches + 2
	def       __magic_name__    (    self			)							->				Union[str, Any]:
							__magic_name__      :       Union[str, Any]       						= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

							__magic_name__      :       Tuple       						= None
							if self.use_labels:
													__magic_name__      :       Any       						= ids_tensor([self.batch_size]      ,       self.type_sequence_label_size			)

							__magic_name__      :       Union[str, Any]       						= self.get_config()

							return config, pixel_values, labels
	def       __magic_name__    (    self			)							->				List[str]:
							return DeiTConfig(
							    image_size=self.image_size      ,       patch_size=self.patch_size      ,       num_channels=self.num_channels      ,       hidden_size=self.hidden_size      ,       num_hidden_layers=self.num_hidden_layers      ,       num_attention_heads=self.num_attention_heads      ,       intermediate_size=self.intermediate_size      ,       hidden_act=self.hidden_act      ,       hidden_dropout_prob=self.hidden_dropout_prob      ,       attention_probs_dropout_prob=self.attention_probs_dropout_prob      ,       is_decoder=lowerCAmelCase__      ,       initializer_range=self.initializer_range      ,       encoder_stride=self.encoder_stride      ,       )
	def       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				Any:
							__magic_name__      :       int       						= TFDeiTModel(config=lowerCAmelCase__			)
							__magic_name__      :       List[Any]       						= model(lowerCAmelCase__			)
							self.parent.assertEqual(result.last_hidden_state.shape      ,       (self.batch_size, self.seq_length, self.hidden_size)			)
	def       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				Optional[Any]:
							__magic_name__      :       int       						= TFDeiTForMaskedImageModeling(config=lowerCAmelCase__			)
							__magic_name__      :       List[str]       						= model(lowerCAmelCase__			)
							self.parent.assertEqual(
							    result.reconstruction.shape      ,       (self.batch_size, self.num_channels, self.image_size, self.image_size)			)

							# test greyscale images
							__magic_name__      :       Tuple       						= 1
							__magic_name__      :       List[Any]       						= TFDeiTForMaskedImageModeling(lowerCAmelCase__			)

							__magic_name__      :       Union[str, Any]       						= floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
							__magic_name__      :       Any       						= model(lowerCAmelCase__			)
							self.parent.assertEqual(result.reconstruction.shape      ,       (self.batch_size, 1, self.image_size, self.image_size)			)
	def       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				Tuple:
							__magic_name__      :       Union[str, Any]       						= self.type_sequence_label_size
							__magic_name__      :       str       						= TFDeiTForImageClassification(lowerCAmelCase__			)
							__magic_name__      :       List[str]       						= model(lowerCAmelCase__      ,       labels=lowerCAmelCase__			)
							self.parent.assertEqual(result.logits.shape      ,       (self.batch_size, self.type_sequence_label_size)			)

							# test greyscale images
							__magic_name__      :       int       						= 1
							__magic_name__      :       List[str]       						= TFDeiTForImageClassification(lowerCAmelCase__			)

							__magic_name__      :       List[str]       						= floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
							__magic_name__      :       Dict       						= model(lowerCAmelCase__      ,       labels=lowerCAmelCase__			)
							self.parent.assertEqual(result.logits.shape      ,       (self.batch_size, self.type_sequence_label_size)			)







	def       __magic_name__    (    self			)							->				List[str]:
							__magic_name__      :       Union[str, Any]       						= self.prepare_config_and_inputs()
							__magic_name__						,__magic_name__						,__magic_name__      :       Union[str, Any]       						= config_and_inputs
							__magic_name__      :       str       						= {"""pixel_values""": pixel_values}
							return config, inputs_dict





@require_tf
class 	snake_case__ (							_lowerCAmelCase						,  _lowerCAmelCase						,  unittest.TestCase				):
	lowercase__						:					int											=   (
	    (
	        TFDeiTModel,
	        TFDeiTForImageClassification,
	        TFDeiTForImageClassificationWithTeacher,
	        TFDeiTForMaskedImageModeling,
	    )
	    if is_tf_available()
	    else ()
	)
	lowercase__						:					Any											=   (
	    {
	        '''feature-extraction''': TFDeiTModel,
	        '''image-classification''': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
	    }
	    if is_tf_available()
	    else {}
	)

	lowercase__						:					int											=   False
	lowercase__						:					List[Any]											=   False
	lowercase__						:					Tuple											=   False
	lowercase__						:					int											=   False
	def       __magic_name__    (    self			)							->				str:
							__magic_name__      :       str       						= TFDeiTModelTester(self			)
							__magic_name__      :       Optional[Any]       						= ConfigTester(self      ,       config_class=lowerCAmelCase__      ,       has_text_modality=lowerCAmelCase__      ,       hidden_size=37			)
	def       __magic_name__    (    self			)							->				Tuple:
							self.config_tester.run_common_tests()
	@unittest.skip(reason="""DeiT does not use inputs_embeds"""			)
	def       __magic_name__    (    self			)							->				Union[str, Any]:
							pass
	def       __magic_name__    (    self			)							->				Union[str, Any]:
							__magic_name__						,__magic_name__      :       Optional[Any]       						= self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													__magic_name__      :       List[Any]       						= model_class(lowerCAmelCase__			)
													self.assertIsInstance(model.get_input_embeddings()      ,       (tf.keras.layers.Layer)			)
													__magic_name__      :       Tuple       						= model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(lowerCAmelCase__      ,       tf.keras.layers.Dense			)			)
	def       __magic_name__    (    self			)							->				Optional[int]:
							__magic_name__						,__magic_name__      :       str       						= self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													__magic_name__      :       Any       						= model_class(lowerCAmelCase__			)
													__magic_name__      :       List[Any]       						= inspect.signature(model.call			)
													# signature.parameters is an OrderedDict => so arg_names order is deterministic
													__magic_name__      :       int       						= [*signature.parameters.keys()]

													__magic_name__      :       List[str]       						= ["""pixel_values"""]
													self.assertListEqual(arg_names[:1]      ,       lowerCAmelCase__			)
	def       __magic_name__    (    self			)							->				List[str]:
							__magic_name__      :       Union[str, Any]       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowerCAmelCase__			)
	def       __magic_name__    (    self			)							->				Tuple:
							__magic_name__      :       Any       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_image_modeling(*lowerCAmelCase__			)
	def       __magic_name__    (    self			)							->				Any:
							__magic_name__      :       Union[str, Any]       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__			)
	def       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__=False			)							->				str:
							__magic_name__      :       Any       						= super()._prepare_for_class(lowerCAmelCase__      ,       lowerCAmelCase__      ,       return_labels=lowerCAmelCase__			)

							if return_labels:
													if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call			).parameters:
																			del inputs_dict["labels"]

							return inputs_dict







	@slow
	def       __magic_name__    (    self			)							->				Dict:
							for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													__magic_name__      :       int       						= TFDeiTModel.from_pretrained(lowerCAmelCase__			)
													self.assertIsNotNone(lowerCAmelCase__			)



def    UpperCamelCase						(	):






						"""simple docstring"""







						__magic_name__      :       List[Any]       						= Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			)
						return image





@require_tf
@require_vision
class 	snake_case__ (							unittest.TestCase				):
	@cached_property
	def       __magic_name__    (    self			)							->				Optional[int]:
							return (
							    DeiTImageProcessor.from_pretrained("""facebook/deit-base-distilled-patch16-224"""			)
							    if is_vision_available()
							    else None
							)







	@slow
	def       __magic_name__    (    self			)							->				List[Any]:
							__magic_name__      :       Optional[int]       						= TFDeiTForImageClassificationWithTeacher.from_pretrained("""facebook/deit-base-distilled-patch16-224"""			)

							__magic_name__      :       Any       						= self.default_image_processor
							__magic_name__      :       Tuple       						= prepare_img()
							__magic_name__      :       Tuple       						= image_processor(images=lowerCAmelCase__      ,       return_tensors="""tf"""			)

							# forward pass
							__magic_name__      :       Dict       						= model(**lowerCAmelCase__			)

							# verify the logits
							__magic_name__      :       Optional[Any]       						= tf.TensorShape((1, 10_00)			)
							self.assertEqual(outputs.logits.shape      ,       lowerCAmelCase__			)

							__magic_name__      :       List[Any]       						= tf.constant([-1.0_2_6_6, 0.1_9_1_2, -1.2_8_6_1]			)

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