



import re

from flax.core.frozen_dict import freeze
from flax.traverse_util import flatten_dict, unflatten_dict
from jax.experimental import PartitionSpec as P


# Sentinels
lowerCamelCase__	=							object()

# For specifying empty leaf dict `{}`
lowerCamelCase__	=							object()


def 							__A(lowerCAmelCase						,  lowerCAmelCase )		->				List[Any]:

		"""simple docstring"""






		_UpperCamelCase						    =	tuple((re.compile(x + """$""" ) for x in qs) )
		for i in range(len(lowerCAmelCase ) - len(lowerCAmelCase ) + 1 ):
				_UpperCamelCase						    =	[x.match(lowerCAmelCase ) for x, y in zip(lowerCAmelCase						,  ks[i:] )]
				if matches and all(lowerCAmelCase ):
						return True
		return False


def 							__A(lowerCAmelCase )		->				Union[str, Any]:

		"""simple docstring"""






		def replace(lowerCAmelCase						,  lowerCAmelCase ):
				for rule, replacement in rules:
						if _match(lowerCAmelCase						,  lowerCAmelCase ):
								return replacement
				return val

		return replace


def 							__A()		->				Tuple:

		"""simple docstring"""






		return [
		    # embeddings
		    (("transformer", "wpe", "embedding"), P("""mp"""						,  lowerCAmelCase )),
		    (("transformer", "wte", "embedding"), P("""mp"""						,  lowerCAmelCase )),
		    # atention
		    (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(lowerCAmelCase						,  """mp""" )),
		    (("attention", "out_proj", "kernel"), P("""mp"""						,  lowerCAmelCase )),
		    (("attention", "out_proj", "bias"), None),
		    # mlp
		    (("mlp", "c_fc", "kernel"), P(lowerCAmelCase						,  """mp""" )),
		    (("mlp", "c_fc", "bias"), P("""mp""" )),
		    (("mlp", "c_proj", "kernel"), P("""mp"""						,  lowerCAmelCase )),
		    (("mlp", "c_proj", "bias"), None),
		    # layer norms
		    ((r"ln_\d+", "bias"), None),
		    ((r"\d+", r"ln_\d+", "scale"), None),
		    (("ln_f", "bias"), None),
		    (("ln_f", "scale"), None),
		]







def 							__A(lowerCAmelCase )		->				str:

		"""simple docstring"""






		_UpperCamelCase						    =	_get_partition_rules()
		_UpperCamelCase						    =	_replacement_rules(lowerCAmelCase )
		_UpperCamelCase						    =	{k: _unmatched for k in flatten_dict(lowerCAmelCase )}
		_UpperCamelCase						    =	{k: replace(lowerCAmelCase						,  lowerCAmelCase ) for k, v in initd.items()}
		assert _unmatched not in result.values(), "Incomplete partition spec."
		return freeze(unflatten_dict(lowerCAmelCase ) )





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

from ...utils import logging


lowerCamelCase__	=							logging.get_logger(__name__)


def 							__A(lowerCAmelCase						,  lowerCAmelCase )		->				List[str]:

		"""simple docstring"""






		_UpperCamelCase						    =	nn.functional.normalize(lowerCAmelCase )
		_UpperCamelCase						    =	nn.functional.normalize(lowerCAmelCase )
		return torch.mm(lowerCAmelCase						,  normalized_text_embeds.t() )







class        lowerCAmelCase__      (   __lowercase	):
						UpperCamelCase_							: Tuple	=		CLIPConfig

						UpperCamelCase_							: str	=		["CLIPEncoderLayer"]

						def __init__(			self       ,							a				)					->      Optional[Any]:


								'''simple docstring'''

								super().__init__(a				)

								_UpperCamelCase						    =	CLIPVisionModel(config.vision_config				)
								_UpperCamelCase						    =	nn.Linear(config.vision_config.hidden_size       ,							config.projection_dim       ,							bias=a				)

								_UpperCamelCase						    =	nn.Parameter(torch.ones(17       ,							config.projection_dim				)       ,							requires_grad=a				)
								_UpperCamelCase						    =	nn.Parameter(torch.ones(3       ,							config.projection_dim				)       ,							requires_grad=a				)

								_UpperCamelCase						    =	nn.Parameter(torch.ones(17				)       ,							requires_grad=a				)
								_UpperCamelCase						    =	nn.Parameter(torch.ones(3				)       ,							requires_grad=a				)

						@torch.no_grad()
						def  A_				(			self       ,							a       ,							a				)					->      str:


								'''simple docstring'''

								_UpperCamelCase						    =	self.vision_model(a				)[1]  # pooled_output
								_UpperCamelCase						    =	self.visual_projection(a				)

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

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

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

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

										result.append(a				)

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

								return images, has_nsfw_concepts







						@torch.no_grad()
						def  A_				(			self       ,							a       ,							a				)					->      Any:


								'''simple docstring'''

								_UpperCamelCase						    =	self.vision_model(a				)[1]  # pooled_output
								_UpperCamelCase						    =	self.visual_projection(a				)

								_UpperCamelCase						    =	cosine_distance(a       ,							self.special_care_embeds				)
								_UpperCamelCase						    =	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
								_UpperCamelCase						    =	0.0

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

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

								return images, has_nsfw_concepts



