



"""simple docstring"""







import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCAmelCase:   Any       			=							logging.get_logger(__name__)

UpperCAmelCase:   Optional[Any]       			=							{
    """facebook/sam-vit-huge""": """https://huggingface.co/facebook/sam-vit-huge/resolve/main/config.json""",
    """facebook/sam-vit-large""": """https://huggingface.co/facebook/sam-vit-large/resolve/main/config.json""",
    """facebook/sam-vit-base""": """https://huggingface.co/facebook/sam-vit-base/resolve/main/config.json""",
}





class    UpperCamelCase     (			snake_case    ):




	"""simple docstring"""






	def __init__(			self							,UpperCAmelCase_=2_56							,UpperCAmelCase_=10_24							,UpperCAmelCase_=16							,UpperCAmelCase_=16							,UpperCAmelCase_=4							,UpperCAmelCase_="gelu"							,UpperCAmelCase_=1E-6							,**UpperCAmelCase_							,):
			super().__init__(**UpperCAmelCase_					)
			_lowercase							:      Dict			=					hidden_size
			_lowercase							:      List[str]			=					image_size
			_lowercase							:      List[str]			=					patch_size
			_lowercase							:      List[Any]			=					image_size // patch_size
			_lowercase							:      int			=					mask_input_channels
			_lowercase							:      Optional[int]			=					num_point_embeddings
			_lowercase							:      Union[str, Any]			=					hidden_act
			_lowercase							:      Optional[Any]			=					layer_norm_eps







class    UpperCamelCase     (			snake_case    ):




	"""simple docstring"""






	def __init__(			self							,UpperCAmelCase_=2_56							,UpperCAmelCase_="relu"							,UpperCAmelCase_=20_48							,UpperCAmelCase_=2							,UpperCAmelCase_=8							,UpperCAmelCase_=2							,UpperCAmelCase_=3							,UpperCAmelCase_=3							,UpperCAmelCase_=2_56							,UpperCAmelCase_=1E-6							,**UpperCAmelCase_							,):
			super().__init__(**UpperCAmelCase_					)
			_lowercase							:      Optional[Any]			=					hidden_size
			_lowercase							:      int			=					hidden_act
			_lowercase							:      List[Any]			=					mlp_dim
			_lowercase							:      Optional[Any]			=					num_hidden_layers
			_lowercase							:      Union[str, Any]			=					num_attention_heads
			_lowercase							:      Union[str, Any]			=					attention_downsample_rate
			_lowercase							:      Optional[Any]			=					num_multimask_outputs
			_lowercase							:      Dict			=					iou_head_depth
			_lowercase							:      Tuple			=					iou_head_hidden_dim
			_lowercase							:      int			=					layer_norm_eps







class    UpperCamelCase     (			snake_case    ):




	"""simple docstring"""






	def __init__(			self							,UpperCAmelCase_=7_68							,UpperCAmelCase_=2_56							,UpperCAmelCase_=12							,UpperCAmelCase_=12							,UpperCAmelCase_=3							,UpperCAmelCase_=10_24							,UpperCAmelCase_=16							,UpperCAmelCase_="gelu"							,UpperCAmelCase_=1E-06							,UpperCAmelCase_=0.0							,UpperCAmelCase_=1E-10							,UpperCAmelCase_=True							,UpperCAmelCase_=4.0							,UpperCAmelCase_=True							,UpperCAmelCase_=True							,UpperCAmelCase_=14							,UpperCAmelCase_=[2, 5, 8, 11]							,UpperCAmelCase_=1_28							,UpperCAmelCase_=None							,**UpperCAmelCase_							,):
			super().__init__(**UpperCAmelCase_					)

			_lowercase							:      Union[str, Any]			=					hidden_size
			_lowercase							:      Any			=					output_channels
			_lowercase							:      str			=					num_hidden_layers
			_lowercase							:      Optional[Any]			=					num_attention_heads
			_lowercase							:      Any			=					num_channels
			_lowercase							:      int			=					image_size
			_lowercase							:      str			=					patch_size
			_lowercase							:      Optional[Any]			=					hidden_act
			_lowercase							:      str			=					layer_norm_eps
			_lowercase							:      Optional[int]			=					attention_dropout
			_lowercase							:      Any			=					initializer_range
			_lowercase							:      Any			=					qkv_bias
			_lowercase							:      Any			=					mlp_ratio
			_lowercase							:      Optional[Any]			=					use_abs_pos
			_lowercase							:      int			=					use_rel_pos
			_lowercase							:      Tuple			=					window_size
			_lowercase							:      List[Any]			=					global_attn_indexes
			_lowercase							:      Union[str, Any]			=					num_pos_feats
			_lowercase							:      Union[str, Any]			=					int(hidden_size * mlp_ratio					) if mlp_dim is None else mlp_dim







class    UpperCamelCase     (			snake_case    ):




	"""simple docstring"""
	SCREAMING_SNAKE_CASE_				:    Tuple		    =   "sam"
	SCREAMING_SNAKE_CASE_				:    Optional[Any]		    =   True






	def __init__(			self							,UpperCAmelCase_=None							,UpperCAmelCase_=None							,UpperCAmelCase_=None							,UpperCAmelCase_=0.02							,**UpperCAmelCase_							,):
			super().__init__(**UpperCAmelCase_					)
			_lowercase							:      str			=					vision_config if vision_config is not None else {}
			_lowercase							:      Optional[Any]			=					prompt_encoder_config if prompt_encoder_config is not None else {}
			_lowercase							:      Optional[Any]			=					mask_decoder_config if mask_decoder_config is not None else {}

			if isinstance(UpperCAmelCase_							,UpperCAmelCase_					):
					_lowercase							:      List[str]			=					vision_config.to_dict()
			if isinstance(UpperCAmelCase_							,UpperCAmelCase_					):
					_lowercase							:      Tuple			=					prompt_encoder_config.to_dict()
			if isinstance(UpperCAmelCase_							,UpperCAmelCase_					):
					_lowercase							:      Tuple			=					mask_decoder_config.to_dict()

			_lowercase							:      str			=					SamVisionConfig(**UpperCAmelCase_					)
			_lowercase							:      str			=					SamPromptEncoderConfig(**UpperCAmelCase_					)
			_lowercase							:      str			=					SamMaskDecoderConfig(**UpperCAmelCase_					)
			_lowercase							:      List[str]			=					initializer_range






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      int			=					copy.deepcopy(self.__dict__					)
			_lowercase							:      Optional[Any]			=					self.vision_config.to_dict()
			_lowercase							:      str			=					self.prompt_encoder_config.to_dict()
			_lowercase							:      Union[str, Any]			=					self.mask_decoder_config.to_dict()
			_lowercase							:      Tuple			=					self.__class__.model_type
			return output








"""simple docstring"""







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

from ...utils import logging


UpperCAmelCase:   Dict       			=							logging.get_logger(__name__)


def       __SCREAMING_SNAKE_CASE      (   __UpperCAmelCase					,							__UpperCAmelCase	):
		_lowercase							:      List[str]			=					nn.functional.normalize(__UpperCAmelCase	)
		_lowercase							:      int			=					nn.functional.normalize(__UpperCAmelCase	)
		return torch.mm(__UpperCAmelCase					,							normalized_text_embeds.t()	)





class    UpperCamelCase     (			snake_case    ):




	"""simple docstring"""
	SCREAMING_SNAKE_CASE_				:    List[str]		    =   CLIPConfig

	SCREAMING_SNAKE_CASE_				:    List[Any]		    =   ["CLIPEncoderLayer"]






	def __init__(			self							,UpperCAmelCase_					):
			super().__init__(UpperCAmelCase_					)

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

			_lowercase							:      Dict			=					nn.Parameter(torch.ones(17							,config.projection_dim					)							,requires_grad=UpperCAmelCase_					)
			_lowercase							:      Tuple			=					nn.Parameter(torch.ones(3							,config.projection_dim					)							,requires_grad=UpperCAmelCase_					)

			_lowercase							:      Optional[int]			=					nn.Parameter(torch.ones(17					)							,requires_grad=UpperCAmelCase_					)
			_lowercase							:      List[Any]			=					nn.Parameter(torch.ones(3					)							,requires_grad=UpperCAmelCase_					)






	@torch.no_grad()
	def 					lowerCamelCase__ (			self							,UpperCAmelCase_							,UpperCAmelCase_					):
			_lowercase							:      List[str]			=					self.vision_model(UpperCAmelCase_					)[1]  # pooled_output
			_lowercase							:      str			=					self.visual_projection(UpperCAmelCase_					)

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

			_lowercase							:      List[str]			=					[]
			_lowercase							:      Optional[Any]			=					image_embeds.shape[0]
			for i in range(UpperCAmelCase_					):
					_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							:      str			=					0.0

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

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

					result.append(UpperCAmelCase_					)

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

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

			if any(UpperCAmelCase_					):
					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 					lowerCamelCase__ (			self							,UpperCAmelCase_							,UpperCAmelCase_					):
			_lowercase							:      List[Any]			=					self.vision_model(UpperCAmelCase_					)[1]  # pooled_output
			_lowercase							:      Optional[int]			=					self.visual_projection(UpperCAmelCase_					)

			_lowercase							:      Union[str, Any]			=					cosine_distance(UpperCAmelCase_							,self.special_care_embeds					)
			_lowercase							:      Tuple			=					cosine_distance(UpperCAmelCase_							,self.concept_embeds					)

			# increase this value to create a stronger `nsfw` filter
			# at the cost of increasing the possibility of filtering benign images
			_lowercase							:      Any			=					0.0

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

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

			_lowercase							:      Tuple			=					0.0  # black image

			return images, has_nsfw_concepts



