Create safety_checker.py
Browse files- safety_checker.py +123 -0
safety_checker.py
ADDED
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel
|
5 |
+
|
6 |
+
|
7 |
+
def cosine_distance(image_embeds, text_embeds):
|
8 |
+
normalized_image_embeds = nn.functional.normalize(image_embeds)
|
9 |
+
normalized_text_embeds = nn.functional.normalize(text_embeds)
|
10 |
+
return torch.mm(normalized_image_embeds, normalized_text_embeds.t())
|
11 |
+
|
12 |
+
|
13 |
+
class StableDiffusionSafetyChecker(PreTrainedModel):
|
14 |
+
config_class = CLIPConfig
|
15 |
+
|
16 |
+
_no_split_modules = ["CLIPEncoderLayer"]
|
17 |
+
|
18 |
+
def __init__(self, config: CLIPConfig):
|
19 |
+
super().__init__(config)
|
20 |
+
|
21 |
+
self.vision_model = CLIPVisionModel(config.vision_config)
|
22 |
+
self.visual_projection = nn.Linear(
|
23 |
+
config.vision_config.hidden_size, config.projection_dim, bias=False
|
24 |
+
)
|
25 |
+
|
26 |
+
self.concept_embeds = nn.Parameter(
|
27 |
+
torch.ones(17, config.projection_dim), requires_grad=False
|
28 |
+
)
|
29 |
+
self.special_care_embeds = nn.Parameter(
|
30 |
+
torch.ones(3, config.projection_dim), requires_grad=False
|
31 |
+
)
|
32 |
+
|
33 |
+
self.concept_embeds_weights = nn.Parameter(torch.ones(17), requires_grad=False)
|
34 |
+
self.special_care_embeds_weights = nn.Parameter(
|
35 |
+
torch.ones(3), requires_grad=False
|
36 |
+
)
|
37 |
+
|
38 |
+
@torch.no_grad()
|
39 |
+
def forward(self, clip_input, images):
|
40 |
+
pooled_output = self.vision_model(clip_input)[1] # pooled_output
|
41 |
+
image_embeds = self.visual_projection(pooled_output)
|
42 |
+
|
43 |
+
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
|
44 |
+
special_cos_dist = (
|
45 |
+
cosine_distance(image_embeds, self.special_care_embeds)
|
46 |
+
.cpu()
|
47 |
+
.float()
|
48 |
+
.numpy()
|
49 |
+
)
|
50 |
+
cos_dist = (
|
51 |
+
cosine_distance(image_embeds, self.concept_embeds).cpu().float().numpy()
|
52 |
+
)
|
53 |
+
|
54 |
+
result = []
|
55 |
+
batch_size = image_embeds.shape[0]
|
56 |
+
for i in range(batch_size):
|
57 |
+
result_img = {
|
58 |
+
"special_scores": {},
|
59 |
+
"special_care": [],
|
60 |
+
"concept_scores": {},
|
61 |
+
"bad_concepts": [],
|
62 |
+
}
|
63 |
+
|
64 |
+
# increase this value to create a stronger `nfsw` filter
|
65 |
+
# at the cost of increasing the possibility of filtering benign images
|
66 |
+
adjustment = 0.0
|
67 |
+
|
68 |
+
for concept_idx in range(len(special_cos_dist[0])):
|
69 |
+
concept_cos = special_cos_dist[i][concept_idx]
|
70 |
+
concept_threshold = self.special_care_embeds_weights[concept_idx].item()
|
71 |
+
result_img["special_scores"][concept_idx] = round(
|
72 |
+
concept_cos - concept_threshold + adjustment, 3
|
73 |
+
)
|
74 |
+
if result_img["special_scores"][concept_idx] > 0:
|
75 |
+
result_img["special_care"].append(
|
76 |
+
{concept_idx, result_img["special_scores"][concept_idx]}
|
77 |
+
)
|
78 |
+
adjustment = 0.01
|
79 |
+
|
80 |
+
for concept_idx in range(len(cos_dist[0])):
|
81 |
+
concept_cos = cos_dist[i][concept_idx]
|
82 |
+
concept_threshold = self.concept_embeds_weights[concept_idx].item()
|
83 |
+
result_img["concept_scores"][concept_idx] = round(
|
84 |
+
concept_cos - concept_threshold + adjustment, 3
|
85 |
+
)
|
86 |
+
if result_img["concept_scores"][concept_idx] > 0:
|
87 |
+
result_img["bad_concepts"].append(concept_idx)
|
88 |
+
|
89 |
+
result.append(result_img)
|
90 |
+
|
91 |
+
has_nsfw_concepts = [len(res["bad_concepts"]) > 0 for res in result]
|
92 |
+
|
93 |
+
return has_nsfw_concepts
|
94 |
+
|
95 |
+
@torch.no_grad()
|
96 |
+
def forward_onnx(self, clip_input: torch.FloatTensor, images: torch.FloatTensor):
|
97 |
+
pooled_output = self.vision_model(clip_input)[1] # pooled_output
|
98 |
+
image_embeds = self.visual_projection(pooled_output)
|
99 |
+
|
100 |
+
special_cos_dist = cosine_distance(image_embeds, self.special_care_embeds)
|
101 |
+
cos_dist = cosine_distance(image_embeds, self.concept_embeds)
|
102 |
+
|
103 |
+
# increase this value to create a stronger `nsfw` filter
|
104 |
+
# at the cost of increasing the possibility of filtering benign images
|
105 |
+
adjustment = 0.0
|
106 |
+
|
107 |
+
special_scores = (
|
108 |
+
special_cos_dist - self.special_care_embeds_weights + adjustment
|
109 |
+
)
|
110 |
+
# special_scores = special_scores.round(decimals=3)
|
111 |
+
special_care = torch.any(special_scores > 0, dim=1)
|
112 |
+
special_adjustment = special_care * 0.01
|
113 |
+
special_adjustment = special_adjustment.unsqueeze(1).expand(
|
114 |
+
-1, cos_dist.shape[1]
|
115 |
+
)
|
116 |
+
|
117 |
+
concept_scores = (cos_dist - self.concept_embeds_weights) + special_adjustment
|
118 |
+
# concept_scores = concept_scores.round(decimals=3)
|
119 |
+
has_nsfw_concepts = torch.any(concept_scores > 0, dim=1)
|
120 |
+
|
121 |
+
images[has_nsfw_concepts] = 0.0 # black image
|
122 |
+
|
123 |
+
return images, has_nsfw_concepts
|