






import csv
from collections import defaultdict
from dataclasses import dataclass, field
from typing import List, Optional

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import ScalarFormatter

from transformers import HfArgumentParser
def 		lowercase__  (				_UpperCamelCase=None       ,							_UpperCamelCase=None) ->			Tuple:
      """simple docstring"""

      return field(default_factory=lambda: default       ,							metadata=_UpperCAmelCase)





@dataclass
class 					A__     :

     '''simple docstring'''






     snake_case__					=					field(
         metadata={"""help""": """The csv file to plot."""}   ,    )
     snake_case__					=					field(
         default=__snake_case   ,    metadata={"""help""": """Whether to plot along batch size or sequence length. Defaults to sequence length."""}   ,    )
     snake_case__					=					field(
         default=__snake_case   ,    metadata={"""help""": """Whether the csv file has time results or memory results. Defaults to memory results."""}   ,    )
     snake_case__					=					field(
         default=__snake_case   ,    metadata={"""help""": """Disable logarithmic scale when plotting"""}   ,    )
     snake_case__					=					field(
         default=__snake_case   ,    metadata={
             """help""": """Whether the csv file has training results or inference results. Defaults to inference results."""
         }   ,    )
     snake_case__					=					field(
         default=__snake_case   ,    metadata={"""help""": """Filename under which the plot will be saved. If unused no plot is saved."""}   ,    )
     snake_case__					=					list_field(
         default=__snake_case   ,    metadata={"""help""": """List of model names that are used instead of the ones in the csv file."""} )

def 		lowercase__  (				_UpperCamelCase) ->			str:
      """simple docstring"""

      try:
            int(_UpperCAmelCase)
            return True
      except ValueError:
            return False
def 		lowercase__  (				_UpperCamelCase) ->			str:
      """simple docstring"""

      try:
            float(_UpperCAmelCase)
            return True
      except ValueError:
            return False





class 					A__     :

     '''simple docstring'''






     def __init__( self      :    Optional[Any]   ,						_SCREAMING_SNAKE_CASE      :    List[Any] ):






           """simple docstring"""




           UpperCamelCase					       =  args
           UpperCamelCase					       =  defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}} )

           with open(self.args.csv_file   ,						newline='' ) as csv_file:
                 UpperCamelCase					       =  csv.DictReader(_SCREAMING_SNAKE_CASE )
                 for row in reader:
                       UpperCamelCase					       =  row["model"]
                       self.result_dict[model_name]["bsz"].append(int(row['batch_size'] ) )
                       self.result_dict[model_name]["seq_len"].append(int(row['sequence_length'] ) )
                       if can_convert_to_int(row['result'] ):
                             # value is not None
                             UpperCamelCase					       =  int(row['result'] )
                       elif can_convert_to_float(row['result'] ):
                             # value is not None
                             UpperCamelCase					       =  float(row['result'] )







     def   _SCREAMING_SNAKE_CASE     ( self      :    List[str] ):






           """simple docstring"""




           UpperCamelCase					       =  plt.subplots()
           UpperCamelCase					       =  "Time usage" if self.args.is_time else "Memory usage"
           UpperCamelCase					       =  title_str + " for training" if self.args.is_train else title_str + " for inference"

           if not self.args.no_log_scale:
                 # set logarithm scales
                 ax.set_xscale('log' )
                 ax.set_yscale('log' )

           for axis in [ax.xaxis, ax.yaxis]:
                 axis.set_major_formatter(ScalarFormatter() )

           for model_name_idx, model_name in enumerate(self.result_dict.keys() ):
                 UpperCamelCase					       =  sorted(set(self.result_dict[model_name]['bsz'] ) )
                 UpperCamelCase					       =  sorted(set(self.result_dict[model_name]['seq_len'] ) )
                 UpperCamelCase					       =  self.result_dict[model_name]["result"]

                 (UpperCamelCase)					       =  (
                     (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes)
                 )

                 UpperCamelCase					       =  (
                     model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx]
                 )

                 for inner_loop_value in inner_loop_array:
                       if self.args.plot_along_batch:
                             UpperCamelCase					       =  np.asarray(
                                 [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results]   ,						dtype=_SCREAMING_SNAKE_CASE   ,						)
                       else:
                             UpperCamelCase					       =  np.asarray(
                                 [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results]   ,						dtype=np.floataa   ,						)

                       (UpperCamelCase)					       =  (
                           ("batch_size", "len") if self.args.plot_along_batch else ("in #tokens", "bsz")
                       )

                       UpperCamelCase					       =  np.asarray(_SCREAMING_SNAKE_CASE   ,						_SCREAMING_SNAKE_CASE )[: len(_SCREAMING_SNAKE_CASE )]
                       plt.scatter(
                           _SCREAMING_SNAKE_CASE   ,						_SCREAMING_SNAKE_CASE   ,						label=f'{label_model_name} - {inner_loop_label}: {inner_loop_value}' )
                       plt.plot(_SCREAMING_SNAKE_CASE   ,						_SCREAMING_SNAKE_CASE   ,						'--' )

                 title_str += f' {label_model_name} vs.'

           UpperCamelCase					       =  title_str[:-4]
           UpperCamelCase					       =  "Time in s" if self.args.is_time else "Memory in MB"

           # plot
           plt.title(_SCREAMING_SNAKE_CASE )
           plt.xlabel(_SCREAMING_SNAKE_CASE )
           plt.ylabel(_SCREAMING_SNAKE_CASE )
           plt.legend()

           if self.args.figure_png_file is not None:
                 plt.savefig(self.args.figure_png_file )
           else:
                 plt.show()

def 		lowercase__  (				) ->			List[str]:
      """simple docstring"""

      UpperCamelCase					       =  HfArgumentParser(_UpperCAmelCase)
      UpperCamelCase					       =  parser.parse_args_into_dataclasses()[0]
      UpperCamelCase					       =  Plot(args=_UpperCAmelCase)
      plot.plot()


if __name__ == "__main__":
       main()





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

from ...utils import logging


UpperCamelCase_						:     int	       =							logging.get_logger(__name__)



def 		UpperCamelCase     (       _UpperCAmelCase  :   Optional[int] ,			_UpperCAmelCase  :   Dict  )   ->			Any:






						'''simple docstring'''

						_lowercase       :	List[Any]           =   nn.functional.normalize(_UpperCAmelCase  )
						_lowercase       :	List[str]           =   nn.functional.normalize(_UpperCAmelCase  )
						return torch.mm(_UpperCAmelCase ,			normalized_text_embeds.t()  )




class   __lowercase						(						__snake_case       ):
	_A       =   CLIPConfig

	_A       =   ["CLIPEncoderLayer"]






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

							_lowercase       :	Tuple           =   CLIPVisionModel(config.vision_config    )
							_lowercase       :	Any           =   nn.Linear(config.vision_config.hidden_size      ,	config.projection_dim      ,	bias=snake_case    )

							_lowercase       :	int           =   nn.Parameter(torch.ones(17      ,	config.projection_dim    )      ,	requires_grad=snake_case    )
							_lowercase       :	str           =   nn.Parameter(torch.ones(3      ,	config.projection_dim    )      ,	requires_grad=snake_case    )

							_lowercase       :	Any           =   nn.Parameter(torch.ones(17    )      ,	requires_grad=snake_case    )
							_lowercase       :	Dict           =   nn.Parameter(torch.ones(3    )      ,	requires_grad=snake_case    )






	@torch.no_grad()
	def       _a(self				: int      ,	snake_case				: Tuple      ,	snake_case				: Optional[Any]    ) ->			Union[str, Any]:
							_lowercase       :	str           =   self.vision_model(snake_case    )[1]  # pooled_output
							_lowercase       :	List[Any]           =   self.visual_projection(snake_case    )

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

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

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

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

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

							return images, has_nsfw_concepts






	@torch.no_grad()
	def       _a(self				: str      ,	snake_case				: torch.FloatTensor      ,	snake_case				: torch.FloatTensor    ) ->			List[str]:
							_lowercase       :	Dict           =   self.vision_model(snake_case    )[1]  # pooled_output
							_lowercase       :	Any           =   self.visual_projection(snake_case    )

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

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

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

							return images, has_nsfw_concepts




