Spaces:
Runtime error
Runtime error
pengdaqian
commited on
Commit
•
91920f4
1
Parent(s):
5ada03b
fix more
Browse files- app.py +4 -13
- model.py +41 -0
- model_test.py +2 -3
- pipeline_openvino_stable_diffusion.py +405 -0
- requirements.txt +5 -1
app.py
CHANGED
@@ -3,6 +3,8 @@ import random
|
|
3 |
import gradio as gr
|
4 |
from datasets import load_dataset
|
5 |
from PIL import Image
|
|
|
|
|
6 |
from trans_google import google_translator
|
7 |
|
8 |
from i18n import i18nTranslator
|
@@ -18,19 +20,6 @@ import torch
|
|
18 |
import base64
|
19 |
from io import BytesIO
|
20 |
|
21 |
-
#
|
22 |
-
model_id = "stabilityai/stable-diffusion-2-1-base"
|
23 |
-
|
24 |
-
scheduler = EulerDiscreteScheduler.from_pretrained(model_id, subfolder="scheduler")
|
25 |
-
pipe = StableDiffusionPipeline.from_pretrained(
|
26 |
-
model_id,
|
27 |
-
scheduler=scheduler,
|
28 |
-
# safety_checker=None,
|
29 |
-
revision="fp16",
|
30 |
-
torch_dtype=torch.float16)
|
31 |
-
|
32 |
-
if torch.cuda.is_available():
|
33 |
-
pipe = pipe.to('cuda')
|
34 |
is_gpu_busy = False
|
35 |
|
36 |
# translator = i18nTranslator()
|
@@ -54,6 +43,8 @@ samplers = [
|
|
54 |
rand = random.Random()
|
55 |
translator = google_translator()
|
56 |
|
|
|
|
|
57 |
|
58 |
def infer(prompt: str, negative: str, width: int, height: int, sampler: str, steps: int, seed: int, scale):
|
59 |
global is_gpu_busy
|
|
|
3 |
import gradio as gr
|
4 |
from datasets import load_dataset
|
5 |
from PIL import Image
|
6 |
+
|
7 |
+
from model import get_sd_small
|
8 |
from trans_google import google_translator
|
9 |
|
10 |
from i18n import i18nTranslator
|
|
|
20 |
import base64
|
21 |
from io import BytesIO
|
22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
is_gpu_busy = False
|
24 |
|
25 |
# translator = i18nTranslator()
|
|
|
43 |
rand = random.Random()
|
44 |
translator = google_translator()
|
45 |
|
46 |
+
pipe = get_sd_small()
|
47 |
+
|
48 |
|
49 |
def infer(prompt: str, negative: str, width: int, height: int, sampler: str, steps: int, seed: int, scale):
|
50 |
global is_gpu_busy
|
model.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from diffusers import StableDiffusionPipeline, EulerDiscreteScheduler, DPMSolverMultistepScheduler, \
|
3 |
+
OnnxStableDiffusionPipeline
|
4 |
+
|
5 |
+
import pipeline_openvino_stable_diffusion
|
6 |
+
|
7 |
+
|
8 |
+
def get_sd_21():
|
9 |
+
model_id = "stabilityai/stable-diffusion-2-1-base"
|
10 |
+
scheduler = EulerDiscreteScheduler.from_pretrained(model_id, subfolder="scheduler")
|
11 |
+
|
12 |
+
if torch.cuda.is_available():
|
13 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
14 |
+
model_id,
|
15 |
+
scheduler=scheduler,
|
16 |
+
# safety_checker=None,
|
17 |
+
revision="fp16",
|
18 |
+
torch_dtype=torch.float16)
|
19 |
+
pipe = pipe.to('cuda')
|
20 |
+
else:
|
21 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
22 |
+
model_id,
|
23 |
+
scheduler=scheduler,
|
24 |
+
# safety_checker=None,
|
25 |
+
revision="fp16",
|
26 |
+
torch_dtype=torch.float16)
|
27 |
+
return pipe
|
28 |
+
|
29 |
+
|
30 |
+
def get_sd_small():
|
31 |
+
model_id = 'OFA-Sys/small-stable-diffusion-v0'
|
32 |
+
scheduler = DPMSolverMultistepScheduler.from_pretrained(model_id, subfolder="scheduler")
|
33 |
+
|
34 |
+
onnx_pipe = OnnxStableDiffusionPipeline.from_pretrained(
|
35 |
+
"OFA-Sys/small-stable-diffusion-v0",
|
36 |
+
scheduler=scheduler,
|
37 |
+
revision="onnx",
|
38 |
+
provider="CPUExecutionProvider",
|
39 |
+
)
|
40 |
+
pipe = pipeline_openvino_stable_diffusion.OpenVINOStableDiffusionPipeline.from_onnx_pipeline(onnx_pipe)
|
41 |
+
return pipe
|
model_test.py
CHANGED
@@ -9,10 +9,9 @@ pipe = StableDiffusionPipeline.from_pretrained(
|
|
9 |
model_id,
|
10 |
scheduler=scheduler,
|
11 |
# safety_checker=None,
|
12 |
-
revision="fp16"
|
13 |
-
torch_dtype=torch.float16)
|
14 |
|
15 |
-
pipe = pipe.to("
|
16 |
|
17 |
prompt = "a photo of an astronaut riding a horse on mars"
|
18 |
image = pipe(prompt).images[0]
|
|
|
9 |
model_id,
|
10 |
scheduler=scheduler,
|
11 |
# safety_checker=None,
|
12 |
+
revision="fp16")
|
|
|
13 |
|
14 |
+
pipe = pipe.to("cpu")
|
15 |
|
16 |
prompt = "a photo of an astronaut riding a horse on mars"
|
17 |
image = pipe(prompt).images[0]
|
pipeline_openvino_stable_diffusion.py
ADDED
@@ -0,0 +1,405 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2022 The OFA-Sys Team.
|
2 |
+
# This source code is licensed under the Apache 2.0 license
|
3 |
+
# found in the LICENSE file in the root directory.
|
4 |
+
# Copyright 2022 The HuggingFace Inc. team.
|
5 |
+
# All rights reserved.
|
6 |
+
# This source code is licensed under the Apache 2.0 license
|
7 |
+
# found in the LICENSE file in the root directory.
|
8 |
+
|
9 |
+
import inspect
|
10 |
+
from typing import Callable, List, Optional, Union
|
11 |
+
|
12 |
+
import numpy as np
|
13 |
+
import torch
|
14 |
+
import os
|
15 |
+
|
16 |
+
from transformers import CLIPFeatureExtractor, CLIPTokenizer
|
17 |
+
|
18 |
+
from diffusers.configuration_utils import FrozenDict
|
19 |
+
from diffusers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
|
20 |
+
from diffusers.utils import deprecate, logging
|
21 |
+
from diffusers import OnnxRuntimeModel
|
22 |
+
|
23 |
+
from diffusers import OnnxStableDiffusionPipeline, DiffusionPipeline
|
24 |
+
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
|
25 |
+
from openvino.runtime import Core
|
26 |
+
ORT_TO_NP_TYPE = {
|
27 |
+
"tensor(bool)": np.bool_,
|
28 |
+
"tensor(int8)": np.int8,
|
29 |
+
"tensor(uint8)": np.uint8,
|
30 |
+
"tensor(int16)": np.int16,
|
31 |
+
"tensor(uint16)": np.uint16,
|
32 |
+
"tensor(int32)": np.int32,
|
33 |
+
"tensor(uint32)": np.uint32,
|
34 |
+
"tensor(int64)": np.int64,
|
35 |
+
"tensor(uint64)": np.uint64,
|
36 |
+
"tensor(float16)": np.float16,
|
37 |
+
"tensor(float)": np.float32,
|
38 |
+
"tensor(double)": np.float64,
|
39 |
+
}
|
40 |
+
|
41 |
+
logger = logging.get_logger(__name__)
|
42 |
+
|
43 |
+
|
44 |
+
class OpenVINOStableDiffusionPipeline(DiffusionPipeline):
|
45 |
+
vae_encoder: OnnxRuntimeModel
|
46 |
+
vae_decoder: OnnxRuntimeModel
|
47 |
+
text_encoder: OnnxRuntimeModel
|
48 |
+
tokenizer: CLIPTokenizer
|
49 |
+
unet: OnnxRuntimeModel
|
50 |
+
scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]
|
51 |
+
safety_checker: OnnxRuntimeModel
|
52 |
+
feature_extractor: CLIPFeatureExtractor
|
53 |
+
|
54 |
+
_optional_components = ["safety_checker", "feature_extractor"]
|
55 |
+
|
56 |
+
def __init__(
|
57 |
+
self,
|
58 |
+
vae_encoder: OnnxRuntimeModel,
|
59 |
+
vae_decoder: OnnxRuntimeModel,
|
60 |
+
text_encoder: OnnxRuntimeModel,
|
61 |
+
tokenizer: CLIPTokenizer,
|
62 |
+
unet: OnnxRuntimeModel,
|
63 |
+
scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
|
64 |
+
safety_checker: OnnxRuntimeModel,
|
65 |
+
feature_extractor: CLIPFeatureExtractor,
|
66 |
+
requires_safety_checker: bool = True,
|
67 |
+
):
|
68 |
+
super().__init__()
|
69 |
+
|
70 |
+
if hasattr(scheduler.config,
|
71 |
+
"steps_offset") and scheduler.config.steps_offset != 1:
|
72 |
+
deprecation_message = (
|
73 |
+
f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
|
74 |
+
f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
|
75 |
+
"to update the config accordingly as leaving `steps_offset` might led to incorrect results"
|
76 |
+
" in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
|
77 |
+
" it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
|
78 |
+
" file")
|
79 |
+
deprecate("steps_offset!=1",
|
80 |
+
"1.0.0",
|
81 |
+
deprecation_message,
|
82 |
+
standard_warn=False)
|
83 |
+
new_config = dict(scheduler.config)
|
84 |
+
new_config["steps_offset"] = 1
|
85 |
+
scheduler._internal_dict = FrozenDict(new_config)
|
86 |
+
|
87 |
+
if hasattr(scheduler.config,
|
88 |
+
"clip_sample") and scheduler.config.clip_sample is True:
|
89 |
+
deprecation_message = (
|
90 |
+
f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
|
91 |
+
" `clip_sample` should be set to False in the configuration file. Please make sure to update the"
|
92 |
+
" config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
|
93 |
+
" future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
|
94 |
+
" nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
|
95 |
+
)
|
96 |
+
deprecate("clip_sample not set",
|
97 |
+
"1.0.0",
|
98 |
+
deprecation_message,
|
99 |
+
standard_warn=False)
|
100 |
+
new_config = dict(scheduler.config)
|
101 |
+
new_config["clip_sample"] = False
|
102 |
+
scheduler._internal_dict = FrozenDict(new_config)
|
103 |
+
|
104 |
+
if safety_checker is None and requires_safety_checker:
|
105 |
+
logger.warning(
|
106 |
+
f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
|
107 |
+
" that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
|
108 |
+
" results in services or applications open to the public. Both the diffusers team and Hugging Face"
|
109 |
+
" strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
|
110 |
+
" it only for use-cases that involve analyzing network behavior or auditing its results. For more"
|
111 |
+
" information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
|
112 |
+
)
|
113 |
+
|
114 |
+
if safety_checker is not None and feature_extractor is None:
|
115 |
+
raise ValueError(
|
116 |
+
"Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
|
117 |
+
" checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
|
118 |
+
)
|
119 |
+
|
120 |
+
self.register_modules(
|
121 |
+
vae_encoder=vae_encoder,
|
122 |
+
vae_decoder=vae_decoder,
|
123 |
+
text_encoder=text_encoder,
|
124 |
+
tokenizer=tokenizer,
|
125 |
+
unet=unet,
|
126 |
+
scheduler=scheduler,
|
127 |
+
safety_checker=safety_checker,
|
128 |
+
feature_extractor=feature_extractor,
|
129 |
+
)
|
130 |
+
self.convert_to_openvino()
|
131 |
+
self.register_to_config(
|
132 |
+
requires_safety_checker=requires_safety_checker)
|
133 |
+
|
134 |
+
@classmethod
|
135 |
+
def from_onnx_pipeline(cls, onnx_pipe: OnnxStableDiffusionPipeline):
|
136 |
+
r"""
|
137 |
+
Create OpenVINOStableDiffusionPipeline from a onnx stable pipeline.
|
138 |
+
Parameters:
|
139 |
+
onnx_pipe (OnnxStableDiffusionPipeline)
|
140 |
+
"""
|
141 |
+
return cls(onnx_pipe.vae_encoder, onnx_pipe.vae_decoder,
|
142 |
+
onnx_pipe.text_encoder, onnx_pipe.tokenizer, onnx_pipe.unet,
|
143 |
+
onnx_pipe.scheduler, onnx_pipe.safety_checker,
|
144 |
+
onnx_pipe.feature_extractor, True)
|
145 |
+
|
146 |
+
def convert_to_openvino(self):
|
147 |
+
ie = Core()
|
148 |
+
|
149 |
+
# VAE decoder
|
150 |
+
vae_decoder_onnx = ie.read_model(
|
151 |
+
model=os.path.join(self.vae_decoder.model_save_dir, "model.onnx"))
|
152 |
+
vae_decoder = ie.compile_model(model=vae_decoder_onnx,
|
153 |
+
device_name="CPU")
|
154 |
+
|
155 |
+
# Text encoder
|
156 |
+
text_encoder_onnx = ie.read_model(
|
157 |
+
model=os.path.join(self.text_encoder.model_save_dir, "model.onnx"))
|
158 |
+
text_encoder = ie.compile_model(model=text_encoder_onnx,
|
159 |
+
device_name="CPU")
|
160 |
+
|
161 |
+
# Unet
|
162 |
+
unet_onnx = ie.read_model(
|
163 |
+
model=os.path.join(self.unet.model_save_dir, "model.onnx"))
|
164 |
+
unet = ie.compile_model(model=unet_onnx, device_name="CPU")
|
165 |
+
|
166 |
+
self.register_modules(vae_decoder=vae_decoder,
|
167 |
+
text_encoder=text_encoder,
|
168 |
+
unet=unet)
|
169 |
+
|
170 |
+
def _encode_prompt(self, prompt, num_images_per_prompt,
|
171 |
+
do_classifier_free_guidance, negative_prompt):
|
172 |
+
r"""
|
173 |
+
Encodes the prompt into text encoder hidden states.
|
174 |
+
Args:
|
175 |
+
prompt (`str` or `List[str]`):
|
176 |
+
prompt to be encoded
|
177 |
+
num_images_per_prompt (`int`):
|
178 |
+
number of images that should be generated per prompt
|
179 |
+
do_classifier_free_guidance (`bool`):
|
180 |
+
whether to use classifier free guidance or not
|
181 |
+
negative_prompt (`str` or `List[str]`):
|
182 |
+
The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
|
183 |
+
if `guidance_scale` is less than `1`).
|
184 |
+
"""
|
185 |
+
batch_size = len(prompt) if isinstance(prompt, list) else 1
|
186 |
+
|
187 |
+
# get prompt text embeddings
|
188 |
+
text_inputs = self.tokenizer(
|
189 |
+
prompt,
|
190 |
+
padding="max_length",
|
191 |
+
max_length=self.tokenizer.model_max_length,
|
192 |
+
truncation=True,
|
193 |
+
return_tensors="np",
|
194 |
+
)
|
195 |
+
text_input_ids = text_inputs.input_ids
|
196 |
+
untruncated_ids = self.tokenizer(prompt,
|
197 |
+
padding="max_length",
|
198 |
+
return_tensors="np").input_ids
|
199 |
+
|
200 |
+
if not np.array_equal(text_input_ids, untruncated_ids):
|
201 |
+
removed_text = self.tokenizer.batch_decode(
|
202 |
+
untruncated_ids[:, self.tokenizer.model_max_length - 1:-1])
|
203 |
+
logger.warning(
|
204 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
205 |
+
f" {self.tokenizer.model_max_length} tokens: {removed_text}")
|
206 |
+
|
207 |
+
prompt_embeds = self.text_encoder(
|
208 |
+
{"input_ids":
|
209 |
+
text_input_ids.astype(np.int32)})[self.text_encoder.outputs[0]]
|
210 |
+
prompt_embeds = np.repeat(prompt_embeds, num_images_per_prompt, axis=0)
|
211 |
+
|
212 |
+
# get unconditional embeddings for classifier free guidance
|
213 |
+
if do_classifier_free_guidance:
|
214 |
+
uncond_tokens: List[str]
|
215 |
+
if negative_prompt is None:
|
216 |
+
uncond_tokens = [""] * batch_size
|
217 |
+
elif type(prompt) is not type(negative_prompt):
|
218 |
+
raise TypeError(
|
219 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
220 |
+
f" {type(prompt)}.")
|
221 |
+
elif isinstance(negative_prompt, str):
|
222 |
+
uncond_tokens = [negative_prompt] * batch_size
|
223 |
+
elif batch_size != len(negative_prompt):
|
224 |
+
raise ValueError(
|
225 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
226 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
227 |
+
" the batch size of `prompt`.")
|
228 |
+
else:
|
229 |
+
uncond_tokens = negative_prompt
|
230 |
+
|
231 |
+
max_length = text_input_ids.shape[-1]
|
232 |
+
uncond_input = self.tokenizer(
|
233 |
+
uncond_tokens,
|
234 |
+
padding="max_length",
|
235 |
+
max_length=max_length,
|
236 |
+
truncation=True,
|
237 |
+
return_tensors="np",
|
238 |
+
)
|
239 |
+
negative_prompt_embeds = self.text_encoder({
|
240 |
+
"input_ids":
|
241 |
+
uncond_input.input_ids.astype(np.int32)
|
242 |
+
})[self.text_encoder.outputs[0]]
|
243 |
+
negative_prompt_embeds = np.repeat(negative_prompt_embeds,
|
244 |
+
num_images_per_prompt,
|
245 |
+
axis=0)
|
246 |
+
|
247 |
+
# For classifier free guidance, we need to do two forward passes.
|
248 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
249 |
+
# to avoid doing two forward passes
|
250 |
+
prompt_embeds = np.concatenate(
|
251 |
+
[negative_prompt_embeds, prompt_embeds])
|
252 |
+
|
253 |
+
return prompt_embeds
|
254 |
+
|
255 |
+
def __call__(
|
256 |
+
self,
|
257 |
+
prompt: Union[str, List[str]],
|
258 |
+
height: Optional[int] = 512,
|
259 |
+
width: Optional[int] = 512,
|
260 |
+
num_inference_steps: Optional[int] = 50,
|
261 |
+
guidance_scale: Optional[float] = 7.5,
|
262 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
263 |
+
num_images_per_prompt: Optional[int] = 1,
|
264 |
+
eta: Optional[float] = 0.0,
|
265 |
+
generator: Optional[np.random.RandomState] = None,
|
266 |
+
latents: Optional[np.ndarray] = None,
|
267 |
+
output_type: Optional[str] = "pil",
|
268 |
+
return_dict: bool = True,
|
269 |
+
callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
|
270 |
+
callback_steps: Optional[int] = 1,
|
271 |
+
):
|
272 |
+
if isinstance(prompt, str):
|
273 |
+
batch_size = 1
|
274 |
+
elif isinstance(prompt, list):
|
275 |
+
batch_size = len(prompt)
|
276 |
+
else:
|
277 |
+
raise ValueError(
|
278 |
+
f"`prompt` has to be of type `str` or `list` but is {type(prompt)}"
|
279 |
+
)
|
280 |
+
|
281 |
+
if height % 8 != 0 or width % 8 != 0:
|
282 |
+
raise ValueError(
|
283 |
+
f"`height` and `width` have to be divisible by 8 but are {height} and {width}."
|
284 |
+
)
|
285 |
+
|
286 |
+
if (callback_steps is None) or (callback_steps is not None and
|
287 |
+
(not isinstance(callback_steps, int)
|
288 |
+
or callback_steps <= 0)):
|
289 |
+
raise ValueError(
|
290 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
291 |
+
f" {type(callback_steps)}.")
|
292 |
+
|
293 |
+
if generator is None:
|
294 |
+
generator = np.random
|
295 |
+
|
296 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
297 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
298 |
+
# corresponds to doing no classifier free guidance.
|
299 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
300 |
+
|
301 |
+
prompt_embeds = self._encode_prompt(prompt, num_images_per_prompt,
|
302 |
+
do_classifier_free_guidance,
|
303 |
+
negative_prompt)
|
304 |
+
|
305 |
+
# get the initial random noise unless the user supplied it
|
306 |
+
latents_dtype = prompt_embeds.dtype
|
307 |
+
latents_shape = (batch_size * num_images_per_prompt, 4, height // 8,
|
308 |
+
width // 8)
|
309 |
+
if latents is None:
|
310 |
+
latents = generator.randn(*latents_shape).astype(latents_dtype)
|
311 |
+
elif latents.shape != latents_shape:
|
312 |
+
raise ValueError(
|
313 |
+
f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}"
|
314 |
+
)
|
315 |
+
|
316 |
+
# set timesteps
|
317 |
+
self.scheduler.set_timesteps(num_inference_steps)
|
318 |
+
|
319 |
+
latents = latents * np.float64(self.scheduler.init_noise_sigma)
|
320 |
+
|
321 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
322 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
323 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
324 |
+
# and should be between [0, 1]
|
325 |
+
accepts_eta = "eta" in set(
|
326 |
+
inspect.signature(self.scheduler.step).parameters.keys())
|
327 |
+
extra_step_kwargs = {}
|
328 |
+
if accepts_eta:
|
329 |
+
extra_step_kwargs["eta"] = eta
|
330 |
+
|
331 |
+
# timestep_dtype = next(
|
332 |
+
# (input.type for input in self.unet.model.get_inputs() if input.name == "timestep"), "tensor(float)"
|
333 |
+
# )
|
334 |
+
timestep_dtype = 'tensor(int64)'
|
335 |
+
timestep_dtype = ORT_TO_NP_TYPE[timestep_dtype]
|
336 |
+
|
337 |
+
for i, t in enumerate(self.progress_bar(self.scheduler.timesteps)):
|
338 |
+
# expand the latents if we are doing classifier free guidance
|
339 |
+
latent_model_input = np.concatenate(
|
340 |
+
[latents] * 2) if do_classifier_free_guidance else latents
|
341 |
+
latent_model_input = self.scheduler.scale_model_input(
|
342 |
+
torch.from_numpy(latent_model_input), t)
|
343 |
+
latent_model_input = latent_model_input.cpu().numpy()
|
344 |
+
|
345 |
+
# predict the noise residual
|
346 |
+
timestep = np.array([t], dtype=timestep_dtype)
|
347 |
+
unet_input = {
|
348 |
+
"sample": latent_model_input,
|
349 |
+
"timestep": timestep,
|
350 |
+
"encoder_hidden_states": prompt_embeds
|
351 |
+
}
|
352 |
+
noise_pred = self.unet(unet_input)[self.unet.outputs[0]]
|
353 |
+
# noise_pred = noise_pred[0]
|
354 |
+
|
355 |
+
# perform guidance
|
356 |
+
if do_classifier_free_guidance:
|
357 |
+
noise_pred_uncond, noise_pred_text = np.split(noise_pred, 2)
|
358 |
+
noise_pred = noise_pred_uncond + guidance_scale * (
|
359 |
+
noise_pred_text - noise_pred_uncond)
|
360 |
+
|
361 |
+
# compute the previous noisy sample x_t -> x_t-1
|
362 |
+
scheduler_output = self.scheduler.step(
|
363 |
+
torch.from_numpy(noise_pred), t, torch.from_numpy(latents),
|
364 |
+
**extra_step_kwargs)
|
365 |
+
latents = scheduler_output.prev_sample.numpy()
|
366 |
+
|
367 |
+
# call the callback, if provided
|
368 |
+
if callback is not None and i % callback_steps == 0:
|
369 |
+
callback(i, t, latents)
|
370 |
+
|
371 |
+
latents = 1 / 0.18215 * latents
|
372 |
+
image = self.vae_decoder({"latent_sample":
|
373 |
+
latents})[self.vae_decoder.outputs[0]]
|
374 |
+
|
375 |
+
image = np.clip(image / 2 + 0.5, 0, 1)
|
376 |
+
image = image.transpose((0, 2, 3, 1))
|
377 |
+
|
378 |
+
if self.safety_checker is not None:
|
379 |
+
safety_checker_input = self.feature_extractor(
|
380 |
+
self.numpy_to_pil(image),
|
381 |
+
return_tensors="np").pixel_values.astype(image.dtype)
|
382 |
+
|
383 |
+
image, has_nsfw_concepts = self.safety_checker(
|
384 |
+
clip_input=safety_checker_input, images=image)
|
385 |
+
|
386 |
+
# There will throw an error if use safety_checker batchsize>1
|
387 |
+
images, has_nsfw_concept = [], []
|
388 |
+
for i in range(image.shape[0]):
|
389 |
+
image_i, has_nsfw_concept_i = self.safety_checker(
|
390 |
+
clip_input=safety_checker_input[i:i + 1],
|
391 |
+
images=image[i:i + 1])
|
392 |
+
images.append(image_i)
|
393 |
+
has_nsfw_concept.append(has_nsfw_concept_i[0])
|
394 |
+
image = np.concatenate(images)
|
395 |
+
else:
|
396 |
+
has_nsfw_concept = None
|
397 |
+
|
398 |
+
if output_type == "pil":
|
399 |
+
image = self.numpy_to_pil(image)
|
400 |
+
|
401 |
+
if not return_dict:
|
402 |
+
return (image, has_nsfw_concept)
|
403 |
+
|
404 |
+
return StableDiffusionPipelineOutput(
|
405 |
+
images=image, nsfw_content_detected=has_nsfw_concept)
|
requirements.txt
CHANGED
@@ -4,4 +4,8 @@ transformers
|
|
4 |
accelerate
|
5 |
scipy
|
6 |
safetensors
|
7 |
-
|
|
|
|
|
|
|
|
|
|
4 |
accelerate
|
5 |
scipy
|
6 |
safetensors
|
7 |
+
onnx
|
8 |
+
openvino
|
9 |
+
onnxruntime-openvino
|
10 |
+
ftfy
|
11 |
+
py-cpuinfo
|