

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

from ...utils import logging


lowerCAmelCase							:  List[str]   	=						logging.get_logger(__name__)







def 			A_      (    _UpperCAmelCase				,	_UpperCAmelCase    ):
						SCREAMING_SNAKE_CASE_: Optional[Any]  		=       nn.functional.normalize(_UpperCAmelCase    )
						SCREAMING_SNAKE_CASE_: List[Any]  		=       nn.functional.normalize(_UpperCAmelCase    )
						return torch.mm(_UpperCAmelCase				,	normalized_text_embeds.t()    )



class   __lowercase				( UpperCAmelCase_	):




			"""simple docstring"""







			_UpperCAmelCase   :							str										=     CLIPConfig

			_UpperCAmelCase   :							Optional[int]										=     ['''CLIPEncoderLayer''']



			def __init__( self  :     List[Any]   ,						lowerCAmelCase__  :     CLIPConfig):
									super().__init__(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: str  		=       CLIPVisionModel(config.vision_config)
									SCREAMING_SNAKE_CASE_: List[str]  		=       nn.Linear(config.vision_config.hidden_size   ,						config.projection_dim   ,						bias=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: str  		=       nn.Parameter(torch.ones(17   ,						config.projection_dim)   ,						requires_grad=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: List[str]  		=       nn.Parameter(torch.ones(3   ,						config.projection_dim)   ,						requires_grad=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: str  		=       nn.Parameter(torch.ones(17)   ,						requires_grad=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: Tuple  		=       nn.Parameter(torch.ones(3)   ,						requires_grad=lowerCAmelCase__)



			@torch.no_grad()
			def        _SCREAMING_SNAKE_CASE			( self  :     int   ,						lowerCAmelCase__  :     List[Any]   ,						lowerCAmelCase__  :     int):
									SCREAMING_SNAKE_CASE_: List[Any]  		=       self.vision_model(lowerCAmelCase__)[1]  # pooled_output
									SCREAMING_SNAKE_CASE_: Tuple  		=       self.visual_projection(lowerCAmelCase__)

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

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

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

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

															result.append(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: Tuple  		=       [len(res["bad_concepts"]) > 0 for res in result]

									return images, has_nsfw_concepts




			@torch.no_grad()
			def        _SCREAMING_SNAKE_CASE			( self  :     List[Any]   ,						lowerCAmelCase__  :     torch.FloatTensor   ,						lowerCAmelCase__  :     torch.FloatTensor):
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       self.vision_model(lowerCAmelCase__)[1]  # pooled_output
									SCREAMING_SNAKE_CASE_: Tuple  		=       self.visual_projection(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: Any  		=       cosine_distance(lowerCAmelCase__   ,						self.special_care_embeds)
									SCREAMING_SNAKE_CASE_: str  		=       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
									SCREAMING_SNAKE_CASE_: Dict  		=       0.0

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

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

									return images, has_nsfw_concepts









def 			A_      (    _UpperCAmelCase    ):
						SCREAMING_SNAKE_CASE_: List[str]  		=       [0] * len(_UpperCAmelCase    )
						SCREAMING_SNAKE_CASE_: List[Any]  		=       []
						SCREAMING_SNAKE_CASE_: str  		=       []
						SCREAMING_SNAKE_CASE_: List[str]  		=       0

						for values in graph.values():
												for i in values:
																		indegree[i] += 1

						for i in range(len(_UpperCAmelCase    )    ):
												if indegree[i] == 0:
																		queue.append(_UpperCAmelCase    )

						while queue:
												SCREAMING_SNAKE_CASE_: Optional[int]  		=       queue.pop(0    )
												cnt += 1
												topo.append(_UpperCAmelCase    )
												for x in graph[vertex]:
																		indegree[x] -= 1
																		if indegree[x] == 0:
																								queue.append(_UpperCAmelCase    )

						if cnt != len(_UpperCAmelCase    ):
												print("Cycle exists"    )
						else:
												print(_UpperCAmelCase    )


# Adjacency List of Graph
lowerCAmelCase							:  Any   	=						{0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []}



topological_sort(graph)






