




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

from ...utils import logging


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




def 		lowerCAmelCase_ (						lowerCamelCase						,  lowerCamelCase ):
				__magic_name__						:						Tuple										=nn.functional.normalize(lowerCamelCase )
				__magic_name__						:						Optional[int]										=nn.functional.normalize(lowerCamelCase )
				return torch.mm(lowerCamelCase						,  normalized_text_embeds.t() )




class 		__A   (      UpperCamelCase__      ):
						UpperCamelCase      =       CLIPConfig

						UpperCamelCase      =       ["""CLIPEncoderLayer"""]

						def __init__(		self :Any     ,			__snake_case :CLIPConfig			):
										'''simple docstring'''

										super().__init__(__snake_case			)

										__magic_name__						:						Optional[Any]										=CLIPVisionModel(config.vision_config			)
										__magic_name__						:						Any										=nn.Linear(config.vision_config.hidden_size     ,			config.projection_dim     ,			bias=__snake_case			)

										__magic_name__						:						List[Any]										=nn.Parameter(torch.ones(17     ,			config.projection_dim			)     ,			requires_grad=__snake_case			)
										__magic_name__						:						int										=nn.Parameter(torch.ones(3     ,			config.projection_dim			)     ,			requires_grad=__snake_case			)

										__magic_name__						:						List[str]										=nn.Parameter(torch.ones(17			)     ,			requires_grad=__snake_case			)
										__magic_name__						:						Tuple										=nn.Parameter(torch.ones(3			)     ,			requires_grad=__snake_case			)

						@torch.no_grad()
						def      A__    (		self :Optional[Any]     ,			__snake_case :List[Any]     ,			__snake_case :str			):
										'''simple docstring'''

										__magic_name__						:						Union[str, Any]										=self.vision_model(__snake_case			)[1]  # pooled_output
										__magic_name__						:						Tuple										=self.visual_projection(__snake_case			)

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

										__magic_name__						:						Dict										=[]
										__magic_name__						:						Any										=image_embeds.shape[0]
										for i in range(__snake_case			):
														__magic_name__						:						Optional[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
														__magic_name__						:						Dict										=0.0

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

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

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

										return images, has_nsfw_concepts


						@torch.no_grad()
						def      A__    (		self :Tuple     ,			__snake_case :torch.FloatTensor     ,			__snake_case :torch.FloatTensor			):
										'''simple docstring'''

										__magic_name__						:						Dict										=self.vision_model(__snake_case			)[1]  # pooled_output
										__magic_name__						:						Union[str, Any]										=self.visual_projection(__snake_case			)

										__magic_name__						:						Optional[Any]										=cosine_distance(__snake_case     ,			self.special_care_embeds			)
										__magic_name__						:						str										=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
										__magic_name__						:						str										=0.0

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

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

										return images, has_nsfw_concepts








import datasets


snake_case							:       int										=	'''\
@InProceedings{conneau2018xnli,
  author = "Conneau, Alexis
                 and Rinott, Ruty
                 and Lample, Guillaume
                 and Williams, Adina
                 and Bowman, Samuel R.
                 and Schwenk, Holger
                 and Stoyanov, Veselin",
  title = "XNLI: Evaluating Cross-lingual Sentence Representations",
  booktitle = "Proceedings of the 2018 Conference on Empirical Methods
               in Natural Language Processing",
  year = "2018",
  publisher = "Association for Computational Linguistics",
  location = "Brussels, Belgium",
}
'''

snake_case							:       Tuple										=	'''\
XNLI is a subset of a few thousand examples from MNLI which has been translated
into a 14 different languages (some low-ish resource). As with MNLI, the goal is
to predict textual entailment (does sentence A imply/contradict/neither sentence
B) and is a classification task (given two sentences, predict one of three
labels).
'''

snake_case							:       Union[str, Any]										=	'''
Computes XNLI score which is just simple accuracy.
Args:
    predictions: Predicted labels.
    references: Ground truth labels.
Returns:
    \'accuracy\': accuracy
Examples:

    >>> predictions = [0, 1]
    >>> references = [0, 1]
    >>> xnli_metric = datasets.load_metric("xnli")
    >>> results = xnli_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'accuracy\': 1.0}
'''
def 							__lowerCamelCase		(					UpperCAmelCase_		:						List[Any]					,    UpperCAmelCase_		:						List[str]		):




      """simple docstring"""





      return (preds == labels).mean()







@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION		,       _KWARGS_DESCRIPTION				)
class 						_snake_case    ( datasets.Metric				):




 def 			SCREAMING_SNAKE_CASE__							(						self       ):
       return datasets.MetricInfo(
           description=_DESCRIPTION   ,    citation=_CITATION   ,    inputs_description=_KWARGS_DESCRIPTION   ,    features=datasets.Features(
               {
                   '''predictions''': datasets.Value('''int64''' if self.config_name != '''sts-b''' else '''float32'''       ),
                   '''references''': datasets.Value('''int64''' if self.config_name != '''sts-b''' else '''float32'''       ),
               }       )   ,    codebase_urls=[]   ,    reference_urls=[]   ,    format='''numpy'''   ,    )




 def 			SCREAMING_SNAKE_CASE__							(						self   ,    _lowerCamelCase   ,    _lowerCamelCase       ):
       return {"accuracy": simple_accuracy(_lowerCamelCase   ,    _lowerCamelCase       )}





