





'''simple docstring'''






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

from ...utils import logging


lowerCAmelCase       		=      logging.get_logger(__name__)






def      __A						(							a_						:  Optional[int]      ,a_						:  Optional[Any]	):
		lowerCAmelCase     :    List[str]						=   nn.functional.normalize(a_	)
		lowerCAmelCase     :    Dict						=   nn.functional.normalize(a_	)
		return torch.mm(a_      ,normalized_text_embeds.t()	)

class 		lowerCamelCase  (      _A       ):
	snake_case_      =   CLIPConfig

	snake_case_      =   ["CLIPEncoderLayer"]



	def __init__(   self		,      a_	):
			super().__init__(a_	)

			lowerCAmelCase     :    Dict						=   CLIPVisionModel(config.vision_config	)
			lowerCAmelCase     :    Optional[Any]						=   nn.Linear(config.vision_config.hidden_size		,      config.projection_dim		,      bias=a_	)

			lowerCAmelCase     :    Tuple						=   nn.Parameter(torch.ones(17		,      config.projection_dim	)		,      requires_grad=a_	)
			lowerCAmelCase     :    List[str]						=   nn.Parameter(torch.ones(3		,      config.projection_dim	)		,      requires_grad=a_	)

			lowerCAmelCase     :    Optional[int]						=   nn.Parameter(torch.ones(17	)		,      requires_grad=a_	)
			lowerCAmelCase     :    List[str]						=   nn.Parameter(torch.ones(3	)		,      requires_grad=a_	)



	@torch.no_grad()
	def   _lowerCamelCase    (   self		,      a_		,      a_	):
			lowerCAmelCase     :    Optional[int]						=   self.vision_model(a_	)[1]  # pooled_output
			lowerCAmelCase     :    str						=   self.visual_projection(a_	)

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

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

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

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

					result.append(a_	)

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

			return images, has_nsfw_concepts





	@torch.no_grad()
	def   _lowerCamelCase    (   self		,      a_		,      a_	):
			lowerCAmelCase     :    Dict						=   self.vision_model(a_	)[1]  # pooled_output
			lowerCAmelCase     :    Tuple						=   self.visual_projection(a_	)

			lowerCAmelCase     :    Dict						=   cosine_distance(a_		,      self.special_care_embeds	)
			lowerCAmelCase     :    Union[str, Any]						=   cosine_distance(a_		,      self.concept_embeds	)

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

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

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

			return images, has_nsfw_concepts










'''simple docstring'''






def      __A						(							a_						:  int	):
		assert (
		    isinstance(a_      ,a_	) and number_of_steps > 0
		), f'''number_of_steps needs to be positive integer, your input {number_of_steps}'''
		if number_of_steps == 1:
				return 1
		lowerCAmelCase	,		lowerCAmelCase     :    int						=   1, 1
		for _ in range(number_of_steps - 1	):
				lowerCAmelCase	,		lowerCAmelCase     :    Union[str, Any]						=   current + previous, current
		return current


if __name__ == "__main__":
					import doctest

					doctest.testmod()



