-
Notifications
You must be signed in to change notification settings - Fork 5.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Do not merge] Script to compare safety checkers #219
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,94 @@ | ||
#!/usr/bin/env python3 | ||
from cgitb import reset | ||
from typing import OrderedDict | ||
import torch, torch.nn as nn | ||
import open_clip | ||
import numpy as np | ||
import yaml | ||
|
||
from open_clip import create_model_and_transforms | ||
|
||
model, _, preprocess = create_model_and_transforms("ViT-L-14", "openai") | ||
|
||
def normalized(a, axis=-1, order=2): | ||
"""Normalize the given array along the specified axis in order to""" | ||
l2 = np.atleast_1d(np.linalg.norm(a, order, axis)) | ||
l2[l2 == 0] = 1 | ||
return a / np.expand_dims(l2, axis) | ||
|
||
def pw_cosine_distance(input_a, input_b): | ||
normalized_input_a = torch.nn.functional.normalize(input_a) | ||
normalized_input_b = torch.nn.functional.normalize(input_b) | ||
return torch.mm(normalized_input_a, normalized_input_b.T) | ||
|
||
class SafetyChecker(nn.Module): | ||
def __init__(self, device = 'cuda') -> None: | ||
super().__init__() | ||
self.clip_model = model.to(device) | ||
self.preprocess = preprocess | ||
self.device = device | ||
safety_settings = yaml.safe_load(open("/home/patrick/safety_settings.yml", "r")) | ||
self.concepts_dict = dict(safety_settings["nsfw"]["concepts"]) | ||
self.special_care_dict = dict(safety_settings["special"]["concepts"]) | ||
self.concept_embeds = self.get_text_embeds( | ||
list(self.concepts_dict.keys())) | ||
self.special_care_embeds = self.get_text_embeds( | ||
list(self.special_care_dict.keys())) | ||
|
||
def get_image_embeds(self, input): | ||
"""Get embeddings for images or tensor""" | ||
with torch.cuda.amp.autocast(): | ||
with torch.no_grad(): | ||
# Preprocess if input is a list of PIL images | ||
if isinstance(input, list): | ||
l = [] | ||
for image in input: | ||
l.append(self.preprocess(image)) | ||
img_tensor = torch.stack(l) | ||
# input is a tensor | ||
elif isinstance(input, torch.Tensor): | ||
img_tensor = input | ||
return self.clip_model.encode_image(img_tensor.half().to(self.device)) | ||
|
||
def get_text_embeds(self, input): | ||
"""Get text embeddings for a list of text""" | ||
with torch.cuda.amp.autocast(): | ||
with torch.no_grad(): | ||
input = open_clip.tokenize(input).to(self.device) | ||
return(self.clip_model.encode_text(input)) | ||
|
||
def forward(self, images): | ||
"""Get embeddings for images and output nsfw and concept scores""" | ||
image_embeds = self.get_image_embeds(images) | ||
concept_list = list(self.concepts_dict.keys()) | ||
special_list = list(self.special_care_dict.keys()) | ||
special_cos_dist = pw_cosine_distance(image_embeds, | ||
self.special_care_embeds).cpu().numpy() | ||
cos_dist = pw_cosine_distance(image_embeds, | ||
self.concept_embeds).cpu().numpy() | ||
result = [] | ||
for i in range(image_embeds.shape[0]): | ||
result_img = { | ||
"special_scores":{}, | ||
"special_care":[], | ||
"concept_scores":{}, | ||
"bad_concepts":[]} | ||
adjustment = 0.05 | ||
for j in range(len(special_cos_dist[0])): | ||
concept_name = special_list[j] | ||
concept_cos = special_cos_dist[i][j] | ||
concept_threshold = self.special_care_dict[concept_name] | ||
result_img["special_scores"][concept_name] = round( | ||
concept_cos - concept_threshold + adjustment,3) | ||
if result_img["special_scores"][concept_name] > 0: | ||
result_img["special_care"].append({concept_name,result_img["special_scores"][concept_name]}) | ||
adjustment = 0.01 | ||
for j in range(len(cos_dist[0])): | ||
concept_name = concept_list[j] | ||
concept_cos = cos_dist[i][j] | ||
concept_threshold = self.concepts_dict[concept_name] | ||
result_img["concept_scores"][concept_name] = round(concept_cos - concept_threshold + adjustment,3) | ||
if result_img["concept_scores"][concept_name]> 0: | ||
result_img["bad_concepts"].append(concept_name) | ||
result.append(result_img) | ||
return result |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This means that if
adjustment > concept_threshold
-> the image will always be a bad imageThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
what's the theory behind this code? why you calculate the similarity between the embedding of the image and a full-ones tensor below:
self.concept_embeds = nn.Parameter(torch.ones(17, config.projection_dim), requires_grad=False)
self.special_care_embeds = nn.Parameter(torch.ones(3, config.projection_dim), requires_grad=False)
thanks very much
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I just means that if cosine similarity is above a certain threshold then images will be blocked