

'''simple docstring'''







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

from ...utils import logging


_lowerCamelCase    =  logging.get_logger(__name__)






def 					_SCREAMING_SNAKE_CASE		(						snake_case_							,       snake_case_	):
	_lowercase							=     nn.functional.normalize(snake_case_	)
	_lowercase							=     nn.functional.normalize(snake_case_	)
	return torch.mm(snake_case_							,       normalized_text_embeds.t()	)





class 					__a   (		_snake_case  ):
						__SCREAMING_SNAKE_CASE     :					Optional[Any]  =      CLIPConfig

						__SCREAMING_SNAKE_CASE     :					List[Any]  =      ['CLIPEncoderLayer']

						def __init__(		self	:						Dict    ,			lowercase__	:						CLIPConfig)						->str:

							"""simple docstring"""



							super().__init__(lowercase__)

							_lowercase							=     CLIPVisionModel(config.vision_config)
							_lowercase							=     nn.Linear(config.vision_config.hidden_size    ,			config.projection_dim    ,			bias=lowercase__)

							_lowercase							=     nn.Parameter(torch.ones(17    ,			config.projection_dim)    ,			requires_grad=lowercase__)
							_lowercase							=     nn.Parameter(torch.ones(3    ,			config.projection_dim)    ,			requires_grad=lowercase__)

							_lowercase							=     nn.Parameter(torch.ones(17)    ,			requires_grad=lowercase__)
							_lowercase							=     nn.Parameter(torch.ones(3)    ,			requires_grad=lowercase__)

						@torch.no_grad()
						def 	_UpperCAmelCase							(		self	:						List[Any]    ,			lowercase__	:						List[Any]    ,			lowercase__	:						Any)						->Optional[int]:

							"""simple docstring"""



							_lowercase							=     self.vision_model(lowercase__)[1]  # pooled_output
							_lowercase							=     self.visual_projection(lowercase__)

							# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
							_lowercase							=     cosine_distance(lowercase__    ,			self.special_care_embeds).cpu().float().numpy()
							_lowercase							=     cosine_distance(lowercase__    ,			self.concept_embeds).cpu().float().numpy()

							_lowercase							=     []
							_lowercase							=     image_embeds.shape[0]
							for i in range(lowercase__):
								_lowercase							=     {"""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							=     0.0

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

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

								result.append(lowercase__)

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

							for idx, has_nsfw_concept in enumerate(lowercase__):
								if has_nsfw_concept:
									if torch.is_tensor(lowercase__) or torch.is_tensor(images[0]):
										_lowercase							=     torch.zeros_like(images[idx])  # black image
									else:
										_lowercase							=     np.zeros(images[idx].shape)  # black image

							if any(lowercase__):
								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 	_UpperCAmelCase							(		self	:						int    ,			lowercase__	:						torch.FloatTensor    ,			lowercase__	:						torch.FloatTensor)						->Tuple:

							"""simple docstring"""



							_lowercase							=     self.vision_model(lowercase__)[1]  # pooled_output
							_lowercase							=     self.visual_projection(lowercase__)

							_lowercase							=     cosine_distance(lowercase__    ,			self.special_care_embeds)
							_lowercase							=     cosine_distance(lowercase__    ,			self.concept_embeds)

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

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

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

							_lowercase							=     0.0  # black image

							return images, has_nsfw_concepts







'''simple docstring'''







from __future__ import annotations

from collections.abc import Generator






def 					_SCREAMING_SNAKE_CASE		(						snake_case_	):
	if not isinstance(snake_case_							,       snake_case_	) or n < 1:
		raise Exception("""Sequence only defined for positive integers"""	)

	yield n
	while n != 1:
		if n % 2 == 0:
			n //= 2
		else:
			_lowercase							=     3 * n + 1
		yield n






def 					_SCREAMING_SNAKE_CASE		(						):
	_lowercase							=     43
	_lowercase							=     tuple(collatz_sequence(snake_case_	)	)
	print(snake_case_	)
	print(F"""Collatz sequence from {n} took {len(snake_case_	)} steps."""	)


if __name__ == "__main__":
							main()




