code: 
  
  
  
  import inspect
  import warnings
  
  import torch
  
  from .state import AcceleratorState, GradientState
  from .utils import DistributedType, honor_type, is_tpu_available
  
  
  if is_tpu_available(check_device=False):
      import torch_xla.core.xla_model as xm
  def 	UpperCamelCase			(     snake_case__ :					Dict ,  snake_case__ :					Optional[int]			)			->  Optional[int]:
     if isinstance(snake_case__ ,  (list, tuple)			):
        return honor_type(snake_case__ ,  (move_to_device(snake_case__ ,  snake_case__			) for t in state)			)
     elif isinstance(snake_case__ ,  snake_case__			):
        return type(snake_case__			)({k: move_to_device(snake_case__ ,  snake_case__			) for k, v in state.items()}			)
     elif isinstance(snake_case__ ,  torch.Tensor			):
        return state.to(snake_case__			)
     return state
  
  
  
  class        lowerCAmelCase_	(						torch.optim.Optimizer							):
         def __init__(    self,    SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_=True,    SCREAMING_SNAKE_CASE_=None )  ->	Tuple:
            UpperCamelCase					:						Optional[Any]					=			optimizer
            UpperCamelCase					:						int					=			scaler
            UpperCamelCase					:						Union[str, Any]					=			AcceleratorState()
            UpperCamelCase					:						List[Any]					=			GradientState()
            UpperCamelCase					:						Optional[Any]					=			device_placement
            UpperCamelCase					:						Union[str, Any]					=			False
            UpperCamelCase					:						Union[str, Any]					=			None
  
            # Handle device placement
            if device_placement:
               UpperCamelCase					:						Optional[Any]					=			self.optimizer.state_dict()
               if self.accelerator_state.distributed_type == DistributedType.TPU:
                  xm.send_cpu_data_to_device(SCREAMING_SNAKE_CASE_,    self.accelerator_state.device )
               else:
                  UpperCamelCase					:						Dict					=			move_to_device(SCREAMING_SNAKE_CASE_,    self.accelerator_state.device )
               self.optimizer.load_state_dict(SCREAMING_SNAKE_CASE_ )
         @property
         def       snake_case_ (    self )  ->	Any:
            return self.optimizer.state
         @state.setter
         def       snake_case_ (    self,    SCREAMING_SNAKE_CASE_ )  ->	Tuple:
            UpperCamelCase					:						Optional[int]					=			state
         @property
         def       snake_case_ (    self )  ->	str:
            return self.optimizer.param_groups
         @param_groups.setter
         def       snake_case_ (    self,    SCREAMING_SNAKE_CASE_ )  ->	Union[str, Any]:
            UpperCamelCase					:						Any					=			param_groups
         @property
         def       snake_case_ (    self )  ->	int:
            return self.optimizer.defaults
         @defaults.setter
         def       snake_case_ (    self,    SCREAMING_SNAKE_CASE_ )  ->	Any:
            UpperCamelCase					:						str					=			defaults
         def       snake_case_ (    self,    SCREAMING_SNAKE_CASE_ )  ->	str:
            self.optimizer.add_param_group(SCREAMING_SNAKE_CASE_ )
         def       snake_case_ (    self,    SCREAMING_SNAKE_CASE_ )  ->	Dict:
            if self.accelerator_state.distributed_type == DistributedType.TPU and self.device_placement:
               xm.send_cpu_data_to_device(SCREAMING_SNAKE_CASE_,    self.accelerator_state.device )
            self.optimizer.load_state_dict(SCREAMING_SNAKE_CASE_ )
         def       snake_case_ (    self )  ->	Union[str, Any]:
            return self.optimizer.state_dict()
         def       snake_case_ (    self,    SCREAMING_SNAKE_CASE_=None )  ->	str:
            if self.gradient_state.sync_gradients:
               UpperCamelCase					:						str					=			'set_to_none' in inspect.signature(self.optimizer.zero_grad ).parameters
               if accept_arg:
                  if set_to_none is None:
                     UpperCamelCase					:						List[Any]					=			False
                  self.optimizer.zero_grad(set_to_none=SCREAMING_SNAKE_CASE_ )
               else:
                  if set_to_none is not None:
                     raise ValueError('`set_to_none` for Optimizer.zero_grad` is not supported by this optimizer.' )
                  self.optimizer.zero_grad()
         def       snake_case_ (    self,    SCREAMING_SNAKE_CASE_=None )  ->	Any:
            if self.gradient_state.sync_gradients:
               if self.accelerator_state.distributed_type == DistributedType.TPU:
                  UpperCamelCase					:						Tuple					=			{'closure': closure} if closure is not None else {}
                  xm.optimizer_step(self.optimizer,    optimizer_args=SCREAMING_SNAKE_CASE_ )
               elif self.scaler is not None:
                  UpperCamelCase					:						Any					=			False
                  if self._last_scale is None:
                     # `get_scale` is an async operation requiring full synchronization
                     # on CPU and GPUs before finishing. As a result, we store away
                     # the prior one to reduce the call overhead
                     UpperCamelCase					:						List[str]					=			self.scaler.get_scale()
                     UpperCamelCase					:						Optional[Any]					=			True
                  self.scaler.step(self.optimizer,    SCREAMING_SNAKE_CASE_ )
                  self.scaler.update()
                  UpperCamelCase					:						List[Any]					=			self.scaler.get_scale()
                  if not new_scale:
                     # If we reduced the loss scale, it means the optimizer step was skipped because of gradient overflow.
                     UpperCamelCase					:						List[str]					=			scale_after < self._last_scale
                  UpperCamelCase					:						Optional[int]					=			scale_after
  
               else:
                  self.optimizer.step(SCREAMING_SNAKE_CASE_ )
         def       snake_case_ (    self,    SCREAMING_SNAKE_CASE_ )  ->	List[Any]:
            for param_group in self.optimizer.param_groups:
               UpperCamelCase					:						Any					=			[parameters_map.get(SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_ ) for p in param_group['params']]
         @property
         def       snake_case_ (    self )  ->	int:
            warnings.warn(
                'The `is_overflow` property is deprecated and will be removed in version 1.0 of Accelerate use '
                '`optimizer.step_was_skipped` instead.',    SCREAMING_SNAKE_CASE_,    )
            return self._is_overflow
         @property
         def       snake_case_ (    self )  ->	Optional[int]:
            return self._is_overflow
         def __getstate__(    self )  ->	List[str]:
            return self.__dict__.copy()
  
  
  
  
  
  
         def __setstate__(    self,    SCREAMING_SNAKE_CASE_ )  ->	List[str]:
            self.__dict__.update(SCREAMING_SNAKE_CASE_ )
  
  
  
  
style_context: 
  
  
  
  import numpy as np
  import torch
  import torch.nn as nn
  from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel
  
  from ...utils import logging
  
  
  __UpperCAmelCase      = logging.get_logger(__name__)
  def 	UpperCamelCase			(     snake_case__ :					List[str] ,  snake_case__ :					str			)			->  Dict:
     UpperCamelCase					:						int					=			nn.functional.normalize(snake_case__			)
     UpperCamelCase					:						Union[str, Any]					=			nn.functional.normalize(snake_case__			)
     return torch.mm(snake_case__ ,  normalized_text_embeds.t()			)
  
  
  
  class        lowerCAmelCase_	(						a__							):
         UpperCAmelCase__       :      int       =						CLIPConfig
  
         UpperCAmelCase__       :      Union[str, Any]       =						["CLIPEncoderLayer"]
         def __init__(    self,    SCREAMING_SNAKE_CASE_ )  ->	List[str]:
            super().__init__(SCREAMING_SNAKE_CASE_ )
  
            UpperCamelCase					:						int					=			CLIPVisionModel(config.vision_config )
            UpperCamelCase					:						int					=			nn.Linear(config.vision_config.hidden_size,    config.projection_dim,    bias=SCREAMING_SNAKE_CASE_ )
  
            UpperCamelCase					:						List[Any]					=			nn.Parameter(torch.ones(17,    config.projection_dim ),    requires_grad=SCREAMING_SNAKE_CASE_ )
            UpperCamelCase					:						str					=			nn.Parameter(torch.ones(3,    config.projection_dim ),    requires_grad=SCREAMING_SNAKE_CASE_ )
  
            UpperCamelCase					:						Dict					=			nn.Parameter(torch.ones(17 ),    requires_grad=SCREAMING_SNAKE_CASE_ )
            UpperCamelCase					:						Optional[Any]					=			nn.Parameter(torch.ones(3 ),    requires_grad=SCREAMING_SNAKE_CASE_ )
         @torch.no_grad()
         def       snake_case_ (    self,    SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_ )  ->	Union[str, Any]:
            UpperCamelCase					:						Optional[int]					=			self.vision_model(SCREAMING_SNAKE_CASE_ )[1]  # pooled_output
            UpperCamelCase					:						int					=			self.visual_projection(SCREAMING_SNAKE_CASE_ )
  
            # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
            UpperCamelCase					:						Optional[Any]					=			cosine_distance(SCREAMING_SNAKE_CASE_,    self.special_care_embeds ).cpu().float().numpy()
            UpperCamelCase					:						Any					=			cosine_distance(SCREAMING_SNAKE_CASE_,    self.concept_embeds ).cpu().float().numpy()
  
            UpperCamelCase					:						str					=			[]
            UpperCamelCase					:						int					=			image_embeds.shape[0]
            for i in range(SCREAMING_SNAKE_CASE_ ):
               UpperCamelCase					:						Optional[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
               UpperCamelCase					:						Optional[Any]					=			0.0
  
               for concept_idx in range(len(special_cos_dist[0] ) ):
                  UpperCamelCase					:						Union[str, Any]					=			special_cos_dist[i][concept_idx]
                  UpperCamelCase					:						Optional[Any]					=			self.special_care_embeds_weights[concept_idx].item()
                  UpperCamelCase					:						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]} )
                     UpperCamelCase					:						Dict					=			0.01
  
               for concept_idx in range(len(cos_dist[0] ) ):
                  UpperCamelCase					:						List[Any]					=			cos_dist[i][concept_idx]
                  UpperCamelCase					:						Optional[int]					=			self.concept_embeds_weights[concept_idx].item()
                  UpperCamelCase					:						Union[str, Any]					=			round(concept_cos - concept_threshold + adjustment,    3 )
                  if result_img["concept_scores"][concept_idx] > 0:
                     result_img["bad_concepts"].append(SCREAMING_SNAKE_CASE_ )
  
               result.append(SCREAMING_SNAKE_CASE_ )
  
            UpperCamelCase					:						int					=			[len(res['bad_concepts'] ) > 0 for res in result]
  
            for idx, has_nsfw_concept in enumerate(SCREAMING_SNAKE_CASE_ ):
               if has_nsfw_concept:
                  if torch.is_tensor(SCREAMING_SNAKE_CASE_ ) or torch.is_tensor(images[0] ):
                     UpperCamelCase					:						List[str]					=			torch.zeros_like(images[idx] )  # black image
                  else:
                     UpperCamelCase					:						int					=			np.zeros(images[idx].shape )  # black image
  
            if any(SCREAMING_SNAKE_CASE_ ):
               logger.warning(
                   'Potential NSFW content was detected in one or more images. A black image will be returned instead.'
                   ' Try again with a different prompt and/or seed.' )
  
            return images, has_nsfw_concepts
  
  
  
  
  
  
         @torch.no_grad()
         def       snake_case_ (    self,    SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_ )  ->	Optional[int]:
            UpperCamelCase					:						Union[str, Any]					=			self.vision_model(SCREAMING_SNAKE_CASE_ )[1]  # pooled_output
            UpperCamelCase					:						str					=			self.visual_projection(SCREAMING_SNAKE_CASE_ )
  
            UpperCamelCase					:						str					=			cosine_distance(SCREAMING_SNAKE_CASE_,    self.special_care_embeds )
            UpperCamelCase					:						Any					=			cosine_distance(SCREAMING_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
            UpperCamelCase					:						Dict					=			0.0
  
            UpperCamelCase					:						str					=			special_cos_dist - self.special_care_embeds_weights + adjustment
            # special_scores = special_scores.round(decimals=3)
            UpperCamelCase					:						List[str]					=			torch.any(special_scores > 0,    dim=1 )
            UpperCamelCase					:						List[Any]					=			special_care * 0.01
            UpperCamelCase					:						List[Any]					=			special_adjustment.unsqueeze(1 ).expand(-1,    cos_dist.shape[1] )
  
            UpperCamelCase					:						List[str]					=			(cos_dist - self.concept_embeds_weights) + special_adjustment
            # concept_scores = concept_scores.round(decimals=3)
            UpperCamelCase					:						Tuple					=			torch.any(concept_scores > 0,    dim=1 )
  
            UpperCamelCase					:						Any					=			0.0  # black image
  
            return images, has_nsfw_concepts
  
  
  
  