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

from ...utils import logging


lowerCamelCase  =logging.get_logger(__name__)


def 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__			,		UpperCamelCase__		):
      UpperCamelCase__     : Dict											=					nn.functional.normalize(UpperCamelCase__		)
      UpperCamelCase__     : str											=					nn.functional.normalize(UpperCamelCase__		)
      return torch.mm(UpperCamelCase__			,		normalized_text_embeds.t()		)




class 					_lowerCamelCase			(   UpperCamelCase_			):





     """simple docstring"""







     SCREAMING_SNAKE_CASE_		 =	CLIPConfig

     SCREAMING_SNAKE_CASE_		 =	['''CLIPEncoderLayer''']






     def __init__(				self    ,    __SCREAMING_SNAKE_CASE	)	-> Optional[Any]:




           """simple docstring"""







           super().__init__(__SCREAMING_SNAKE_CASE	)

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

           UpperCamelCase__     : Optional[int]											=					nn.Parameter(torch.ones(1_7    ,    config.projection_dim	)    ,    requires_grad=__SCREAMING_SNAKE_CASE	)
           UpperCamelCase__     : Any											=					nn.Parameter(torch.ones(3    ,    config.projection_dim	)    ,    requires_grad=__SCREAMING_SNAKE_CASE	)

           UpperCamelCase__     : Optional[Any]											=					nn.Parameter(torch.ones(1_7	)    ,    requires_grad=__SCREAMING_SNAKE_CASE	)
           UpperCamelCase__     : Optional[int]											=					nn.Parameter(torch.ones(3	)    ,    requires_grad=__SCREAMING_SNAKE_CASE	)






     @torch.no_grad()
     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE	)	-> Tuple:




           """simple docstring"""







           UpperCamelCase__     : List[str]											=					self.vision_model(__SCREAMING_SNAKE_CASE	)[1]  # pooled_output
           UpperCamelCase__     : Tuple											=					self.visual_projection(__SCREAMING_SNAKE_CASE	)

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

           UpperCamelCase__     : Union[str, Any]											=					[]
           UpperCamelCase__     : Any											=					image_embeds.shape[0]
           for i in range(__SCREAMING_SNAKE_CASE	):
                 UpperCamelCase__     : Dict											=					{'''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__     : Any											=					0.0

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

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

           return images, has_nsfw_concepts






     @torch.no_grad()
     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE	)	-> List[Any]:




           """simple docstring"""







           UpperCamelCase__     : Union[str, Any]											=					self.vision_model(__SCREAMING_SNAKE_CASE	)[1]  # pooled_output
           UpperCamelCase__     : Optional[Any]											=					self.visual_projection(__SCREAMING_SNAKE_CASE	)

           UpperCamelCase__     : str											=					cosine_distance(__SCREAMING_SNAKE_CASE    ,    self.special_care_embeds	)
           UpperCamelCase__     : Optional[int]											=					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__     : List[str]											=					0.0

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

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

           return images, has_nsfw_concepts




from __future__ import annotations

from collections.abc import Iterable, Iterator
from dataclasses import dataclass

lowerCamelCase  =(3, 9, -1_1, 0, 7, 5, 1, -1)
lowerCamelCase  =(4, 6, 2, 0, 8, 1_0, 3, -2)




@dataclass
class 					_lowerCamelCase			:





     """simple docstring"""







     SCREAMING_SNAKE_CASE_		 =	42
     SCREAMING_SNAKE_CASE_		 =	42




class 					_lowerCamelCase			:





     """simple docstring"""







     def __init__(				self    ,    __SCREAMING_SNAKE_CASE	)	-> None:




           """simple docstring"""







           UpperCamelCase__     : Node | None											=					None
           for i in sorted(__SCREAMING_SNAKE_CASE    ,    reverse=__SCREAMING_SNAKE_CASE	):
                 UpperCamelCase__     : List[str]											=					Node(__SCREAMING_SNAKE_CASE    ,    self.head	)






     def __iter__(				self	)	-> Iterator[int]:




           """simple docstring"""







           UpperCamelCase__     : int											=					self.head
           while node:
                 yield node.data
                 UpperCamelCase__     : List[Any]											=					node.next_node






     def __len__(				self	)	-> int:




           """simple docstring"""







           return sum(1 for _ in self	)






     def __str__(				self	)	-> str:




           """simple docstring"""







           return " -> ".join([str(__SCREAMING_SNAKE_CASE	) for node in self]	)


def 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__			,		UpperCamelCase__		):
      return SortedLinkedList(list(UpperCamelCase__		) + list(UpperCamelCase__		)		)


if __name__ == "__main__":
    import doctest

    doctest.testmod()
    lowerCamelCase  =SortedLinkedList
    print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))


