




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

from ...utils import logging


__lowerCamelCase   :						Optional[Any]				=			logging.get_logger(__name__)







def 		lowercase__   (		__A:	List[Any]							,__A:	Optional[int]				):





					'''simple docstring'''






					__magic_name__							:	Optional[int]    							=							nn.functional.normalize(__A				)
					__magic_name__							:	Optional[Any]    							=							nn.functional.normalize(__A				)
					return torch.mm(__A							,normalized_text_embeds.t()				)


class    lowerCamelCase    (		_lowerCamelCase						):






			'''simple docstring'''





			UpperCamelCase__								=CLIPConfig

			UpperCamelCase__								=['''CLIPEncoderLayer''']

			def __init__( self			:   List[str]       ,						lowerCamelCase_			:   CLIPConfig  )						->   List[str]:
								super().__init__(lowerCamelCase_  )

								__magic_name__							:	List[str]    							=							CLIPVisionModel(config.vision_config  )
								__magic_name__							:	Any    							=							nn.Linear(config.vision_config.hidden_size       ,						config.projection_dim       ,						bias=lowerCamelCase_  )

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

								__magic_name__							:	Optional[Any]    							=							nn.Parameter(torch.ones(17  )       ,						requires_grad=lowerCamelCase_  )
								__magic_name__							:	List[Any]    							=							nn.Parameter(torch.ones(3  )       ,						requires_grad=lowerCamelCase_  )

			@torch.no_grad()
			def 							UpperCAmelCase__       ( self			:   List[str]       ,						lowerCamelCase_			:   Tuple       ,						lowerCamelCase_			:   str  )						->   Any:
								__magic_name__							:	Any    							=							self.vision_model(lowerCamelCase_  )[1]  # pooled_output
								__magic_name__							:	Union[str, Any]    							=							self.visual_projection(lowerCamelCase_  )

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

								__magic_name__							:	Optional[int]    							=							[]
								__magic_name__							:	Union[str, Any]    							=							image_embeds.shape[0]
								for i in range(lowerCamelCase_  ):
													__magic_name__							:	List[str]    							=							{'''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__							:	Tuple    							=							0.0

													for concept_idx in range(len(special_cos_dist[0]  )  ):
																		__magic_name__							:	List[str]    							=							special_cos_dist[i][concept_idx]
																		__magic_name__							:	Tuple    							=							self.special_care_embeds_weights[concept_idx].item()
																		__magic_name__							:	Optional[Any]    							=							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__							:	List[str]    							=							0.0_1

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

													result.append(lowerCamelCase_  )

								__magic_name__							:	Any    							=							[len(res['''bad_concepts''']  ) > 0 for res in result]

								return images, has_nsfw_concepts


			@torch.no_grad()
			def 							UpperCAmelCase__       ( self			:   Dict       ,						lowerCamelCase_			:   torch.FloatTensor       ,						lowerCamelCase_			:   torch.FloatTensor  )						->   Dict:
								__magic_name__							:	Dict    							=							self.vision_model(lowerCamelCase_  )[1]  # pooled_output
								__magic_name__							:	Tuple    							=							self.visual_projection(lowerCamelCase_  )

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

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

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

								return images, has_nsfw_concepts








from sklearn.metrics import mean_squared_error

import datasets


__lowerCamelCase   :						List[str]				=			'''\
@article{scikit-learn,
 title={Scikit-learn: Machine Learning in {P}ython},
 author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
 journal={Journal of Machine Learning Research},
 volume={12},
 pages={2825--2830},
 year={2011}
}
'''

__lowerCamelCase   :						Optional[int]				=			'''\
Mean Squared Error(MSE) is the average of the square of difference between the predicted
and actual values.
'''


__lowerCamelCase   :						str				=			'''
Args:
    predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Estimated target values.
    references: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Ground truth (correct) target values.
    sample_weight: array-like of shape (n_samples,), default=None
        Sample weights.
    multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average"
        Defines aggregating of multiple output values. Array-like value defines weights used to average errors.

        "raw_values" : Returns a full set of errors in case of multioutput input.

        "uniform_average" : Errors of all outputs are averaged with uniform weight.

    squared : bool, default=True
        If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.

Returns:
    mse : mean squared error.
Examples:

    >>> mse_metric = datasets.load_metric("mse")
    >>> predictions = [2.5, 0.0, 2, 8]
    >>> references = [3, -0.5, 2, 7]
    >>> results = mse_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'mse\': 0.375}
    >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)
    >>> print(rmse_result)
    {\'mse\': 0.6123724356957945}

    If you\'re using multi-dimensional lists, then set the config as follows :

    >>> mse_metric = datasets.load_metric("mse", "multilist")
    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]
    >>> references = [[0, 2], [-1, 2], [8, -5]]
    >>> results = mse_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'mse\': 0.7083333333333334}
    >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\')
    >>> print(results) # doctest: +NORMALIZE_WHITESPACE
    {\'mse\': array([0.41666667, 1. ])}
'''


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






			'''simple docstring'''





			def 							UpperCAmelCase__       ( self			:   Dict  )						->   Tuple:
								return datasets.MetricInfo(
								    description=_DESCRIPTION       ,						citation=_CITATION       ,						inputs_description=_KWARGS_DESCRIPTION       ,						features=datasets.Features(self._get_feature_types()  )       ,						reference_urls=[
								        '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html'''
								    ]       ,						)

			def 							UpperCAmelCase__       ( self			:   List[Any]  )						->   Any:
								if self.config_name == "multilist":
													return {
													    "predictions": datasets.Sequence(datasets.Value('''float'''  )  ),
													    "references": datasets.Sequence(datasets.Value('''float'''  )  ),
													}
								else:
													return {
													    "predictions": datasets.Value('''float'''  ),
													    "references": datasets.Value('''float'''  ),
													}


			def 							UpperCAmelCase__       ( self			:   Union[str, Any]       ,						lowerCamelCase_			:   Optional[Any]       ,						lowerCamelCase_			:   int       ,						lowerCamelCase_			:   int=None       ,						lowerCamelCase_			:   List[Any]="uniform_average"       ,						lowerCamelCase_			:   List[str]=True  )						->   List[str]:
								__magic_name__							:	Tuple    							=							mean_squared_error(
								    lowerCamelCase_       ,						lowerCamelCase_       ,						sample_weight=lowerCamelCase_       ,						multioutput=lowerCamelCase_       ,						squared=lowerCamelCase_  )

								return {"mse": mse}



