陆鹿 commited on
Commit
ff88d5b
1 Parent(s): 2d8d07a

:tada: init

Browse files
Files changed (3) hide show
  1. app.py +110 -0
  2. pipeline_openvino_stable_diffusion.py +405 -0
  3. requirements.txt +9 -0
app.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffusers import StableDiffusionPipeline, StableDiffusionImg2ImgPipeline, DPMSolverMultistepScheduler
2
+ import gradio as gr
3
+ import torch
4
+ from PIL import Image
5
+ from diffusers import OnnxStableDiffusionPipeline
6
+ import pipeline_openvino_stable_diffusion
7
+
8
+ model_id = 'OFA-Sys/small-stable-diffusion-v0'
9
+ prefix = ''
10
+
11
+ scheduler = DPMSolverMultistepScheduler.from_pretrained(model_id, subfolder="scheduler")
12
+
13
+
14
+ onnx_pipe = OnnxStableDiffusionPipeline.from_pretrained(
15
+ "OFA-Sys/small-stable-diffusion-v0",
16
+ revision="onnx",
17
+ provider="CPUExecutionProvider",
18
+ )
19
+ pipe = pipeline_openvino_stable_diffusion.OpenVINOStableDiffusionPipeline.from_onnx_pipeline(onnx_pipe)
20
+
21
+ def error_str(error, title="Error"):
22
+ return f"""#### {title}
23
+ {error}""" if error else ""
24
+
25
+ def inference(prompt, guidance, steps, width=512, height=512, seed=0, neg_prompt="", auto_prefix=False):
26
+
27
+ generator = torch.Generator('cuda').manual_seed(seed) if seed != 0 else None
28
+ prompt = f"{prefix} {prompt}" if auto_prefix else prompt
29
+
30
+ try:
31
+ return txt_to_img(prompt, neg_prompt, guidance, steps, width, height, generator), None
32
+ except Exception as e:
33
+ return None, error_str(e)
34
+
35
+ def txt_to_img(prompt, neg_prompt, guidance, steps, width, height, generator):
36
+
37
+ result = pipe(
38
+ prompt,
39
+ negative_prompt = neg_prompt,
40
+ num_inference_steps = int(steps),
41
+ guidance_scale = guidance,
42
+ width = width,
43
+ height = height,
44
+ generator = generator)
45
+
46
+ return result.images[0]
47
+
48
+
49
+ css = """.main-div div{display:inline-flex;align-items:center;gap:.8rem;font-size:1.75rem}.main-div div h1{font-weight:900;margin-bottom:7px}.main-div p{margin-bottom:10px;font-size:94%}a{text-decoration:underline}.tabs{margin-top:0;margin-bottom:0}#gallery{min-height:20rem}
50
+ """
51
+ with gr.Blocks(css=css) as demo:
52
+ gr.HTML(
53
+ f"""
54
+ <div class="main-div">
55
+ <div>
56
+ <h1>Small Stable Diffusion V0</h1>
57
+ </div>
58
+ <p>
59
+ Demo for <a href="https://huggingface.co/OFA-Sys/small-stable-diffusion-v0">Small Stable Diffusion V0</a> Stable Diffusion model.<br>
60
+
61
+ </p>
62
+ Running on CPUs with <a href="https://github.com/OFA-Sys/diffusion-deploy">diffusion-deploy</a> to speedup the inference.
63
+
64
+ </div>
65
+ """
66
+ )
67
+ with gr.Row():
68
+
69
+ with gr.Column(scale=55):
70
+ with gr.Group():
71
+ with gr.Row():
72
+ prompt = gr.Textbox(label="Prompt", show_label=False, max_lines=2,placeholder=f"{prefix} [your prompt]").style(container=False)
73
+ generate = gr.Button(value="Generate").style(rounded=(False, True, True, False))
74
+
75
+ image_out = gr.Image(height=512)
76
+ error_output = gr.Markdown()
77
+
78
+ with gr.Column(scale=45):
79
+ with gr.Tab("Options"):
80
+ with gr.Group():
81
+ neg_prompt = gr.Textbox(label="Negative prompt", placeholder="What to exclude from the image")
82
+
83
+
84
+ with gr.Row():
85
+ guidance = gr.Slider(label="Guidance scale", value=7.5, maximum=15)
86
+ steps = gr.Slider(label="Steps", value=15, minimum=2, maximum=75, step=1)
87
+
88
+ with gr.Row():
89
+ width = gr.Slider(label="Width", value=512, minimum=64, maximum=1024, step=8)
90
+ height = gr.Slider(label="Height", value=512, minimum=64, maximum=1024, step=8)
91
+
92
+ seed = gr.Slider(0, 2147483647, label='Seed (0 = random)', value=0, step=1)
93
+
94
+
95
+
96
+
97
+ inputs = [prompt, guidance, steps, width, height, seed, neg_prompt, auto_prefix]
98
+ outputs = [image_out, error_output]
99
+ prompt.submit(inference, inputs=inputs, outputs=outputs)
100
+ generate.click(inference, inputs=inputs, outputs=outputs)
101
+
102
+ gr.HTML("""
103
+ <div style="border-top: 1px solid #303030;">
104
+ <br>
105
+ <p>This space was created using <a href="https://huggingface.co/spaces/anzorq/sd-space-creator">SD Space Creator</a>.</p>
106
+ </div>
107
+ """)
108
+
109
+ demo.queue(concurrency_count=1)
110
+ demo.launch()
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.onnx_utils 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 ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cu113
2
+ torch
3
+ diffusers
4
+ #transformers
5
+ git+https://github.com/huggingface/transformers
6
+ accelerate
7
+ ftfy
8
+ onnxruntime-openvino
9
+ openvino