




'''simple docstring'''






from __future__ import annotations




def 		a_( lowerCamelCase      )				->list[int]:






       '''simple docstring'''




       if not list_of_ints:
              return []

       if min(lowerCamelCase      ) < 0:
              raise ValueError('''All numbers must be positive'''      )

       lowercase  :		Any						=      max(len(bin(lowerCamelCase      )[2:]      ) for x in list_of_ints      )
       return _msd_radix_sort(lowerCamelCase   ,				lowerCamelCase      )




def 		a_( lowerCamelCase   ,				lowerCamelCase      )				->list[int]:






       '''simple docstring'''




       if bit_position == 0 or len(lowerCamelCase      ) in [0, 1]:
              return list_of_ints

       lowercase  :		Union[str, Any]						=      []
       lowercase  :		Dict						=      []
       # Split numbers based on bit at bit_position from the right
       for number in list_of_ints:
              if (number >> (bit_position - 1)) & 1:
                     # number has a one at bit bit_position
                     ones.append(lowerCamelCase      )
              else:
                     # number has a zero at bit bit_position
                     zeros.append(lowerCamelCase      )

    # recursively split both lists further
       lowercase  :		int						=      _msd_radix_sort(lowerCamelCase   ,				bit_position - 1      )
       lowercase  :		str						=      _msd_radix_sort(lowerCamelCase   ,				bit_position - 1      )

       # recombine lists
       lowercase  :		Optional[Any]						=      zeros
       res.extend(lowerCamelCase      )

       return res




def 		a_( lowerCamelCase      )				->Any:






       '''simple docstring'''




       lowercase  :		List[str]						=      len(lowerCamelCase      )
       if not list_of_ints or length == 1:
              return

       if min(lowerCamelCase      ) < 0:
              raise ValueError('''All numbers must be positive'''      )

       lowercase  :		Optional[int]						=      max(len(bin(lowerCamelCase      )[2:]      ) for x in list_of_ints      )
       _msd_radix_sort_inplace(lowerCamelCase   ,				lowerCamelCase   ,				0   ,				lowerCamelCase      )




def 		a_( lowerCamelCase   ,				lowerCamelCase   ,				lowerCamelCase   ,				lowerCamelCase      )				->List[Any]:






       '''simple docstring'''




       if bit_position == 0 or end_index - begin_index <= 1:
              return

       bit_position -= 1

       lowercase  :		str						=      begin_index
       lowercase  :		str						=      end_index - 1
       while i <= j:
              lowercase  :		Optional[int]						=      False
              if not (list_of_ints[i] >> bit_position) & 1:
                     # found zero at the beginning
                     i += 1
                     lowercase  :		Union[str, Any]						=      True
              if (list_of_ints[j] >> bit_position) & 1:
                     # found one at the end
                     j -= 1
                     lowercase  :		Tuple						=      True

              if changed:
                     continue

              lowercase,     lowercase  :		List[str]						=      list_of_ints[j], list_of_ints[i]
              j -= 1
              if j != i:
                     i += 1

       _msd_radix_sort_inplace(lowerCamelCase   ,				lowerCamelCase   ,				lowerCamelCase   ,				lowerCamelCase      )
       _msd_radix_sort_inplace(lowerCamelCase   ,				lowerCamelCase   ,				lowerCamelCase   ,				lowerCamelCase      )


if __name__ == "__main__":
      import doctest

      doctest.testmod()










'''simple docstring'''






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

from ...utils import logging


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




def 		a_( lowerCamelCase   ,				lowerCamelCase      )				->Optional[int]:






       '''simple docstring'''




       lowercase  :		List[str]						=      nn.functional.normalize(lowerCamelCase      )
       lowercase  :		Optional[int]						=      nn.functional.normalize(lowerCamelCase      )
       return torch.mm(lowerCamelCase   ,				normalized_text_embeds.t()      )





class   SCREAMING_SNAKE_CASE_		(       lowerCamelCase_				):
 __snake_case	:     List[str]			   =      CLIPConfig

 __snake_case	:     Optional[int]			   =      ["CLIPEncoderLayer"]



 def __init__(  self   ,		A ):






        '''simple docstring'''




        super().__init__(A )

        lowercase  :		Optional[Any]						=      CLIPVisionModel(config.vision_config )
        lowercase  :		Tuple						=      nn.Linear(config.vision_config.hidden_size   ,		config.projection_dim   ,		bias=A )

        lowercase  :		Any						=      nn.Parameter(torch.ones(17   ,		config.projection_dim )   ,		requires_grad=A )
        lowercase  :		int						=      nn.Parameter(torch.ones(3   ,		config.projection_dim )   ,		requires_grad=A )

        lowercase  :		List[str]						=      nn.Parameter(torch.ones(17 )   ,		requires_grad=A )
        lowercase  :		str						=      nn.Parameter(torch.ones(3 )   ,		requires_grad=A )



 @torch.no_grad()
 def    SCREAMING_SNAKE_CASE(  self   ,		A   ,		A ):






        '''simple docstring'''




        lowercase  :		Union[str, Any]						=      self.vision_model(A )[1]  # pooled_output
        lowercase  :		List[Any]						=      self.visual_projection(A )

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

        lowercase  :		Dict						=      []
        lowercase  :		str						=      image_embeds.shape[0]
        for i in range(A ):
               lowercase  :		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
               lowercase  :		str						=      0.0

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

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

               result.append(A )

        lowercase  :		Dict						=      [len(res['''bad_concepts'''] ) > 0 for res in result]

        for idx, has_nsfw_concept in enumerate(A ):
               if has_nsfw_concept:
                      if torch.is_tensor(A ) or torch.is_tensor(images[0] ):
                             lowercase  :		Any						=      torch.zeros_like(images[idx] )  # black image
                      else:
                             lowercase  :		Tuple						=      np.zeros(images[idx].shape )  # black image

        if any(A ):
               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    SCREAMING_SNAKE_CASE(  self   ,		A   ,		A ):






        '''simple docstring'''




        lowercase  :		Dict						=      self.vision_model(A )[1]  # pooled_output
        lowercase  :		Optional[int]						=      self.visual_projection(A )

        lowercase  :		Tuple						=      cosine_distance(A   ,		self.special_care_embeds )
        lowercase  :		List[str]						=      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
        lowercase  :		List[str]						=      0.0

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

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

        lowercase  :		Dict						=      0.0  # black image

        return images, has_nsfw_concepts




