Spaces:
Runtime error
Runtime error
safety checker
Browse files
server/pipelines/controlnetLoraSDXL-Lightning.py
CHANGED
|
@@ -9,6 +9,7 @@ from diffusers import (
|
|
| 9 |
from compel import Compel, ReturnedEmbeddingsType
|
| 10 |
import torch
|
| 11 |
from pipelines.utils.canny_gpu import SobelOperator
|
|
|
|
| 12 |
from huggingface_hub import hf_hub_download
|
| 13 |
from safetensors.torch import load_file
|
| 14 |
|
|
@@ -17,7 +18,6 @@ try:
|
|
| 17 |
except:
|
| 18 |
pass
|
| 19 |
|
| 20 |
-
import psutil
|
| 21 |
from config import Args
|
| 22 |
from pydantic import BaseModel, Field
|
| 23 |
from PIL import Image
|
|
@@ -35,7 +35,7 @@ default_prompt = "Portrait of The Terminator with , glare pose, detailed, intric
|
|
| 35 |
default_negative_prompt = "blurry, low quality, render, 3D, oversaturated"
|
| 36 |
page_content = """
|
| 37 |
<h1 class="text-3xl font-bold">Real-Time Latent Consistency Model SDXL</h1>
|
| 38 |
-
<h3 class="text-xl font-bold">SDXL-Lightining +
|
| 39 |
<p class="text-sm">
|
| 40 |
This demo showcases
|
| 41 |
<a
|
|
@@ -84,9 +84,6 @@ class Pipeline:
|
|
| 84 |
seed: int = Field(
|
| 85 |
2159232, min=0, title="Seed", field="seed", hide=True, id="seed"
|
| 86 |
)
|
| 87 |
-
steps: int = Field(
|
| 88 |
-
1, min=1, max=10, title="Steps", field="range", hide=True, id="steps"
|
| 89 |
-
)
|
| 90 |
width: int = Field(
|
| 91 |
1024, min=2, max=15, title="Width", disabled=True, hide=True, id="width"
|
| 92 |
)
|
|
@@ -172,6 +169,8 @@ class Pipeline:
|
|
| 172 |
)
|
| 173 |
|
| 174 |
def __init__(self, args: Args, device: torch.device, torch_dtype: torch.dtype):
|
|
|
|
|
|
|
| 175 |
|
| 176 |
if args.taesd:
|
| 177 |
vae = AutoencoderTiny.from_pretrained(
|
|
@@ -204,7 +203,7 @@ class Pipeline:
|
|
| 204 |
|
| 205 |
self.canny_torch = SobelOperator(device=device)
|
| 206 |
self.pipe.set_progress_bar_config(disable=True)
|
| 207 |
-
self.pipe.to(device=device, dtype=torch_dtype)
|
| 208 |
|
| 209 |
if args.sfast:
|
| 210 |
from sfast.compilers.stable_diffusion_pipeline_compiler import (
|
|
@@ -242,7 +241,7 @@ class Pipeline:
|
|
| 242 |
control_image=[Image.new("RGB", (768, 768))],
|
| 243 |
)
|
| 244 |
|
| 245 |
-
def predict(self, params: "Pipeline.InputParams") -> Image.Image:
|
| 246 |
generator = torch.manual_seed(params.seed)
|
| 247 |
|
| 248 |
prompt = params.prompt
|
|
@@ -265,7 +264,7 @@ class Pipeline:
|
|
| 265 |
control_image = self.canny_torch(
|
| 266 |
params.image, params.canny_low_threshold, params.canny_high_threshold
|
| 267 |
)
|
| 268 |
-
steps =
|
| 269 |
strength = params.strength
|
| 270 |
if int(steps * strength) < 1:
|
| 271 |
steps = math.ceil(1 / max(0.10, strength))
|
|
@@ -281,7 +280,7 @@ class Pipeline:
|
|
| 281 |
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
| 282 |
generator=generator,
|
| 283 |
strength=strength,
|
| 284 |
-
num_inference_steps=
|
| 285 |
guidance_scale=params.guidance_scale,
|
| 286 |
width=params.width,
|
| 287 |
height=params.height,
|
|
@@ -290,14 +289,13 @@ class Pipeline:
|
|
| 290 |
control_guidance_start=params.controlnet_start,
|
| 291 |
control_guidance_end=params.controlnet_end,
|
| 292 |
)
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
)
|
| 299 |
-
if nsfw_content_detected:
|
| 300 |
return None
|
|
|
|
| 301 |
result_image = results.images[0]
|
| 302 |
if params.debug_canny:
|
| 303 |
# paste control_image on top of result_image
|
|
|
|
| 9 |
from compel import Compel, ReturnedEmbeddingsType
|
| 10 |
import torch
|
| 11 |
from pipelines.utils.canny_gpu import SobelOperator
|
| 12 |
+
from pipelines.utils.safety_checker import SafetyChecker
|
| 13 |
from huggingface_hub import hf_hub_download
|
| 14 |
from safetensors.torch import load_file
|
| 15 |
|
|
|
|
| 18 |
except:
|
| 19 |
pass
|
| 20 |
|
|
|
|
| 21 |
from config import Args
|
| 22 |
from pydantic import BaseModel, Field
|
| 23 |
from PIL import Image
|
|
|
|
| 35 |
default_negative_prompt = "blurry, low quality, render, 3D, oversaturated"
|
| 36 |
page_content = """
|
| 37 |
<h1 class="text-3xl font-bold">Real-Time Latent Consistency Model SDXL</h1>
|
| 38 |
+
<h3 class="text-xl font-bold">SDXL-Lightining + Controlnet</h3>
|
| 39 |
<p class="text-sm">
|
| 40 |
This demo showcases
|
| 41 |
<a
|
|
|
|
| 84 |
seed: int = Field(
|
| 85 |
2159232, min=0, title="Seed", field="seed", hide=True, id="seed"
|
| 86 |
)
|
|
|
|
|
|
|
|
|
|
| 87 |
width: int = Field(
|
| 88 |
1024, min=2, max=15, title="Width", disabled=True, hide=True, id="width"
|
| 89 |
)
|
|
|
|
| 169 |
)
|
| 170 |
|
| 171 |
def __init__(self, args: Args, device: torch.device, torch_dtype: torch.dtype):
|
| 172 |
+
if args.safety_checker:
|
| 173 |
+
self.safety_checker = SafetyChecker(device=device.type)
|
| 174 |
|
| 175 |
if args.taesd:
|
| 176 |
vae = AutoencoderTiny.from_pretrained(
|
|
|
|
| 203 |
|
| 204 |
self.canny_torch = SobelOperator(device=device)
|
| 205 |
self.pipe.set_progress_bar_config(disable=True)
|
| 206 |
+
self.pipe.to(device=device, dtype=torch_dtype)
|
| 207 |
|
| 208 |
if args.sfast:
|
| 209 |
from sfast.compilers.stable_diffusion_pipeline_compiler import (
|
|
|
|
| 241 |
control_image=[Image.new("RGB", (768, 768))],
|
| 242 |
)
|
| 243 |
|
| 244 |
+
def predict(self, params: "Pipeline.InputParams") -> Image.Image | None:
|
| 245 |
generator = torch.manual_seed(params.seed)
|
| 246 |
|
| 247 |
prompt = params.prompt
|
|
|
|
| 264 |
control_image = self.canny_torch(
|
| 265 |
params.image, params.canny_low_threshold, params.canny_high_threshold
|
| 266 |
)
|
| 267 |
+
steps = NUM_STEPS
|
| 268 |
strength = params.strength
|
| 269 |
if int(steps * strength) < 1:
|
| 270 |
steps = math.ceil(1 / max(0.10, strength))
|
|
|
|
| 280 |
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
| 281 |
generator=generator,
|
| 282 |
strength=strength,
|
| 283 |
+
num_inference_steps=NUM_STEPS,
|
| 284 |
guidance_scale=params.guidance_scale,
|
| 285 |
width=params.width,
|
| 286 |
height=params.height,
|
|
|
|
| 289 |
control_guidance_start=params.controlnet_start,
|
| 290 |
control_guidance_end=params.controlnet_end,
|
| 291 |
)
|
| 292 |
+
images = results.images
|
| 293 |
+
if self.safety_checker:
|
| 294 |
+
images, has_nsfw_concepts = self.safety_checker(images)
|
| 295 |
+
print(has_nsfw_concepts)
|
| 296 |
+
if any(has_nsfw_concepts):
|
|
|
|
|
|
|
| 297 |
return None
|
| 298 |
+
|
| 299 |
result_image = results.images[0]
|
| 300 |
if params.debug_canny:
|
| 301 |
# paste control_image on top of result_image
|
server/pipelines/utils/safety_checker.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torch.nn as nn
|
| 17 |
+
from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel
|
| 18 |
+
from PIL import Image
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def cosine_distance(image_embeds, text_embeds):
|
| 22 |
+
normalized_image_embeds = nn.functional.normalize(image_embeds)
|
| 23 |
+
normalized_text_embeds = nn.functional.normalize(text_embeds)
|
| 24 |
+
return torch.mm(normalized_image_embeds, normalized_text_embeds.t())
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class StableDiffusionSafetyChecker(PreTrainedModel):
|
| 28 |
+
config_class = CLIPConfig
|
| 29 |
+
|
| 30 |
+
_no_split_modules = ["CLIPEncoderLayer"]
|
| 31 |
+
|
| 32 |
+
def __init__(self, config: CLIPConfig):
|
| 33 |
+
super().__init__(config)
|
| 34 |
+
|
| 35 |
+
self.vision_model = CLIPVisionModel(config.vision_config)
|
| 36 |
+
self.visual_projection = nn.Linear(
|
| 37 |
+
config.vision_config.hidden_size, config.projection_dim, bias=False
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
self.concept_embeds = nn.Parameter(
|
| 41 |
+
torch.ones(17, config.projection_dim), requires_grad=False
|
| 42 |
+
)
|
| 43 |
+
self.special_care_embeds = nn.Parameter(
|
| 44 |
+
torch.ones(3, config.projection_dim), requires_grad=False
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
self.concept_embeds_weights = nn.Parameter(torch.ones(17), requires_grad=False)
|
| 48 |
+
self.special_care_embeds_weights = nn.Parameter(
|
| 49 |
+
torch.ones(3), requires_grad=False
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
@torch.no_grad()
|
| 53 |
+
def forward(self, clip_input, images):
|
| 54 |
+
pooled_output = self.vision_model(clip_input)[1] # pooled_output
|
| 55 |
+
image_embeds = self.visual_projection(pooled_output)
|
| 56 |
+
|
| 57 |
+
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
|
| 58 |
+
special_cos_dist = (
|
| 59 |
+
cosine_distance(image_embeds, self.special_care_embeds)
|
| 60 |
+
.cpu()
|
| 61 |
+
.float()
|
| 62 |
+
.numpy()
|
| 63 |
+
)
|
| 64 |
+
cos_dist = (
|
| 65 |
+
cosine_distance(image_embeds, self.concept_embeds).cpu().float().numpy()
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
result = []
|
| 69 |
+
batch_size = image_embeds.shape[0]
|
| 70 |
+
for i in range(batch_size):
|
| 71 |
+
result_img = {
|
| 72 |
+
"special_scores": {},
|
| 73 |
+
"special_care": [],
|
| 74 |
+
"concept_scores": {},
|
| 75 |
+
"bad_concepts": [],
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
# increase this value to create a stronger `nfsw` filter
|
| 79 |
+
# at the cost of increasing the possibility of filtering benign images
|
| 80 |
+
adjustment = 0.0
|
| 81 |
+
|
| 82 |
+
for concept_idx in range(len(special_cos_dist[0])):
|
| 83 |
+
concept_cos = special_cos_dist[i][concept_idx]
|
| 84 |
+
concept_threshold = self.special_care_embeds_weights[concept_idx].item()
|
| 85 |
+
result_img["special_scores"][concept_idx] = round(
|
| 86 |
+
concept_cos - concept_threshold + adjustment, 3
|
| 87 |
+
)
|
| 88 |
+
if result_img["special_scores"][concept_idx] > 0:
|
| 89 |
+
result_img["special_care"].append(
|
| 90 |
+
{concept_idx, result_img["special_scores"][concept_idx]}
|
| 91 |
+
)
|
| 92 |
+
adjustment = 0.01
|
| 93 |
+
|
| 94 |
+
for concept_idx in range(len(cos_dist[0])):
|
| 95 |
+
concept_cos = cos_dist[i][concept_idx]
|
| 96 |
+
concept_threshold = self.concept_embeds_weights[concept_idx].item()
|
| 97 |
+
result_img["concept_scores"][concept_idx] = round(
|
| 98 |
+
concept_cos - concept_threshold + adjustment, 3
|
| 99 |
+
)
|
| 100 |
+
if result_img["concept_scores"][concept_idx] > 0:
|
| 101 |
+
result_img["bad_concepts"].append(concept_idx)
|
| 102 |
+
|
| 103 |
+
result.append(result_img)
|
| 104 |
+
|
| 105 |
+
has_nsfw_concepts = [len(res["bad_concepts"]) > 0 for res in result]
|
| 106 |
+
|
| 107 |
+
return has_nsfw_concepts
|
| 108 |
+
|
| 109 |
+
@torch.no_grad()
|
| 110 |
+
def forward_onnx(self, clip_input: torch.FloatTensor, images: torch.FloatTensor):
|
| 111 |
+
pooled_output = self.vision_model(clip_input)[1] # pooled_output
|
| 112 |
+
image_embeds = self.visual_projection(pooled_output)
|
| 113 |
+
|
| 114 |
+
special_cos_dist = cosine_distance(image_embeds, self.special_care_embeds)
|
| 115 |
+
cos_dist = cosine_distance(image_embeds, self.concept_embeds)
|
| 116 |
+
|
| 117 |
+
# increase this value to create a stronger `nsfw` filter
|
| 118 |
+
# at the cost of increasing the possibility of filtering benign images
|
| 119 |
+
adjustment = 0.0
|
| 120 |
+
|
| 121 |
+
special_scores = (
|
| 122 |
+
special_cos_dist - self.special_care_embeds_weights + adjustment
|
| 123 |
+
)
|
| 124 |
+
# special_scores = special_scores.round(decimals=3)
|
| 125 |
+
special_care = torch.any(special_scores > 0, dim=1)
|
| 126 |
+
special_adjustment = special_care * 0.01
|
| 127 |
+
special_adjustment = special_adjustment.unsqueeze(1).expand(
|
| 128 |
+
-1, cos_dist.shape[1]
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
concept_scores = (cos_dist - self.concept_embeds_weights) + special_adjustment
|
| 132 |
+
# concept_scores = concept_scores.round(decimals=3)
|
| 133 |
+
has_nsfw_concepts = torch.any(concept_scores > 0, dim=1)
|
| 134 |
+
|
| 135 |
+
images[has_nsfw_concepts] = 0.0 # black image
|
| 136 |
+
|
| 137 |
+
return images, has_nsfw_concepts
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class SafetyChecker:
|
| 141 |
+
def __init__(self, device="cuda"):
|
| 142 |
+
from transformers import CLIPFeatureExtractor
|
| 143 |
+
|
| 144 |
+
self.device = device
|
| 145 |
+
self.safety_checker = StableDiffusionSafetyChecker.from_pretrained(
|
| 146 |
+
"CompVis/stable-diffusion-safety-checker"
|
| 147 |
+
).to(device)
|
| 148 |
+
self.feature_extractor = CLIPFeatureExtractor.from_pretrained(
|
| 149 |
+
"openai/clip-vit-base-patch32"
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
def __call__(
|
| 153 |
+
self, images: list[Image.Image]
|
| 154 |
+
) -> tuple[list[Image.Image], list[bool]]:
|
| 155 |
+
safety_checker_input = self.feature_extractor(images, return_tensors="pt").to(
|
| 156 |
+
self.device
|
| 157 |
+
)
|
| 158 |
+
has_nsfw_concepts = self.safety_checker(
|
| 159 |
+
images=[images],
|
| 160 |
+
clip_input=safety_checker_input.pixel_values.to(self.device),
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
return images, has_nsfw_concepts
|