dbaranchuk commited on
Commit
18ee153
·
verified ·
1 Parent(s): 1997530

Create inference.py

Browse files
Files changed (1) hide show
  1. inference.py +322 -0
inference.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import torch
3
+
4
+ from typing import Any, Callable, Dict, List, Optional, Union
5
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
6
+ from diffusers.utils import (
7
+ USE_PEFT_BACKEND,
8
+ is_torch_xla_available,
9
+ logging,
10
+ replace_example_docstring,
11
+ scale_lora_layers,
12
+ unscale_lora_layers,
13
+ )
14
+ from diffusers.pipelines.stable_diffusion_3.pipeline_output import StableDiffusion3PipelineOutput
15
+
16
+ if is_torch_xla_available():
17
+ import torch_xla.core.xla_model as xm
18
+
19
+ XLA_AVAILABLE = True
20
+ else:
21
+ XLA_AVAILABLE = False
22
+
23
+
24
+ def retrieve_timesteps(
25
+ scheduler,
26
+ num_inference_steps: Optional[int] = None,
27
+ device: Optional[Union[str, torch.device]] = None,
28
+ timesteps: Optional[List[int]] = None,
29
+ sigmas: Optional[List[float]] = None,
30
+ **kwargs,
31
+ ):
32
+ if timesteps is not None and sigmas is not None:
33
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
34
+ if timesteps is not None:
35
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
36
+ if not accepts_timesteps:
37
+ raise ValueError(
38
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
39
+ f" timestep schedules. Please check whether you are using the correct scheduler."
40
+ )
41
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
42
+ timesteps = scheduler.timesteps
43
+ num_inference_steps = len(timesteps)
44
+ elif sigmas is not None:
45
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
46
+ if not accept_sigmas:
47
+ raise ValueError(
48
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
49
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
50
+ )
51
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
52
+ timesteps = scheduler.timesteps
53
+ num_inference_steps = len(timesteps)
54
+ else:
55
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
56
+ timesteps = scheduler.timesteps
57
+
58
+ return timesteps, num_inference_steps
59
+
60
+
61
+ @torch.no_grad()
62
+ def run(
63
+ self,
64
+ prompt: Union[str, List[str]] = None,
65
+ prompt_2: Optional[Union[str, List[str]]] = None,
66
+ prompt_3: Optional[Union[str, List[str]]] = None,
67
+ height: Optional[int] = None,
68
+ width: Optional[int] = None,
69
+ num_inference_steps: int = 28,
70
+ sigmas: Optional[List[float]] = None,
71
+ scales: List[float] = None,
72
+ guidance_scale: float = 7.0,
73
+ negative_prompt: Optional[Union[str, List[str]]] = None,
74
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
75
+ negative_prompt_3: Optional[Union[str, List[str]]] = None,
76
+ num_images_per_prompt: Optional[int] = 1,
77
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
78
+ latents: Optional[torch.FloatTensor] = None,
79
+ prompt_embeds: Optional[torch.FloatTensor] = None,
80
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
81
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
82
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
83
+ ip_adapter_image: Optional[PipelineImageInput] = None,
84
+ ip_adapter_image_embeds: Optional[torch.Tensor] = None,
85
+ output_type: Optional[str] = "pil",
86
+ return_dict: bool = True,
87
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
88
+ clip_skip: Optional[int] = None,
89
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
90
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
91
+ max_sequence_length: int = 256,
92
+ skip_guidance_layers: List[int] = None,
93
+ skip_layer_guidance_scale: float = 2.8,
94
+ skip_layer_guidance_stop: float = 0.2,
95
+ skip_layer_guidance_start: float = 0.01,
96
+ mu: Optional[float] = None,
97
+ ):
98
+ height = height or self.default_sample_size * self.vae_scale_factor
99
+ width = width or self.default_sample_size * self.vae_scale_factor
100
+
101
+ # 1. Check inputs. Raise error if not correct
102
+ self.check_inputs(
103
+ prompt,
104
+ prompt_2,
105
+ prompt_3,
106
+ height,
107
+ width,
108
+ negative_prompt=negative_prompt,
109
+ negative_prompt_2=negative_prompt_2,
110
+ negative_prompt_3=negative_prompt_3,
111
+ prompt_embeds=prompt_embeds,
112
+ negative_prompt_embeds=negative_prompt_embeds,
113
+ pooled_prompt_embeds=pooled_prompt_embeds,
114
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
115
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
116
+ max_sequence_length=max_sequence_length,
117
+ )
118
+
119
+ self._guidance_scale = guidance_scale
120
+ self._skip_layer_guidance_scale = skip_layer_guidance_scale
121
+ self._clip_skip = clip_skip
122
+ self._joint_attention_kwargs = joint_attention_kwargs
123
+ self._interrupt = False
124
+
125
+ # 2. Define call parameters
126
+ if prompt is not None and isinstance(prompt, str):
127
+ batch_size = 1
128
+ elif prompt is not None and isinstance(prompt, list):
129
+ batch_size = len(prompt)
130
+ else:
131
+ batch_size = prompt_embeds.shape[0]
132
+
133
+ device = self._execution_device
134
+
135
+ lora_scale = (
136
+ self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
137
+ )
138
+ (
139
+ prompt_embeds,
140
+ negative_prompt_embeds,
141
+ pooled_prompt_embeds,
142
+ negative_pooled_prompt_embeds,
143
+ ) = self.encode_prompt(
144
+ prompt=prompt,
145
+ prompt_2=prompt_2,
146
+ prompt_3=prompt_3,
147
+ negative_prompt=negative_prompt,
148
+ negative_prompt_2=negative_prompt_2,
149
+ negative_prompt_3=negative_prompt_3,
150
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
151
+ prompt_embeds=prompt_embeds,
152
+ negative_prompt_embeds=negative_prompt_embeds,
153
+ pooled_prompt_embeds=pooled_prompt_embeds,
154
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
155
+ device=device,
156
+ clip_skip=self.clip_skip,
157
+ num_images_per_prompt=num_images_per_prompt,
158
+ max_sequence_length=max_sequence_length,
159
+ lora_scale=lora_scale,
160
+ )
161
+
162
+ if self.do_classifier_free_guidance:
163
+ if skip_guidance_layers is not None:
164
+ original_prompt_embeds = prompt_embeds
165
+ original_pooled_prompt_embeds = pooled_prompt_embeds
166
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
167
+ pooled_prompt_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds], dim=0)
168
+
169
+ # 4. Prepare latent variables
170
+ num_channels_latents = self.transformer.config.in_channels
171
+ latents = self.prepare_latents(
172
+ batch_size * num_images_per_prompt,
173
+ num_channels_latents,
174
+ height,
175
+ width,
176
+ prompt_embeds.dtype,
177
+ device,
178
+ generator,
179
+ latents,
180
+ )
181
+
182
+ # 5. Prepare timesteps
183
+ scheduler_kwargs = {}
184
+ if self.scheduler.config.get("use_dynamic_shifting", None) and mu is None:
185
+ _, _, height, width = latents.shape
186
+ image_seq_len = (height // self.transformer.config.patch_size) * (
187
+ width // self.transformer.config.patch_size
188
+ )
189
+ mu = calculate_shift(
190
+ image_seq_len,
191
+ self.scheduler.config.get("base_image_seq_len", 256),
192
+ self.scheduler.config.get("max_image_seq_len", 4096),
193
+ self.scheduler.config.get("base_shift", 0.5),
194
+ self.scheduler.config.get("max_shift", 1.16),
195
+ )
196
+ scheduler_kwargs["mu"] = mu
197
+ elif mu is not None:
198
+ scheduler_kwargs["mu"] = mu
199
+ timesteps, num_inference_steps = retrieve_timesteps(
200
+ self.scheduler,
201
+ num_inference_steps,
202
+ device,
203
+ sigmas=sigmas,
204
+ **scheduler_kwargs,
205
+ )
206
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
207
+ self._num_timesteps = len(timesteps)
208
+
209
+ # 6. Prepare image embeddings
210
+ if (ip_adapter_image is not None and self.is_ip_adapter_active) or ip_adapter_image_embeds is not None:
211
+ ip_adapter_image_embeds = self.prepare_ip_adapter_image_embeds(
212
+ ip_adapter_image,
213
+ ip_adapter_image_embeds,
214
+ device,
215
+ batch_size * num_images_per_prompt,
216
+ self.do_classifier_free_guidance,
217
+ )
218
+
219
+ if self.joint_attention_kwargs is None:
220
+ self._joint_attention_kwargs = {"ip_adapter_image_embeds": ip_adapter_image_embeds}
221
+ else:
222
+ self._joint_attention_kwargs.update(ip_adapter_image_embeds=ip_adapter_image_embeds)
223
+
224
+ # 7. Denoising loop
225
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
226
+ for i, t in enumerate(timesteps):
227
+ if self.interrupt:
228
+ continue
229
+
230
+ # expand the latents if we are doing classifier free guidance
231
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
232
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
233
+ timestep = t.expand(latent_model_input.shape[0])
234
+
235
+ noise_pred = self.transformer(
236
+ hidden_states=latent_model_input,
237
+ timestep=timestep,
238
+ encoder_hidden_states=prompt_embeds,
239
+ pooled_projections=pooled_prompt_embeds,
240
+ joint_attention_kwargs=self.joint_attention_kwargs,
241
+ return_dict=False,
242
+ )[0]
243
+
244
+ # perform guidance
245
+ if self.do_classifier_free_guidance:
246
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
247
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
248
+ should_skip_layers = (
249
+ True
250
+ if i > num_inference_steps * skip_layer_guidance_start
251
+ and i < num_inference_steps * skip_layer_guidance_stop
252
+ else False
253
+ )
254
+ if skip_guidance_layers is not None and should_skip_layers:
255
+ timestep = t.expand(latents.shape[0])
256
+ latent_model_input = latents
257
+ noise_pred_skip_layers = self.transformer(
258
+ hidden_states=latent_model_input,
259
+ timestep=timestep,
260
+ encoder_hidden_states=original_prompt_embeds,
261
+ pooled_projections=original_pooled_prompt_embeds,
262
+ joint_attention_kwargs=self.joint_attention_kwargs,
263
+ return_dict=False,
264
+ skip_layers=skip_guidance_layers,
265
+ )[0]
266
+ noise_pred = (
267
+ noise_pred + (noise_pred_text - noise_pred_skip_layers) * self._skip_layer_guidance_scale
268
+ )
269
+
270
+ # compute the previous noisy sample x_t -> x_t-1
271
+ latents_dtype = latents.dtype
272
+ sigma = self.scheduler.sigmas[i]
273
+ sigma_next = self.scheduler.sigmas[i + 1]
274
+ x0_pred = (latents - sigma * noise_pred)
275
+ try:
276
+ x0_pred = torch.nn.functional.interpolate(x0_pred, size=scales[i + 1])
277
+ except IndexError:
278
+ x0_pred = x0_pred
279
+ noise = torch.randn(x0_pred.shape, generator=generator).to('cuda').half()
280
+ latents = (1 - sigma_next) * x0_pred + sigma_next * noise
281
+
282
+ if latents.dtype != latents_dtype:
283
+ if torch.backends.mps.is_available():
284
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
285
+ latents = latents.to(latents_dtype)
286
+
287
+ if callback_on_step_end is not None:
288
+ callback_kwargs = {}
289
+ for k in callback_on_step_end_tensor_inputs:
290
+ callback_kwargs[k] = locals()[k]
291
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
292
+
293
+ latents = callback_outputs.pop("latents", latents)
294
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
295
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
296
+ negative_pooled_prompt_embeds = callback_outputs.pop(
297
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
298
+ )
299
+
300
+ # call the callback, if provided
301
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
302
+ progress_bar.update()
303
+
304
+ if XLA_AVAILABLE:
305
+ xm.mark_step()
306
+
307
+ if output_type == "latent":
308
+ image = latents
309
+
310
+ else:
311
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
312
+
313
+ image = self.vae.decode(latents, return_dict=False)[0]
314
+ image = self.image_processor.postprocess(image, output_type=output_type)
315
+
316
+ # Offload all models
317
+ self.maybe_free_model_hooks()
318
+
319
+ if not return_dict:
320
+ return (image,)
321
+
322
+ return StableDiffusion3PipelineOutput(images=image)