

'''simple docstring'''

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

from ...utils import logging


a       :      List[Any]  	=			logging.get_logger(__name__)





def 				lowercase (					__magic_name__			,   __magic_name__							):



					'''simple docstring'''







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







class   UpperCamelCase__   (       lowercase__       ):


		"""simple docstring"""

		SCREAMING_SNAKE_CASE__  :     List[str]       =							CLIPConfig

		SCREAMING_SNAKE_CASE__  :     List[Any]       =							["CLIPEncoderLayer"]







		def __init__(			self   ,      snake_case      ):


							'''simple docstring'''

							super().__init__(snake_case      )

							UpperCAmelCase		:							str        =       CLIPVisionModel(config.vision_config      )
							UpperCAmelCase		:							int        =       nn.Linear(config.vision_config.hidden_size   ,      config.projection_dim   ,      bias=snake_case      )

							UpperCAmelCase		:							List[str]        =       nn.Parameter(torch.ones(1_7   ,      config.projection_dim      )   ,      requires_grad=snake_case      )
							UpperCAmelCase		:							str        =       nn.Parameter(torch.ones(3   ,      config.projection_dim      )   ,      requires_grad=snake_case      )

							UpperCAmelCase		:							Union[str, Any]        =       nn.Parameter(torch.ones(1_7      )   ,      requires_grad=snake_case      )
							UpperCAmelCase		:							Optional[int]        =       nn.Parameter(torch.ones(3      )   ,      requires_grad=snake_case      )







		@torch.no_grad()
		def 				A_	(			self   ,      snake_case   ,      snake_case      ):


							'''simple docstring'''

							UpperCAmelCase		:							int        =       self.vision_model(snake_case      )[1]  # pooled_output
							UpperCAmelCase		:							Optional[Any]        =       self.visual_projection(snake_case      )

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

							UpperCAmelCase		:							Optional[int]        =       []
							UpperCAmelCase		:							Tuple        =       image_embeds.shape[0]
							for i in range(snake_case      ):
												UpperCAmelCase		:							List[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
												UpperCAmelCase		:							List[str]        =       0.0

												for concept_idx in range(len(special_cos_dist[0]      )      ):
																	UpperCAmelCase		:							int        =       special_cos_dist[i][concept_idx]
																	UpperCAmelCase		:							int        =       self.special_care_embeds_weights[concept_idx].item()
																	UpperCAmelCase		:							List[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]}      )
																						UpperCAmelCase		:							Any        =       0.01

												for concept_idx in range(len(cos_dist[0]      )      ):
																	UpperCAmelCase		:							int        =       cos_dist[i][concept_idx]
																	UpperCAmelCase		:							Any        =       self.concept_embeds_weights[concept_idx].item()
																	UpperCAmelCase		:							List[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      )

							UpperCAmelCase		:							int        =       [len(res["bad_concepts"]      ) > 0 for res in result]

							for idx, has_nsfw_concept in enumerate(snake_case      ):
												if has_nsfw_concept:
																	if torch.is_tensor(snake_case      ) or torch.is_tensor(images[0]      ):
																						UpperCAmelCase		:							Any        =       torch.zeros_like(images[idx]      )  # black image
																	else:
																						UpperCAmelCase		:							Optional[int]        =       np.zeros(images[idx].shape      )  # black image

							if any(snake_case      ):
												logger.warning(
												    "Potential NSFW content was detected in one or more images. A black image will be returned instead."
												    " Try again with a different prompt and/or seed."      )

							return images, has_nsfw_concepts







		@torch.no_grad()
		def 				A_	(			self   ,      snake_case   ,      snake_case      ):


							'''simple docstring'''

							UpperCAmelCase		:							Optional[Any]        =       self.vision_model(snake_case      )[1]  # pooled_output
							UpperCAmelCase		:							Tuple        =       self.visual_projection(snake_case      )

							UpperCAmelCase		:							List[Any]        =       cosine_distance(snake_case   ,      self.special_care_embeds      )
							UpperCAmelCase		:							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
							UpperCAmelCase		:							Dict        =       0.0

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

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

							UpperCAmelCase		:							Optional[int]        =       0.0  # black image

							return images, has_nsfw_concepts



'''simple docstring'''

from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


a       :      List[Any]  	=			logging.get_logger(__name__)

a       :      Dict  	=			{
    "apple/mobilevitv2-1.0": "https://huggingface.co/apple/mobilevitv2-1.0/resolve/main/config.json",
}







class   UpperCamelCase__   (       lowercase__       ):


		"""simple docstring"""

		SCREAMING_SNAKE_CASE__  :     List[Any]       =							"mobilevitv2"







		def __init__(			self   ,      snake_case=3   ,      snake_case=2_5_6   ,      snake_case=2   ,      snake_case=2.0   ,      snake_case="swish"   ,      snake_case=3   ,      snake_case=3_2   ,      snake_case=0.1   ,      snake_case=0.02   ,      snake_case=1e-5   ,      snake_case=5_1_2   ,      snake_case=[6, 1_2, 1_8]   ,      snake_case=0.1   ,      snake_case=2_5_5   ,      snake_case=[2, 4, 3]   ,      snake_case=[1_2_8, 1_9_2, 2_5_6]   ,      snake_case=1.0   ,      snake_case=2   ,      snake_case=0.0   ,      snake_case=0.0   ,      **snake_case   ,      ):


							'''simple docstring'''

							super().__init__(**snake_case      )

							UpperCAmelCase		:							Tuple        =       num_channels
							UpperCAmelCase		:							Optional[int]        =       image_size
							UpperCAmelCase		:							Optional[int]        =       patch_size
							UpperCAmelCase		:							Optional[int]        =       expand_ratio
							UpperCAmelCase		:							List[Any]        =       hidden_act
							UpperCAmelCase		:							Optional[Any]        =       conv_kernel_size
							UpperCAmelCase		:							str        =       output_stride
							UpperCAmelCase		:							Optional[Any]        =       initializer_range
							UpperCAmelCase		:							Optional[Any]        =       layer_norm_eps
							UpperCAmelCase		:							List[str]        =       n_attn_blocks
							UpperCAmelCase		:							Any        =       base_attn_unit_dims
							UpperCAmelCase		:							str        =       width_multiplier
							UpperCAmelCase		:							Optional[int]        =       ffn_multiplier
							UpperCAmelCase		:							List[Any]        =       ffn_dropout
							UpperCAmelCase		:							List[str]        =       attn_dropout
							UpperCAmelCase		:							Optional[Any]        =       classifier_dropout_prob

							# decode head attributes for semantic segmentation
							UpperCAmelCase		:							Optional[Any]        =       aspp_out_channels
							UpperCAmelCase		:							Dict        =       atrous_rates
							UpperCAmelCase		:							int        =       aspp_dropout_prob
							UpperCAmelCase		:							List[str]        =       semantic_loss_ignore_index







class   UpperCamelCase__   (       lowercase__       ):


		"""simple docstring"""

		SCREAMING_SNAKE_CASE__  :     Optional[int]       =							version.parse("1.11"       )







		@property
		def 				A_	(			self      ):


							'''simple docstring'''

							return OrderedDict([("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"})]      )







		@property
		def 				A_	(			self      ):


							'''simple docstring'''

							if self.task == "image-classification":
												return OrderedDict([("logits", {0: "batch"})]      )
							else:
												return OrderedDict([("last_hidden_state", {0: "batch"}), ("pooler_output", {0: "batch"})]      )







		@property
		def 				A_	(			self      ):


							'''simple docstring'''

							return 1e-4
