Datasets:

ArXiv:
Diffusers Bot commited on
Commit
fcb9f8b
1 Parent(s): 4711372

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. v0.22.0/README.md +0 -0
  2. v0.22.0/bit_diffusion.py +264 -0
  3. v0.22.0/checkpoint_merger.py +280 -0
  4. v0.22.0/clip_guided_images_mixing_stable_diffusion.py +455 -0
  5. v0.22.0/clip_guided_stable_diffusion.py +347 -0
  6. v0.22.0/clip_guided_stable_diffusion_img2img.py +493 -0
  7. v0.22.0/composable_stable_diffusion.py +581 -0
  8. v0.22.0/ddim_noise_comparative_analysis.py +190 -0
  9. v0.22.0/edict_pipeline.py +264 -0
  10. v0.22.0/iadb.py +149 -0
  11. v0.22.0/imagic_stable_diffusion.py +496 -0
  12. v0.22.0/img2img_inpainting.py +464 -0
  13. v0.22.0/interpolate_stable_diffusion.py +525 -0
  14. v0.22.0/latent_consistency_img2img.py +829 -0
  15. v0.22.0/latent_consistency_txt2img.py +730 -0
  16. v0.22.0/lpw_stable_diffusion.py +1471 -0
  17. v0.22.0/lpw_stable_diffusion_onnx.py +1147 -0
  18. v0.22.0/lpw_stable_diffusion_xl.py +1288 -0
  19. v0.22.0/magic_mix.py +152 -0
  20. v0.22.0/masked_stable_diffusion_img2img.py +262 -0
  21. v0.22.0/mixture_canvas.py +503 -0
  22. v0.22.0/mixture_tiling.py +405 -0
  23. v0.22.0/multilingual_stable_diffusion.py +437 -0
  24. v0.22.0/one_step_unet.py +24 -0
  25. v0.22.0/pipeline_fabric.py +751 -0
  26. v0.22.0/pipeline_prompt2prompt.py +860 -0
  27. v0.22.0/pipeline_zero1to3.py +891 -0
  28. v0.22.0/run_onnx_controlnet.py +910 -0
  29. v0.22.0/run_tensorrt_controlnet.py +1021 -0
  30. v0.22.0/sd_text2img_k_diffusion.py +475 -0
  31. v0.22.0/seed_resize_stable_diffusion.py +367 -0
  32. v0.22.0/speech_to_image_diffusion.py +262 -0
  33. v0.22.0/stable_diffusion_comparison.py +405 -0
  34. v0.22.0/stable_diffusion_controlnet_img2img.py +990 -0
  35. v0.22.0/stable_diffusion_controlnet_inpaint.py +1139 -0
  36. v0.22.0/stable_diffusion_controlnet_inpaint_img2img.py +1120 -0
  37. v0.22.0/stable_diffusion_controlnet_reference.py +836 -0
  38. v0.22.0/stable_diffusion_ipex.py +858 -0
  39. v0.22.0/stable_diffusion_mega.py +227 -0
  40. v0.22.0/stable_diffusion_reference.py +797 -0
  41. v0.22.0/stable_diffusion_repaint.py +957 -0
  42. v0.22.0/stable_diffusion_tensorrt_img2img.py +1055 -0
  43. v0.22.0/stable_diffusion_tensorrt_inpaint.py +1107 -0
  44. v0.22.0/stable_diffusion_tensorrt_txt2img.py +928 -0
  45. v0.22.0/stable_diffusion_xl_reference.py +807 -0
  46. v0.22.0/stable_unclip.py +288 -0
  47. v0.22.0/text_inpainting.py +302 -0
  48. v0.22.0/tiled_upscaling.py +298 -0
  49. v0.22.0/unclip_image_interpolation.py +496 -0
  50. v0.22.0/unclip_text_interpolation.py +574 -0
v0.22.0/README.md ADDED
The diff for this file is too large to render. See raw diff
 
v0.22.0/bit_diffusion.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Tuple, Union
2
+
3
+ import torch
4
+ from einops import rearrange, reduce
5
+
6
+ from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNet2DConditionModel
7
+ from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput
8
+ from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput
9
+
10
+
11
+ BITS = 8
12
+
13
+
14
+ # convert to bit representations and back taken from https://github.com/lucidrains/bit-diffusion/blob/main/bit_diffusion/bit_diffusion.py
15
+ def decimal_to_bits(x, bits=BITS):
16
+ """expects image tensor ranging from 0 to 1, outputs bit tensor ranging from -1 to 1"""
17
+ device = x.device
18
+
19
+ x = (x * 255).int().clamp(0, 255)
20
+
21
+ mask = 2 ** torch.arange(bits - 1, -1, -1, device=device)
22
+ mask = rearrange(mask, "d -> d 1 1")
23
+ x = rearrange(x, "b c h w -> b c 1 h w")
24
+
25
+ bits = ((x & mask) != 0).float()
26
+ bits = rearrange(bits, "b c d h w -> b (c d) h w")
27
+ bits = bits * 2 - 1
28
+ return bits
29
+
30
+
31
+ def bits_to_decimal(x, bits=BITS):
32
+ """expects bits from -1 to 1, outputs image tensor from 0 to 1"""
33
+ device = x.device
34
+
35
+ x = (x > 0).int()
36
+ mask = 2 ** torch.arange(bits - 1, -1, -1, device=device, dtype=torch.int32)
37
+
38
+ mask = rearrange(mask, "d -> d 1 1")
39
+ x = rearrange(x, "b (c d) h w -> b c d h w", d=8)
40
+ dec = reduce(x * mask, "b c d h w -> b c h w", "sum")
41
+ return (dec / 255).clamp(0.0, 1.0)
42
+
43
+
44
+ # modified scheduler step functions for clamping the predicted x_0 between -bit_scale and +bit_scale
45
+ def ddim_bit_scheduler_step(
46
+ self,
47
+ model_output: torch.FloatTensor,
48
+ timestep: int,
49
+ sample: torch.FloatTensor,
50
+ eta: float = 0.0,
51
+ use_clipped_model_output: bool = True,
52
+ generator=None,
53
+ return_dict: bool = True,
54
+ ) -> Union[DDIMSchedulerOutput, Tuple]:
55
+ """
56
+ Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion
57
+ process from the learned model outputs (most often the predicted noise).
58
+ Args:
59
+ model_output (`torch.FloatTensor`): direct output from learned diffusion model.
60
+ timestep (`int`): current discrete timestep in the diffusion chain.
61
+ sample (`torch.FloatTensor`):
62
+ current instance of sample being created by diffusion process.
63
+ eta (`float`): weight of noise for added noise in diffusion step.
64
+ use_clipped_model_output (`bool`): TODO
65
+ generator: random number generator.
66
+ return_dict (`bool`): option for returning tuple rather than DDIMSchedulerOutput class
67
+ Returns:
68
+ [`~schedulers.scheduling_utils.DDIMSchedulerOutput`] or `tuple`:
69
+ [`~schedulers.scheduling_utils.DDIMSchedulerOutput`] if `return_dict` is True, otherwise a `tuple`. When
70
+ returning a tuple, the first element is the sample tensor.
71
+ """
72
+ if self.num_inference_steps is None:
73
+ raise ValueError(
74
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
75
+ )
76
+
77
+ # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf
78
+ # Ideally, read DDIM paper in-detail understanding
79
+
80
+ # Notation (<variable name> -> <name in paper>
81
+ # - pred_noise_t -> e_theta(x_t, t)
82
+ # - pred_original_sample -> f_theta(x_t, t) or x_0
83
+ # - std_dev_t -> sigma_t
84
+ # - eta -> η
85
+ # - pred_sample_direction -> "direction pointing to x_t"
86
+ # - pred_prev_sample -> "x_t-1"
87
+
88
+ # 1. get previous step value (=t-1)
89
+ prev_timestep = timestep - self.config.num_train_timesteps // self.num_inference_steps
90
+
91
+ # 2. compute alphas, betas
92
+ alpha_prod_t = self.alphas_cumprod[timestep]
93
+ alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
94
+
95
+ beta_prod_t = 1 - alpha_prod_t
96
+
97
+ # 3. compute predicted original sample from predicted noise also called
98
+ # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
99
+ pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
100
+
101
+ # 4. Clip "predicted x_0"
102
+ scale = self.bit_scale
103
+ if self.config.clip_sample:
104
+ pred_original_sample = torch.clamp(pred_original_sample, -scale, scale)
105
+
106
+ # 5. compute variance: "sigma_t(η)" -> see formula (16)
107
+ # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
108
+ variance = self._get_variance(timestep, prev_timestep)
109
+ std_dev_t = eta * variance ** (0.5)
110
+
111
+ if use_clipped_model_output:
112
+ # the model_output is always re-derived from the clipped x_0 in Glide
113
+ model_output = (sample - alpha_prod_t ** (0.5) * pred_original_sample) / beta_prod_t ** (0.5)
114
+
115
+ # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
116
+ pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * model_output
117
+
118
+ # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
119
+ prev_sample = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction
120
+
121
+ if eta > 0:
122
+ # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072
123
+ device = model_output.device if torch.is_tensor(model_output) else "cpu"
124
+ noise = torch.randn(model_output.shape, dtype=model_output.dtype, generator=generator).to(device)
125
+ variance = self._get_variance(timestep, prev_timestep) ** (0.5) * eta * noise
126
+
127
+ prev_sample = prev_sample + variance
128
+
129
+ if not return_dict:
130
+ return (prev_sample,)
131
+
132
+ return DDIMSchedulerOutput(prev_sample=prev_sample, pred_original_sample=pred_original_sample)
133
+
134
+
135
+ def ddpm_bit_scheduler_step(
136
+ self,
137
+ model_output: torch.FloatTensor,
138
+ timestep: int,
139
+ sample: torch.FloatTensor,
140
+ prediction_type="epsilon",
141
+ generator=None,
142
+ return_dict: bool = True,
143
+ ) -> Union[DDPMSchedulerOutput, Tuple]:
144
+ """
145
+ Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion
146
+ process from the learned model outputs (most often the predicted noise).
147
+ Args:
148
+ model_output (`torch.FloatTensor`): direct output from learned diffusion model.
149
+ timestep (`int`): current discrete timestep in the diffusion chain.
150
+ sample (`torch.FloatTensor`):
151
+ current instance of sample being created by diffusion process.
152
+ prediction_type (`str`, default `epsilon`):
153
+ indicates whether the model predicts the noise (epsilon), or the samples (`sample`).
154
+ generator: random number generator.
155
+ return_dict (`bool`): option for returning tuple rather than DDPMSchedulerOutput class
156
+ Returns:
157
+ [`~schedulers.scheduling_utils.DDPMSchedulerOutput`] or `tuple`:
158
+ [`~schedulers.scheduling_utils.DDPMSchedulerOutput`] if `return_dict` is True, otherwise a `tuple`. When
159
+ returning a tuple, the first element is the sample tensor.
160
+ """
161
+ t = timestep
162
+
163
+ if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]:
164
+ model_output, predicted_variance = torch.split(model_output, sample.shape[1], dim=1)
165
+ else:
166
+ predicted_variance = None
167
+
168
+ # 1. compute alphas, betas
169
+ alpha_prod_t = self.alphas_cumprod[t]
170
+ alpha_prod_t_prev = self.alphas_cumprod[t - 1] if t > 0 else self.one
171
+ beta_prod_t = 1 - alpha_prod_t
172
+ beta_prod_t_prev = 1 - alpha_prod_t_prev
173
+
174
+ # 2. compute predicted original sample from predicted noise also called
175
+ # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf
176
+ if prediction_type == "epsilon":
177
+ pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
178
+ elif prediction_type == "sample":
179
+ pred_original_sample = model_output
180
+ else:
181
+ raise ValueError(f"Unsupported prediction_type {prediction_type}.")
182
+
183
+ # 3. Clip "predicted x_0"
184
+ scale = self.bit_scale
185
+ if self.config.clip_sample:
186
+ pred_original_sample = torch.clamp(pred_original_sample, -scale, scale)
187
+
188
+ # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t
189
+ # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
190
+ pred_original_sample_coeff = (alpha_prod_t_prev ** (0.5) * self.betas[t]) / beta_prod_t
191
+ current_sample_coeff = self.alphas[t] ** (0.5) * beta_prod_t_prev / beta_prod_t
192
+
193
+ # 5. Compute predicted previous sample µ_t
194
+ # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
195
+ pred_prev_sample = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample
196
+
197
+ # 6. Add noise
198
+ variance = 0
199
+ if t > 0:
200
+ noise = torch.randn(
201
+ model_output.size(), dtype=model_output.dtype, layout=model_output.layout, generator=generator
202
+ ).to(model_output.device)
203
+ variance = (self._get_variance(t, predicted_variance=predicted_variance) ** 0.5) * noise
204
+
205
+ pred_prev_sample = pred_prev_sample + variance
206
+
207
+ if not return_dict:
208
+ return (pred_prev_sample,)
209
+
210
+ return DDPMSchedulerOutput(prev_sample=pred_prev_sample, pred_original_sample=pred_original_sample)
211
+
212
+
213
+ class BitDiffusion(DiffusionPipeline):
214
+ def __init__(
215
+ self,
216
+ unet: UNet2DConditionModel,
217
+ scheduler: Union[DDIMScheduler, DDPMScheduler],
218
+ bit_scale: Optional[float] = 1.0,
219
+ ):
220
+ super().__init__()
221
+ self.bit_scale = bit_scale
222
+ self.scheduler.step = (
223
+ ddim_bit_scheduler_step if isinstance(scheduler, DDIMScheduler) else ddpm_bit_scheduler_step
224
+ )
225
+
226
+ self.register_modules(unet=unet, scheduler=scheduler)
227
+
228
+ @torch.no_grad()
229
+ def __call__(
230
+ self,
231
+ height: Optional[int] = 256,
232
+ width: Optional[int] = 256,
233
+ num_inference_steps: Optional[int] = 50,
234
+ generator: Optional[torch.Generator] = None,
235
+ batch_size: Optional[int] = 1,
236
+ output_type: Optional[str] = "pil",
237
+ return_dict: bool = True,
238
+ **kwargs,
239
+ ) -> Union[Tuple, ImagePipelineOutput]:
240
+ latents = torch.randn(
241
+ (batch_size, self.unet.config.in_channels, height, width),
242
+ generator=generator,
243
+ )
244
+ latents = decimal_to_bits(latents) * self.bit_scale
245
+ latents = latents.to(self.device)
246
+
247
+ self.scheduler.set_timesteps(num_inference_steps)
248
+
249
+ for t in self.progress_bar(self.scheduler.timesteps):
250
+ # predict the noise residual
251
+ noise_pred = self.unet(latents, t).sample
252
+
253
+ # compute the previous noisy sample x_t -> x_t-1
254
+ latents = self.scheduler.step(noise_pred, t, latents).prev_sample
255
+
256
+ image = bits_to_decimal(latents)
257
+
258
+ if output_type == "pil":
259
+ image = self.numpy_to_pil(image)
260
+
261
+ if not return_dict:
262
+ return (image,)
263
+
264
+ return ImagePipelineOutput(images=image)
v0.22.0/checkpoint_merger.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import os
3
+ from typing import Dict, List, Union
4
+
5
+ import safetensors.torch
6
+ import torch
7
+ from huggingface_hub import snapshot_download
8
+
9
+ from diffusers import DiffusionPipeline, __version__
10
+ from diffusers.schedulers.scheduling_utils import SCHEDULER_CONFIG_NAME
11
+ from diffusers.utils import CONFIG_NAME, DIFFUSERS_CACHE, ONNX_WEIGHTS_NAME, WEIGHTS_NAME
12
+
13
+
14
+ class CheckpointMergerPipeline(DiffusionPipeline):
15
+ """
16
+ A class that that supports merging diffusion models based on the discussion here:
17
+ https://github.com/huggingface/diffusers/issues/877
18
+
19
+ Example usage:-
20
+
21
+ pipe = DiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", custom_pipeline="checkpoint_merger.py")
22
+
23
+ merged_pipe = pipe.merge(["CompVis/stable-diffusion-v1-4","prompthero/openjourney"], interp = 'inv_sigmoid', alpha = 0.8, force = True)
24
+
25
+ merged_pipe.to('cuda')
26
+
27
+ prompt = "An astronaut riding a unicycle on Mars"
28
+
29
+ results = merged_pipe(prompt)
30
+
31
+ ## For more details, see the docstring for the merge method.
32
+
33
+ """
34
+
35
+ def __init__(self):
36
+ self.register_to_config()
37
+ super().__init__()
38
+
39
+ def _compare_model_configs(self, dict0, dict1):
40
+ if dict0 == dict1:
41
+ return True
42
+ else:
43
+ config0, meta_keys0 = self._remove_meta_keys(dict0)
44
+ config1, meta_keys1 = self._remove_meta_keys(dict1)
45
+ if config0 == config1:
46
+ print(f"Warning !: Mismatch in keys {meta_keys0} and {meta_keys1}.")
47
+ return True
48
+ return False
49
+
50
+ def _remove_meta_keys(self, config_dict: Dict):
51
+ meta_keys = []
52
+ temp_dict = config_dict.copy()
53
+ for key in config_dict.keys():
54
+ if key.startswith("_"):
55
+ temp_dict.pop(key)
56
+ meta_keys.append(key)
57
+ return (temp_dict, meta_keys)
58
+
59
+ @torch.no_grad()
60
+ def merge(self, pretrained_model_name_or_path_list: List[Union[str, os.PathLike]], **kwargs):
61
+ """
62
+ Returns a new pipeline object of the class 'DiffusionPipeline' with the merged checkpoints(weights) of the models passed
63
+ in the argument 'pretrained_model_name_or_path_list' as a list.
64
+
65
+ Parameters:
66
+ -----------
67
+ pretrained_model_name_or_path_list : A list of valid pretrained model names in the HuggingFace hub or paths to locally stored models in the HuggingFace format.
68
+
69
+ **kwargs:
70
+ Supports all the default DiffusionPipeline.get_config_dict kwargs viz..
71
+
72
+ cache_dir, resume_download, force_download, proxies, local_files_only, use_auth_token, revision, torch_dtype, device_map.
73
+
74
+ alpha - The interpolation parameter. Ranges from 0 to 1. It affects the ratio in which the checkpoints are merged. A 0.8 alpha
75
+ would mean that the first model checkpoints would affect the final result far less than an alpha of 0.2
76
+
77
+ interp - The interpolation method to use for the merging. Supports "sigmoid", "inv_sigmoid", "add_diff" and None.
78
+ Passing None uses the default interpolation which is weighted sum interpolation. For merging three checkpoints, only "add_diff" is supported.
79
+
80
+ force - Whether to ignore mismatch in model_config.json for the current models. Defaults to False.
81
+
82
+ """
83
+ # Default kwargs from DiffusionPipeline
84
+ cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
85
+ resume_download = kwargs.pop("resume_download", False)
86
+ force_download = kwargs.pop("force_download", False)
87
+ proxies = kwargs.pop("proxies", None)
88
+ local_files_only = kwargs.pop("local_files_only", False)
89
+ use_auth_token = kwargs.pop("use_auth_token", None)
90
+ revision = kwargs.pop("revision", None)
91
+ torch_dtype = kwargs.pop("torch_dtype", None)
92
+ device_map = kwargs.pop("device_map", None)
93
+
94
+ alpha = kwargs.pop("alpha", 0.5)
95
+ interp = kwargs.pop("interp", None)
96
+
97
+ print("Received list", pretrained_model_name_or_path_list)
98
+ print(f"Combining with alpha={alpha}, interpolation mode={interp}")
99
+
100
+ checkpoint_count = len(pretrained_model_name_or_path_list)
101
+ # Ignore result from model_index_json comparision of the two checkpoints
102
+ force = kwargs.pop("force", False)
103
+
104
+ # If less than 2 checkpoints, nothing to merge. If more than 3, not supported for now.
105
+ if checkpoint_count > 3 or checkpoint_count < 2:
106
+ raise ValueError(
107
+ "Received incorrect number of checkpoints to merge. Ensure that either 2 or 3 checkpoints are being"
108
+ " passed."
109
+ )
110
+
111
+ print("Received the right number of checkpoints")
112
+ # chkpt0, chkpt1 = pretrained_model_name_or_path_list[0:2]
113
+ # chkpt2 = pretrained_model_name_or_path_list[2] if checkpoint_count == 3 else None
114
+
115
+ # Validate that the checkpoints can be merged
116
+ # Step 1: Load the model config and compare the checkpoints. We'll compare the model_index.json first while ignoring the keys starting with '_'
117
+ config_dicts = []
118
+ for pretrained_model_name_or_path in pretrained_model_name_or_path_list:
119
+ config_dict = DiffusionPipeline.load_config(
120
+ pretrained_model_name_or_path,
121
+ cache_dir=cache_dir,
122
+ resume_download=resume_download,
123
+ force_download=force_download,
124
+ proxies=proxies,
125
+ local_files_only=local_files_only,
126
+ use_auth_token=use_auth_token,
127
+ revision=revision,
128
+ )
129
+ config_dicts.append(config_dict)
130
+
131
+ comparison_result = True
132
+ for idx in range(1, len(config_dicts)):
133
+ comparison_result &= self._compare_model_configs(config_dicts[idx - 1], config_dicts[idx])
134
+ if not force and comparison_result is False:
135
+ raise ValueError("Incompatible checkpoints. Please check model_index.json for the models.")
136
+ print(config_dicts[0], config_dicts[1])
137
+ print("Compatible model_index.json files found")
138
+ # Step 2: Basic Validation has succeeded. Let's download the models and save them into our local files.
139
+ cached_folders = []
140
+ for pretrained_model_name_or_path, config_dict in zip(pretrained_model_name_or_path_list, config_dicts):
141
+ folder_names = [k for k in config_dict.keys() if not k.startswith("_")]
142
+ allow_patterns = [os.path.join(k, "*") for k in folder_names]
143
+ allow_patterns += [
144
+ WEIGHTS_NAME,
145
+ SCHEDULER_CONFIG_NAME,
146
+ CONFIG_NAME,
147
+ ONNX_WEIGHTS_NAME,
148
+ DiffusionPipeline.config_name,
149
+ ]
150
+ requested_pipeline_class = config_dict.get("_class_name")
151
+ user_agent = {"diffusers": __version__, "pipeline_class": requested_pipeline_class}
152
+
153
+ cached_folder = (
154
+ pretrained_model_name_or_path
155
+ if os.path.isdir(pretrained_model_name_or_path)
156
+ else snapshot_download(
157
+ pretrained_model_name_or_path,
158
+ cache_dir=cache_dir,
159
+ resume_download=resume_download,
160
+ proxies=proxies,
161
+ local_files_only=local_files_only,
162
+ use_auth_token=use_auth_token,
163
+ revision=revision,
164
+ allow_patterns=allow_patterns,
165
+ user_agent=user_agent,
166
+ )
167
+ )
168
+ print("Cached Folder", cached_folder)
169
+ cached_folders.append(cached_folder)
170
+
171
+ # Step 3:-
172
+ # Load the first checkpoint as a diffusion pipeline and modify its module state_dict in place
173
+ final_pipe = DiffusionPipeline.from_pretrained(
174
+ cached_folders[0], torch_dtype=torch_dtype, device_map=device_map
175
+ )
176
+ final_pipe.to(self.device)
177
+
178
+ checkpoint_path_2 = None
179
+ if len(cached_folders) > 2:
180
+ checkpoint_path_2 = os.path.join(cached_folders[2])
181
+
182
+ if interp == "sigmoid":
183
+ theta_func = CheckpointMergerPipeline.sigmoid
184
+ elif interp == "inv_sigmoid":
185
+ theta_func = CheckpointMergerPipeline.inv_sigmoid
186
+ elif interp == "add_diff":
187
+ theta_func = CheckpointMergerPipeline.add_difference
188
+ else:
189
+ theta_func = CheckpointMergerPipeline.weighted_sum
190
+
191
+ # Find each module's state dict.
192
+ for attr in final_pipe.config.keys():
193
+ if not attr.startswith("_"):
194
+ checkpoint_path_1 = os.path.join(cached_folders[1], attr)
195
+ if os.path.exists(checkpoint_path_1):
196
+ files = [
197
+ *glob.glob(os.path.join(checkpoint_path_1, "*.safetensors")),
198
+ *glob.glob(os.path.join(checkpoint_path_1, "*.bin")),
199
+ ]
200
+ checkpoint_path_1 = files[0] if len(files) > 0 else None
201
+ if len(cached_folders) < 3:
202
+ checkpoint_path_2 = None
203
+ else:
204
+ checkpoint_path_2 = os.path.join(cached_folders[2], attr)
205
+ if os.path.exists(checkpoint_path_2):
206
+ files = [
207
+ *glob.glob(os.path.join(checkpoint_path_2, "*.safetensors")),
208
+ *glob.glob(os.path.join(checkpoint_path_2, "*.bin")),
209
+ ]
210
+ checkpoint_path_2 = files[0] if len(files) > 0 else None
211
+ # For an attr if both checkpoint_path_1 and 2 are None, ignore.
212
+ # If atleast one is present, deal with it according to interp method, of course only if the state_dict keys match.
213
+ if checkpoint_path_1 is None and checkpoint_path_2 is None:
214
+ print(f"Skipping {attr}: not present in 2nd or 3d model")
215
+ continue
216
+ try:
217
+ module = getattr(final_pipe, attr)
218
+ if isinstance(module, bool): # ignore requires_safety_checker boolean
219
+ continue
220
+ theta_0 = getattr(module, "state_dict")
221
+ theta_0 = theta_0()
222
+
223
+ update_theta_0 = getattr(module, "load_state_dict")
224
+ theta_1 = (
225
+ safetensors.torch.load_file(checkpoint_path_1)
226
+ if (checkpoint_path_1.endswith(".safetensors"))
227
+ else torch.load(checkpoint_path_1, map_location="cpu")
228
+ )
229
+ theta_2 = None
230
+ if checkpoint_path_2:
231
+ theta_2 = (
232
+ safetensors.torch.load_file(checkpoint_path_2)
233
+ if (checkpoint_path_2.endswith(".safetensors"))
234
+ else torch.load(checkpoint_path_2, map_location="cpu")
235
+ )
236
+
237
+ if not theta_0.keys() == theta_1.keys():
238
+ print(f"Skipping {attr}: key mismatch")
239
+ continue
240
+ if theta_2 and not theta_1.keys() == theta_2.keys():
241
+ print(f"Skipping {attr}:y mismatch")
242
+ except Exception as e:
243
+ print(f"Skipping {attr} do to an unexpected error: {str(e)}")
244
+ continue
245
+ print(f"MERGING {attr}")
246
+
247
+ for key in theta_0.keys():
248
+ if theta_2:
249
+ theta_0[key] = theta_func(theta_0[key], theta_1[key], theta_2[key], alpha)
250
+ else:
251
+ theta_0[key] = theta_func(theta_0[key], theta_1[key], None, alpha)
252
+
253
+ del theta_1
254
+ del theta_2
255
+ update_theta_0(theta_0)
256
+
257
+ del theta_0
258
+ return final_pipe
259
+
260
+ @staticmethod
261
+ def weighted_sum(theta0, theta1, theta2, alpha):
262
+ return ((1 - alpha) * theta0) + (alpha * theta1)
263
+
264
+ # Smoothstep (https://en.wikipedia.org/wiki/Smoothstep)
265
+ @staticmethod
266
+ def sigmoid(theta0, theta1, theta2, alpha):
267
+ alpha = alpha * alpha * (3 - (2 * alpha))
268
+ return theta0 + ((theta1 - theta0) * alpha)
269
+
270
+ # Inverse Smoothstep (https://en.wikipedia.org/wiki/Smoothstep)
271
+ @staticmethod
272
+ def inv_sigmoid(theta0, theta1, theta2, alpha):
273
+ import math
274
+
275
+ alpha = 0.5 - math.sin(math.asin(1.0 - 2.0 * alpha) / 3.0)
276
+ return theta0 + ((theta1 - theta0) * alpha)
277
+
278
+ @staticmethod
279
+ def add_difference(theta0, theta1, theta2, alpha):
280
+ return theta0 + (theta1 - theta2) * (1.0 - alpha)
v0.22.0/clip_guided_images_mixing_stable_diffusion.py ADDED
@@ -0,0 +1,455 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import inspect
3
+ from typing import Optional, Union
4
+
5
+ import numpy as np
6
+ import PIL.Image
7
+ import torch
8
+ from torch.nn import functional as F
9
+ from torchvision import transforms
10
+ from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer
11
+
12
+ from diffusers import (
13
+ AutoencoderKL,
14
+ DDIMScheduler,
15
+ DiffusionPipeline,
16
+ DPMSolverMultistepScheduler,
17
+ LMSDiscreteScheduler,
18
+ PNDMScheduler,
19
+ UNet2DConditionModel,
20
+ )
21
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
22
+ from diffusers.utils import PIL_INTERPOLATION
23
+ from diffusers.utils.torch_utils import randn_tensor
24
+
25
+
26
+ def preprocess(image, w, h):
27
+ if isinstance(image, torch.Tensor):
28
+ return image
29
+ elif isinstance(image, PIL.Image.Image):
30
+ image = [image]
31
+
32
+ if isinstance(image[0], PIL.Image.Image):
33
+ image = [np.array(i.resize((w, h), resample=PIL_INTERPOLATION["lanczos"]))[None, :] for i in image]
34
+ image = np.concatenate(image, axis=0)
35
+ image = np.array(image).astype(np.float32) / 255.0
36
+ image = image.transpose(0, 3, 1, 2)
37
+ image = 2.0 * image - 1.0
38
+ image = torch.from_numpy(image)
39
+ elif isinstance(image[0], torch.Tensor):
40
+ image = torch.cat(image, dim=0)
41
+ return image
42
+
43
+
44
+ def slerp(t, v0, v1, DOT_THRESHOLD=0.9995):
45
+ if not isinstance(v0, np.ndarray):
46
+ inputs_are_torch = True
47
+ input_device = v0.device
48
+ v0 = v0.cpu().numpy()
49
+ v1 = v1.cpu().numpy()
50
+
51
+ dot = np.sum(v0 * v1 / (np.linalg.norm(v0) * np.linalg.norm(v1)))
52
+ if np.abs(dot) > DOT_THRESHOLD:
53
+ v2 = (1 - t) * v0 + t * v1
54
+ else:
55
+ theta_0 = np.arccos(dot)
56
+ sin_theta_0 = np.sin(theta_0)
57
+ theta_t = theta_0 * t
58
+ sin_theta_t = np.sin(theta_t)
59
+ s0 = np.sin(theta_0 - theta_t) / sin_theta_0
60
+ s1 = sin_theta_t / sin_theta_0
61
+ v2 = s0 * v0 + s1 * v1
62
+
63
+ if inputs_are_torch:
64
+ v2 = torch.from_numpy(v2).to(input_device)
65
+
66
+ return v2
67
+
68
+
69
+ def spherical_dist_loss(x, y):
70
+ x = F.normalize(x, dim=-1)
71
+ y = F.normalize(y, dim=-1)
72
+ return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2)
73
+
74
+
75
+ def set_requires_grad(model, value):
76
+ for param in model.parameters():
77
+ param.requires_grad = value
78
+
79
+
80
+ class CLIPGuidedImagesMixingStableDiffusion(DiffusionPipeline):
81
+ def __init__(
82
+ self,
83
+ vae: AutoencoderKL,
84
+ text_encoder: CLIPTextModel,
85
+ clip_model: CLIPModel,
86
+ tokenizer: CLIPTokenizer,
87
+ unet: UNet2DConditionModel,
88
+ scheduler: Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler],
89
+ feature_extractor: CLIPFeatureExtractor,
90
+ coca_model=None,
91
+ coca_tokenizer=None,
92
+ coca_transform=None,
93
+ ):
94
+ super().__init__()
95
+ self.register_modules(
96
+ vae=vae,
97
+ text_encoder=text_encoder,
98
+ clip_model=clip_model,
99
+ tokenizer=tokenizer,
100
+ unet=unet,
101
+ scheduler=scheduler,
102
+ feature_extractor=feature_extractor,
103
+ coca_model=coca_model,
104
+ coca_tokenizer=coca_tokenizer,
105
+ coca_transform=coca_transform,
106
+ )
107
+ self.feature_extractor_size = (
108
+ feature_extractor.size
109
+ if isinstance(feature_extractor.size, int)
110
+ else feature_extractor.size["shortest_edge"]
111
+ )
112
+ self.normalize = transforms.Normalize(mean=feature_extractor.image_mean, std=feature_extractor.image_std)
113
+ set_requires_grad(self.text_encoder, False)
114
+ set_requires_grad(self.clip_model, False)
115
+
116
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
117
+ if slice_size == "auto":
118
+ # half the attention head size is usually a good trade-off between
119
+ # speed and memory
120
+ slice_size = self.unet.config.attention_head_dim // 2
121
+ self.unet.set_attention_slice(slice_size)
122
+
123
+ def disable_attention_slicing(self):
124
+ self.enable_attention_slicing(None)
125
+
126
+ def freeze_vae(self):
127
+ set_requires_grad(self.vae, False)
128
+
129
+ def unfreeze_vae(self):
130
+ set_requires_grad(self.vae, True)
131
+
132
+ def freeze_unet(self):
133
+ set_requires_grad(self.unet, False)
134
+
135
+ def unfreeze_unet(self):
136
+ set_requires_grad(self.unet, True)
137
+
138
+ def get_timesteps(self, num_inference_steps, strength, device):
139
+ # get the original timestep using init_timestep
140
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
141
+
142
+ t_start = max(num_inference_steps - init_timestep, 0)
143
+ timesteps = self.scheduler.timesteps[t_start:]
144
+
145
+ return timesteps, num_inference_steps - t_start
146
+
147
+ def prepare_latents(self, image, timestep, batch_size, dtype, device, generator=None):
148
+ if not isinstance(image, torch.Tensor):
149
+ raise ValueError(f"`image` has to be of type `torch.Tensor` but is {type(image)}")
150
+
151
+ image = image.to(device=device, dtype=dtype)
152
+
153
+ if isinstance(generator, list):
154
+ init_latents = [
155
+ self.vae.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(batch_size)
156
+ ]
157
+ init_latents = torch.cat(init_latents, dim=0)
158
+ else:
159
+ init_latents = self.vae.encode(image).latent_dist.sample(generator)
160
+
161
+ # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
162
+ init_latents = 0.18215 * init_latents
163
+ init_latents = init_latents.repeat_interleave(batch_size, dim=0)
164
+
165
+ noise = randn_tensor(init_latents.shape, generator=generator, device=device, dtype=dtype)
166
+
167
+ # get latents
168
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
169
+ latents = init_latents
170
+
171
+ return latents
172
+
173
+ def get_image_description(self, image):
174
+ transformed_image = self.coca_transform(image).unsqueeze(0)
175
+ with torch.no_grad(), torch.cuda.amp.autocast():
176
+ generated = self.coca_model.generate(transformed_image.to(device=self.device, dtype=self.coca_model.dtype))
177
+ generated = self.coca_tokenizer.decode(generated[0].cpu().numpy())
178
+ return generated.split("<end_of_text>")[0].replace("<start_of_text>", "").rstrip(" .,")
179
+
180
+ def get_clip_image_embeddings(self, image, batch_size):
181
+ clip_image_input = self.feature_extractor.preprocess(image)
182
+ clip_image_features = torch.from_numpy(clip_image_input["pixel_values"][0]).unsqueeze(0).to(self.device).half()
183
+ image_embeddings_clip = self.clip_model.get_image_features(clip_image_features)
184
+ image_embeddings_clip = image_embeddings_clip / image_embeddings_clip.norm(p=2, dim=-1, keepdim=True)
185
+ image_embeddings_clip = image_embeddings_clip.repeat_interleave(batch_size, dim=0)
186
+ return image_embeddings_clip
187
+
188
+ @torch.enable_grad()
189
+ def cond_fn(
190
+ self,
191
+ latents,
192
+ timestep,
193
+ index,
194
+ text_embeddings,
195
+ noise_pred_original,
196
+ original_image_embeddings_clip,
197
+ clip_guidance_scale,
198
+ ):
199
+ latents = latents.detach().requires_grad_()
200
+
201
+ latent_model_input = self.scheduler.scale_model_input(latents, timestep)
202
+
203
+ # predict the noise residual
204
+ noise_pred = self.unet(latent_model_input, timestep, encoder_hidden_states=text_embeddings).sample
205
+
206
+ if isinstance(self.scheduler, (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler)):
207
+ alpha_prod_t = self.scheduler.alphas_cumprod[timestep]
208
+ beta_prod_t = 1 - alpha_prod_t
209
+ # compute predicted original sample from predicted noise also called
210
+ # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
211
+ pred_original_sample = (latents - beta_prod_t ** (0.5) * noise_pred) / alpha_prod_t ** (0.5)
212
+
213
+ fac = torch.sqrt(beta_prod_t)
214
+ sample = pred_original_sample * (fac) + latents * (1 - fac)
215
+ elif isinstance(self.scheduler, LMSDiscreteScheduler):
216
+ sigma = self.scheduler.sigmas[index]
217
+ sample = latents - sigma * noise_pred
218
+ else:
219
+ raise ValueError(f"scheduler type {type(self.scheduler)} not supported")
220
+
221
+ # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
222
+ sample = 1 / 0.18215 * sample
223
+ image = self.vae.decode(sample).sample
224
+ image = (image / 2 + 0.5).clamp(0, 1)
225
+
226
+ image = transforms.Resize(self.feature_extractor_size)(image)
227
+ image = self.normalize(image).to(latents.dtype)
228
+
229
+ image_embeddings_clip = self.clip_model.get_image_features(image)
230
+ image_embeddings_clip = image_embeddings_clip / image_embeddings_clip.norm(p=2, dim=-1, keepdim=True)
231
+
232
+ loss = spherical_dist_loss(image_embeddings_clip, original_image_embeddings_clip).mean() * clip_guidance_scale
233
+
234
+ grads = -torch.autograd.grad(loss, latents)[0]
235
+
236
+ if isinstance(self.scheduler, LMSDiscreteScheduler):
237
+ latents = latents.detach() + grads * (sigma**2)
238
+ noise_pred = noise_pred_original
239
+ else:
240
+ noise_pred = noise_pred_original - torch.sqrt(beta_prod_t) * grads
241
+ return noise_pred, latents
242
+
243
+ @torch.no_grad()
244
+ def __call__(
245
+ self,
246
+ style_image: Union[torch.FloatTensor, PIL.Image.Image],
247
+ content_image: Union[torch.FloatTensor, PIL.Image.Image],
248
+ style_prompt: Optional[str] = None,
249
+ content_prompt: Optional[str] = None,
250
+ height: Optional[int] = 512,
251
+ width: Optional[int] = 512,
252
+ noise_strength: float = 0.6,
253
+ num_inference_steps: Optional[int] = 50,
254
+ guidance_scale: Optional[float] = 7.5,
255
+ batch_size: Optional[int] = 1,
256
+ eta: float = 0.0,
257
+ clip_guidance_scale: Optional[float] = 100,
258
+ generator: Optional[torch.Generator] = None,
259
+ output_type: Optional[str] = "pil",
260
+ return_dict: bool = True,
261
+ slerp_latent_style_strength: float = 0.8,
262
+ slerp_prompt_style_strength: float = 0.1,
263
+ slerp_clip_image_style_strength: float = 0.1,
264
+ ):
265
+ if isinstance(generator, list) and len(generator) != batch_size:
266
+ raise ValueError(f"You have passed {batch_size} batch_size, but only {len(generator)} generators.")
267
+
268
+ if height % 8 != 0 or width % 8 != 0:
269
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
270
+
271
+ if isinstance(generator, torch.Generator) and batch_size > 1:
272
+ generator = [generator] + [None] * (batch_size - 1)
273
+
274
+ coca_is_none = [
275
+ ("model", self.coca_model is None),
276
+ ("tokenizer", self.coca_tokenizer is None),
277
+ ("transform", self.coca_transform is None),
278
+ ]
279
+ coca_is_none = [x[0] for x in coca_is_none if x[1]]
280
+ coca_is_none_str = ", ".join(coca_is_none)
281
+ # generate prompts with coca model if prompt is None
282
+ if content_prompt is None:
283
+ if len(coca_is_none):
284
+ raise ValueError(
285
+ f"Content prompt is None and CoCa [{coca_is_none_str}] is None."
286
+ f"Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline."
287
+ )
288
+ content_prompt = self.get_image_description(content_image)
289
+ if style_prompt is None:
290
+ if len(coca_is_none):
291
+ raise ValueError(
292
+ f"Style prompt is None and CoCa [{coca_is_none_str}] is None."
293
+ f" Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline."
294
+ )
295
+ style_prompt = self.get_image_description(style_image)
296
+
297
+ # get prompt text embeddings for content and style
298
+ content_text_input = self.tokenizer(
299
+ content_prompt,
300
+ padding="max_length",
301
+ max_length=self.tokenizer.model_max_length,
302
+ truncation=True,
303
+ return_tensors="pt",
304
+ )
305
+ content_text_embeddings = self.text_encoder(content_text_input.input_ids.to(self.device))[0]
306
+
307
+ style_text_input = self.tokenizer(
308
+ style_prompt,
309
+ padding="max_length",
310
+ max_length=self.tokenizer.model_max_length,
311
+ truncation=True,
312
+ return_tensors="pt",
313
+ )
314
+ style_text_embeddings = self.text_encoder(style_text_input.input_ids.to(self.device))[0]
315
+
316
+ text_embeddings = slerp(slerp_prompt_style_strength, content_text_embeddings, style_text_embeddings)
317
+
318
+ # duplicate text embeddings for each generation per prompt
319
+ text_embeddings = text_embeddings.repeat_interleave(batch_size, dim=0)
320
+
321
+ # set timesteps
322
+ accepts_offset = "offset" in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys())
323
+ extra_set_kwargs = {}
324
+ if accepts_offset:
325
+ extra_set_kwargs["offset"] = 1
326
+
327
+ self.scheduler.set_timesteps(num_inference_steps, **extra_set_kwargs)
328
+ # Some schedulers like PNDM have timesteps as arrays
329
+ # It's more optimized to move all timesteps to correct device beforehand
330
+ self.scheduler.timesteps.to(self.device)
331
+
332
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, noise_strength, self.device)
333
+ latent_timestep = timesteps[:1].repeat(batch_size)
334
+
335
+ # Preprocess image
336
+ preprocessed_content_image = preprocess(content_image, width, height)
337
+ content_latents = self.prepare_latents(
338
+ preprocessed_content_image, latent_timestep, batch_size, text_embeddings.dtype, self.device, generator
339
+ )
340
+
341
+ preprocessed_style_image = preprocess(style_image, width, height)
342
+ style_latents = self.prepare_latents(
343
+ preprocessed_style_image, latent_timestep, batch_size, text_embeddings.dtype, self.device, generator
344
+ )
345
+
346
+ latents = slerp(slerp_latent_style_strength, content_latents, style_latents)
347
+
348
+ if clip_guidance_scale > 0:
349
+ content_clip_image_embedding = self.get_clip_image_embeddings(content_image, batch_size)
350
+ style_clip_image_embedding = self.get_clip_image_embeddings(style_image, batch_size)
351
+ clip_image_embeddings = slerp(
352
+ slerp_clip_image_style_strength, content_clip_image_embedding, style_clip_image_embedding
353
+ )
354
+
355
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
356
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
357
+ # corresponds to doing no classifier free guidance.
358
+ do_classifier_free_guidance = guidance_scale > 1.0
359
+ # get unconditional embeddings for classifier free guidance
360
+ if do_classifier_free_guidance:
361
+ max_length = content_text_input.input_ids.shape[-1]
362
+ uncond_input = self.tokenizer([""], padding="max_length", max_length=max_length, return_tensors="pt")
363
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
364
+ # duplicate unconditional embeddings for each generation per prompt
365
+ uncond_embeddings = uncond_embeddings.repeat_interleave(batch_size, dim=0)
366
+
367
+ # For classifier free guidance, we need to do two forward passes.
368
+ # Here we concatenate the unconditional and text embeddings into a single batch
369
+ # to avoid doing two forward passes
370
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
371
+
372
+ # get the initial random noise unless the user supplied it
373
+
374
+ # Unlike in other pipelines, latents need to be generated in the target device
375
+ # for 1-to-1 results reproducibility with the CompVis implementation.
376
+ # However this currently doesn't work in `mps`.
377
+ latents_shape = (batch_size, self.unet.config.in_channels, height // 8, width // 8)
378
+ latents_dtype = text_embeddings.dtype
379
+ if latents is None:
380
+ if self.device.type == "mps":
381
+ # randn does not work reproducibly on mps
382
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
383
+ self.device
384
+ )
385
+ else:
386
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
387
+ else:
388
+ if latents.shape != latents_shape:
389
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
390
+ latents = latents.to(self.device)
391
+
392
+ # scale the initial noise by the standard deviation required by the scheduler
393
+ latents = latents * self.scheduler.init_noise_sigma
394
+
395
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
396
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
397
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
398
+ # and should be between [0, 1]
399
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
400
+ extra_step_kwargs = {}
401
+ if accepts_eta:
402
+ extra_step_kwargs["eta"] = eta
403
+
404
+ # check if the scheduler accepts generator
405
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
406
+ if accepts_generator:
407
+ extra_step_kwargs["generator"] = generator
408
+
409
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
410
+ for i, t in enumerate(timesteps):
411
+ # expand the latents if we are doing classifier free guidance
412
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
413
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
414
+
415
+ # predict the noise residual
416
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
417
+
418
+ # perform classifier free guidance
419
+ if do_classifier_free_guidance:
420
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
421
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
422
+
423
+ # perform clip guidance
424
+ if clip_guidance_scale > 0:
425
+ text_embeddings_for_guidance = (
426
+ text_embeddings.chunk(2)[1] if do_classifier_free_guidance else text_embeddings
427
+ )
428
+ noise_pred, latents = self.cond_fn(
429
+ latents,
430
+ t,
431
+ i,
432
+ text_embeddings_for_guidance,
433
+ noise_pred,
434
+ clip_image_embeddings,
435
+ clip_guidance_scale,
436
+ )
437
+
438
+ # compute the previous noisy sample x_t -> x_t-1
439
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
440
+
441
+ progress_bar.update()
442
+ # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
443
+ latents = 1 / 0.18215 * latents
444
+ image = self.vae.decode(latents).sample
445
+
446
+ image = (image / 2 + 0.5).clamp(0, 1)
447
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
448
+
449
+ if output_type == "pil":
450
+ image = self.numpy_to_pil(image)
451
+
452
+ if not return_dict:
453
+ return (image, None)
454
+
455
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=None)
v0.22.0/clip_guided_stable_diffusion.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import List, Optional, Union
3
+
4
+ import torch
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+ from torchvision import transforms
8
+ from transformers import CLIPImageProcessor, CLIPModel, CLIPTextModel, CLIPTokenizer
9
+
10
+ from diffusers import (
11
+ AutoencoderKL,
12
+ DDIMScheduler,
13
+ DiffusionPipeline,
14
+ DPMSolverMultistepScheduler,
15
+ LMSDiscreteScheduler,
16
+ PNDMScheduler,
17
+ UNet2DConditionModel,
18
+ )
19
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
20
+
21
+
22
+ class MakeCutouts(nn.Module):
23
+ def __init__(self, cut_size, cut_power=1.0):
24
+ super().__init__()
25
+
26
+ self.cut_size = cut_size
27
+ self.cut_power = cut_power
28
+
29
+ def forward(self, pixel_values, num_cutouts):
30
+ sideY, sideX = pixel_values.shape[2:4]
31
+ max_size = min(sideX, sideY)
32
+ min_size = min(sideX, sideY, self.cut_size)
33
+ cutouts = []
34
+ for _ in range(num_cutouts):
35
+ size = int(torch.rand([]) ** self.cut_power * (max_size - min_size) + min_size)
36
+ offsetx = torch.randint(0, sideX - size + 1, ())
37
+ offsety = torch.randint(0, sideY - size + 1, ())
38
+ cutout = pixel_values[:, :, offsety : offsety + size, offsetx : offsetx + size]
39
+ cutouts.append(F.adaptive_avg_pool2d(cutout, self.cut_size))
40
+ return torch.cat(cutouts)
41
+
42
+
43
+ def spherical_dist_loss(x, y):
44
+ x = F.normalize(x, dim=-1)
45
+ y = F.normalize(y, dim=-1)
46
+ return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2)
47
+
48
+
49
+ def set_requires_grad(model, value):
50
+ for param in model.parameters():
51
+ param.requires_grad = value
52
+
53
+
54
+ class CLIPGuidedStableDiffusion(DiffusionPipeline):
55
+ """CLIP guided stable diffusion based on the amazing repo by @crowsonkb and @Jack000
56
+ - https://github.com/Jack000/glid-3-xl
57
+ - https://github.dev/crowsonkb/k-diffusion
58
+ """
59
+
60
+ def __init__(
61
+ self,
62
+ vae: AutoencoderKL,
63
+ text_encoder: CLIPTextModel,
64
+ clip_model: CLIPModel,
65
+ tokenizer: CLIPTokenizer,
66
+ unet: UNet2DConditionModel,
67
+ scheduler: Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler],
68
+ feature_extractor: CLIPImageProcessor,
69
+ ):
70
+ super().__init__()
71
+ self.register_modules(
72
+ vae=vae,
73
+ text_encoder=text_encoder,
74
+ clip_model=clip_model,
75
+ tokenizer=tokenizer,
76
+ unet=unet,
77
+ scheduler=scheduler,
78
+ feature_extractor=feature_extractor,
79
+ )
80
+
81
+ self.normalize = transforms.Normalize(mean=feature_extractor.image_mean, std=feature_extractor.image_std)
82
+ self.cut_out_size = (
83
+ feature_extractor.size
84
+ if isinstance(feature_extractor.size, int)
85
+ else feature_extractor.size["shortest_edge"]
86
+ )
87
+ self.make_cutouts = MakeCutouts(self.cut_out_size)
88
+
89
+ set_requires_grad(self.text_encoder, False)
90
+ set_requires_grad(self.clip_model, False)
91
+
92
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
93
+ if slice_size == "auto":
94
+ # half the attention head size is usually a good trade-off between
95
+ # speed and memory
96
+ slice_size = self.unet.config.attention_head_dim // 2
97
+ self.unet.set_attention_slice(slice_size)
98
+
99
+ def disable_attention_slicing(self):
100
+ self.enable_attention_slicing(None)
101
+
102
+ def freeze_vae(self):
103
+ set_requires_grad(self.vae, False)
104
+
105
+ def unfreeze_vae(self):
106
+ set_requires_grad(self.vae, True)
107
+
108
+ def freeze_unet(self):
109
+ set_requires_grad(self.unet, False)
110
+
111
+ def unfreeze_unet(self):
112
+ set_requires_grad(self.unet, True)
113
+
114
+ @torch.enable_grad()
115
+ def cond_fn(
116
+ self,
117
+ latents,
118
+ timestep,
119
+ index,
120
+ text_embeddings,
121
+ noise_pred_original,
122
+ text_embeddings_clip,
123
+ clip_guidance_scale,
124
+ num_cutouts,
125
+ use_cutouts=True,
126
+ ):
127
+ latents = latents.detach().requires_grad_()
128
+
129
+ latent_model_input = self.scheduler.scale_model_input(latents, timestep)
130
+
131
+ # predict the noise residual
132
+ noise_pred = self.unet(latent_model_input, timestep, encoder_hidden_states=text_embeddings).sample
133
+
134
+ if isinstance(self.scheduler, (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler)):
135
+ alpha_prod_t = self.scheduler.alphas_cumprod[timestep]
136
+ beta_prod_t = 1 - alpha_prod_t
137
+ # compute predicted original sample from predicted noise also called
138
+ # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
139
+ pred_original_sample = (latents - beta_prod_t ** (0.5) * noise_pred) / alpha_prod_t ** (0.5)
140
+
141
+ fac = torch.sqrt(beta_prod_t)
142
+ sample = pred_original_sample * (fac) + latents * (1 - fac)
143
+ elif isinstance(self.scheduler, LMSDiscreteScheduler):
144
+ sigma = self.scheduler.sigmas[index]
145
+ sample = latents - sigma * noise_pred
146
+ else:
147
+ raise ValueError(f"scheduler type {type(self.scheduler)} not supported")
148
+
149
+ sample = 1 / self.vae.config.scaling_factor * sample
150
+ image = self.vae.decode(sample).sample
151
+ image = (image / 2 + 0.5).clamp(0, 1)
152
+
153
+ if use_cutouts:
154
+ image = self.make_cutouts(image, num_cutouts)
155
+ else:
156
+ image = transforms.Resize(self.cut_out_size)(image)
157
+ image = self.normalize(image).to(latents.dtype)
158
+
159
+ image_embeddings_clip = self.clip_model.get_image_features(image)
160
+ image_embeddings_clip = image_embeddings_clip / image_embeddings_clip.norm(p=2, dim=-1, keepdim=True)
161
+
162
+ if use_cutouts:
163
+ dists = spherical_dist_loss(image_embeddings_clip, text_embeddings_clip)
164
+ dists = dists.view([num_cutouts, sample.shape[0], -1])
165
+ loss = dists.sum(2).mean(0).sum() * clip_guidance_scale
166
+ else:
167
+ loss = spherical_dist_loss(image_embeddings_clip, text_embeddings_clip).mean() * clip_guidance_scale
168
+
169
+ grads = -torch.autograd.grad(loss, latents)[0]
170
+
171
+ if isinstance(self.scheduler, LMSDiscreteScheduler):
172
+ latents = latents.detach() + grads * (sigma**2)
173
+ noise_pred = noise_pred_original
174
+ else:
175
+ noise_pred = noise_pred_original - torch.sqrt(beta_prod_t) * grads
176
+ return noise_pred, latents
177
+
178
+ @torch.no_grad()
179
+ def __call__(
180
+ self,
181
+ prompt: Union[str, List[str]],
182
+ height: Optional[int] = 512,
183
+ width: Optional[int] = 512,
184
+ num_inference_steps: Optional[int] = 50,
185
+ guidance_scale: Optional[float] = 7.5,
186
+ num_images_per_prompt: Optional[int] = 1,
187
+ eta: float = 0.0,
188
+ clip_guidance_scale: Optional[float] = 100,
189
+ clip_prompt: Optional[Union[str, List[str]]] = None,
190
+ num_cutouts: Optional[int] = 4,
191
+ use_cutouts: Optional[bool] = True,
192
+ generator: Optional[torch.Generator] = None,
193
+ latents: Optional[torch.FloatTensor] = None,
194
+ output_type: Optional[str] = "pil",
195
+ return_dict: bool = True,
196
+ ):
197
+ if isinstance(prompt, str):
198
+ batch_size = 1
199
+ elif isinstance(prompt, list):
200
+ batch_size = len(prompt)
201
+ else:
202
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
203
+
204
+ if height % 8 != 0 or width % 8 != 0:
205
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
206
+
207
+ # get prompt text embeddings
208
+ text_input = self.tokenizer(
209
+ prompt,
210
+ padding="max_length",
211
+ max_length=self.tokenizer.model_max_length,
212
+ truncation=True,
213
+ return_tensors="pt",
214
+ )
215
+ text_embeddings = self.text_encoder(text_input.input_ids.to(self.device))[0]
216
+ # duplicate text embeddings for each generation per prompt
217
+ text_embeddings = text_embeddings.repeat_interleave(num_images_per_prompt, dim=0)
218
+
219
+ if clip_guidance_scale > 0:
220
+ if clip_prompt is not None:
221
+ clip_text_input = self.tokenizer(
222
+ clip_prompt,
223
+ padding="max_length",
224
+ max_length=self.tokenizer.model_max_length,
225
+ truncation=True,
226
+ return_tensors="pt",
227
+ ).input_ids.to(self.device)
228
+ else:
229
+ clip_text_input = text_input.input_ids.to(self.device)
230
+ text_embeddings_clip = self.clip_model.get_text_features(clip_text_input)
231
+ text_embeddings_clip = text_embeddings_clip / text_embeddings_clip.norm(p=2, dim=-1, keepdim=True)
232
+ # duplicate text embeddings clip for each generation per prompt
233
+ text_embeddings_clip = text_embeddings_clip.repeat_interleave(num_images_per_prompt, dim=0)
234
+
235
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
236
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
237
+ # corresponds to doing no classifier free guidance.
238
+ do_classifier_free_guidance = guidance_scale > 1.0
239
+ # get unconditional embeddings for classifier free guidance
240
+ if do_classifier_free_guidance:
241
+ max_length = text_input.input_ids.shape[-1]
242
+ uncond_input = self.tokenizer([""], padding="max_length", max_length=max_length, return_tensors="pt")
243
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
244
+ # duplicate unconditional embeddings for each generation per prompt
245
+ uncond_embeddings = uncond_embeddings.repeat_interleave(num_images_per_prompt, dim=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
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
251
+
252
+ # get the initial random noise unless the user supplied it
253
+
254
+ # Unlike in other pipelines, latents need to be generated in the target device
255
+ # for 1-to-1 results reproducibility with the CompVis implementation.
256
+ # However this currently doesn't work in `mps`.
257
+ latents_shape = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
258
+ latents_dtype = text_embeddings.dtype
259
+ if latents is None:
260
+ if self.device.type == "mps":
261
+ # randn does not work reproducibly on mps
262
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
263
+ self.device
264
+ )
265
+ else:
266
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
267
+ else:
268
+ if latents.shape != latents_shape:
269
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
270
+ latents = latents.to(self.device)
271
+
272
+ # set timesteps
273
+ accepts_offset = "offset" in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys())
274
+ extra_set_kwargs = {}
275
+ if accepts_offset:
276
+ extra_set_kwargs["offset"] = 1
277
+
278
+ self.scheduler.set_timesteps(num_inference_steps, **extra_set_kwargs)
279
+
280
+ # Some schedulers like PNDM have timesteps as arrays
281
+ # It's more optimized to move all timesteps to correct device beforehand
282
+ timesteps_tensor = self.scheduler.timesteps.to(self.device)
283
+
284
+ # scale the initial noise by the standard deviation required by the scheduler
285
+ latents = latents * self.scheduler.init_noise_sigma
286
+
287
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
288
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
289
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
290
+ # and should be between [0, 1]
291
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
292
+ extra_step_kwargs = {}
293
+ if accepts_eta:
294
+ extra_step_kwargs["eta"] = eta
295
+
296
+ # check if the scheduler accepts generator
297
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
298
+ if accepts_generator:
299
+ extra_step_kwargs["generator"] = generator
300
+
301
+ for i, t in enumerate(self.progress_bar(timesteps_tensor)):
302
+ # expand the latents if we are doing classifier free guidance
303
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
304
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
305
+
306
+ # predict the noise residual
307
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
308
+
309
+ # perform classifier free guidance
310
+ if do_classifier_free_guidance:
311
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
312
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
313
+
314
+ # perform clip guidance
315
+ if clip_guidance_scale > 0:
316
+ text_embeddings_for_guidance = (
317
+ text_embeddings.chunk(2)[1] if do_classifier_free_guidance else text_embeddings
318
+ )
319
+ noise_pred, latents = self.cond_fn(
320
+ latents,
321
+ t,
322
+ i,
323
+ text_embeddings_for_guidance,
324
+ noise_pred,
325
+ text_embeddings_clip,
326
+ clip_guidance_scale,
327
+ num_cutouts,
328
+ use_cutouts,
329
+ )
330
+
331
+ # compute the previous noisy sample x_t -> x_t-1
332
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
333
+
334
+ # scale and decode the image latents with vae
335
+ latents = 1 / self.vae.config.scaling_factor * latents
336
+ image = self.vae.decode(latents).sample
337
+
338
+ image = (image / 2 + 0.5).clamp(0, 1)
339
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
340
+
341
+ if output_type == "pil":
342
+ image = self.numpy_to_pil(image)
343
+
344
+ if not return_dict:
345
+ return (image, None)
346
+
347
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=None)
v0.22.0/clip_guided_stable_diffusion_img2img.py ADDED
@@ -0,0 +1,493 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import List, Optional, Union
3
+
4
+ import numpy as np
5
+ import PIL.Image
6
+ import torch
7
+ from torch import nn
8
+ from torch.nn import functional as F
9
+ from torchvision import transforms
10
+ from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer
11
+
12
+ from diffusers import (
13
+ AutoencoderKL,
14
+ DDIMScheduler,
15
+ DiffusionPipeline,
16
+ DPMSolverMultistepScheduler,
17
+ LMSDiscreteScheduler,
18
+ PNDMScheduler,
19
+ UNet2DConditionModel,
20
+ )
21
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
22
+ from diffusers.utils import PIL_INTERPOLATION, deprecate
23
+ from diffusers.utils.torch_utils import randn_tensor
24
+
25
+
26
+ EXAMPLE_DOC_STRING = """
27
+ Examples:
28
+ ```
29
+ from io import BytesIO
30
+
31
+ import requests
32
+ import torch
33
+ from diffusers import DiffusionPipeline
34
+ from PIL import Image
35
+ from transformers import CLIPFeatureExtractor, CLIPModel
36
+
37
+ feature_extractor = CLIPFeatureExtractor.from_pretrained(
38
+ "laion/CLIP-ViT-B-32-laion2B-s34B-b79K"
39
+ )
40
+ clip_model = CLIPModel.from_pretrained(
41
+ "laion/CLIP-ViT-B-32-laion2B-s34B-b79K", torch_dtype=torch.float16
42
+ )
43
+
44
+
45
+ guided_pipeline = DiffusionPipeline.from_pretrained(
46
+ "CompVis/stable-diffusion-v1-4",
47
+ # custom_pipeline="clip_guided_stable_diffusion",
48
+ custom_pipeline="/home/njindal/diffusers/examples/community/clip_guided_stable_diffusion.py",
49
+ clip_model=clip_model,
50
+ feature_extractor=feature_extractor,
51
+ torch_dtype=torch.float16,
52
+ )
53
+ guided_pipeline.enable_attention_slicing()
54
+ guided_pipeline = guided_pipeline.to("cuda")
55
+
56
+ prompt = "fantasy book cover, full moon, fantasy forest landscape, golden vector elements, fantasy magic, dark light night, intricate, elegant, sharp focus, illustration, highly detailed, digital painting, concept art, matte, art by WLOP and Artgerm and Albert Bierstadt, masterpiece"
57
+
58
+ url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
59
+
60
+ response = requests.get(url)
61
+ init_image = Image.open(BytesIO(response.content)).convert("RGB")
62
+
63
+ image = guided_pipeline(
64
+ prompt=prompt,
65
+ num_inference_steps=30,
66
+ image=init_image,
67
+ strength=0.75,
68
+ guidance_scale=7.5,
69
+ clip_guidance_scale=100,
70
+ num_cutouts=4,
71
+ use_cutouts=False,
72
+ ).images[0]
73
+ display(image)
74
+ ```
75
+ """
76
+
77
+
78
+ def preprocess(image, w, h):
79
+ if isinstance(image, torch.Tensor):
80
+ return image
81
+ elif isinstance(image, PIL.Image.Image):
82
+ image = [image]
83
+
84
+ if isinstance(image[0], PIL.Image.Image):
85
+ image = [np.array(i.resize((w, h), resample=PIL_INTERPOLATION["lanczos"]))[None, :] for i in image]
86
+ image = np.concatenate(image, axis=0)
87
+ image = np.array(image).astype(np.float32) / 255.0
88
+ image = image.transpose(0, 3, 1, 2)
89
+ image = 2.0 * image - 1.0
90
+ image = torch.from_numpy(image)
91
+ elif isinstance(image[0], torch.Tensor):
92
+ image = torch.cat(image, dim=0)
93
+ return image
94
+
95
+
96
+ class MakeCutouts(nn.Module):
97
+ def __init__(self, cut_size, cut_power=1.0):
98
+ super().__init__()
99
+
100
+ self.cut_size = cut_size
101
+ self.cut_power = cut_power
102
+
103
+ def forward(self, pixel_values, num_cutouts):
104
+ sideY, sideX = pixel_values.shape[2:4]
105
+ max_size = min(sideX, sideY)
106
+ min_size = min(sideX, sideY, self.cut_size)
107
+ cutouts = []
108
+ for _ in range(num_cutouts):
109
+ size = int(torch.rand([]) ** self.cut_power * (max_size - min_size) + min_size)
110
+ offsetx = torch.randint(0, sideX - size + 1, ())
111
+ offsety = torch.randint(0, sideY - size + 1, ())
112
+ cutout = pixel_values[:, :, offsety : offsety + size, offsetx : offsetx + size]
113
+ cutouts.append(F.adaptive_avg_pool2d(cutout, self.cut_size))
114
+ return torch.cat(cutouts)
115
+
116
+
117
+ def spherical_dist_loss(x, y):
118
+ x = F.normalize(x, dim=-1)
119
+ y = F.normalize(y, dim=-1)
120
+ return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2)
121
+
122
+
123
+ def set_requires_grad(model, value):
124
+ for param in model.parameters():
125
+ param.requires_grad = value
126
+
127
+
128
+ class CLIPGuidedStableDiffusion(DiffusionPipeline):
129
+ """CLIP guided stable diffusion based on the amazing repo by @crowsonkb and @Jack000
130
+ - https://github.com/Jack000/glid-3-xl
131
+ - https://github.dev/crowsonkb/k-diffusion
132
+ """
133
+
134
+ def __init__(
135
+ self,
136
+ vae: AutoencoderKL,
137
+ text_encoder: CLIPTextModel,
138
+ clip_model: CLIPModel,
139
+ tokenizer: CLIPTokenizer,
140
+ unet: UNet2DConditionModel,
141
+ scheduler: Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler],
142
+ feature_extractor: CLIPFeatureExtractor,
143
+ ):
144
+ super().__init__()
145
+ self.register_modules(
146
+ vae=vae,
147
+ text_encoder=text_encoder,
148
+ clip_model=clip_model,
149
+ tokenizer=tokenizer,
150
+ unet=unet,
151
+ scheduler=scheduler,
152
+ feature_extractor=feature_extractor,
153
+ )
154
+
155
+ self.normalize = transforms.Normalize(mean=feature_extractor.image_mean, std=feature_extractor.image_std)
156
+ self.cut_out_size = (
157
+ feature_extractor.size
158
+ if isinstance(feature_extractor.size, int)
159
+ else feature_extractor.size["shortest_edge"]
160
+ )
161
+ self.make_cutouts = MakeCutouts(self.cut_out_size)
162
+
163
+ set_requires_grad(self.text_encoder, False)
164
+ set_requires_grad(self.clip_model, False)
165
+
166
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
167
+ if slice_size == "auto":
168
+ # half the attention head size is usually a good trade-off between
169
+ # speed and memory
170
+ slice_size = self.unet.config.attention_head_dim // 2
171
+ self.unet.set_attention_slice(slice_size)
172
+
173
+ def disable_attention_slicing(self):
174
+ self.enable_attention_slicing(None)
175
+
176
+ def freeze_vae(self):
177
+ set_requires_grad(self.vae, False)
178
+
179
+ def unfreeze_vae(self):
180
+ set_requires_grad(self.vae, True)
181
+
182
+ def freeze_unet(self):
183
+ set_requires_grad(self.unet, False)
184
+
185
+ def unfreeze_unet(self):
186
+ set_requires_grad(self.unet, True)
187
+
188
+ def get_timesteps(self, num_inference_steps, strength, device):
189
+ # get the original timestep using init_timestep
190
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
191
+
192
+ t_start = max(num_inference_steps - init_timestep, 0)
193
+ timesteps = self.scheduler.timesteps[t_start:]
194
+
195
+ return timesteps, num_inference_steps - t_start
196
+
197
+ def prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None):
198
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
199
+ raise ValueError(
200
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
201
+ )
202
+
203
+ image = image.to(device=device, dtype=dtype)
204
+
205
+ batch_size = batch_size * num_images_per_prompt
206
+ if isinstance(generator, list) and len(generator) != batch_size:
207
+ raise ValueError(
208
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
209
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
210
+ )
211
+
212
+ if isinstance(generator, list):
213
+ init_latents = [
214
+ self.vae.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(batch_size)
215
+ ]
216
+ init_latents = torch.cat(init_latents, dim=0)
217
+ else:
218
+ init_latents = self.vae.encode(image).latent_dist.sample(generator)
219
+
220
+ init_latents = self.vae.config.scaling_factor * init_latents
221
+
222
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
223
+ # expand init_latents for batch_size
224
+ deprecation_message = (
225
+ f"You have passed {batch_size} text prompts (`prompt`), but only {init_latents.shape[0]} initial"
226
+ " images (`image`). Initial images are now duplicating to match the number of text prompts. Note"
227
+ " that this behavior is deprecated and will be removed in a version 1.0.0. Please make sure to update"
228
+ " your script to pass as many initial images as text prompts to suppress this warning."
229
+ )
230
+ deprecate("len(prompt) != len(image)", "1.0.0", deprecation_message, standard_warn=False)
231
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
232
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
233
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
234
+ raise ValueError(
235
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
236
+ )
237
+ else:
238
+ init_latents = torch.cat([init_latents], dim=0)
239
+
240
+ shape = init_latents.shape
241
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
242
+
243
+ # get latents
244
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
245
+ latents = init_latents
246
+
247
+ return latents
248
+
249
+ @torch.enable_grad()
250
+ def cond_fn(
251
+ self,
252
+ latents,
253
+ timestep,
254
+ index,
255
+ text_embeddings,
256
+ noise_pred_original,
257
+ text_embeddings_clip,
258
+ clip_guidance_scale,
259
+ num_cutouts,
260
+ use_cutouts=True,
261
+ ):
262
+ latents = latents.detach().requires_grad_()
263
+
264
+ latent_model_input = self.scheduler.scale_model_input(latents, timestep)
265
+
266
+ # predict the noise residual
267
+ noise_pred = self.unet(latent_model_input, timestep, encoder_hidden_states=text_embeddings).sample
268
+
269
+ if isinstance(self.scheduler, (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler)):
270
+ alpha_prod_t = self.scheduler.alphas_cumprod[timestep]
271
+ beta_prod_t = 1 - alpha_prod_t
272
+ # compute predicted original sample from predicted noise also called
273
+ # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
274
+ pred_original_sample = (latents - beta_prod_t ** (0.5) * noise_pred) / alpha_prod_t ** (0.5)
275
+
276
+ fac = torch.sqrt(beta_prod_t)
277
+ sample = pred_original_sample * (fac) + latents * (1 - fac)
278
+ elif isinstance(self.scheduler, LMSDiscreteScheduler):
279
+ sigma = self.scheduler.sigmas[index]
280
+ sample = latents - sigma * noise_pred
281
+ else:
282
+ raise ValueError(f"scheduler type {type(self.scheduler)} not supported")
283
+
284
+ sample = 1 / self.vae.config.scaling_factor * sample
285
+ image = self.vae.decode(sample).sample
286
+ image = (image / 2 + 0.5).clamp(0, 1)
287
+
288
+ if use_cutouts:
289
+ image = self.make_cutouts(image, num_cutouts)
290
+ else:
291
+ image = transforms.Resize(self.cut_out_size)(image)
292
+ image = self.normalize(image).to(latents.dtype)
293
+
294
+ image_embeddings_clip = self.clip_model.get_image_features(image)
295
+ image_embeddings_clip = image_embeddings_clip / image_embeddings_clip.norm(p=2, dim=-1, keepdim=True)
296
+
297
+ if use_cutouts:
298
+ dists = spherical_dist_loss(image_embeddings_clip, text_embeddings_clip)
299
+ dists = dists.view([num_cutouts, sample.shape[0], -1])
300
+ loss = dists.sum(2).mean(0).sum() * clip_guidance_scale
301
+ else:
302
+ loss = spherical_dist_loss(image_embeddings_clip, text_embeddings_clip).mean() * clip_guidance_scale
303
+
304
+ grads = -torch.autograd.grad(loss, latents)[0]
305
+
306
+ if isinstance(self.scheduler, LMSDiscreteScheduler):
307
+ latents = latents.detach() + grads * (sigma**2)
308
+ noise_pred = noise_pred_original
309
+ else:
310
+ noise_pred = noise_pred_original - torch.sqrt(beta_prod_t) * grads
311
+ return noise_pred, latents
312
+
313
+ @torch.no_grad()
314
+ def __call__(
315
+ self,
316
+ prompt: Union[str, List[str]],
317
+ height: Optional[int] = 512,
318
+ width: Optional[int] = 512,
319
+ image: Union[torch.FloatTensor, PIL.Image.Image] = None,
320
+ strength: float = 0.8,
321
+ num_inference_steps: Optional[int] = 50,
322
+ guidance_scale: Optional[float] = 7.5,
323
+ num_images_per_prompt: Optional[int] = 1,
324
+ eta: float = 0.0,
325
+ clip_guidance_scale: Optional[float] = 100,
326
+ clip_prompt: Optional[Union[str, List[str]]] = None,
327
+ num_cutouts: Optional[int] = 4,
328
+ use_cutouts: Optional[bool] = True,
329
+ generator: Optional[torch.Generator] = None,
330
+ latents: Optional[torch.FloatTensor] = None,
331
+ output_type: Optional[str] = "pil",
332
+ return_dict: bool = True,
333
+ ):
334
+ if isinstance(prompt, str):
335
+ batch_size = 1
336
+ elif isinstance(prompt, list):
337
+ batch_size = len(prompt)
338
+ else:
339
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
340
+
341
+ if height % 8 != 0 or width % 8 != 0:
342
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
343
+
344
+ # get prompt text embeddings
345
+ text_input = self.tokenizer(
346
+ prompt,
347
+ padding="max_length",
348
+ max_length=self.tokenizer.model_max_length,
349
+ truncation=True,
350
+ return_tensors="pt",
351
+ )
352
+ text_embeddings = self.text_encoder(text_input.input_ids.to(self.device))[0]
353
+ # duplicate text embeddings for each generation per prompt
354
+ text_embeddings = text_embeddings.repeat_interleave(num_images_per_prompt, dim=0)
355
+
356
+ # set timesteps
357
+ accepts_offset = "offset" in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys())
358
+ extra_set_kwargs = {}
359
+ if accepts_offset:
360
+ extra_set_kwargs["offset"] = 1
361
+
362
+ self.scheduler.set_timesteps(num_inference_steps, **extra_set_kwargs)
363
+ # Some schedulers like PNDM have timesteps as arrays
364
+ # It's more optimized to move all timesteps to correct device beforehand
365
+ self.scheduler.timesteps.to(self.device)
366
+
367
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, self.device)
368
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
369
+
370
+ # Preprocess image
371
+ image = preprocess(image, width, height)
372
+ latents = self.prepare_latents(
373
+ image, latent_timestep, batch_size, num_images_per_prompt, text_embeddings.dtype, self.device, generator
374
+ )
375
+
376
+ if clip_guidance_scale > 0:
377
+ if clip_prompt is not None:
378
+ clip_text_input = self.tokenizer(
379
+ clip_prompt,
380
+ padding="max_length",
381
+ max_length=self.tokenizer.model_max_length,
382
+ truncation=True,
383
+ return_tensors="pt",
384
+ ).input_ids.to(self.device)
385
+ else:
386
+ clip_text_input = text_input.input_ids.to(self.device)
387
+ text_embeddings_clip = self.clip_model.get_text_features(clip_text_input)
388
+ text_embeddings_clip = text_embeddings_clip / text_embeddings_clip.norm(p=2, dim=-1, keepdim=True)
389
+ # duplicate text embeddings clip for each generation per prompt
390
+ text_embeddings_clip = text_embeddings_clip.repeat_interleave(num_images_per_prompt, dim=0)
391
+
392
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
393
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
394
+ # corresponds to doing no classifier free guidance.
395
+ do_classifier_free_guidance = guidance_scale > 1.0
396
+ # get unconditional embeddings for classifier free guidance
397
+ if do_classifier_free_guidance:
398
+ max_length = text_input.input_ids.shape[-1]
399
+ uncond_input = self.tokenizer([""], padding="max_length", max_length=max_length, return_tensors="pt")
400
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
401
+ # duplicate unconditional embeddings for each generation per prompt
402
+ uncond_embeddings = uncond_embeddings.repeat_interleave(num_images_per_prompt, dim=0)
403
+
404
+ # For classifier free guidance, we need to do two forward passes.
405
+ # Here we concatenate the unconditional and text embeddings into a single batch
406
+ # to avoid doing two forward passes
407
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
408
+
409
+ # get the initial random noise unless the user supplied it
410
+
411
+ # Unlike in other pipelines, latents need to be generated in the target device
412
+ # for 1-to-1 results reproducibility with the CompVis implementation.
413
+ # However this currently doesn't work in `mps`.
414
+ latents_shape = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
415
+ latents_dtype = text_embeddings.dtype
416
+ if latents is None:
417
+ if self.device.type == "mps":
418
+ # randn does not work reproducibly on mps
419
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
420
+ self.device
421
+ )
422
+ else:
423
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
424
+ else:
425
+ if latents.shape != latents_shape:
426
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
427
+ latents = latents.to(self.device)
428
+
429
+ # scale the initial noise by the standard deviation required by the scheduler
430
+ latents = latents * self.scheduler.init_noise_sigma
431
+
432
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
433
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
434
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
435
+ # and should be between [0, 1]
436
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
437
+ extra_step_kwargs = {}
438
+ if accepts_eta:
439
+ extra_step_kwargs["eta"] = eta
440
+
441
+ # check if the scheduler accepts generator
442
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
443
+ if accepts_generator:
444
+ extra_step_kwargs["generator"] = generator
445
+
446
+ with self.progress_bar(total=num_inference_steps):
447
+ for i, t in enumerate(timesteps):
448
+ # expand the latents if we are doing classifier free guidance
449
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
450
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
451
+
452
+ # predict the noise residual
453
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
454
+
455
+ # perform classifier free guidance
456
+ if do_classifier_free_guidance:
457
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
458
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
459
+
460
+ # perform clip guidance
461
+ if clip_guidance_scale > 0:
462
+ text_embeddings_for_guidance = (
463
+ text_embeddings.chunk(2)[1] if do_classifier_free_guidance else text_embeddings
464
+ )
465
+ noise_pred, latents = self.cond_fn(
466
+ latents,
467
+ t,
468
+ i,
469
+ text_embeddings_for_guidance,
470
+ noise_pred,
471
+ text_embeddings_clip,
472
+ clip_guidance_scale,
473
+ num_cutouts,
474
+ use_cutouts,
475
+ )
476
+
477
+ # compute the previous noisy sample x_t -> x_t-1
478
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
479
+
480
+ # scale and decode the image latents with vae
481
+ latents = 1 / self.vae.config.scaling_factor * latents
482
+ image = self.vae.decode(latents).sample
483
+
484
+ image = (image / 2 + 0.5).clamp(0, 1)
485
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
486
+
487
+ if output_type == "pil":
488
+ image = self.numpy_to_pil(image)
489
+
490
+ if not return_dict:
491
+ return (image, None)
492
+
493
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=None)
v0.22.0/composable_stable_diffusion.py ADDED
@@ -0,0 +1,581 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 inspect
16
+ from typing import Callable, List, Optional, Union
17
+
18
+ import torch
19
+ from packaging import version
20
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
21
+
22
+ from diffusers import DiffusionPipeline
23
+ from diffusers.configuration_utils import FrozenDict
24
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
25
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
26
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
27
+ from diffusers.schedulers import (
28
+ DDIMScheduler,
29
+ DPMSolverMultistepScheduler,
30
+ EulerAncestralDiscreteScheduler,
31
+ EulerDiscreteScheduler,
32
+ LMSDiscreteScheduler,
33
+ PNDMScheduler,
34
+ )
35
+ from diffusers.utils import deprecate, is_accelerate_available, logging
36
+
37
+
38
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
39
+
40
+
41
+ class ComposableStableDiffusionPipeline(DiffusionPipeline):
42
+ r"""
43
+ Pipeline for text-to-image generation using Stable Diffusion.
44
+
45
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
46
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
47
+
48
+ Args:
49
+ vae ([`AutoencoderKL`]):
50
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
51
+ text_encoder ([`CLIPTextModel`]):
52
+ Frozen text-encoder. Stable Diffusion uses the text portion of
53
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
54
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
55
+ tokenizer (`CLIPTokenizer`):
56
+ Tokenizer of class
57
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
58
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
59
+ scheduler ([`SchedulerMixin`]):
60
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
61
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
62
+ safety_checker ([`StableDiffusionSafetyChecker`]):
63
+ Classification module that estimates whether generated images could be considered offensive or harmful.
64
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
65
+ feature_extractor ([`CLIPImageProcessor`]):
66
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
67
+ """
68
+ _optional_components = ["safety_checker", "feature_extractor"]
69
+
70
+ def __init__(
71
+ self,
72
+ vae: AutoencoderKL,
73
+ text_encoder: CLIPTextModel,
74
+ tokenizer: CLIPTokenizer,
75
+ unet: UNet2DConditionModel,
76
+ scheduler: Union[
77
+ DDIMScheduler,
78
+ PNDMScheduler,
79
+ LMSDiscreteScheduler,
80
+ EulerDiscreteScheduler,
81
+ EulerAncestralDiscreteScheduler,
82
+ DPMSolverMultistepScheduler,
83
+ ],
84
+ safety_checker: StableDiffusionSafetyChecker,
85
+ feature_extractor: CLIPImageProcessor,
86
+ requires_safety_checker: bool = True,
87
+ ):
88
+ super().__init__()
89
+
90
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
91
+ deprecation_message = (
92
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
93
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
94
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
95
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
96
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
97
+ " file"
98
+ )
99
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
100
+ new_config = dict(scheduler.config)
101
+ new_config["steps_offset"] = 1
102
+ scheduler._internal_dict = FrozenDict(new_config)
103
+
104
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
105
+ deprecation_message = (
106
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
107
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
108
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
109
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
110
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
111
+ )
112
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
113
+ new_config = dict(scheduler.config)
114
+ new_config["clip_sample"] = False
115
+ scheduler._internal_dict = FrozenDict(new_config)
116
+
117
+ if safety_checker is None and requires_safety_checker:
118
+ logger.warning(
119
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
120
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
121
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
122
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
123
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
124
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
125
+ )
126
+
127
+ if safety_checker is not None and feature_extractor is None:
128
+ raise ValueError(
129
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
130
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
131
+ )
132
+
133
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
134
+ version.parse(unet.config._diffusers_version).base_version
135
+ ) < version.parse("0.9.0.dev0")
136
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
137
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
138
+ deprecation_message = (
139
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
140
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
141
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
142
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
143
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
144
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
145
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
146
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
147
+ " the `unet/config.json` file"
148
+ )
149
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
150
+ new_config = dict(unet.config)
151
+ new_config["sample_size"] = 64
152
+ unet._internal_dict = FrozenDict(new_config)
153
+
154
+ self.register_modules(
155
+ vae=vae,
156
+ text_encoder=text_encoder,
157
+ tokenizer=tokenizer,
158
+ unet=unet,
159
+ scheduler=scheduler,
160
+ safety_checker=safety_checker,
161
+ feature_extractor=feature_extractor,
162
+ )
163
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
164
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
165
+
166
+ def enable_vae_slicing(self):
167
+ r"""
168
+ Enable sliced VAE decoding.
169
+
170
+ When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
171
+ steps. This is useful to save some memory and allow larger batch sizes.
172
+ """
173
+ self.vae.enable_slicing()
174
+
175
+ def disable_vae_slicing(self):
176
+ r"""
177
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to
178
+ computing decoding in one step.
179
+ """
180
+ self.vae.disable_slicing()
181
+
182
+ def enable_sequential_cpu_offload(self, gpu_id=0):
183
+ r"""
184
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
185
+ text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
186
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
187
+ """
188
+ if is_accelerate_available():
189
+ from accelerate import cpu_offload
190
+ else:
191
+ raise ImportError("Please install accelerate via `pip install accelerate`")
192
+
193
+ device = torch.device(f"cuda:{gpu_id}")
194
+
195
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]:
196
+ if cpu_offloaded_model is not None:
197
+ cpu_offload(cpu_offloaded_model, device)
198
+
199
+ if self.safety_checker is not None:
200
+ # TODO(Patrick) - there is currently a bug with cpu offload of nn.Parameter in accelerate
201
+ # fix by only offloading self.safety_checker for now
202
+ cpu_offload(self.safety_checker.vision_model, device)
203
+
204
+ @property
205
+ def _execution_device(self):
206
+ r"""
207
+ Returns the device on which the pipeline's models will be executed. After calling
208
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
209
+ hooks.
210
+ """
211
+ if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"):
212
+ return self.device
213
+ for module in self.unet.modules():
214
+ if (
215
+ hasattr(module, "_hf_hook")
216
+ and hasattr(module._hf_hook, "execution_device")
217
+ and module._hf_hook.execution_device is not None
218
+ ):
219
+ return torch.device(module._hf_hook.execution_device)
220
+ return self.device
221
+
222
+ def _encode_prompt(self, prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt):
223
+ r"""
224
+ Encodes the prompt into text encoder hidden states.
225
+
226
+ Args:
227
+ prompt (`str` or `list(int)`):
228
+ prompt to be encoded
229
+ device: (`torch.device`):
230
+ torch device
231
+ num_images_per_prompt (`int`):
232
+ number of images that should be generated per prompt
233
+ do_classifier_free_guidance (`bool`):
234
+ whether to use classifier free guidance or not
235
+ negative_prompt (`str` or `List[str]`):
236
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
237
+ if `guidance_scale` is less than `1`).
238
+ """
239
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
240
+
241
+ text_inputs = self.tokenizer(
242
+ prompt,
243
+ padding="max_length",
244
+ max_length=self.tokenizer.model_max_length,
245
+ truncation=True,
246
+ return_tensors="pt",
247
+ )
248
+ text_input_ids = text_inputs.input_ids
249
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
250
+
251
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
252
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
253
+ logger.warning(
254
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
255
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
256
+ )
257
+
258
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
259
+ attention_mask = text_inputs.attention_mask.to(device)
260
+ else:
261
+ attention_mask = None
262
+
263
+ text_embeddings = self.text_encoder(
264
+ text_input_ids.to(device),
265
+ attention_mask=attention_mask,
266
+ )
267
+ text_embeddings = text_embeddings[0]
268
+
269
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
270
+ bs_embed, seq_len, _ = text_embeddings.shape
271
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
272
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
273
+
274
+ # get unconditional embeddings for classifier free guidance
275
+ if do_classifier_free_guidance:
276
+ uncond_tokens: List[str]
277
+ if negative_prompt is None:
278
+ uncond_tokens = [""] * batch_size
279
+ elif type(prompt) is not type(negative_prompt):
280
+ raise TypeError(
281
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
282
+ f" {type(prompt)}."
283
+ )
284
+ elif isinstance(negative_prompt, str):
285
+ uncond_tokens = [negative_prompt]
286
+ elif batch_size != len(negative_prompt):
287
+ raise ValueError(
288
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
289
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
290
+ " the batch size of `prompt`."
291
+ )
292
+ else:
293
+ uncond_tokens = negative_prompt
294
+
295
+ max_length = text_input_ids.shape[-1]
296
+ uncond_input = self.tokenizer(
297
+ uncond_tokens,
298
+ padding="max_length",
299
+ max_length=max_length,
300
+ truncation=True,
301
+ return_tensors="pt",
302
+ )
303
+
304
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
305
+ attention_mask = uncond_input.attention_mask.to(device)
306
+ else:
307
+ attention_mask = None
308
+
309
+ uncond_embeddings = self.text_encoder(
310
+ uncond_input.input_ids.to(device),
311
+ attention_mask=attention_mask,
312
+ )
313
+ uncond_embeddings = uncond_embeddings[0]
314
+
315
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
316
+ seq_len = uncond_embeddings.shape[1]
317
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
318
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
319
+
320
+ # For classifier free guidance, we need to do two forward passes.
321
+ # Here we concatenate the unconditional and text embeddings into a single batch
322
+ # to avoid doing two forward passes
323
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
324
+
325
+ return text_embeddings
326
+
327
+ def run_safety_checker(self, image, device, dtype):
328
+ if self.safety_checker is not None:
329
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
330
+ image, has_nsfw_concept = self.safety_checker(
331
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
332
+ )
333
+ else:
334
+ has_nsfw_concept = None
335
+ return image, has_nsfw_concept
336
+
337
+ def decode_latents(self, latents):
338
+ latents = 1 / 0.18215 * latents
339
+ image = self.vae.decode(latents).sample
340
+ image = (image / 2 + 0.5).clamp(0, 1)
341
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
342
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
343
+ return image
344
+
345
+ def prepare_extra_step_kwargs(self, generator, eta):
346
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
347
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
348
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
349
+ # and should be between [0, 1]
350
+
351
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
352
+ extra_step_kwargs = {}
353
+ if accepts_eta:
354
+ extra_step_kwargs["eta"] = eta
355
+
356
+ # check if the scheduler accepts generator
357
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
358
+ if accepts_generator:
359
+ extra_step_kwargs["generator"] = generator
360
+ return extra_step_kwargs
361
+
362
+ def check_inputs(self, prompt, height, width, callback_steps):
363
+ if not isinstance(prompt, str) and not isinstance(prompt, list):
364
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
365
+
366
+ if height % 8 != 0 or width % 8 != 0:
367
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
368
+
369
+ if (callback_steps is None) or (
370
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
371
+ ):
372
+ raise ValueError(
373
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
374
+ f" {type(callback_steps)}."
375
+ )
376
+
377
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
378
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
379
+ if latents is None:
380
+ if device.type == "mps":
381
+ # randn does not work reproducibly on mps
382
+ latents = torch.randn(shape, generator=generator, device="cpu", dtype=dtype).to(device)
383
+ else:
384
+ latents = torch.randn(shape, generator=generator, device=device, dtype=dtype)
385
+ else:
386
+ if latents.shape != shape:
387
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
388
+ latents = latents.to(device)
389
+
390
+ # scale the initial noise by the standard deviation required by the scheduler
391
+ latents = latents * self.scheduler.init_noise_sigma
392
+ return latents
393
+
394
+ @torch.no_grad()
395
+ def __call__(
396
+ self,
397
+ prompt: Union[str, List[str]],
398
+ height: Optional[int] = None,
399
+ width: Optional[int] = None,
400
+ num_inference_steps: int = 50,
401
+ guidance_scale: float = 7.5,
402
+ negative_prompt: Optional[Union[str, List[str]]] = None,
403
+ num_images_per_prompt: Optional[int] = 1,
404
+ eta: float = 0.0,
405
+ generator: Optional[torch.Generator] = None,
406
+ latents: Optional[torch.FloatTensor] = None,
407
+ output_type: Optional[str] = "pil",
408
+ return_dict: bool = True,
409
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
410
+ callback_steps: int = 1,
411
+ weights: Optional[str] = "",
412
+ ):
413
+ r"""
414
+ Function invoked when calling the pipeline for generation.
415
+
416
+ Args:
417
+ prompt (`str` or `List[str]`):
418
+ The prompt or prompts to guide the image generation.
419
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
420
+ The height in pixels of the generated image.
421
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
422
+ The width in pixels of the generated image.
423
+ num_inference_steps (`int`, *optional*, defaults to 50):
424
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
425
+ expense of slower inference.
426
+ guidance_scale (`float`, *optional*, defaults to 5.0):
427
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
428
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
429
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
430
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
431
+ usually at the expense of lower image quality.
432
+ negative_prompt (`str` or `List[str]`, *optional*):
433
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
434
+ if `guidance_scale` is less than `1`).
435
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
436
+ The number of images to generate per prompt.
437
+ eta (`float`, *optional*, defaults to 0.0):
438
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
439
+ [`schedulers.DDIMScheduler`], will be ignored for others.
440
+ generator (`torch.Generator`, *optional*):
441
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
442
+ deterministic.
443
+ latents (`torch.FloatTensor`, *optional*):
444
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
445
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
446
+ tensor will ge generated by sampling using the supplied random `generator`.
447
+ output_type (`str`, *optional*, defaults to `"pil"`):
448
+ The output format of the generate image. Choose between
449
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
450
+ return_dict (`bool`, *optional*, defaults to `True`):
451
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
452
+ plain tuple.
453
+ callback (`Callable`, *optional*):
454
+ A function that will be called every `callback_steps` steps during inference. The function will be
455
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
456
+ callback_steps (`int`, *optional*, defaults to 1):
457
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
458
+ called at every step.
459
+
460
+ Returns:
461
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
462
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
463
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
464
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
465
+ (nsfw) content, according to the `safety_checker`.
466
+ """
467
+ # 0. Default height and width to unet
468
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
469
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
470
+
471
+ # 1. Check inputs. Raise error if not correct
472
+ self.check_inputs(prompt, height, width, callback_steps)
473
+
474
+ # 2. Define call parameters
475
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
476
+ device = self._execution_device
477
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
478
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
479
+ # corresponds to doing no classifier free guidance.
480
+ do_classifier_free_guidance = guidance_scale > 1.0
481
+
482
+ if "|" in prompt:
483
+ prompt = [x.strip() for x in prompt.split("|")]
484
+ print(f"composing {prompt}...")
485
+
486
+ if not weights:
487
+ # specify weights for prompts (excluding the unconditional score)
488
+ print("using equal positive weights (conjunction) for all prompts...")
489
+ weights = torch.tensor([guidance_scale] * len(prompt), device=self.device).reshape(-1, 1, 1, 1)
490
+ else:
491
+ # set prompt weight for each
492
+ num_prompts = len(prompt) if isinstance(prompt, list) else 1
493
+ weights = [float(w.strip()) for w in weights.split("|")]
494
+ # guidance scale as the default
495
+ if len(weights) < num_prompts:
496
+ weights.append(guidance_scale)
497
+ else:
498
+ weights = weights[:num_prompts]
499
+ assert len(weights) == len(prompt), "weights specified are not equal to the number of prompts"
500
+ weights = torch.tensor(weights, device=self.device).reshape(-1, 1, 1, 1)
501
+ else:
502
+ weights = guidance_scale
503
+
504
+ # 3. Encode input prompt
505
+ text_embeddings = self._encode_prompt(
506
+ prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt
507
+ )
508
+
509
+ # 4. Prepare timesteps
510
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
511
+ timesteps = self.scheduler.timesteps
512
+
513
+ # 5. Prepare latent variables
514
+ num_channels_latents = self.unet.config.in_channels
515
+ latents = self.prepare_latents(
516
+ batch_size * num_images_per_prompt,
517
+ num_channels_latents,
518
+ height,
519
+ width,
520
+ text_embeddings.dtype,
521
+ device,
522
+ generator,
523
+ latents,
524
+ )
525
+
526
+ # composable diffusion
527
+ if isinstance(prompt, list) and batch_size == 1:
528
+ # remove extra unconditional embedding
529
+ # N = one unconditional embed + conditional embeds
530
+ text_embeddings = text_embeddings[len(prompt) - 1 :]
531
+
532
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
533
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
534
+
535
+ # 7. Denoising loop
536
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
537
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
538
+ for i, t in enumerate(timesteps):
539
+ # expand the latents if we are doing classifier free guidance
540
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
541
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
542
+
543
+ # predict the noise residual
544
+ noise_pred = []
545
+ for j in range(text_embeddings.shape[0]):
546
+ noise_pred.append(
547
+ self.unet(latent_model_input[:1], t, encoder_hidden_states=text_embeddings[j : j + 1]).sample
548
+ )
549
+ noise_pred = torch.cat(noise_pred, dim=0)
550
+
551
+ # perform guidance
552
+ if do_classifier_free_guidance:
553
+ noise_pred_uncond, noise_pred_text = noise_pred[:1], noise_pred[1:]
554
+ noise_pred = noise_pred_uncond + (weights * (noise_pred_text - noise_pred_uncond)).sum(
555
+ dim=0, keepdims=True
556
+ )
557
+
558
+ # compute the previous noisy sample x_t -> x_t-1
559
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
560
+
561
+ # call the callback, if provided
562
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
563
+ progress_bar.update()
564
+ if callback is not None and i % callback_steps == 0:
565
+ step_idx = i // getattr(self.scheduler, "order", 1)
566
+ callback(step_idx, t, latents)
567
+
568
+ # 8. Post-processing
569
+ image = self.decode_latents(latents)
570
+
571
+ # 9. Run safety checker
572
+ image, has_nsfw_concept = self.run_safety_checker(image, device, text_embeddings.dtype)
573
+
574
+ # 10. Convert to PIL
575
+ if output_type == "pil":
576
+ image = self.numpy_to_pil(image)
577
+
578
+ if not return_dict:
579
+ return (image, has_nsfw_concept)
580
+
581
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.22.0/ddim_noise_comparative_analysis.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 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
+ from typing import List, Optional, Tuple, Union
16
+
17
+ import PIL.Image
18
+ import torch
19
+ from torchvision import transforms
20
+
21
+ from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
22
+ from diffusers.schedulers import DDIMScheduler
23
+ from diffusers.utils.torch_utils import randn_tensor
24
+
25
+
26
+ trans = transforms.Compose(
27
+ [
28
+ transforms.Resize((256, 256)),
29
+ transforms.ToTensor(),
30
+ transforms.Normalize([0.5], [0.5]),
31
+ ]
32
+ )
33
+
34
+
35
+ def preprocess(image):
36
+ if isinstance(image, torch.Tensor):
37
+ return image
38
+ elif isinstance(image, PIL.Image.Image):
39
+ image = [image]
40
+
41
+ image = [trans(img.convert("RGB")) for img in image]
42
+ image = torch.stack(image)
43
+ return image
44
+
45
+
46
+ class DDIMNoiseComparativeAnalysisPipeline(DiffusionPipeline):
47
+ r"""
48
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
49
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
50
+
51
+ Parameters:
52
+ unet ([`UNet2DModel`]): U-Net architecture to denoise the encoded image.
53
+ scheduler ([`SchedulerMixin`]):
54
+ A scheduler to be used in combination with `unet` to denoise the encoded image. Can be one of
55
+ [`DDPMScheduler`], or [`DDIMScheduler`].
56
+ """
57
+
58
+ def __init__(self, unet, scheduler):
59
+ super().__init__()
60
+
61
+ # make sure scheduler can always be converted to DDIM
62
+ scheduler = DDIMScheduler.from_config(scheduler.config)
63
+
64
+ self.register_modules(unet=unet, scheduler=scheduler)
65
+
66
+ def check_inputs(self, strength):
67
+ if strength < 0 or strength > 1:
68
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
69
+
70
+ def get_timesteps(self, num_inference_steps, strength, device):
71
+ # get the original timestep using init_timestep
72
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
73
+
74
+ t_start = max(num_inference_steps - init_timestep, 0)
75
+ timesteps = self.scheduler.timesteps[t_start:]
76
+
77
+ return timesteps, num_inference_steps - t_start
78
+
79
+ def prepare_latents(self, image, timestep, batch_size, dtype, device, generator=None):
80
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
81
+ raise ValueError(
82
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
83
+ )
84
+
85
+ init_latents = image.to(device=device, dtype=dtype)
86
+
87
+ if isinstance(generator, list) and len(generator) != batch_size:
88
+ raise ValueError(
89
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
90
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
91
+ )
92
+
93
+ shape = init_latents.shape
94
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
95
+
96
+ # get latents
97
+ print("add noise to latents at timestep", timestep)
98
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
99
+ latents = init_latents
100
+
101
+ return latents
102
+
103
+ @torch.no_grad()
104
+ def __call__(
105
+ self,
106
+ image: Union[torch.FloatTensor, PIL.Image.Image] = None,
107
+ strength: float = 0.8,
108
+ batch_size: int = 1,
109
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
110
+ eta: float = 0.0,
111
+ num_inference_steps: int = 50,
112
+ use_clipped_model_output: Optional[bool] = None,
113
+ output_type: Optional[str] = "pil",
114
+ return_dict: bool = True,
115
+ ) -> Union[ImagePipelineOutput, Tuple]:
116
+ r"""
117
+ Args:
118
+ image (`torch.FloatTensor` or `PIL.Image.Image`):
119
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
120
+ process.
121
+ strength (`float`, *optional*, defaults to 0.8):
122
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
123
+ will be used as a starting point, adding more noise to it the larger the `strength`. The number of
124
+ denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
125
+ be maximum and the denoising process will run for the full number of iterations specified in
126
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
127
+ batch_size (`int`, *optional*, defaults to 1):
128
+ The number of images to generate.
129
+ generator (`torch.Generator`, *optional*):
130
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
131
+ to make generation deterministic.
132
+ eta (`float`, *optional*, defaults to 0.0):
133
+ The eta parameter which controls the scale of the variance (0 is DDIM and 1 is one type of DDPM).
134
+ num_inference_steps (`int`, *optional*, defaults to 50):
135
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
136
+ expense of slower inference.
137
+ use_clipped_model_output (`bool`, *optional*, defaults to `None`):
138
+ if `True` or `False`, see documentation for `DDIMScheduler.step`. If `None`, nothing is passed
139
+ downstream to the scheduler. So use `None` for schedulers which don't support this argument.
140
+ output_type (`str`, *optional*, defaults to `"pil"`):
141
+ The output format of the generate image. Choose between
142
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
143
+ return_dict (`bool`, *optional*, defaults to `True`):
144
+ Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple.
145
+
146
+ Returns:
147
+ [`~pipelines.ImagePipelineOutput`] or `tuple`: [`~pipelines.utils.ImagePipelineOutput`] if `return_dict` is
148
+ True, otherwise a `tuple. When returning a tuple, the first element is a list with the generated images.
149
+ """
150
+ # 1. Check inputs. Raise error if not correct
151
+ self.check_inputs(strength)
152
+
153
+ # 2. Preprocess image
154
+ image = preprocess(image)
155
+
156
+ # 3. set timesteps
157
+ self.scheduler.set_timesteps(num_inference_steps, device=self.device)
158
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, self.device)
159
+ latent_timestep = timesteps[:1].repeat(batch_size)
160
+
161
+ # 4. Prepare latent variables
162
+ latents = self.prepare_latents(image, latent_timestep, batch_size, self.unet.dtype, self.device, generator)
163
+ image = latents
164
+
165
+ # 5. Denoising loop
166
+ for t in self.progress_bar(timesteps):
167
+ # 1. predict noise model_output
168
+ model_output = self.unet(image, t).sample
169
+
170
+ # 2. predict previous mean of image x_t-1 and add variance depending on eta
171
+ # eta corresponds to η in paper and should be between [0, 1]
172
+ # do x_t -> x_t-1
173
+ image = self.scheduler.step(
174
+ model_output,
175
+ t,
176
+ image,
177
+ eta=eta,
178
+ use_clipped_model_output=use_clipped_model_output,
179
+ generator=generator,
180
+ ).prev_sample
181
+
182
+ image = (image / 2 + 0.5).clamp(0, 1)
183
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
184
+ if output_type == "pil":
185
+ image = self.numpy_to_pil(image)
186
+
187
+ if not return_dict:
188
+ return (image, latent_timestep.item())
189
+
190
+ return ImagePipelineOutput(images=image)
v0.22.0/edict_pipeline.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ import torch
4
+ from PIL import Image
5
+ from tqdm.auto import tqdm
6
+ from transformers import CLIPTextModel, CLIPTokenizer
7
+
8
+ from diffusers import AutoencoderKL, DDIMScheduler, DiffusionPipeline, UNet2DConditionModel
9
+ from diffusers.image_processor import VaeImageProcessor
10
+ from diffusers.utils import (
11
+ deprecate,
12
+ )
13
+
14
+
15
+ class EDICTPipeline(DiffusionPipeline):
16
+ def __init__(
17
+ self,
18
+ vae: AutoencoderKL,
19
+ text_encoder: CLIPTextModel,
20
+ tokenizer: CLIPTokenizer,
21
+ unet: UNet2DConditionModel,
22
+ scheduler: DDIMScheduler,
23
+ mixing_coeff: float = 0.93,
24
+ leapfrog_steps: bool = True,
25
+ ):
26
+ self.mixing_coeff = mixing_coeff
27
+ self.leapfrog_steps = leapfrog_steps
28
+
29
+ super().__init__()
30
+ self.register_modules(
31
+ vae=vae,
32
+ text_encoder=text_encoder,
33
+ tokenizer=tokenizer,
34
+ unet=unet,
35
+ scheduler=scheduler,
36
+ )
37
+
38
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
39
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
40
+
41
+ def _encode_prompt(
42
+ self, prompt: str, negative_prompt: Optional[str] = None, do_classifier_free_guidance: bool = False
43
+ ):
44
+ text_inputs = self.tokenizer(
45
+ prompt,
46
+ padding="max_length",
47
+ max_length=self.tokenizer.model_max_length,
48
+ truncation=True,
49
+ return_tensors="pt",
50
+ )
51
+
52
+ prompt_embeds = self.text_encoder(text_inputs.input_ids.to(self.device)).last_hidden_state
53
+
54
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=self.device)
55
+
56
+ if do_classifier_free_guidance:
57
+ uncond_tokens = "" if negative_prompt is None else negative_prompt
58
+
59
+ uncond_input = self.tokenizer(
60
+ uncond_tokens,
61
+ padding="max_length",
62
+ max_length=self.tokenizer.model_max_length,
63
+ truncation=True,
64
+ return_tensors="pt",
65
+ )
66
+
67
+ negative_prompt_embeds = self.text_encoder(uncond_input.input_ids.to(self.device)).last_hidden_state
68
+
69
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
70
+
71
+ return prompt_embeds
72
+
73
+ def denoise_mixing_layer(self, x: torch.Tensor, y: torch.Tensor):
74
+ x = self.mixing_coeff * x + (1 - self.mixing_coeff) * y
75
+ y = self.mixing_coeff * y + (1 - self.mixing_coeff) * x
76
+
77
+ return [x, y]
78
+
79
+ def noise_mixing_layer(self, x: torch.Tensor, y: torch.Tensor):
80
+ y = (y - (1 - self.mixing_coeff) * x) / self.mixing_coeff
81
+ x = (x - (1 - self.mixing_coeff) * y) / self.mixing_coeff
82
+
83
+ return [x, y]
84
+
85
+ def _get_alpha_and_beta(self, t: torch.Tensor):
86
+ # as self.alphas_cumprod is always in cpu
87
+ t = int(t)
88
+
89
+ alpha_prod = self.scheduler.alphas_cumprod[t] if t >= 0 else self.scheduler.final_alpha_cumprod
90
+
91
+ return alpha_prod, 1 - alpha_prod
92
+
93
+ def noise_step(
94
+ self,
95
+ base: torch.Tensor,
96
+ model_input: torch.Tensor,
97
+ model_output: torch.Tensor,
98
+ timestep: torch.Tensor,
99
+ ):
100
+ prev_timestep = timestep - self.scheduler.config.num_train_timesteps / self.scheduler.num_inference_steps
101
+
102
+ alpha_prod_t, beta_prod_t = self._get_alpha_and_beta(timestep)
103
+ alpha_prod_t_prev, beta_prod_t_prev = self._get_alpha_and_beta(prev_timestep)
104
+
105
+ a_t = (alpha_prod_t_prev / alpha_prod_t) ** 0.5
106
+ b_t = -a_t * (beta_prod_t**0.5) + beta_prod_t_prev**0.5
107
+
108
+ next_model_input = (base - b_t * model_output) / a_t
109
+
110
+ return model_input, next_model_input.to(base.dtype)
111
+
112
+ def denoise_step(
113
+ self,
114
+ base: torch.Tensor,
115
+ model_input: torch.Tensor,
116
+ model_output: torch.Tensor,
117
+ timestep: torch.Tensor,
118
+ ):
119
+ prev_timestep = timestep - self.scheduler.config.num_train_timesteps / self.scheduler.num_inference_steps
120
+
121
+ alpha_prod_t, beta_prod_t = self._get_alpha_and_beta(timestep)
122
+ alpha_prod_t_prev, beta_prod_t_prev = self._get_alpha_and_beta(prev_timestep)
123
+
124
+ a_t = (alpha_prod_t_prev / alpha_prod_t) ** 0.5
125
+ b_t = -a_t * (beta_prod_t**0.5) + beta_prod_t_prev**0.5
126
+ next_model_input = a_t * base + b_t * model_output
127
+
128
+ return model_input, next_model_input.to(base.dtype)
129
+
130
+ @torch.no_grad()
131
+ def decode_latents(self, latents: torch.Tensor):
132
+ latents = 1 / self.vae.config.scaling_factor * latents
133
+ image = self.vae.decode(latents).sample
134
+ image = (image / 2 + 0.5).clamp(0, 1)
135
+ return image
136
+
137
+ @torch.no_grad()
138
+ def prepare_latents(
139
+ self,
140
+ image: Image.Image,
141
+ text_embeds: torch.Tensor,
142
+ timesteps: torch.Tensor,
143
+ guidance_scale: float,
144
+ generator: Optional[torch.Generator] = None,
145
+ ):
146
+ do_classifier_free_guidance = guidance_scale > 1.0
147
+
148
+ image = image.to(device=self.device, dtype=text_embeds.dtype)
149
+ latent = self.vae.encode(image).latent_dist.sample(generator)
150
+
151
+ latent = self.vae.config.scaling_factor * latent
152
+
153
+ coupled_latents = [latent.clone(), latent.clone()]
154
+
155
+ for i, t in tqdm(enumerate(timesteps), total=len(timesteps)):
156
+ coupled_latents = self.noise_mixing_layer(x=coupled_latents[0], y=coupled_latents[1])
157
+
158
+ # j - model_input index, k - base index
159
+ for j in range(2):
160
+ k = j ^ 1
161
+
162
+ if self.leapfrog_steps:
163
+ if i % 2 == 0:
164
+ k, j = j, k
165
+
166
+ model_input = coupled_latents[j]
167
+ base = coupled_latents[k]
168
+
169
+ latent_model_input = torch.cat([model_input] * 2) if do_classifier_free_guidance else model_input
170
+
171
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeds).sample
172
+
173
+ if do_classifier_free_guidance:
174
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
175
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
176
+
177
+ base, model_input = self.noise_step(
178
+ base=base,
179
+ model_input=model_input,
180
+ model_output=noise_pred,
181
+ timestep=t,
182
+ )
183
+
184
+ coupled_latents[k] = model_input
185
+
186
+ return coupled_latents
187
+
188
+ @torch.no_grad()
189
+ def __call__(
190
+ self,
191
+ base_prompt: str,
192
+ target_prompt: str,
193
+ image: Image.Image,
194
+ guidance_scale: float = 3.0,
195
+ num_inference_steps: int = 50,
196
+ strength: float = 0.8,
197
+ negative_prompt: Optional[str] = None,
198
+ generator: Optional[torch.Generator] = None,
199
+ output_type: Optional[str] = "pil",
200
+ ):
201
+ do_classifier_free_guidance = guidance_scale > 1.0
202
+
203
+ image = self.image_processor.preprocess(image)
204
+
205
+ base_embeds = self._encode_prompt(base_prompt, negative_prompt, do_classifier_free_guidance)
206
+ target_embeds = self._encode_prompt(target_prompt, negative_prompt, do_classifier_free_guidance)
207
+
208
+ self.scheduler.set_timesteps(num_inference_steps, self.device)
209
+
210
+ t_limit = num_inference_steps - int(num_inference_steps * strength)
211
+ fwd_timesteps = self.scheduler.timesteps[t_limit:]
212
+ bwd_timesteps = fwd_timesteps.flip(0)
213
+
214
+ coupled_latents = self.prepare_latents(image, base_embeds, bwd_timesteps, guidance_scale, generator)
215
+
216
+ for i, t in tqdm(enumerate(fwd_timesteps), total=len(fwd_timesteps)):
217
+ # j - model_input index, k - base index
218
+ for k in range(2):
219
+ j = k ^ 1
220
+
221
+ if self.leapfrog_steps:
222
+ if i % 2 == 1:
223
+ k, j = j, k
224
+
225
+ model_input = coupled_latents[j]
226
+ base = coupled_latents[k]
227
+
228
+ latent_model_input = torch.cat([model_input] * 2) if do_classifier_free_guidance else model_input
229
+
230
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=target_embeds).sample
231
+
232
+ if do_classifier_free_guidance:
233
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
234
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
235
+
236
+ base, model_input = self.denoise_step(
237
+ base=base,
238
+ model_input=model_input,
239
+ model_output=noise_pred,
240
+ timestep=t,
241
+ )
242
+
243
+ coupled_latents[k] = model_input
244
+
245
+ coupled_latents = self.denoise_mixing_layer(x=coupled_latents[0], y=coupled_latents[1])
246
+
247
+ # either one is fine
248
+ final_latent = coupled_latents[0]
249
+
250
+ if output_type not in ["latent", "pt", "np", "pil"]:
251
+ deprecation_message = (
252
+ f"the output_type {output_type} is outdated. Please make sure to set it to one of these instead: "
253
+ "`pil`, `np`, `pt`, `latent`"
254
+ )
255
+ deprecate("Unsupported output_type", "1.0.0", deprecation_message, standard_warn=False)
256
+ output_type = "np"
257
+
258
+ if output_type == "latent":
259
+ image = final_latent
260
+ else:
261
+ image = self.decode_latents(final_latent)
262
+ image = self.image_processor.postprocess(image, output_type=output_type)
263
+
264
+ return image
v0.22.0/iadb.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional, Tuple, Union
2
+
3
+ import torch
4
+
5
+ from diffusers import DiffusionPipeline
6
+ from diffusers.configuration_utils import ConfigMixin
7
+ from diffusers.pipeline_utils import ImagePipelineOutput
8
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin
9
+
10
+
11
+ class IADBScheduler(SchedulerMixin, ConfigMixin):
12
+ """
13
+ IADBScheduler is a scheduler for the Iterative α-(de)Blending denoising method. It is simple and minimalist.
14
+
15
+ For more details, see the original paper: https://arxiv.org/abs/2305.03486 and the blog post: https://ggx-research.github.io/publication/2023/05/10/publication-iadb.html
16
+ """
17
+
18
+ def step(
19
+ self,
20
+ model_output: torch.FloatTensor,
21
+ timestep: int,
22
+ x_alpha: torch.FloatTensor,
23
+ ) -> torch.FloatTensor:
24
+ """
25
+ Predict the sample at the previous timestep by reversing the ODE. Core function to propagate the diffusion
26
+ process from the learned model outputs (most often the predicted noise).
27
+
28
+ Args:
29
+ model_output (`torch.FloatTensor`): direct output from learned diffusion model. It is the direction from x0 to x1.
30
+ timestep (`float`): current timestep in the diffusion chain.
31
+ x_alpha (`torch.FloatTensor`): x_alpha sample for the current timestep
32
+
33
+ Returns:
34
+ `torch.FloatTensor`: the sample at the previous timestep
35
+
36
+ """
37
+ if self.num_inference_steps is None:
38
+ raise ValueError(
39
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
40
+ )
41
+
42
+ alpha = timestep / self.num_inference_steps
43
+ alpha_next = (timestep + 1) / self.num_inference_steps
44
+
45
+ d = model_output
46
+
47
+ x_alpha = x_alpha + (alpha_next - alpha) * d
48
+
49
+ return x_alpha
50
+
51
+ def set_timesteps(self, num_inference_steps: int):
52
+ self.num_inference_steps = num_inference_steps
53
+
54
+ def add_noise(
55
+ self,
56
+ original_samples: torch.FloatTensor,
57
+ noise: torch.FloatTensor,
58
+ alpha: torch.FloatTensor,
59
+ ) -> torch.FloatTensor:
60
+ return original_samples * alpha + noise * (1 - alpha)
61
+
62
+ def __len__(self):
63
+ return self.config.num_train_timesteps
64
+
65
+
66
+ class IADBPipeline(DiffusionPipeline):
67
+ r"""
68
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
69
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
70
+
71
+ Parameters:
72
+ unet ([`UNet2DModel`]): U-Net architecture to denoise the encoded image.
73
+ scheduler ([`SchedulerMixin`]):
74
+ A scheduler to be used in combination with `unet` to denoise the encoded image. Can be one of
75
+ [`DDPMScheduler`], or [`DDIMScheduler`].
76
+ """
77
+
78
+ def __init__(self, unet, scheduler):
79
+ super().__init__()
80
+
81
+ self.register_modules(unet=unet, scheduler=scheduler)
82
+
83
+ @torch.no_grad()
84
+ def __call__(
85
+ self,
86
+ batch_size: int = 1,
87
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
88
+ num_inference_steps: int = 50,
89
+ output_type: Optional[str] = "pil",
90
+ return_dict: bool = True,
91
+ ) -> Union[ImagePipelineOutput, Tuple]:
92
+ r"""
93
+ Args:
94
+ batch_size (`int`, *optional*, defaults to 1):
95
+ The number of images to generate.
96
+ num_inference_steps (`int`, *optional*, defaults to 50):
97
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
98
+ expense of slower inference.
99
+ output_type (`str`, *optional*, defaults to `"pil"`):
100
+ The output format of the generate image. Choose between
101
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
102
+ return_dict (`bool`, *optional*, defaults to `True`):
103
+ Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple.
104
+
105
+ Returns:
106
+ [`~pipelines.ImagePipelineOutput`] or `tuple`: [`~pipelines.utils.ImagePipelineOutput`] if `return_dict` is
107
+ True, otherwise a `tuple. When returning a tuple, the first element is a list with the generated images.
108
+ """
109
+
110
+ # Sample gaussian noise to begin loop
111
+ if isinstance(self.unet.config.sample_size, int):
112
+ image_shape = (
113
+ batch_size,
114
+ self.unet.config.in_channels,
115
+ self.unet.config.sample_size,
116
+ self.unet.config.sample_size,
117
+ )
118
+ else:
119
+ image_shape = (batch_size, self.unet.config.in_channels, *self.unet.config.sample_size)
120
+
121
+ if isinstance(generator, list) and len(generator) != batch_size:
122
+ raise ValueError(
123
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
124
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
125
+ )
126
+
127
+ image = torch.randn(image_shape, generator=generator, device=self.device, dtype=self.unet.dtype)
128
+
129
+ # set step values
130
+ self.scheduler.set_timesteps(num_inference_steps)
131
+ x_alpha = image.clone()
132
+ for t in self.progress_bar(range(num_inference_steps)):
133
+ alpha = t / num_inference_steps
134
+
135
+ # 1. predict noise model_output
136
+ model_output = self.unet(x_alpha, torch.tensor(alpha, device=x_alpha.device)).sample
137
+
138
+ # 2. step
139
+ x_alpha = self.scheduler.step(model_output, t, x_alpha)
140
+
141
+ image = (x_alpha * 0.5 + 0.5).clamp(0, 1)
142
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
143
+ if output_type == "pil":
144
+ image = self.numpy_to_pil(image)
145
+
146
+ if not return_dict:
147
+ return (image,)
148
+
149
+ return ImagePipelineOutput(images=image)
v0.22.0/imagic_stable_diffusion.py ADDED
@@ -0,0 +1,496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ modeled after the textual_inversion.py / train_dreambooth.py and the work
3
+ of justinpinkney here: https://github.com/justinpinkney/stable-diffusion/blob/main/notebooks/imagic.ipynb
4
+ """
5
+ import inspect
6
+ import warnings
7
+ from typing import List, Optional, Union
8
+
9
+ import numpy as np
10
+ import PIL.Image
11
+ import torch
12
+ import torch.nn.functional as F
13
+ from accelerate import Accelerator
14
+
15
+ # TODO: remove and import from diffusers.utils when the new version of diffusers is released
16
+ from packaging import version
17
+ from tqdm.auto import tqdm
18
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
19
+
20
+ from diffusers import DiffusionPipeline
21
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
22
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
23
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
24
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
25
+ from diffusers.utils import logging
26
+
27
+
28
+ if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
29
+ PIL_INTERPOLATION = {
30
+ "linear": PIL.Image.Resampling.BILINEAR,
31
+ "bilinear": PIL.Image.Resampling.BILINEAR,
32
+ "bicubic": PIL.Image.Resampling.BICUBIC,
33
+ "lanczos": PIL.Image.Resampling.LANCZOS,
34
+ "nearest": PIL.Image.Resampling.NEAREST,
35
+ }
36
+ else:
37
+ PIL_INTERPOLATION = {
38
+ "linear": PIL.Image.LINEAR,
39
+ "bilinear": PIL.Image.BILINEAR,
40
+ "bicubic": PIL.Image.BICUBIC,
41
+ "lanczos": PIL.Image.LANCZOS,
42
+ "nearest": PIL.Image.NEAREST,
43
+ }
44
+ # ------------------------------------------------------------------------------
45
+
46
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
47
+
48
+
49
+ def preprocess(image):
50
+ w, h = image.size
51
+ w, h = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32
52
+ image = image.resize((w, h), resample=PIL_INTERPOLATION["lanczos"])
53
+ image = np.array(image).astype(np.float32) / 255.0
54
+ image = image[None].transpose(0, 3, 1, 2)
55
+ image = torch.from_numpy(image)
56
+ return 2.0 * image - 1.0
57
+
58
+
59
+ class ImagicStableDiffusionPipeline(DiffusionPipeline):
60
+ r"""
61
+ Pipeline for imagic image editing.
62
+ See paper here: https://arxiv.org/pdf/2210.09276.pdf
63
+
64
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
65
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
66
+ Args:
67
+ vae ([`AutoencoderKL`]):
68
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
69
+ text_encoder ([`CLIPTextModel`]):
70
+ Frozen text-encoder. Stable Diffusion uses the text portion of
71
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
72
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
73
+ tokenizer (`CLIPTokenizer`):
74
+ Tokenizer of class
75
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
76
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
77
+ scheduler ([`SchedulerMixin`]):
78
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
79
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
80
+ safety_checker ([`StableDiffusionSafetyChecker`]):
81
+ Classification module that estimates whether generated images could be considered offsensive or harmful.
82
+ Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.
83
+ feature_extractor ([`CLIPImageProcessor`]):
84
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
85
+ """
86
+
87
+ def __init__(
88
+ self,
89
+ vae: AutoencoderKL,
90
+ text_encoder: CLIPTextModel,
91
+ tokenizer: CLIPTokenizer,
92
+ unet: UNet2DConditionModel,
93
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
94
+ safety_checker: StableDiffusionSafetyChecker,
95
+ feature_extractor: CLIPImageProcessor,
96
+ ):
97
+ super().__init__()
98
+ self.register_modules(
99
+ vae=vae,
100
+ text_encoder=text_encoder,
101
+ tokenizer=tokenizer,
102
+ unet=unet,
103
+ scheduler=scheduler,
104
+ safety_checker=safety_checker,
105
+ feature_extractor=feature_extractor,
106
+ )
107
+
108
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
109
+ r"""
110
+ Enable sliced attention computation.
111
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
112
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
113
+ Args:
114
+ slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
115
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
116
+ a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
117
+ `attention_head_dim` must be a multiple of `slice_size`.
118
+ """
119
+ if slice_size == "auto":
120
+ # half the attention head size is usually a good trade-off between
121
+ # speed and memory
122
+ slice_size = self.unet.config.attention_head_dim // 2
123
+ self.unet.set_attention_slice(slice_size)
124
+
125
+ def disable_attention_slicing(self):
126
+ r"""
127
+ Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
128
+ back to computing attention in one step.
129
+ """
130
+ # set slice_size = `None` to disable `attention slicing`
131
+ self.enable_attention_slicing(None)
132
+
133
+ def train(
134
+ self,
135
+ prompt: Union[str, List[str]],
136
+ image: Union[torch.FloatTensor, PIL.Image.Image],
137
+ height: Optional[int] = 512,
138
+ width: Optional[int] = 512,
139
+ generator: Optional[torch.Generator] = None,
140
+ embedding_learning_rate: float = 0.001,
141
+ diffusion_model_learning_rate: float = 2e-6,
142
+ text_embedding_optimization_steps: int = 500,
143
+ model_fine_tuning_optimization_steps: int = 1000,
144
+ **kwargs,
145
+ ):
146
+ r"""
147
+ Function invoked when calling the pipeline for generation.
148
+ Args:
149
+ prompt (`str` or `List[str]`):
150
+ The prompt or prompts to guide the image generation.
151
+ height (`int`, *optional*, defaults to 512):
152
+ The height in pixels of the generated image.
153
+ width (`int`, *optional*, defaults to 512):
154
+ The width in pixels of the generated image.
155
+ num_inference_steps (`int`, *optional*, defaults to 50):
156
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
157
+ expense of slower inference.
158
+ guidance_scale (`float`, *optional*, defaults to 7.5):
159
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
160
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
161
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
162
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
163
+ usually at the expense of lower image quality.
164
+ eta (`float`, *optional*, defaults to 0.0):
165
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
166
+ [`schedulers.DDIMScheduler`], will be ignored for others.
167
+ generator (`torch.Generator`, *optional*):
168
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
169
+ deterministic.
170
+ latents (`torch.FloatTensor`, *optional*):
171
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
172
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
173
+ tensor will ge generated by sampling using the supplied random `generator`.
174
+ output_type (`str`, *optional*, defaults to `"pil"`):
175
+ The output format of the generate image. Choose between
176
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `nd.array`.
177
+ return_dict (`bool`, *optional*, defaults to `True`):
178
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
179
+ plain tuple.
180
+ Returns:
181
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
182
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
183
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
184
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
185
+ (nsfw) content, according to the `safety_checker`.
186
+ """
187
+ accelerator = Accelerator(
188
+ gradient_accumulation_steps=1,
189
+ mixed_precision="fp16",
190
+ )
191
+
192
+ if "torch_device" in kwargs:
193
+ device = kwargs.pop("torch_device")
194
+ warnings.warn(
195
+ "`torch_device` is deprecated as an input argument to `__call__` and will be removed in v0.3.0."
196
+ " Consider using `pipe.to(torch_device)` instead."
197
+ )
198
+
199
+ if device is None:
200
+ device = "cuda" if torch.cuda.is_available() else "cpu"
201
+ self.to(device)
202
+
203
+ if height % 8 != 0 or width % 8 != 0:
204
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
205
+
206
+ # Freeze vae and unet
207
+ self.vae.requires_grad_(False)
208
+ self.unet.requires_grad_(False)
209
+ self.text_encoder.requires_grad_(False)
210
+ self.unet.eval()
211
+ self.vae.eval()
212
+ self.text_encoder.eval()
213
+
214
+ if accelerator.is_main_process:
215
+ accelerator.init_trackers(
216
+ "imagic",
217
+ config={
218
+ "embedding_learning_rate": embedding_learning_rate,
219
+ "text_embedding_optimization_steps": text_embedding_optimization_steps,
220
+ },
221
+ )
222
+
223
+ # get text embeddings for prompt
224
+ text_input = self.tokenizer(
225
+ prompt,
226
+ padding="max_length",
227
+ max_length=self.tokenizer.model_max_length,
228
+ truncation=True,
229
+ return_tensors="pt",
230
+ )
231
+ text_embeddings = torch.nn.Parameter(
232
+ self.text_encoder(text_input.input_ids.to(self.device))[0], requires_grad=True
233
+ )
234
+ text_embeddings = text_embeddings.detach()
235
+ text_embeddings.requires_grad_()
236
+ text_embeddings_orig = text_embeddings.clone()
237
+
238
+ # Initialize the optimizer
239
+ optimizer = torch.optim.Adam(
240
+ [text_embeddings], # only optimize the embeddings
241
+ lr=embedding_learning_rate,
242
+ )
243
+
244
+ if isinstance(image, PIL.Image.Image):
245
+ image = preprocess(image)
246
+
247
+ latents_dtype = text_embeddings.dtype
248
+ image = image.to(device=self.device, dtype=latents_dtype)
249
+ init_latent_image_dist = self.vae.encode(image).latent_dist
250
+ image_latents = init_latent_image_dist.sample(generator=generator)
251
+ image_latents = 0.18215 * image_latents
252
+
253
+ progress_bar = tqdm(range(text_embedding_optimization_steps), disable=not accelerator.is_local_main_process)
254
+ progress_bar.set_description("Steps")
255
+
256
+ global_step = 0
257
+
258
+ logger.info("First optimizing the text embedding to better reconstruct the init image")
259
+ for _ in range(text_embedding_optimization_steps):
260
+ with accelerator.accumulate(text_embeddings):
261
+ # Sample noise that we'll add to the latents
262
+ noise = torch.randn(image_latents.shape).to(image_latents.device)
263
+ timesteps = torch.randint(1000, (1,), device=image_latents.device)
264
+
265
+ # Add noise to the latents according to the noise magnitude at each timestep
266
+ # (this is the forward diffusion process)
267
+ noisy_latents = self.scheduler.add_noise(image_latents, noise, timesteps)
268
+
269
+ # Predict the noise residual
270
+ noise_pred = self.unet(noisy_latents, timesteps, text_embeddings).sample
271
+
272
+ loss = F.mse_loss(noise_pred, noise, reduction="none").mean([1, 2, 3]).mean()
273
+ accelerator.backward(loss)
274
+
275
+ optimizer.step()
276
+ optimizer.zero_grad()
277
+
278
+ # Checks if the accelerator has performed an optimization step behind the scenes
279
+ if accelerator.sync_gradients:
280
+ progress_bar.update(1)
281
+ global_step += 1
282
+
283
+ logs = {"loss": loss.detach().item()} # , "lr": lr_scheduler.get_last_lr()[0]}
284
+ progress_bar.set_postfix(**logs)
285
+ accelerator.log(logs, step=global_step)
286
+
287
+ accelerator.wait_for_everyone()
288
+
289
+ text_embeddings.requires_grad_(False)
290
+
291
+ # Now we fine tune the unet to better reconstruct the image
292
+ self.unet.requires_grad_(True)
293
+ self.unet.train()
294
+ optimizer = torch.optim.Adam(
295
+ self.unet.parameters(), # only optimize unet
296
+ lr=diffusion_model_learning_rate,
297
+ )
298
+ progress_bar = tqdm(range(model_fine_tuning_optimization_steps), disable=not accelerator.is_local_main_process)
299
+
300
+ logger.info("Next fine tuning the entire model to better reconstruct the init image")
301
+ for _ in range(model_fine_tuning_optimization_steps):
302
+ with accelerator.accumulate(self.unet.parameters()):
303
+ # Sample noise that we'll add to the latents
304
+ noise = torch.randn(image_latents.shape).to(image_latents.device)
305
+ timesteps = torch.randint(1000, (1,), device=image_latents.device)
306
+
307
+ # Add noise to the latents according to the noise magnitude at each timestep
308
+ # (this is the forward diffusion process)
309
+ noisy_latents = self.scheduler.add_noise(image_latents, noise, timesteps)
310
+
311
+ # Predict the noise residual
312
+ noise_pred = self.unet(noisy_latents, timesteps, text_embeddings).sample
313
+
314
+ loss = F.mse_loss(noise_pred, noise, reduction="none").mean([1, 2, 3]).mean()
315
+ accelerator.backward(loss)
316
+
317
+ optimizer.step()
318
+ optimizer.zero_grad()
319
+
320
+ # Checks if the accelerator has performed an optimization step behind the scenes
321
+ if accelerator.sync_gradients:
322
+ progress_bar.update(1)
323
+ global_step += 1
324
+
325
+ logs = {"loss": loss.detach().item()} # , "lr": lr_scheduler.get_last_lr()[0]}
326
+ progress_bar.set_postfix(**logs)
327
+ accelerator.log(logs, step=global_step)
328
+
329
+ accelerator.wait_for_everyone()
330
+ self.text_embeddings_orig = text_embeddings_orig
331
+ self.text_embeddings = text_embeddings
332
+
333
+ @torch.no_grad()
334
+ def __call__(
335
+ self,
336
+ alpha: float = 1.2,
337
+ height: Optional[int] = 512,
338
+ width: Optional[int] = 512,
339
+ num_inference_steps: Optional[int] = 50,
340
+ generator: Optional[torch.Generator] = None,
341
+ output_type: Optional[str] = "pil",
342
+ return_dict: bool = True,
343
+ guidance_scale: float = 7.5,
344
+ eta: float = 0.0,
345
+ ):
346
+ r"""
347
+ Function invoked when calling the pipeline for generation.
348
+ Args:
349
+ prompt (`str` or `List[str]`):
350
+ The prompt or prompts to guide the image generation.
351
+ height (`int`, *optional*, defaults to 512):
352
+ The height in pixels of the generated image.
353
+ width (`int`, *optional*, defaults to 512):
354
+ The width in pixels of the generated image.
355
+ num_inference_steps (`int`, *optional*, defaults to 50):
356
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
357
+ expense of slower inference.
358
+ guidance_scale (`float`, *optional*, defaults to 7.5):
359
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
360
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
361
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
362
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
363
+ usually at the expense of lower image quality.
364
+ eta (`float`, *optional*, defaults to 0.0):
365
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
366
+ [`schedulers.DDIMScheduler`], will be ignored for others.
367
+ generator (`torch.Generator`, *optional*):
368
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
369
+ deterministic.
370
+ latents (`torch.FloatTensor`, *optional*):
371
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
372
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
373
+ tensor will ge generated by sampling using the supplied random `generator`.
374
+ output_type (`str`, *optional*, defaults to `"pil"`):
375
+ The output format of the generate image. Choose between
376
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `nd.array`.
377
+ return_dict (`bool`, *optional*, defaults to `True`):
378
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
379
+ plain tuple.
380
+ Returns:
381
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
382
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
383
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
384
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
385
+ (nsfw) content, according to the `safety_checker`.
386
+ """
387
+ if height % 8 != 0 or width % 8 != 0:
388
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
389
+ if self.text_embeddings is None:
390
+ raise ValueError("Please run the pipe.train() before trying to generate an image.")
391
+ if self.text_embeddings_orig is None:
392
+ raise ValueError("Please run the pipe.train() before trying to generate an image.")
393
+
394
+ text_embeddings = alpha * self.text_embeddings_orig + (1 - alpha) * self.text_embeddings
395
+
396
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
397
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
398
+ # corresponds to doing no classifier free guidance.
399
+ do_classifier_free_guidance = guidance_scale > 1.0
400
+ # get unconditional embeddings for classifier free guidance
401
+ if do_classifier_free_guidance:
402
+ uncond_tokens = [""]
403
+ max_length = self.tokenizer.model_max_length
404
+ uncond_input = self.tokenizer(
405
+ uncond_tokens,
406
+ padding="max_length",
407
+ max_length=max_length,
408
+ truncation=True,
409
+ return_tensors="pt",
410
+ )
411
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
412
+
413
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
414
+ seq_len = uncond_embeddings.shape[1]
415
+ uncond_embeddings = uncond_embeddings.view(1, seq_len, -1)
416
+
417
+ # For classifier free guidance, we need to do two forward passes.
418
+ # Here we concatenate the unconditional and text embeddings into a single batch
419
+ # to avoid doing two forward passes
420
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
421
+
422
+ # get the initial random noise unless the user supplied it
423
+
424
+ # Unlike in other pipelines, latents need to be generated in the target device
425
+ # for 1-to-1 results reproducibility with the CompVis implementation.
426
+ # However this currently doesn't work in `mps`.
427
+ latents_shape = (1, self.unet.config.in_channels, height // 8, width // 8)
428
+ latents_dtype = text_embeddings.dtype
429
+ if self.device.type == "mps":
430
+ # randn does not exist on mps
431
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
432
+ self.device
433
+ )
434
+ else:
435
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
436
+
437
+ # set timesteps
438
+ self.scheduler.set_timesteps(num_inference_steps)
439
+
440
+ # Some schedulers like PNDM have timesteps as arrays
441
+ # It's more optimized to move all timesteps to correct device beforehand
442
+ timesteps_tensor = self.scheduler.timesteps.to(self.device)
443
+
444
+ # scale the initial noise by the standard deviation required by the scheduler
445
+ latents = latents * self.scheduler.init_noise_sigma
446
+
447
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
448
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
449
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
450
+ # and should be between [0, 1]
451
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
452
+ extra_step_kwargs = {}
453
+ if accepts_eta:
454
+ extra_step_kwargs["eta"] = eta
455
+
456
+ for i, t in enumerate(self.progress_bar(timesteps_tensor)):
457
+ # expand the latents if we are doing classifier free guidance
458
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
459
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
460
+
461
+ # predict the noise residual
462
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
463
+
464
+ # perform guidance
465
+ if do_classifier_free_guidance:
466
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
467
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
468
+
469
+ # compute the previous noisy sample x_t -> x_t-1
470
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
471
+
472
+ latents = 1 / 0.18215 * latents
473
+ image = self.vae.decode(latents).sample
474
+
475
+ image = (image / 2 + 0.5).clamp(0, 1)
476
+
477
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
478
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
479
+
480
+ if self.safety_checker is not None:
481
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(
482
+ self.device
483
+ )
484
+ image, has_nsfw_concept = self.safety_checker(
485
+ images=image, clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype)
486
+ )
487
+ else:
488
+ has_nsfw_concept = None
489
+
490
+ if output_type == "pil":
491
+ image = self.numpy_to_pil(image)
492
+
493
+ if not return_dict:
494
+ return (image, has_nsfw_concept)
495
+
496
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.22.0/img2img_inpainting.py ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import Callable, List, Optional, Tuple, Union
3
+
4
+ import numpy as np
5
+ import PIL.Image
6
+ import torch
7
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
8
+
9
+ from diffusers import DiffusionPipeline
10
+ from diffusers.configuration_utils import FrozenDict
11
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
12
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
13
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
14
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
15
+ from diffusers.utils import deprecate, logging
16
+
17
+
18
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
19
+
20
+
21
+ def prepare_mask_and_masked_image(image, mask):
22
+ image = np.array(image.convert("RGB"))
23
+ image = image[None].transpose(0, 3, 1, 2)
24
+ image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
25
+
26
+ mask = np.array(mask.convert("L"))
27
+ mask = mask.astype(np.float32) / 255.0
28
+ mask = mask[None, None]
29
+ mask[mask < 0.5] = 0
30
+ mask[mask >= 0.5] = 1
31
+ mask = torch.from_numpy(mask)
32
+
33
+ masked_image = image * (mask < 0.5)
34
+
35
+ return mask, masked_image
36
+
37
+
38
+ def check_size(image, height, width):
39
+ if isinstance(image, PIL.Image.Image):
40
+ w, h = image.size
41
+ elif isinstance(image, torch.Tensor):
42
+ *_, h, w = image.shape
43
+
44
+ if h != height or w != width:
45
+ raise ValueError(f"Image size should be {height}x{width}, but got {h}x{w}")
46
+
47
+
48
+ def overlay_inner_image(image, inner_image, paste_offset: Tuple[int] = (0, 0)):
49
+ inner_image = inner_image.convert("RGBA")
50
+ image = image.convert("RGB")
51
+
52
+ image.paste(inner_image, paste_offset, inner_image)
53
+ image = image.convert("RGB")
54
+
55
+ return image
56
+
57
+
58
+ class ImageToImageInpaintingPipeline(DiffusionPipeline):
59
+ r"""
60
+ Pipeline for text-guided image-to-image inpainting using Stable Diffusion. *This is an experimental feature*.
61
+
62
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
63
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
64
+
65
+ Args:
66
+ vae ([`AutoencoderKL`]):
67
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
68
+ text_encoder ([`CLIPTextModel`]):
69
+ Frozen text-encoder. Stable Diffusion uses the text portion of
70
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
71
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
72
+ tokenizer (`CLIPTokenizer`):
73
+ Tokenizer of class
74
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
75
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
76
+ scheduler ([`SchedulerMixin`]):
77
+ A scheduler to be used in combination with `unet` to denoise the encoded image latens. Can be one of
78
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
79
+ safety_checker ([`StableDiffusionSafetyChecker`]):
80
+ Classification module that estimates whether generated images could be considered offensive or harmful.
81
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
82
+ feature_extractor ([`CLIPImageProcessor`]):
83
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
84
+ """
85
+
86
+ def __init__(
87
+ self,
88
+ vae: AutoencoderKL,
89
+ text_encoder: CLIPTextModel,
90
+ tokenizer: CLIPTokenizer,
91
+ unet: UNet2DConditionModel,
92
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
93
+ safety_checker: StableDiffusionSafetyChecker,
94
+ feature_extractor: CLIPImageProcessor,
95
+ ):
96
+ super().__init__()
97
+
98
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
99
+ deprecation_message = (
100
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
101
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
102
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
103
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
104
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
105
+ " file"
106
+ )
107
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
108
+ new_config = dict(scheduler.config)
109
+ new_config["steps_offset"] = 1
110
+ scheduler._internal_dict = FrozenDict(new_config)
111
+
112
+ if safety_checker is None:
113
+ logger.warning(
114
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
115
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
116
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
117
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
118
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
119
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
120
+ )
121
+
122
+ self.register_modules(
123
+ vae=vae,
124
+ text_encoder=text_encoder,
125
+ tokenizer=tokenizer,
126
+ unet=unet,
127
+ scheduler=scheduler,
128
+ safety_checker=safety_checker,
129
+ feature_extractor=feature_extractor,
130
+ )
131
+
132
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
133
+ r"""
134
+ Enable sliced attention computation.
135
+
136
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
137
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
138
+
139
+ Args:
140
+ slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
141
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
142
+ a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
143
+ `attention_head_dim` must be a multiple of `slice_size`.
144
+ """
145
+ if slice_size == "auto":
146
+ # half the attention head size is usually a good trade-off between
147
+ # speed and memory
148
+ slice_size = self.unet.config.attention_head_dim // 2
149
+ self.unet.set_attention_slice(slice_size)
150
+
151
+ def disable_attention_slicing(self):
152
+ r"""
153
+ Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
154
+ back to computing attention in one step.
155
+ """
156
+ # set slice_size = `None` to disable `attention slicing`
157
+ self.enable_attention_slicing(None)
158
+
159
+ @torch.no_grad()
160
+ def __call__(
161
+ self,
162
+ prompt: Union[str, List[str]],
163
+ image: Union[torch.FloatTensor, PIL.Image.Image],
164
+ inner_image: Union[torch.FloatTensor, PIL.Image.Image],
165
+ mask_image: Union[torch.FloatTensor, PIL.Image.Image],
166
+ height: int = 512,
167
+ width: int = 512,
168
+ num_inference_steps: int = 50,
169
+ guidance_scale: float = 7.5,
170
+ negative_prompt: Optional[Union[str, List[str]]] = None,
171
+ num_images_per_prompt: Optional[int] = 1,
172
+ eta: float = 0.0,
173
+ generator: Optional[torch.Generator] = None,
174
+ latents: Optional[torch.FloatTensor] = None,
175
+ output_type: Optional[str] = "pil",
176
+ return_dict: bool = True,
177
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
178
+ callback_steps: int = 1,
179
+ **kwargs,
180
+ ):
181
+ r"""
182
+ Function invoked when calling the pipeline for generation.
183
+
184
+ Args:
185
+ prompt (`str` or `List[str]`):
186
+ The prompt or prompts to guide the image generation.
187
+ image (`torch.Tensor` or `PIL.Image.Image`):
188
+ `Image`, or tensor representing an image batch which will be inpainted, *i.e.* parts of the image will
189
+ be masked out with `mask_image` and repainted according to `prompt`.
190
+ inner_image (`torch.Tensor` or `PIL.Image.Image`):
191
+ `Image`, or tensor representing an image batch which will be overlayed onto `image`. Non-transparent
192
+ regions of `inner_image` must fit inside white pixels in `mask_image`. Expects four channels, with
193
+ the last channel representing the alpha channel, which will be used to blend `inner_image` with
194
+ `image`. If not provided, it will be forcibly cast to RGBA.
195
+ mask_image (`PIL.Image.Image`):
196
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
197
+ repainted, while black pixels will be preserved. If `mask_image` is a PIL image, it will be converted
198
+ to a single channel (luminance) before use. If it's a tensor, it should contain one color channel (L)
199
+ instead of 3, so the expected shape would be `(B, H, W, 1)`.
200
+ height (`int`, *optional*, defaults to 512):
201
+ The height in pixels of the generated image.
202
+ width (`int`, *optional*, defaults to 512):
203
+ The width in pixels of the generated image.
204
+ num_inference_steps (`int`, *optional*, defaults to 50):
205
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
206
+ expense of slower inference.
207
+ guidance_scale (`float`, *optional*, defaults to 7.5):
208
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
209
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
210
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
211
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
212
+ usually at the expense of lower image quality.
213
+ negative_prompt (`str` or `List[str]`, *optional*):
214
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
215
+ if `guidance_scale` is less than `1`).
216
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
217
+ The number of images to generate per prompt.
218
+ eta (`float`, *optional*, defaults to 0.0):
219
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
220
+ [`schedulers.DDIMScheduler`], will be ignored for others.
221
+ generator (`torch.Generator`, *optional*):
222
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
223
+ deterministic.
224
+ latents (`torch.FloatTensor`, *optional*):
225
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
226
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
227
+ tensor will ge generated by sampling using the supplied random `generator`.
228
+ output_type (`str`, *optional*, defaults to `"pil"`):
229
+ The output format of the generate image. Choose between
230
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
231
+ return_dict (`bool`, *optional*, defaults to `True`):
232
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
233
+ plain tuple.
234
+ callback (`Callable`, *optional*):
235
+ A function that will be called every `callback_steps` steps during inference. The function will be
236
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
237
+ callback_steps (`int`, *optional*, defaults to 1):
238
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
239
+ called at every step.
240
+
241
+ Returns:
242
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
243
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
244
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
245
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
246
+ (nsfw) content, according to the `safety_checker`.
247
+ """
248
+
249
+ if isinstance(prompt, str):
250
+ batch_size = 1
251
+ elif isinstance(prompt, list):
252
+ batch_size = len(prompt)
253
+ else:
254
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
255
+
256
+ if height % 8 != 0 or width % 8 != 0:
257
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
258
+
259
+ if (callback_steps is None) or (
260
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
261
+ ):
262
+ raise ValueError(
263
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
264
+ f" {type(callback_steps)}."
265
+ )
266
+
267
+ # check if input sizes are correct
268
+ check_size(image, height, width)
269
+ check_size(inner_image, height, width)
270
+ check_size(mask_image, height, width)
271
+
272
+ # get prompt text embeddings
273
+ text_inputs = self.tokenizer(
274
+ prompt,
275
+ padding="max_length",
276
+ max_length=self.tokenizer.model_max_length,
277
+ return_tensors="pt",
278
+ )
279
+ text_input_ids = text_inputs.input_ids
280
+
281
+ if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
282
+ removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :])
283
+ logger.warning(
284
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
285
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
286
+ )
287
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
288
+ text_embeddings = self.text_encoder(text_input_ids.to(self.device))[0]
289
+
290
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
291
+ bs_embed, seq_len, _ = text_embeddings.shape
292
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
293
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
294
+
295
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
296
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
297
+ # corresponds to doing no classifier free guidance.
298
+ do_classifier_free_guidance = guidance_scale > 1.0
299
+ # get unconditional embeddings for classifier free guidance
300
+ if do_classifier_free_guidance:
301
+ uncond_tokens: List[str]
302
+ if negative_prompt is None:
303
+ uncond_tokens = [""]
304
+ elif type(prompt) is not type(negative_prompt):
305
+ raise TypeError(
306
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
307
+ f" {type(prompt)}."
308
+ )
309
+ elif isinstance(negative_prompt, str):
310
+ uncond_tokens = [negative_prompt]
311
+ elif batch_size != len(negative_prompt):
312
+ raise ValueError(
313
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
314
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
315
+ " the batch size of `prompt`."
316
+ )
317
+ else:
318
+ uncond_tokens = negative_prompt
319
+
320
+ max_length = text_input_ids.shape[-1]
321
+ uncond_input = self.tokenizer(
322
+ uncond_tokens,
323
+ padding="max_length",
324
+ max_length=max_length,
325
+ truncation=True,
326
+ return_tensors="pt",
327
+ )
328
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
329
+
330
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
331
+ seq_len = uncond_embeddings.shape[1]
332
+ uncond_embeddings = uncond_embeddings.repeat(batch_size, num_images_per_prompt, 1)
333
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
334
+
335
+ # For classifier free guidance, we need to do two forward passes.
336
+ # Here we concatenate the unconditional and text embeddings into a single batch
337
+ # to avoid doing two forward passes
338
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
339
+
340
+ # get the initial random noise unless the user supplied it
341
+ # Unlike in other pipelines, latents need to be generated in the target device
342
+ # for 1-to-1 results reproducibility with the CompVis implementation.
343
+ # However this currently doesn't work in `mps`.
344
+ num_channels_latents = self.vae.config.latent_channels
345
+ latents_shape = (batch_size * num_images_per_prompt, num_channels_latents, height // 8, width // 8)
346
+ latents_dtype = text_embeddings.dtype
347
+ if latents is None:
348
+ if self.device.type == "mps":
349
+ # randn does not exist on mps
350
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
351
+ self.device
352
+ )
353
+ else:
354
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
355
+ else:
356
+ if latents.shape != latents_shape:
357
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
358
+ latents = latents.to(self.device)
359
+
360
+ # overlay the inner image
361
+ image = overlay_inner_image(image, inner_image)
362
+
363
+ # prepare mask and masked_image
364
+ mask, masked_image = prepare_mask_and_masked_image(image, mask_image)
365
+ mask = mask.to(device=self.device, dtype=text_embeddings.dtype)
366
+ masked_image = masked_image.to(device=self.device, dtype=text_embeddings.dtype)
367
+
368
+ # resize the mask to latents shape as we concatenate the mask to the latents
369
+ mask = torch.nn.functional.interpolate(mask, size=(height // 8, width // 8))
370
+
371
+ # encode the mask image into latents space so we can concatenate it to the latents
372
+ masked_image_latents = self.vae.encode(masked_image).latent_dist.sample(generator=generator)
373
+ masked_image_latents = 0.18215 * masked_image_latents
374
+
375
+ # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method
376
+ mask = mask.repeat(batch_size * num_images_per_prompt, 1, 1, 1)
377
+ masked_image_latents = masked_image_latents.repeat(batch_size * num_images_per_prompt, 1, 1, 1)
378
+
379
+ mask = torch.cat([mask] * 2) if do_classifier_free_guidance else mask
380
+ masked_image_latents = (
381
+ torch.cat([masked_image_latents] * 2) if do_classifier_free_guidance else masked_image_latents
382
+ )
383
+
384
+ num_channels_mask = mask.shape[1]
385
+ num_channels_masked_image = masked_image_latents.shape[1]
386
+
387
+ if num_channels_latents + num_channels_mask + num_channels_masked_image != self.unet.config.in_channels:
388
+ raise ValueError(
389
+ f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects"
390
+ f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +"
391
+ f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}"
392
+ f" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of"
393
+ " `pipeline.unet` or your `mask_image` or `image` input."
394
+ )
395
+
396
+ # set timesteps
397
+ self.scheduler.set_timesteps(num_inference_steps)
398
+
399
+ # Some schedulers like PNDM have timesteps as arrays
400
+ # It's more optimized to move all timesteps to correct device beforehand
401
+ timesteps_tensor = self.scheduler.timesteps.to(self.device)
402
+
403
+ # scale the initial noise by the standard deviation required by the scheduler
404
+ latents = latents * self.scheduler.init_noise_sigma
405
+
406
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
407
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
408
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
409
+ # and should be between [0, 1]
410
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
411
+ extra_step_kwargs = {}
412
+ if accepts_eta:
413
+ extra_step_kwargs["eta"] = eta
414
+
415
+ for i, t in enumerate(self.progress_bar(timesteps_tensor)):
416
+ # expand the latents if we are doing classifier free guidance
417
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
418
+
419
+ # concat latents, mask, masked_image_latents in the channel dimension
420
+ latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1)
421
+
422
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
423
+
424
+ # predict the noise residual
425
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
426
+
427
+ # perform guidance
428
+ if do_classifier_free_guidance:
429
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
430
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
431
+
432
+ # compute the previous noisy sample x_t -> x_t-1
433
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
434
+
435
+ # call the callback, if provided
436
+ if callback is not None and i % callback_steps == 0:
437
+ step_idx = i // getattr(self.scheduler, "order", 1)
438
+ callback(step_idx, t, latents)
439
+
440
+ latents = 1 / 0.18215 * latents
441
+ image = self.vae.decode(latents).sample
442
+
443
+ image = (image / 2 + 0.5).clamp(0, 1)
444
+
445
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
446
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
447
+
448
+ if self.safety_checker is not None:
449
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(
450
+ self.device
451
+ )
452
+ image, has_nsfw_concept = self.safety_checker(
453
+ images=image, clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype)
454
+ )
455
+ else:
456
+ has_nsfw_concept = None
457
+
458
+ if output_type == "pil":
459
+ image = self.numpy_to_pil(image)
460
+
461
+ if not return_dict:
462
+ return (image, has_nsfw_concept)
463
+
464
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.22.0/interpolate_stable_diffusion.py ADDED
@@ -0,0 +1,525 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import time
3
+ from pathlib import Path
4
+ from typing import Callable, List, Optional, Union
5
+
6
+ import numpy as np
7
+ import torch
8
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
9
+
10
+ from diffusers import DiffusionPipeline
11
+ from diffusers.configuration_utils import FrozenDict
12
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
13
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
14
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
15
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
16
+ from diffusers.utils import deprecate, logging
17
+
18
+
19
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
20
+
21
+
22
+ def slerp(t, v0, v1, DOT_THRESHOLD=0.9995):
23
+ """helper function to spherically interpolate two arrays v1 v2"""
24
+
25
+ if not isinstance(v0, np.ndarray):
26
+ inputs_are_torch = True
27
+ input_device = v0.device
28
+ v0 = v0.cpu().numpy()
29
+ v1 = v1.cpu().numpy()
30
+
31
+ dot = np.sum(v0 * v1 / (np.linalg.norm(v0) * np.linalg.norm(v1)))
32
+ if np.abs(dot) > DOT_THRESHOLD:
33
+ v2 = (1 - t) * v0 + t * v1
34
+ else:
35
+ theta_0 = np.arccos(dot)
36
+ sin_theta_0 = np.sin(theta_0)
37
+ theta_t = theta_0 * t
38
+ sin_theta_t = np.sin(theta_t)
39
+ s0 = np.sin(theta_0 - theta_t) / sin_theta_0
40
+ s1 = sin_theta_t / sin_theta_0
41
+ v2 = s0 * v0 + s1 * v1
42
+
43
+ if inputs_are_torch:
44
+ v2 = torch.from_numpy(v2).to(input_device)
45
+
46
+ return v2
47
+
48
+
49
+ class StableDiffusionWalkPipeline(DiffusionPipeline):
50
+ r"""
51
+ Pipeline for text-to-image generation using Stable Diffusion.
52
+
53
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
54
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
55
+
56
+ Args:
57
+ vae ([`AutoencoderKL`]):
58
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
59
+ text_encoder ([`CLIPTextModel`]):
60
+ Frozen text-encoder. Stable Diffusion uses the text portion of
61
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
62
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
63
+ tokenizer (`CLIPTokenizer`):
64
+ Tokenizer of class
65
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
66
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
67
+ scheduler ([`SchedulerMixin`]):
68
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
69
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
70
+ safety_checker ([`StableDiffusionSafetyChecker`]):
71
+ Classification module that estimates whether generated images could be considered offensive or harmful.
72
+ Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.
73
+ feature_extractor ([`CLIPImageProcessor`]):
74
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
75
+ """
76
+
77
+ def __init__(
78
+ self,
79
+ vae: AutoencoderKL,
80
+ text_encoder: CLIPTextModel,
81
+ tokenizer: CLIPTokenizer,
82
+ unet: UNet2DConditionModel,
83
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
84
+ safety_checker: StableDiffusionSafetyChecker,
85
+ feature_extractor: CLIPImageProcessor,
86
+ ):
87
+ super().__init__()
88
+
89
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
90
+ deprecation_message = (
91
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
92
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
93
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
94
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
95
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
96
+ " file"
97
+ )
98
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
99
+ new_config = dict(scheduler.config)
100
+ new_config["steps_offset"] = 1
101
+ scheduler._internal_dict = FrozenDict(new_config)
102
+
103
+ if safety_checker is None:
104
+ logger.warning(
105
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
106
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
107
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
108
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
109
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
110
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
111
+ )
112
+
113
+ self.register_modules(
114
+ vae=vae,
115
+ text_encoder=text_encoder,
116
+ tokenizer=tokenizer,
117
+ unet=unet,
118
+ scheduler=scheduler,
119
+ safety_checker=safety_checker,
120
+ feature_extractor=feature_extractor,
121
+ )
122
+
123
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
124
+ r"""
125
+ Enable sliced attention computation.
126
+
127
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
128
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
129
+
130
+ Args:
131
+ slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
132
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
133
+ a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
134
+ `attention_head_dim` must be a multiple of `slice_size`.
135
+ """
136
+ if slice_size == "auto":
137
+ # half the attention head size is usually a good trade-off between
138
+ # speed and memory
139
+ slice_size = self.unet.config.attention_head_dim // 2
140
+ self.unet.set_attention_slice(slice_size)
141
+
142
+ def disable_attention_slicing(self):
143
+ r"""
144
+ Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
145
+ back to computing attention in one step.
146
+ """
147
+ # set slice_size = `None` to disable `attention slicing`
148
+ self.enable_attention_slicing(None)
149
+
150
+ @torch.no_grad()
151
+ def __call__(
152
+ self,
153
+ prompt: Optional[Union[str, List[str]]] = None,
154
+ height: int = 512,
155
+ width: int = 512,
156
+ num_inference_steps: int = 50,
157
+ guidance_scale: float = 7.5,
158
+ negative_prompt: Optional[Union[str, List[str]]] = None,
159
+ num_images_per_prompt: Optional[int] = 1,
160
+ eta: float = 0.0,
161
+ generator: Optional[torch.Generator] = None,
162
+ latents: Optional[torch.FloatTensor] = None,
163
+ output_type: Optional[str] = "pil",
164
+ return_dict: bool = True,
165
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
166
+ callback_steps: int = 1,
167
+ text_embeddings: Optional[torch.FloatTensor] = None,
168
+ **kwargs,
169
+ ):
170
+ r"""
171
+ Function invoked when calling the pipeline for generation.
172
+
173
+ Args:
174
+ prompt (`str` or `List[str]`, *optional*, defaults to `None`):
175
+ The prompt or prompts to guide the image generation. If not provided, `text_embeddings` is required.
176
+ height (`int`, *optional*, defaults to 512):
177
+ The height in pixels of the generated image.
178
+ width (`int`, *optional*, defaults to 512):
179
+ The width in pixels of the generated image.
180
+ num_inference_steps (`int`, *optional*, defaults to 50):
181
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
182
+ expense of slower inference.
183
+ guidance_scale (`float`, *optional*, defaults to 7.5):
184
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
185
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
186
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
187
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
188
+ usually at the expense of lower image quality.
189
+ negative_prompt (`str` or `List[str]`, *optional*):
190
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
191
+ if `guidance_scale` is less than `1`).
192
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
193
+ The number of images to generate per prompt.
194
+ eta (`float`, *optional*, defaults to 0.0):
195
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
196
+ [`schedulers.DDIMScheduler`], will be ignored for others.
197
+ generator (`torch.Generator`, *optional*):
198
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
199
+ deterministic.
200
+ latents (`torch.FloatTensor`, *optional*):
201
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
202
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
203
+ tensor will ge generated by sampling using the supplied random `generator`.
204
+ output_type (`str`, *optional*, defaults to `"pil"`):
205
+ The output format of the generate image. Choose between
206
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
207
+ return_dict (`bool`, *optional*, defaults to `True`):
208
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
209
+ plain tuple.
210
+ callback (`Callable`, *optional*):
211
+ A function that will be called every `callback_steps` steps during inference. The function will be
212
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
213
+ callback_steps (`int`, *optional*, defaults to 1):
214
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
215
+ called at every step.
216
+ text_embeddings (`torch.FloatTensor`, *optional*, defaults to `None`):
217
+ Pre-generated text embeddings to be used as inputs for image generation. Can be used in place of
218
+ `prompt` to avoid re-computing the embeddings. If not provided, the embeddings will be generated from
219
+ the supplied `prompt`.
220
+
221
+ Returns:
222
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
223
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
224
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
225
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
226
+ (nsfw) content, according to the `safety_checker`.
227
+ """
228
+
229
+ if height % 8 != 0 or width % 8 != 0:
230
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
231
+
232
+ if (callback_steps is None) or (
233
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
234
+ ):
235
+ raise ValueError(
236
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
237
+ f" {type(callback_steps)}."
238
+ )
239
+
240
+ if text_embeddings is None:
241
+ if isinstance(prompt, str):
242
+ batch_size = 1
243
+ elif isinstance(prompt, list):
244
+ batch_size = len(prompt)
245
+ else:
246
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
247
+
248
+ # get prompt text embeddings
249
+ text_inputs = self.tokenizer(
250
+ prompt,
251
+ padding="max_length",
252
+ max_length=self.tokenizer.model_max_length,
253
+ return_tensors="pt",
254
+ )
255
+ text_input_ids = text_inputs.input_ids
256
+
257
+ if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
258
+ removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :])
259
+ print(
260
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
261
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
262
+ )
263
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
264
+ text_embeddings = self.text_encoder(text_input_ids.to(self.device))[0]
265
+ else:
266
+ batch_size = text_embeddings.shape[0]
267
+
268
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
269
+ bs_embed, seq_len, _ = text_embeddings.shape
270
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
271
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
272
+
273
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
274
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
275
+ # corresponds to doing no classifier free guidance.
276
+ do_classifier_free_guidance = guidance_scale > 1.0
277
+ # get unconditional embeddings for classifier free guidance
278
+ if do_classifier_free_guidance:
279
+ uncond_tokens: List[str]
280
+ if negative_prompt is None:
281
+ uncond_tokens = [""] * batch_size
282
+ elif type(prompt) is not type(negative_prompt):
283
+ raise TypeError(
284
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
285
+ f" {type(prompt)}."
286
+ )
287
+ elif isinstance(negative_prompt, str):
288
+ uncond_tokens = [negative_prompt]
289
+ elif batch_size != len(negative_prompt):
290
+ raise ValueError(
291
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
292
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
293
+ " the batch size of `prompt`."
294
+ )
295
+ else:
296
+ uncond_tokens = negative_prompt
297
+
298
+ max_length = self.tokenizer.model_max_length
299
+ uncond_input = self.tokenizer(
300
+ uncond_tokens,
301
+ padding="max_length",
302
+ max_length=max_length,
303
+ truncation=True,
304
+ return_tensors="pt",
305
+ )
306
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
307
+
308
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
309
+ seq_len = uncond_embeddings.shape[1]
310
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
311
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
312
+
313
+ # For classifier free guidance, we need to do two forward passes.
314
+ # Here we concatenate the unconditional and text embeddings into a single batch
315
+ # to avoid doing two forward passes
316
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
317
+
318
+ # get the initial random noise unless the user supplied it
319
+
320
+ # Unlike in other pipelines, latents need to be generated in the target device
321
+ # for 1-to-1 results reproducibility with the CompVis implementation.
322
+ # However this currently doesn't work in `mps`.
323
+ latents_shape = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
324
+ latents_dtype = text_embeddings.dtype
325
+ if latents is None:
326
+ if self.device.type == "mps":
327
+ # randn does not work reproducibly on mps
328
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
329
+ self.device
330
+ )
331
+ else:
332
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
333
+ else:
334
+ if latents.shape != latents_shape:
335
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
336
+ latents = latents.to(self.device)
337
+
338
+ # set timesteps
339
+ self.scheduler.set_timesteps(num_inference_steps)
340
+
341
+ # Some schedulers like PNDM have timesteps as arrays
342
+ # It's more optimized to move all timesteps to correct device beforehand
343
+ timesteps_tensor = self.scheduler.timesteps.to(self.device)
344
+
345
+ # scale the initial noise by the standard deviation required by the scheduler
346
+ latents = latents * self.scheduler.init_noise_sigma
347
+
348
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
349
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
350
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
351
+ # and should be between [0, 1]
352
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
353
+ extra_step_kwargs = {}
354
+ if accepts_eta:
355
+ extra_step_kwargs["eta"] = eta
356
+
357
+ for i, t in enumerate(self.progress_bar(timesteps_tensor)):
358
+ # expand the latents if we are doing classifier free guidance
359
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
360
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
361
+
362
+ # predict the noise residual
363
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
364
+
365
+ # perform guidance
366
+ if do_classifier_free_guidance:
367
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
368
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
369
+
370
+ # compute the previous noisy sample x_t -> x_t-1
371
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
372
+
373
+ # call the callback, if provided
374
+ if callback is not None and i % callback_steps == 0:
375
+ step_idx = i // getattr(self.scheduler, "order", 1)
376
+ callback(step_idx, t, latents)
377
+
378
+ latents = 1 / 0.18215 * latents
379
+ image = self.vae.decode(latents).sample
380
+
381
+ image = (image / 2 + 0.5).clamp(0, 1)
382
+
383
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
384
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
385
+
386
+ if self.safety_checker is not None:
387
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(
388
+ self.device
389
+ )
390
+ image, has_nsfw_concept = self.safety_checker(
391
+ images=image, clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype)
392
+ )
393
+ else:
394
+ has_nsfw_concept = None
395
+
396
+ if output_type == "pil":
397
+ image = self.numpy_to_pil(image)
398
+
399
+ if not return_dict:
400
+ return (image, has_nsfw_concept)
401
+
402
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
403
+
404
+ def embed_text(self, text):
405
+ """takes in text and turns it into text embeddings"""
406
+ text_input = self.tokenizer(
407
+ text,
408
+ padding="max_length",
409
+ max_length=self.tokenizer.model_max_length,
410
+ truncation=True,
411
+ return_tensors="pt",
412
+ )
413
+ with torch.no_grad():
414
+ embed = self.text_encoder(text_input.input_ids.to(self.device))[0]
415
+ return embed
416
+
417
+ def get_noise(self, seed, dtype=torch.float32, height=512, width=512):
418
+ """Takes in random seed and returns corresponding noise vector"""
419
+ return torch.randn(
420
+ (1, self.unet.config.in_channels, height // 8, width // 8),
421
+ generator=torch.Generator(device=self.device).manual_seed(seed),
422
+ device=self.device,
423
+ dtype=dtype,
424
+ )
425
+
426
+ def walk(
427
+ self,
428
+ prompts: List[str],
429
+ seeds: List[int],
430
+ num_interpolation_steps: Optional[int] = 6,
431
+ output_dir: Optional[str] = "./dreams",
432
+ name: Optional[str] = None,
433
+ batch_size: Optional[int] = 1,
434
+ height: Optional[int] = 512,
435
+ width: Optional[int] = 512,
436
+ guidance_scale: Optional[float] = 7.5,
437
+ num_inference_steps: Optional[int] = 50,
438
+ eta: Optional[float] = 0.0,
439
+ ) -> List[str]:
440
+ """
441
+ Walks through a series of prompts and seeds, interpolating between them and saving the results to disk.
442
+
443
+ Args:
444
+ prompts (`List[str]`):
445
+ List of prompts to generate images for.
446
+ seeds (`List[int]`):
447
+ List of seeds corresponding to provided prompts. Must be the same length as prompts.
448
+ num_interpolation_steps (`int`, *optional*, defaults to 6):
449
+ Number of interpolation steps to take between prompts.
450
+ output_dir (`str`, *optional*, defaults to `./dreams`):
451
+ Directory to save the generated images to.
452
+ name (`str`, *optional*, defaults to `None`):
453
+ Subdirectory of `output_dir` to save the generated images to. If `None`, the name will
454
+ be the current time.
455
+ batch_size (`int`, *optional*, defaults to 1):
456
+ Number of images to generate at once.
457
+ height (`int`, *optional*, defaults to 512):
458
+ Height of the generated images.
459
+ width (`int`, *optional*, defaults to 512):
460
+ Width of the generated images.
461
+ guidance_scale (`float`, *optional*, defaults to 7.5):
462
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
463
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
464
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
465
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
466
+ usually at the expense of lower image quality.
467
+ num_inference_steps (`int`, *optional*, defaults to 50):
468
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
469
+ expense of slower inference.
470
+ eta (`float`, *optional*, defaults to 0.0):
471
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
472
+ [`schedulers.DDIMScheduler`], will be ignored for others.
473
+
474
+ Returns:
475
+ `List[str]`: List of paths to the generated images.
476
+ """
477
+ if not len(prompts) == len(seeds):
478
+ raise ValueError(
479
+ f"Number of prompts and seeds must be equalGot {len(prompts)} prompts and {len(seeds)} seeds"
480
+ )
481
+
482
+ name = name or time.strftime("%Y%m%d-%H%M%S")
483
+ save_path = Path(output_dir) / name
484
+ save_path.mkdir(exist_ok=True, parents=True)
485
+
486
+ frame_idx = 0
487
+ frame_filepaths = []
488
+ for prompt_a, prompt_b, seed_a, seed_b in zip(prompts, prompts[1:], seeds, seeds[1:]):
489
+ # Embed Text
490
+ embed_a = self.embed_text(prompt_a)
491
+ embed_b = self.embed_text(prompt_b)
492
+
493
+ # Get Noise
494
+ noise_dtype = embed_a.dtype
495
+ noise_a = self.get_noise(seed_a, noise_dtype, height, width)
496
+ noise_b = self.get_noise(seed_b, noise_dtype, height, width)
497
+
498
+ noise_batch, embeds_batch = None, None
499
+ T = np.linspace(0.0, 1.0, num_interpolation_steps)
500
+ for i, t in enumerate(T):
501
+ noise = slerp(float(t), noise_a, noise_b)
502
+ embed = torch.lerp(embed_a, embed_b, t)
503
+
504
+ noise_batch = noise if noise_batch is None else torch.cat([noise_batch, noise], dim=0)
505
+ embeds_batch = embed if embeds_batch is None else torch.cat([embeds_batch, embed], dim=0)
506
+
507
+ batch_is_ready = embeds_batch.shape[0] == batch_size or i + 1 == T.shape[0]
508
+ if batch_is_ready:
509
+ outputs = self(
510
+ latents=noise_batch,
511
+ text_embeddings=embeds_batch,
512
+ height=height,
513
+ width=width,
514
+ guidance_scale=guidance_scale,
515
+ eta=eta,
516
+ num_inference_steps=num_inference_steps,
517
+ )
518
+ noise_batch, embeds_batch = None, None
519
+
520
+ for image in outputs["images"]:
521
+ frame_filepath = str(save_path / f"frame_{frame_idx:06d}.png")
522
+ image.save(frame_filepath)
523
+ frame_filepaths.append(frame_filepath)
524
+ frame_idx += 1
525
+ return frame_filepaths
v0.22.0/latent_consistency_img2img.py ADDED
@@ -0,0 +1,829 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Stanford University Team and 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
+ # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion
16
+ # and https://github.com/hojonathanho/diffusion
17
+
18
+ import math
19
+ from dataclasses import dataclass
20
+ from typing import Any, Dict, List, Optional, Tuple, Union
21
+
22
+ import numpy as np
23
+ import PIL.Image
24
+ import torch
25
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
26
+
27
+ from diffusers import AutoencoderKL, ConfigMixin, DiffusionPipeline, SchedulerMixin, UNet2DConditionModel, logging
28
+ from diffusers.configuration_utils import register_to_config
29
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
30
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
31
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
32
+ from diffusers.utils import BaseOutput
33
+ from diffusers.utils.torch_utils import randn_tensor
34
+
35
+
36
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
37
+
38
+
39
+ class LatentConsistencyModelImg2ImgPipeline(DiffusionPipeline):
40
+ _optional_components = ["scheduler"]
41
+
42
+ def __init__(
43
+ self,
44
+ vae: AutoencoderKL,
45
+ text_encoder: CLIPTextModel,
46
+ tokenizer: CLIPTokenizer,
47
+ unet: UNet2DConditionModel,
48
+ scheduler: "LCMSchedulerWithTimestamp",
49
+ safety_checker: StableDiffusionSafetyChecker,
50
+ feature_extractor: CLIPImageProcessor,
51
+ requires_safety_checker: bool = True,
52
+ ):
53
+ super().__init__()
54
+
55
+ scheduler = (
56
+ scheduler
57
+ if scheduler is not None
58
+ else LCMSchedulerWithTimestamp(
59
+ beta_start=0.00085, beta_end=0.0120, beta_schedule="scaled_linear", prediction_type="epsilon"
60
+ )
61
+ )
62
+
63
+ self.register_modules(
64
+ vae=vae,
65
+ text_encoder=text_encoder,
66
+ tokenizer=tokenizer,
67
+ unet=unet,
68
+ scheduler=scheduler,
69
+ safety_checker=safety_checker,
70
+ feature_extractor=feature_extractor,
71
+ )
72
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
73
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
74
+
75
+ def _encode_prompt(
76
+ self,
77
+ prompt,
78
+ device,
79
+ num_images_per_prompt,
80
+ prompt_embeds: None,
81
+ ):
82
+ r"""
83
+ Encodes the prompt into text encoder hidden states.
84
+ Args:
85
+ prompt (`str` or `List[str]`, *optional*):
86
+ prompt to be encoded
87
+ device: (`torch.device`):
88
+ torch device
89
+ num_images_per_prompt (`int`):
90
+ number of images that should be generated per prompt
91
+ prompt_embeds (`torch.FloatTensor`, *optional*):
92
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
93
+ provided, text embeddings will be generated from `prompt` input argument.
94
+ """
95
+
96
+ if prompt is not None and isinstance(prompt, str):
97
+ pass
98
+ elif prompt is not None and isinstance(prompt, list):
99
+ len(prompt)
100
+ else:
101
+ prompt_embeds.shape[0]
102
+
103
+ if prompt_embeds is None:
104
+ text_inputs = self.tokenizer(
105
+ prompt,
106
+ padding="max_length",
107
+ max_length=self.tokenizer.model_max_length,
108
+ truncation=True,
109
+ return_tensors="pt",
110
+ )
111
+ text_input_ids = text_inputs.input_ids
112
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
113
+
114
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
115
+ text_input_ids, untruncated_ids
116
+ ):
117
+ removed_text = self.tokenizer.batch_decode(
118
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
119
+ )
120
+ logger.warning(
121
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
122
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
123
+ )
124
+
125
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
126
+ attention_mask = text_inputs.attention_mask.to(device)
127
+ else:
128
+ attention_mask = None
129
+
130
+ prompt_embeds = self.text_encoder(
131
+ text_input_ids.to(device),
132
+ attention_mask=attention_mask,
133
+ )
134
+ prompt_embeds = prompt_embeds[0]
135
+
136
+ if self.text_encoder is not None:
137
+ prompt_embeds_dtype = self.text_encoder.dtype
138
+ elif self.unet is not None:
139
+ prompt_embeds_dtype = self.unet.dtype
140
+ else:
141
+ prompt_embeds_dtype = prompt_embeds.dtype
142
+
143
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
144
+
145
+ bs_embed, seq_len, _ = prompt_embeds.shape
146
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
147
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
148
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
149
+
150
+ # Don't need to get uncond prompt embedding because of LCM Guided Distillation
151
+ return prompt_embeds
152
+
153
+ def run_safety_checker(self, image, device, dtype):
154
+ if self.safety_checker is None:
155
+ has_nsfw_concept = None
156
+ else:
157
+ if torch.is_tensor(image):
158
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
159
+ else:
160
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
161
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
162
+ image, has_nsfw_concept = self.safety_checker(
163
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
164
+ )
165
+ return image, has_nsfw_concept
166
+
167
+ def prepare_latents(
168
+ self,
169
+ image,
170
+ timestep,
171
+ batch_size,
172
+ num_channels_latents,
173
+ height,
174
+ width,
175
+ dtype,
176
+ device,
177
+ latents=None,
178
+ generator=None,
179
+ ):
180
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
181
+
182
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
183
+ raise ValueError(
184
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
185
+ )
186
+
187
+ image = image.to(device=device, dtype=dtype)
188
+
189
+ # batch_size = batch_size * num_images_per_prompt
190
+
191
+ if image.shape[1] == 4:
192
+ init_latents = image
193
+
194
+ else:
195
+ if isinstance(generator, list) and len(generator) != batch_size:
196
+ raise ValueError(
197
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
198
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
199
+ )
200
+
201
+ elif isinstance(generator, list):
202
+ init_latents = [
203
+ self.vae.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(batch_size)
204
+ ]
205
+ init_latents = torch.cat(init_latents, dim=0)
206
+ else:
207
+ init_latents = self.vae.encode(image).latent_dist.sample(generator)
208
+
209
+ init_latents = self.vae.config.scaling_factor * init_latents
210
+
211
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
212
+ # expand init_latents for batch_size
213
+ (
214
+ f"You have passed {batch_size} text prompts (`prompt`), but only {init_latents.shape[0]} initial"
215
+ " images (`image`). Initial images are now duplicating to match the number of text prompts. Note"
216
+ " that this behavior is deprecated and will be removed in a version 1.0.0. Please make sure to update"
217
+ " your script to pass as many initial images as text prompts to suppress this warning."
218
+ )
219
+ # deprecate("len(prompt) != len(image)", "1.0.0", deprecation_message, standard_warn=False)
220
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
221
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
222
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
223
+ raise ValueError(
224
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
225
+ )
226
+ else:
227
+ init_latents = torch.cat([init_latents], dim=0)
228
+
229
+ shape = init_latents.shape
230
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
231
+
232
+ # get latents
233
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
234
+ latents = init_latents
235
+
236
+ return latents
237
+
238
+ if latents is None:
239
+ latents = torch.randn(shape, dtype=dtype).to(device)
240
+ else:
241
+ latents = latents.to(device)
242
+ # scale the initial noise by the standard deviation required by the scheduler
243
+ latents = latents * self.scheduler.init_noise_sigma
244
+ return latents
245
+
246
+ def get_w_embedding(self, w, embedding_dim=512, dtype=torch.float32):
247
+ """
248
+ see https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
249
+ Args:
250
+ timesteps: torch.Tensor: generate embedding vectors at these timesteps
251
+ embedding_dim: int: dimension of the embeddings to generate
252
+ dtype: data type of the generated embeddings
253
+ Returns:
254
+ embedding vectors with shape `(len(timesteps), embedding_dim)`
255
+ """
256
+ assert len(w.shape) == 1
257
+ w = w * 1000.0
258
+
259
+ half_dim = embedding_dim // 2
260
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
261
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
262
+ emb = w.to(dtype)[:, None] * emb[None, :]
263
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
264
+ if embedding_dim % 2 == 1: # zero pad
265
+ emb = torch.nn.functional.pad(emb, (0, 1))
266
+ assert emb.shape == (w.shape[0], embedding_dim)
267
+ return emb
268
+
269
+ def get_timesteps(self, num_inference_steps, strength, device):
270
+ # get the original timestep using init_timestep
271
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
272
+
273
+ t_start = max(num_inference_steps - init_timestep, 0)
274
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
275
+
276
+ return timesteps, num_inference_steps - t_start
277
+
278
+ @torch.no_grad()
279
+ def __call__(
280
+ self,
281
+ prompt: Union[str, List[str]] = None,
282
+ image: PipelineImageInput = None,
283
+ strength: float = 0.8,
284
+ height: Optional[int] = 768,
285
+ width: Optional[int] = 768,
286
+ guidance_scale: float = 7.5,
287
+ num_images_per_prompt: Optional[int] = 1,
288
+ latents: Optional[torch.FloatTensor] = None,
289
+ num_inference_steps: int = 4,
290
+ lcm_origin_steps: int = 50,
291
+ prompt_embeds: Optional[torch.FloatTensor] = None,
292
+ output_type: Optional[str] = "pil",
293
+ return_dict: bool = True,
294
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
295
+ ):
296
+ # 0. Default height and width to unet
297
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
298
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
299
+
300
+ # 2. Define call parameters
301
+ if prompt is not None and isinstance(prompt, str):
302
+ batch_size = 1
303
+ elif prompt is not None and isinstance(prompt, list):
304
+ batch_size = len(prompt)
305
+ else:
306
+ batch_size = prompt_embeds.shape[0]
307
+
308
+ device = self._execution_device
309
+ # do_classifier_free_guidance = guidance_scale > 0.0 # In LCM Implementation: cfg_noise = noise_cond + cfg_scale * (noise_cond - noise_uncond) , (cfg_scale > 0.0 using CFG)
310
+
311
+ # 3. Encode input prompt
312
+ prompt_embeds = self._encode_prompt(
313
+ prompt,
314
+ device,
315
+ num_images_per_prompt,
316
+ prompt_embeds=prompt_embeds,
317
+ )
318
+
319
+ # 3.5 encode image
320
+ image = self.image_processor.preprocess(image)
321
+
322
+ # 4. Prepare timesteps
323
+ self.scheduler.set_timesteps(strength, num_inference_steps, lcm_origin_steps)
324
+ # timesteps = self.scheduler.timesteps
325
+ # timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, 1.0, device)
326
+ timesteps = self.scheduler.timesteps
327
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
328
+
329
+ print("timesteps: ", timesteps)
330
+
331
+ # 5. Prepare latent variable
332
+ num_channels_latents = self.unet.config.in_channels
333
+ latents = self.prepare_latents(
334
+ image,
335
+ latent_timestep,
336
+ batch_size * num_images_per_prompt,
337
+ num_channels_latents,
338
+ height,
339
+ width,
340
+ prompt_embeds.dtype,
341
+ device,
342
+ latents,
343
+ )
344
+ bs = batch_size * num_images_per_prompt
345
+
346
+ # 6. Get Guidance Scale Embedding
347
+ w = torch.tensor(guidance_scale).repeat(bs)
348
+ w_embedding = self.get_w_embedding(w, embedding_dim=256).to(device=device, dtype=latents.dtype)
349
+
350
+ # 7. LCM MultiStep Sampling Loop:
351
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
352
+ for i, t in enumerate(timesteps):
353
+ ts = torch.full((bs,), t, device=device, dtype=torch.long)
354
+ latents = latents.to(prompt_embeds.dtype)
355
+
356
+ # model prediction (v-prediction, eps, x)
357
+ model_pred = self.unet(
358
+ latents,
359
+ ts,
360
+ timestep_cond=w_embedding,
361
+ encoder_hidden_states=prompt_embeds,
362
+ cross_attention_kwargs=cross_attention_kwargs,
363
+ return_dict=False,
364
+ )[0]
365
+
366
+ # compute the previous noisy sample x_t -> x_t-1
367
+ latents, denoised = self.scheduler.step(model_pred, i, t, latents, return_dict=False)
368
+
369
+ # # call the callback, if provided
370
+ # if i == len(timesteps) - 1:
371
+ progress_bar.update()
372
+
373
+ denoised = denoised.to(prompt_embeds.dtype)
374
+ if not output_type == "latent":
375
+ image = self.vae.decode(denoised / self.vae.config.scaling_factor, return_dict=False)[0]
376
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
377
+ else:
378
+ image = denoised
379
+ has_nsfw_concept = None
380
+
381
+ if has_nsfw_concept is None:
382
+ do_denormalize = [True] * image.shape[0]
383
+ else:
384
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
385
+
386
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
387
+
388
+ if not return_dict:
389
+ return (image, has_nsfw_concept)
390
+
391
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
392
+
393
+
394
+ @dataclass
395
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM
396
+ class LCMSchedulerOutput(BaseOutput):
397
+ """
398
+ Output class for the scheduler's `step` function output.
399
+ Args:
400
+ prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
401
+ Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
402
+ denoising loop.
403
+ pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
404
+ The predicted denoised sample `(x_{0})` based on the model output from the current timestep.
405
+ `pred_original_sample` can be used to preview progress or for guidance.
406
+ """
407
+
408
+ prev_sample: torch.FloatTensor
409
+ denoised: Optional[torch.FloatTensor] = None
410
+
411
+
412
+ # Copied from diffusers.schedulers.scheduling_ddpm.betas_for_alpha_bar
413
+ def betas_for_alpha_bar(
414
+ num_diffusion_timesteps,
415
+ max_beta=0.999,
416
+ alpha_transform_type="cosine",
417
+ ):
418
+ """
419
+ Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
420
+ (1-beta) over time from t = [0,1].
421
+ Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
422
+ to that part of the diffusion process.
423
+ Args:
424
+ num_diffusion_timesteps (`int`): the number of betas to produce.
425
+ max_beta (`float`): the maximum beta to use; use values lower than 1 to
426
+ prevent singularities.
427
+ alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar.
428
+ Choose from `cosine` or `exp`
429
+ Returns:
430
+ betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
431
+ """
432
+ if alpha_transform_type == "cosine":
433
+
434
+ def alpha_bar_fn(t):
435
+ return math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2
436
+
437
+ elif alpha_transform_type == "exp":
438
+
439
+ def alpha_bar_fn(t):
440
+ return math.exp(t * -12.0)
441
+
442
+ else:
443
+ raise ValueError(f"Unsupported alpha_tranform_type: {alpha_transform_type}")
444
+
445
+ betas = []
446
+ for i in range(num_diffusion_timesteps):
447
+ t1 = i / num_diffusion_timesteps
448
+ t2 = (i + 1) / num_diffusion_timesteps
449
+ betas.append(min(1 - alpha_bar_fn(t2) / alpha_bar_fn(t1), max_beta))
450
+ return torch.tensor(betas, dtype=torch.float32)
451
+
452
+
453
+ def rescale_zero_terminal_snr(betas):
454
+ """
455
+ Rescales betas to have zero terminal SNR Based on https://arxiv.org/pdf/2305.08891.pdf (Algorithm 1)
456
+ Args:
457
+ betas (`torch.FloatTensor`):
458
+ the betas that the scheduler is being initialized with.
459
+ Returns:
460
+ `torch.FloatTensor`: rescaled betas with zero terminal SNR
461
+ """
462
+ # Convert betas to alphas_bar_sqrt
463
+ alphas = 1.0 - betas
464
+ alphas_cumprod = torch.cumprod(alphas, dim=0)
465
+ alphas_bar_sqrt = alphas_cumprod.sqrt()
466
+
467
+ # Store old values.
468
+ alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone()
469
+ alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone()
470
+
471
+ # Shift so the last timestep is zero.
472
+ alphas_bar_sqrt -= alphas_bar_sqrt_T
473
+
474
+ # Scale so the first timestep is back to the old value.
475
+ alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T)
476
+
477
+ # Convert alphas_bar_sqrt to betas
478
+ alphas_bar = alphas_bar_sqrt**2 # Revert sqrt
479
+ alphas = alphas_bar[1:] / alphas_bar[:-1] # Revert cumprod
480
+ alphas = torch.cat([alphas_bar[0:1], alphas])
481
+ betas = 1 - alphas
482
+
483
+ return betas
484
+
485
+
486
+ class LCMSchedulerWithTimestamp(SchedulerMixin, ConfigMixin):
487
+ """
488
+ This class modifies LCMScheduler to add a timestamp argument to set_timesteps
489
+
490
+
491
+ `LCMScheduler` extends the denoising procedure introduced in denoising diffusion probabilistic models (DDPMs) with
492
+ non-Markovian guidance.
493
+ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
494
+ methods the library implements for all schedulers such as loading and saving.
495
+ Args:
496
+ num_train_timesteps (`int`, defaults to 1000):
497
+ The number of diffusion steps to train the model.
498
+ beta_start (`float`, defaults to 0.0001):
499
+ The starting `beta` value of inference.
500
+ beta_end (`float`, defaults to 0.02):
501
+ The final `beta` value.
502
+ beta_schedule (`str`, defaults to `"linear"`):
503
+ The beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
504
+ `linear`, `scaled_linear`, or `squaredcos_cap_v2`.
505
+ trained_betas (`np.ndarray`, *optional*):
506
+ Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`.
507
+ clip_sample (`bool`, defaults to `True`):
508
+ Clip the predicted sample for numerical stability.
509
+ clip_sample_range (`float`, defaults to 1.0):
510
+ The maximum magnitude for sample clipping. Valid only when `clip_sample=True`.
511
+ set_alpha_to_one (`bool`, defaults to `True`):
512
+ Each diffusion step uses the alphas product value at that step and at the previous one. For the final step
513
+ there is no previous alpha. When this option is `True` the previous alpha product is fixed to `1`,
514
+ otherwise it uses the alpha value at step 0.
515
+ steps_offset (`int`, defaults to 0):
516
+ An offset added to the inference steps. You can use a combination of `offset=1` and
517
+ `set_alpha_to_one=False` to make the last step use step 0 for the previous alpha product like in Stable
518
+ Diffusion.
519
+ prediction_type (`str`, defaults to `epsilon`, *optional*):
520
+ Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
521
+ `sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen
522
+ Video](https://imagen.research.google/video/paper.pdf) paper).
523
+ thresholding (`bool`, defaults to `False`):
524
+ Whether to use the "dynamic thresholding" method. This is unsuitable for latent-space diffusion models such
525
+ as Stable Diffusion.
526
+ dynamic_thresholding_ratio (`float`, defaults to 0.995):
527
+ The ratio for the dynamic thresholding method. Valid only when `thresholding=True`.
528
+ sample_max_value (`float`, defaults to 1.0):
529
+ The threshold value for dynamic thresholding. Valid only when `thresholding=True`.
530
+ timestep_spacing (`str`, defaults to `"leading"`):
531
+ The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
532
+ Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
533
+ rescale_betas_zero_snr (`bool`, defaults to `False`):
534
+ Whether to rescale the betas to have zero terminal SNR. This enables the model to generate very bright and
535
+ dark samples instead of limiting it to samples with medium brightness. Loosely related to
536
+ [`--offset_noise`](https://github.com/huggingface/diffusers/blob/74fd735eb073eb1d774b1ab4154a0876eb82f055/examples/dreambooth/train_dreambooth.py#L506).
537
+ """
538
+
539
+ # _compatibles = [e.name for e in KarrasDiffusionSchedulers]
540
+ order = 1
541
+
542
+ @register_to_config
543
+ def __init__(
544
+ self,
545
+ num_train_timesteps: int = 1000,
546
+ beta_start: float = 0.0001,
547
+ beta_end: float = 0.02,
548
+ beta_schedule: str = "linear",
549
+ trained_betas: Optional[Union[np.ndarray, List[float]]] = None,
550
+ clip_sample: bool = True,
551
+ set_alpha_to_one: bool = True,
552
+ steps_offset: int = 0,
553
+ prediction_type: str = "epsilon",
554
+ thresholding: bool = False,
555
+ dynamic_thresholding_ratio: float = 0.995,
556
+ clip_sample_range: float = 1.0,
557
+ sample_max_value: float = 1.0,
558
+ timestep_spacing: str = "leading",
559
+ rescale_betas_zero_snr: bool = False,
560
+ ):
561
+ if trained_betas is not None:
562
+ self.betas = torch.tensor(trained_betas, dtype=torch.float32)
563
+ elif beta_schedule == "linear":
564
+ self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32)
565
+ elif beta_schedule == "scaled_linear":
566
+ # this schedule is very specific to the latent diffusion model.
567
+ self.betas = (
568
+ torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2
569
+ )
570
+ elif beta_schedule == "squaredcos_cap_v2":
571
+ # Glide cosine schedule
572
+ self.betas = betas_for_alpha_bar(num_train_timesteps)
573
+ else:
574
+ raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}")
575
+
576
+ # Rescale for zero SNR
577
+ if rescale_betas_zero_snr:
578
+ self.betas = rescale_zero_terminal_snr(self.betas)
579
+
580
+ self.alphas = 1.0 - self.betas
581
+ self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
582
+
583
+ # At every step in ddim, we are looking into the previous alphas_cumprod
584
+ # For the final step, there is no previous alphas_cumprod because we are already at 0
585
+ # `set_alpha_to_one` decides whether we set this parameter simply to one or
586
+ # whether we use the final alpha of the "non-previous" one.
587
+ self.final_alpha_cumprod = torch.tensor(1.0) if set_alpha_to_one else self.alphas_cumprod[0]
588
+
589
+ # standard deviation of the initial noise distribution
590
+ self.init_noise_sigma = 1.0
591
+
592
+ # setable values
593
+ self.num_inference_steps = None
594
+ self.timesteps = torch.from_numpy(np.arange(0, num_train_timesteps)[::-1].copy().astype(np.int64))
595
+
596
+ def scale_model_input(self, sample: torch.FloatTensor, timestep: Optional[int] = None) -> torch.FloatTensor:
597
+ """
598
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
599
+ current timestep.
600
+ Args:
601
+ sample (`torch.FloatTensor`):
602
+ The input sample.
603
+ timestep (`int`, *optional*):
604
+ The current timestep in the diffusion chain.
605
+ Returns:
606
+ `torch.FloatTensor`:
607
+ A scaled input sample.
608
+ """
609
+ return sample
610
+
611
+ def _get_variance(self, timestep, prev_timestep):
612
+ alpha_prod_t = self.alphas_cumprod[timestep]
613
+ alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
614
+ beta_prod_t = 1 - alpha_prod_t
615
+ beta_prod_t_prev = 1 - alpha_prod_t_prev
616
+
617
+ variance = (beta_prod_t_prev / beta_prod_t) * (1 - alpha_prod_t / alpha_prod_t_prev)
618
+
619
+ return variance
620
+
621
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample
622
+ def _threshold_sample(self, sample: torch.FloatTensor) -> torch.FloatTensor:
623
+ """
624
+ "Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
625
+ prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
626
+ s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
627
+ pixels from saturation at each step. We find that dynamic thresholding results in significantly better
628
+ photorealism as well as better image-text alignment, especially when using very large guidance weights."
629
+ https://arxiv.org/abs/2205.11487
630
+ """
631
+ dtype = sample.dtype
632
+ batch_size, channels, height, width = sample.shape
633
+
634
+ if dtype not in (torch.float32, torch.float64):
635
+ sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half
636
+
637
+ # Flatten sample for doing quantile calculation along each image
638
+ sample = sample.reshape(batch_size, channels * height * width)
639
+
640
+ abs_sample = sample.abs() # "a certain percentile absolute pixel value"
641
+
642
+ s = torch.quantile(abs_sample, self.config.dynamic_thresholding_ratio, dim=1)
643
+ s = torch.clamp(
644
+ s, min=1, max=self.config.sample_max_value
645
+ ) # When clamped to min=1, equivalent to standard clipping to [-1, 1]
646
+
647
+ s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0
648
+ sample = torch.clamp(sample, -s, s) / s # "we threshold xt0 to the range [-s, s] and then divide by s"
649
+
650
+ sample = sample.reshape(batch_size, channels, height, width)
651
+ sample = sample.to(dtype)
652
+
653
+ return sample
654
+
655
+ def set_timesteps(
656
+ self, stength, num_inference_steps: int, lcm_origin_steps: int, device: Union[str, torch.device] = None
657
+ ):
658
+ """
659
+ Sets the discrete timesteps used for the diffusion chain (to be run before inference).
660
+ Args:
661
+ num_inference_steps (`int`):
662
+ The number of diffusion steps used when generating samples with a pre-trained model.
663
+ """
664
+
665
+ if num_inference_steps > self.config.num_train_timesteps:
666
+ raise ValueError(
667
+ f"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:"
668
+ f" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle"
669
+ f" maximal {self.config.num_train_timesteps} timesteps."
670
+ )
671
+
672
+ self.num_inference_steps = num_inference_steps
673
+
674
+ # LCM Timesteps Setting: # Linear Spacing
675
+ c = self.config.num_train_timesteps // lcm_origin_steps
676
+ lcm_origin_timesteps = (
677
+ np.asarray(list(range(1, int(lcm_origin_steps * stength) + 1))) * c - 1
678
+ ) # LCM Training Steps Schedule
679
+ skipping_step = len(lcm_origin_timesteps) // num_inference_steps
680
+ timesteps = lcm_origin_timesteps[::-skipping_step][:num_inference_steps] # LCM Inference Steps Schedule
681
+
682
+ self.timesteps = torch.from_numpy(timesteps.copy()).to(device)
683
+
684
+ def get_scalings_for_boundary_condition_discrete(self, t):
685
+ self.sigma_data = 0.5 # Default: 0.5
686
+
687
+ # By dividing 0.1: This is almost a delta function at t=0.
688
+ c_skip = self.sigma_data**2 / ((t / 0.1) ** 2 + self.sigma_data**2)
689
+ c_out = (t / 0.1) / ((t / 0.1) ** 2 + self.sigma_data**2) ** 0.5
690
+ return c_skip, c_out
691
+
692
+ def step(
693
+ self,
694
+ model_output: torch.FloatTensor,
695
+ timeindex: int,
696
+ timestep: int,
697
+ sample: torch.FloatTensor,
698
+ eta: float = 0.0,
699
+ use_clipped_model_output: bool = False,
700
+ generator=None,
701
+ variance_noise: Optional[torch.FloatTensor] = None,
702
+ return_dict: bool = True,
703
+ ) -> Union[LCMSchedulerOutput, Tuple]:
704
+ """
705
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
706
+ process from the learned model outputs (most often the predicted noise).
707
+ Args:
708
+ model_output (`torch.FloatTensor`):
709
+ The direct output from learned diffusion model.
710
+ timestep (`float`):
711
+ The current discrete timestep in the diffusion chain.
712
+ sample (`torch.FloatTensor`):
713
+ A current instance of a sample created by the diffusion process.
714
+ eta (`float`):
715
+ The weight of noise for added noise in diffusion step.
716
+ use_clipped_model_output (`bool`, defaults to `False`):
717
+ If `True`, computes "corrected" `model_output` from the clipped predicted original sample. Necessary
718
+ because predicted original sample is clipped to [-1, 1] when `self.config.clip_sample` is `True`. If no
719
+ clipping has happened, "corrected" `model_output` would coincide with the one provided as input and
720
+ `use_clipped_model_output` has no effect.
721
+ generator (`torch.Generator`, *optional*):
722
+ A random number generator.
723
+ variance_noise (`torch.FloatTensor`):
724
+ Alternative to generating noise with `generator` by directly providing the noise for the variance
725
+ itself. Useful for methods such as [`CycleDiffusion`].
726
+ return_dict (`bool`, *optional*, defaults to `True`):
727
+ Whether or not to return a [`~schedulers.scheduling_lcm.LCMSchedulerOutput`] or `tuple`.
728
+ Returns:
729
+ [`~schedulers.scheduling_utils.LCMSchedulerOutput`] or `tuple`:
730
+ If return_dict is `True`, [`~schedulers.scheduling_lcm.LCMSchedulerOutput`] is returned, otherwise a
731
+ tuple is returned where the first element is the sample tensor.
732
+ """
733
+ if self.num_inference_steps is None:
734
+ raise ValueError(
735
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
736
+ )
737
+
738
+ # 1. get previous step value
739
+ prev_timeindex = timeindex + 1
740
+ if prev_timeindex < len(self.timesteps):
741
+ prev_timestep = self.timesteps[prev_timeindex]
742
+ else:
743
+ prev_timestep = timestep
744
+
745
+ # 2. compute alphas, betas
746
+ alpha_prod_t = self.alphas_cumprod[timestep]
747
+ alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
748
+
749
+ beta_prod_t = 1 - alpha_prod_t
750
+ beta_prod_t_prev = 1 - alpha_prod_t_prev
751
+
752
+ # 3. Get scalings for boundary conditions
753
+ c_skip, c_out = self.get_scalings_for_boundary_condition_discrete(timestep)
754
+
755
+ # 4. Different Parameterization:
756
+ parameterization = self.config.prediction_type
757
+
758
+ if parameterization == "epsilon": # noise-prediction
759
+ pred_x0 = (sample - beta_prod_t.sqrt() * model_output) / alpha_prod_t.sqrt()
760
+
761
+ elif parameterization == "sample": # x-prediction
762
+ pred_x0 = model_output
763
+
764
+ elif parameterization == "v_prediction": # v-prediction
765
+ pred_x0 = alpha_prod_t.sqrt() * sample - beta_prod_t.sqrt() * model_output
766
+
767
+ # 4. Denoise model output using boundary conditions
768
+ denoised = c_out * pred_x0 + c_skip * sample
769
+
770
+ # 5. Sample z ~ N(0, I), For MultiStep Inference
771
+ # Noise is not used for one-step sampling.
772
+ if len(self.timesteps) > 1:
773
+ noise = torch.randn(model_output.shape).to(model_output.device)
774
+ prev_sample = alpha_prod_t_prev.sqrt() * denoised + beta_prod_t_prev.sqrt() * noise
775
+ else:
776
+ prev_sample = denoised
777
+
778
+ if not return_dict:
779
+ return (prev_sample, denoised)
780
+
781
+ return LCMSchedulerOutput(prev_sample=prev_sample, denoised=denoised)
782
+
783
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.add_noise
784
+ def add_noise(
785
+ self,
786
+ original_samples: torch.FloatTensor,
787
+ noise: torch.FloatTensor,
788
+ timesteps: torch.IntTensor,
789
+ ) -> torch.FloatTensor:
790
+ # Make sure alphas_cumprod and timestep have same device and dtype as original_samples
791
+ alphas_cumprod = self.alphas_cumprod.to(device=original_samples.device, dtype=original_samples.dtype)
792
+ timesteps = timesteps.to(original_samples.device)
793
+
794
+ sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
795
+ sqrt_alpha_prod = sqrt_alpha_prod.flatten()
796
+ while len(sqrt_alpha_prod.shape) < len(original_samples.shape):
797
+ sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
798
+
799
+ sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
800
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
801
+ while len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape):
802
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
803
+
804
+ noisy_samples = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise
805
+ return noisy_samples
806
+
807
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.get_velocity
808
+ def get_velocity(
809
+ self, sample: torch.FloatTensor, noise: torch.FloatTensor, timesteps: torch.IntTensor
810
+ ) -> torch.FloatTensor:
811
+ # Make sure alphas_cumprod and timestep have same device and dtype as sample
812
+ alphas_cumprod = self.alphas_cumprod.to(device=sample.device, dtype=sample.dtype)
813
+ timesteps = timesteps.to(sample.device)
814
+
815
+ sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
816
+ sqrt_alpha_prod = sqrt_alpha_prod.flatten()
817
+ while len(sqrt_alpha_prod.shape) < len(sample.shape):
818
+ sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
819
+
820
+ sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
821
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
822
+ while len(sqrt_one_minus_alpha_prod.shape) < len(sample.shape):
823
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
824
+
825
+ velocity = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample
826
+ return velocity
827
+
828
+ def __len__(self):
829
+ return self.config.num_train_timesteps
v0.22.0/latent_consistency_txt2img.py ADDED
@@ -0,0 +1,730 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Stanford University Team and 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
+ # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion
16
+ # and https://github.com/hojonathanho/diffusion
17
+
18
+ import math
19
+ from dataclasses import dataclass
20
+ from typing import Any, Dict, List, Optional, Tuple, Union
21
+
22
+ import numpy as np
23
+ import torch
24
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
25
+
26
+ from diffusers import AutoencoderKL, ConfigMixin, DiffusionPipeline, SchedulerMixin, UNet2DConditionModel, logging
27
+ from diffusers.configuration_utils import register_to_config
28
+ from diffusers.image_processor import VaeImageProcessor
29
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
30
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
31
+ from diffusers.utils import BaseOutput
32
+
33
+
34
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
35
+
36
+
37
+ class LatentConsistencyModelPipeline(DiffusionPipeline):
38
+ _optional_components = ["scheduler"]
39
+
40
+ def __init__(
41
+ self,
42
+ vae: AutoencoderKL,
43
+ text_encoder: CLIPTextModel,
44
+ tokenizer: CLIPTokenizer,
45
+ unet: UNet2DConditionModel,
46
+ scheduler: "LCMScheduler",
47
+ safety_checker: StableDiffusionSafetyChecker,
48
+ feature_extractor: CLIPImageProcessor,
49
+ requires_safety_checker: bool = True,
50
+ ):
51
+ super().__init__()
52
+
53
+ scheduler = (
54
+ scheduler
55
+ if scheduler is not None
56
+ else LCMScheduler(
57
+ beta_start=0.00085, beta_end=0.0120, beta_schedule="scaled_linear", prediction_type="epsilon"
58
+ )
59
+ )
60
+
61
+ self.register_modules(
62
+ vae=vae,
63
+ text_encoder=text_encoder,
64
+ tokenizer=tokenizer,
65
+ unet=unet,
66
+ scheduler=scheduler,
67
+ safety_checker=safety_checker,
68
+ feature_extractor=feature_extractor,
69
+ )
70
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
71
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
72
+
73
+ def _encode_prompt(
74
+ self,
75
+ prompt,
76
+ device,
77
+ num_images_per_prompt,
78
+ prompt_embeds: None,
79
+ ):
80
+ r"""
81
+ Encodes the prompt into text encoder hidden states.
82
+ Args:
83
+ prompt (`str` or `List[str]`, *optional*):
84
+ prompt to be encoded
85
+ device: (`torch.device`):
86
+ torch device
87
+ num_images_per_prompt (`int`):
88
+ number of images that should be generated per prompt
89
+ prompt_embeds (`torch.FloatTensor`, *optional*):
90
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
91
+ provided, text embeddings will be generated from `prompt` input argument.
92
+ """
93
+
94
+ if prompt is not None and isinstance(prompt, str):
95
+ pass
96
+ elif prompt is not None and isinstance(prompt, list):
97
+ len(prompt)
98
+ else:
99
+ prompt_embeds.shape[0]
100
+
101
+ if prompt_embeds is None:
102
+ text_inputs = self.tokenizer(
103
+ prompt,
104
+ padding="max_length",
105
+ max_length=self.tokenizer.model_max_length,
106
+ truncation=True,
107
+ return_tensors="pt",
108
+ )
109
+ text_input_ids = text_inputs.input_ids
110
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
111
+
112
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
113
+ text_input_ids, untruncated_ids
114
+ ):
115
+ removed_text = self.tokenizer.batch_decode(
116
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
117
+ )
118
+ logger.warning(
119
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
120
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
121
+ )
122
+
123
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
124
+ attention_mask = text_inputs.attention_mask.to(device)
125
+ else:
126
+ attention_mask = None
127
+
128
+ prompt_embeds = self.text_encoder(
129
+ text_input_ids.to(device),
130
+ attention_mask=attention_mask,
131
+ )
132
+ prompt_embeds = prompt_embeds[0]
133
+
134
+ if self.text_encoder is not None:
135
+ prompt_embeds_dtype = self.text_encoder.dtype
136
+ elif self.unet is not None:
137
+ prompt_embeds_dtype = self.unet.dtype
138
+ else:
139
+ prompt_embeds_dtype = prompt_embeds.dtype
140
+
141
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
142
+
143
+ bs_embed, seq_len, _ = prompt_embeds.shape
144
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
145
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
146
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
147
+
148
+ # Don't need to get uncond prompt embedding because of LCM Guided Distillation
149
+ return prompt_embeds
150
+
151
+ def run_safety_checker(self, image, device, dtype):
152
+ if self.safety_checker is None:
153
+ has_nsfw_concept = None
154
+ else:
155
+ if torch.is_tensor(image):
156
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
157
+ else:
158
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
159
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
160
+ image, has_nsfw_concept = self.safety_checker(
161
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
162
+ )
163
+ return image, has_nsfw_concept
164
+
165
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, latents=None):
166
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
167
+ if latents is None:
168
+ latents = torch.randn(shape, dtype=dtype).to(device)
169
+ else:
170
+ latents = latents.to(device)
171
+ # scale the initial noise by the standard deviation required by the scheduler
172
+ latents = latents * self.scheduler.init_noise_sigma
173
+ return latents
174
+
175
+ def get_w_embedding(self, w, embedding_dim=512, dtype=torch.float32):
176
+ """
177
+ see https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
178
+ Args:
179
+ timesteps: torch.Tensor: generate embedding vectors at these timesteps
180
+ embedding_dim: int: dimension of the embeddings to generate
181
+ dtype: data type of the generated embeddings
182
+ Returns:
183
+ embedding vectors with shape `(len(timesteps), embedding_dim)`
184
+ """
185
+ assert len(w.shape) == 1
186
+ w = w * 1000.0
187
+
188
+ half_dim = embedding_dim // 2
189
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
190
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
191
+ emb = w.to(dtype)[:, None] * emb[None, :]
192
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
193
+ if embedding_dim % 2 == 1: # zero pad
194
+ emb = torch.nn.functional.pad(emb, (0, 1))
195
+ assert emb.shape == (w.shape[0], embedding_dim)
196
+ return emb
197
+
198
+ @torch.no_grad()
199
+ def __call__(
200
+ self,
201
+ prompt: Union[str, List[str]] = None,
202
+ height: Optional[int] = 768,
203
+ width: Optional[int] = 768,
204
+ guidance_scale: float = 7.5,
205
+ num_images_per_prompt: Optional[int] = 1,
206
+ latents: Optional[torch.FloatTensor] = None,
207
+ num_inference_steps: int = 4,
208
+ lcm_origin_steps: int = 50,
209
+ prompt_embeds: Optional[torch.FloatTensor] = None,
210
+ output_type: Optional[str] = "pil",
211
+ return_dict: bool = True,
212
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
213
+ ):
214
+ # 0. Default height and width to unet
215
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
216
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
217
+
218
+ # 2. Define call parameters
219
+ if prompt is not None and isinstance(prompt, str):
220
+ batch_size = 1
221
+ elif prompt is not None and isinstance(prompt, list):
222
+ batch_size = len(prompt)
223
+ else:
224
+ batch_size = prompt_embeds.shape[0]
225
+
226
+ device = self._execution_device
227
+ # do_classifier_free_guidance = guidance_scale > 0.0 # In LCM Implementation: cfg_noise = noise_cond + cfg_scale * (noise_cond - noise_uncond) , (cfg_scale > 0.0 using CFG)
228
+
229
+ # 3. Encode input prompt
230
+ prompt_embeds = self._encode_prompt(
231
+ prompt,
232
+ device,
233
+ num_images_per_prompt,
234
+ prompt_embeds=prompt_embeds,
235
+ )
236
+
237
+ # 4. Prepare timesteps
238
+ self.scheduler.set_timesteps(num_inference_steps, lcm_origin_steps)
239
+ timesteps = self.scheduler.timesteps
240
+
241
+ # 5. Prepare latent variable
242
+ num_channels_latents = self.unet.config.in_channels
243
+ latents = self.prepare_latents(
244
+ batch_size * num_images_per_prompt,
245
+ num_channels_latents,
246
+ height,
247
+ width,
248
+ prompt_embeds.dtype,
249
+ device,
250
+ latents,
251
+ )
252
+ bs = batch_size * num_images_per_prompt
253
+
254
+ # 6. Get Guidance Scale Embedding
255
+ w = torch.tensor(guidance_scale).repeat(bs)
256
+ w_embedding = self.get_w_embedding(w, embedding_dim=256).to(device=device, dtype=latents.dtype)
257
+
258
+ # 7. LCM MultiStep Sampling Loop:
259
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
260
+ for i, t in enumerate(timesteps):
261
+ ts = torch.full((bs,), t, device=device, dtype=torch.long)
262
+ latents = latents.to(prompt_embeds.dtype)
263
+
264
+ # model prediction (v-prediction, eps, x)
265
+ model_pred = self.unet(
266
+ latents,
267
+ ts,
268
+ timestep_cond=w_embedding,
269
+ encoder_hidden_states=prompt_embeds,
270
+ cross_attention_kwargs=cross_attention_kwargs,
271
+ return_dict=False,
272
+ )[0]
273
+
274
+ # compute the previous noisy sample x_t -> x_t-1
275
+ latents, denoised = self.scheduler.step(model_pred, i, t, latents, return_dict=False)
276
+
277
+ # # call the callback, if provided
278
+ # if i == len(timesteps) - 1:
279
+ progress_bar.update()
280
+
281
+ denoised = denoised.to(prompt_embeds.dtype)
282
+ if not output_type == "latent":
283
+ image = self.vae.decode(denoised / self.vae.config.scaling_factor, return_dict=False)[0]
284
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
285
+ else:
286
+ image = denoised
287
+ has_nsfw_concept = None
288
+
289
+ if has_nsfw_concept is None:
290
+ do_denormalize = [True] * image.shape[0]
291
+ else:
292
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
293
+
294
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
295
+
296
+ if not return_dict:
297
+ return (image, has_nsfw_concept)
298
+
299
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
300
+
301
+
302
+ @dataclass
303
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM
304
+ class LCMSchedulerOutput(BaseOutput):
305
+ """
306
+ Output class for the scheduler's `step` function output.
307
+ Args:
308
+ prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
309
+ Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
310
+ denoising loop.
311
+ pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
312
+ The predicted denoised sample `(x_{0})` based on the model output from the current timestep.
313
+ `pred_original_sample` can be used to preview progress or for guidance.
314
+ """
315
+
316
+ prev_sample: torch.FloatTensor
317
+ denoised: Optional[torch.FloatTensor] = None
318
+
319
+
320
+ # Copied from diffusers.schedulers.scheduling_ddpm.betas_for_alpha_bar
321
+ def betas_for_alpha_bar(
322
+ num_diffusion_timesteps,
323
+ max_beta=0.999,
324
+ alpha_transform_type="cosine",
325
+ ):
326
+ """
327
+ Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
328
+ (1-beta) over time from t = [0,1].
329
+ Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
330
+ to that part of the diffusion process.
331
+ Args:
332
+ num_diffusion_timesteps (`int`): the number of betas to produce.
333
+ max_beta (`float`): the maximum beta to use; use values lower than 1 to
334
+ prevent singularities.
335
+ alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar.
336
+ Choose from `cosine` or `exp`
337
+ Returns:
338
+ betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
339
+ """
340
+ if alpha_transform_type == "cosine":
341
+
342
+ def alpha_bar_fn(t):
343
+ return math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2
344
+
345
+ elif alpha_transform_type == "exp":
346
+
347
+ def alpha_bar_fn(t):
348
+ return math.exp(t * -12.0)
349
+
350
+ else:
351
+ raise ValueError(f"Unsupported alpha_tranform_type: {alpha_transform_type}")
352
+
353
+ betas = []
354
+ for i in range(num_diffusion_timesteps):
355
+ t1 = i / num_diffusion_timesteps
356
+ t2 = (i + 1) / num_diffusion_timesteps
357
+ betas.append(min(1 - alpha_bar_fn(t2) / alpha_bar_fn(t1), max_beta))
358
+ return torch.tensor(betas, dtype=torch.float32)
359
+
360
+
361
+ def rescale_zero_terminal_snr(betas):
362
+ """
363
+ Rescales betas to have zero terminal SNR Based on https://arxiv.org/pdf/2305.08891.pdf (Algorithm 1)
364
+ Args:
365
+ betas (`torch.FloatTensor`):
366
+ the betas that the scheduler is being initialized with.
367
+ Returns:
368
+ `torch.FloatTensor`: rescaled betas with zero terminal SNR
369
+ """
370
+ # Convert betas to alphas_bar_sqrt
371
+ alphas = 1.0 - betas
372
+ alphas_cumprod = torch.cumprod(alphas, dim=0)
373
+ alphas_bar_sqrt = alphas_cumprod.sqrt()
374
+
375
+ # Store old values.
376
+ alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone()
377
+ alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone()
378
+
379
+ # Shift so the last timestep is zero.
380
+ alphas_bar_sqrt -= alphas_bar_sqrt_T
381
+
382
+ # Scale so the first timestep is back to the old value.
383
+ alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T)
384
+
385
+ # Convert alphas_bar_sqrt to betas
386
+ alphas_bar = alphas_bar_sqrt**2 # Revert sqrt
387
+ alphas = alphas_bar[1:] / alphas_bar[:-1] # Revert cumprod
388
+ alphas = torch.cat([alphas_bar[0:1], alphas])
389
+ betas = 1 - alphas
390
+
391
+ return betas
392
+
393
+
394
+ class LCMScheduler(SchedulerMixin, ConfigMixin):
395
+ """
396
+ `LCMScheduler` extends the denoising procedure introduced in denoising diffusion probabilistic models (DDPMs) with
397
+ non-Markovian guidance.
398
+ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
399
+ methods the library implements for all schedulers such as loading and saving.
400
+ Args:
401
+ num_train_timesteps (`int`, defaults to 1000):
402
+ The number of diffusion steps to train the model.
403
+ beta_start (`float`, defaults to 0.0001):
404
+ The starting `beta` value of inference.
405
+ beta_end (`float`, defaults to 0.02):
406
+ The final `beta` value.
407
+ beta_schedule (`str`, defaults to `"linear"`):
408
+ The beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
409
+ `linear`, `scaled_linear`, or `squaredcos_cap_v2`.
410
+ trained_betas (`np.ndarray`, *optional*):
411
+ Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`.
412
+ clip_sample (`bool`, defaults to `True`):
413
+ Clip the predicted sample for numerical stability.
414
+ clip_sample_range (`float`, defaults to 1.0):
415
+ The maximum magnitude for sample clipping. Valid only when `clip_sample=True`.
416
+ set_alpha_to_one (`bool`, defaults to `True`):
417
+ Each diffusion step uses the alphas product value at that step and at the previous one. For the final step
418
+ there is no previous alpha. When this option is `True` the previous alpha product is fixed to `1`,
419
+ otherwise it uses the alpha value at step 0.
420
+ steps_offset (`int`, defaults to 0):
421
+ An offset added to the inference steps. You can use a combination of `offset=1` and
422
+ `set_alpha_to_one=False` to make the last step use step 0 for the previous alpha product like in Stable
423
+ Diffusion.
424
+ prediction_type (`str`, defaults to `epsilon`, *optional*):
425
+ Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
426
+ `sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen
427
+ Video](https://imagen.research.google/video/paper.pdf) paper).
428
+ thresholding (`bool`, defaults to `False`):
429
+ Whether to use the "dynamic thresholding" method. This is unsuitable for latent-space diffusion models such
430
+ as Stable Diffusion.
431
+ dynamic_thresholding_ratio (`float`, defaults to 0.995):
432
+ The ratio for the dynamic thresholding method. Valid only when `thresholding=True`.
433
+ sample_max_value (`float`, defaults to 1.0):
434
+ The threshold value for dynamic thresholding. Valid only when `thresholding=True`.
435
+ timestep_spacing (`str`, defaults to `"leading"`):
436
+ The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
437
+ Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
438
+ rescale_betas_zero_snr (`bool`, defaults to `False`):
439
+ Whether to rescale the betas to have zero terminal SNR. This enables the model to generate very bright and
440
+ dark samples instead of limiting it to samples with medium brightness. Loosely related to
441
+ [`--offset_noise`](https://github.com/huggingface/diffusers/blob/74fd735eb073eb1d774b1ab4154a0876eb82f055/examples/dreambooth/train_dreambooth.py#L506).
442
+ """
443
+
444
+ # _compatibles = [e.name for e in KarrasDiffusionSchedulers]
445
+ order = 1
446
+
447
+ @register_to_config
448
+ def __init__(
449
+ self,
450
+ num_train_timesteps: int = 1000,
451
+ beta_start: float = 0.0001,
452
+ beta_end: float = 0.02,
453
+ beta_schedule: str = "linear",
454
+ trained_betas: Optional[Union[np.ndarray, List[float]]] = None,
455
+ clip_sample: bool = True,
456
+ set_alpha_to_one: bool = True,
457
+ steps_offset: int = 0,
458
+ prediction_type: str = "epsilon",
459
+ thresholding: bool = False,
460
+ dynamic_thresholding_ratio: float = 0.995,
461
+ clip_sample_range: float = 1.0,
462
+ sample_max_value: float = 1.0,
463
+ timestep_spacing: str = "leading",
464
+ rescale_betas_zero_snr: bool = False,
465
+ ):
466
+ if trained_betas is not None:
467
+ self.betas = torch.tensor(trained_betas, dtype=torch.float32)
468
+ elif beta_schedule == "linear":
469
+ self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32)
470
+ elif beta_schedule == "scaled_linear":
471
+ # this schedule is very specific to the latent diffusion model.
472
+ self.betas = (
473
+ torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2
474
+ )
475
+ elif beta_schedule == "squaredcos_cap_v2":
476
+ # Glide cosine schedule
477
+ self.betas = betas_for_alpha_bar(num_train_timesteps)
478
+ else:
479
+ raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}")
480
+
481
+ # Rescale for zero SNR
482
+ if rescale_betas_zero_snr:
483
+ self.betas = rescale_zero_terminal_snr(self.betas)
484
+
485
+ self.alphas = 1.0 - self.betas
486
+ self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
487
+
488
+ # At every step in ddim, we are looking into the previous alphas_cumprod
489
+ # For the final step, there is no previous alphas_cumprod because we are already at 0
490
+ # `set_alpha_to_one` decides whether we set this parameter simply to one or
491
+ # whether we use the final alpha of the "non-previous" one.
492
+ self.final_alpha_cumprod = torch.tensor(1.0) if set_alpha_to_one else self.alphas_cumprod[0]
493
+
494
+ # standard deviation of the initial noise distribution
495
+ self.init_noise_sigma = 1.0
496
+
497
+ # setable values
498
+ self.num_inference_steps = None
499
+ self.timesteps = torch.from_numpy(np.arange(0, num_train_timesteps)[::-1].copy().astype(np.int64))
500
+
501
+ def scale_model_input(self, sample: torch.FloatTensor, timestep: Optional[int] = None) -> torch.FloatTensor:
502
+ """
503
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
504
+ current timestep.
505
+ Args:
506
+ sample (`torch.FloatTensor`):
507
+ The input sample.
508
+ timestep (`int`, *optional*):
509
+ The current timestep in the diffusion chain.
510
+ Returns:
511
+ `torch.FloatTensor`:
512
+ A scaled input sample.
513
+ """
514
+ return sample
515
+
516
+ def _get_variance(self, timestep, prev_timestep):
517
+ alpha_prod_t = self.alphas_cumprod[timestep]
518
+ alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
519
+ beta_prod_t = 1 - alpha_prod_t
520
+ beta_prod_t_prev = 1 - alpha_prod_t_prev
521
+
522
+ variance = (beta_prod_t_prev / beta_prod_t) * (1 - alpha_prod_t / alpha_prod_t_prev)
523
+
524
+ return variance
525
+
526
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample
527
+ def _threshold_sample(self, sample: torch.FloatTensor) -> torch.FloatTensor:
528
+ """
529
+ "Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
530
+ prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
531
+ s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
532
+ pixels from saturation at each step. We find that dynamic thresholding results in significantly better
533
+ photorealism as well as better image-text alignment, especially when using very large guidance weights."
534
+ https://arxiv.org/abs/2205.11487
535
+ """
536
+ dtype = sample.dtype
537
+ batch_size, channels, height, width = sample.shape
538
+
539
+ if dtype not in (torch.float32, torch.float64):
540
+ sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half
541
+
542
+ # Flatten sample for doing quantile calculation along each image
543
+ sample = sample.reshape(batch_size, channels * height * width)
544
+
545
+ abs_sample = sample.abs() # "a certain percentile absolute pixel value"
546
+
547
+ s = torch.quantile(abs_sample, self.config.dynamic_thresholding_ratio, dim=1)
548
+ s = torch.clamp(
549
+ s, min=1, max=self.config.sample_max_value
550
+ ) # When clamped to min=1, equivalent to standard clipping to [-1, 1]
551
+
552
+ s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0
553
+ sample = torch.clamp(sample, -s, s) / s # "we threshold xt0 to the range [-s, s] and then divide by s"
554
+
555
+ sample = sample.reshape(batch_size, channels, height, width)
556
+ sample = sample.to(dtype)
557
+
558
+ return sample
559
+
560
+ def set_timesteps(self, num_inference_steps: int, lcm_origin_steps: int, device: Union[str, torch.device] = None):
561
+ """
562
+ Sets the discrete timesteps used for the diffusion chain (to be run before inference).
563
+ Args:
564
+ num_inference_steps (`int`):
565
+ The number of diffusion steps used when generating samples with a pre-trained model.
566
+ """
567
+
568
+ if num_inference_steps > self.config.num_train_timesteps:
569
+ raise ValueError(
570
+ f"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:"
571
+ f" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle"
572
+ f" maximal {self.config.num_train_timesteps} timesteps."
573
+ )
574
+
575
+ self.num_inference_steps = num_inference_steps
576
+
577
+ # LCM Timesteps Setting: # Linear Spacing
578
+ c = self.config.num_train_timesteps // lcm_origin_steps
579
+ lcm_origin_timesteps = np.asarray(list(range(1, lcm_origin_steps + 1))) * c - 1 # LCM Training Steps Schedule
580
+ skipping_step = len(lcm_origin_timesteps) // num_inference_steps
581
+ timesteps = lcm_origin_timesteps[::-skipping_step][:num_inference_steps] # LCM Inference Steps Schedule
582
+
583
+ self.timesteps = torch.from_numpy(timesteps.copy()).to(device)
584
+
585
+ def get_scalings_for_boundary_condition_discrete(self, t):
586
+ self.sigma_data = 0.5 # Default: 0.5
587
+
588
+ # By dividing 0.1: This is almost a delta function at t=0.
589
+ c_skip = self.sigma_data**2 / ((t / 0.1) ** 2 + self.sigma_data**2)
590
+ c_out = (t / 0.1) / ((t / 0.1) ** 2 + self.sigma_data**2) ** 0.5
591
+ return c_skip, c_out
592
+
593
+ def step(
594
+ self,
595
+ model_output: torch.FloatTensor,
596
+ timeindex: int,
597
+ timestep: int,
598
+ sample: torch.FloatTensor,
599
+ eta: float = 0.0,
600
+ use_clipped_model_output: bool = False,
601
+ generator=None,
602
+ variance_noise: Optional[torch.FloatTensor] = None,
603
+ return_dict: bool = True,
604
+ ) -> Union[LCMSchedulerOutput, Tuple]:
605
+ """
606
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
607
+ process from the learned model outputs (most often the predicted noise).
608
+ Args:
609
+ model_output (`torch.FloatTensor`):
610
+ The direct output from learned diffusion model.
611
+ timestep (`float`):
612
+ The current discrete timestep in the diffusion chain.
613
+ sample (`torch.FloatTensor`):
614
+ A current instance of a sample created by the diffusion process.
615
+ eta (`float`):
616
+ The weight of noise for added noise in diffusion step.
617
+ use_clipped_model_output (`bool`, defaults to `False`):
618
+ If `True`, computes "corrected" `model_output` from the clipped predicted original sample. Necessary
619
+ because predicted original sample is clipped to [-1, 1] when `self.config.clip_sample` is `True`. If no
620
+ clipping has happened, "corrected" `model_output` would coincide with the one provided as input and
621
+ `use_clipped_model_output` has no effect.
622
+ generator (`torch.Generator`, *optional*):
623
+ A random number generator.
624
+ variance_noise (`torch.FloatTensor`):
625
+ Alternative to generating noise with `generator` by directly providing the noise for the variance
626
+ itself. Useful for methods such as [`CycleDiffusion`].
627
+ return_dict (`bool`, *optional*, defaults to `True`):
628
+ Whether or not to return a [`~schedulers.scheduling_lcm.LCMSchedulerOutput`] or `tuple`.
629
+ Returns:
630
+ [`~schedulers.scheduling_utils.LCMSchedulerOutput`] or `tuple`:
631
+ If return_dict is `True`, [`~schedulers.scheduling_lcm.LCMSchedulerOutput`] is returned, otherwise a
632
+ tuple is returned where the first element is the sample tensor.
633
+ """
634
+ if self.num_inference_steps is None:
635
+ raise ValueError(
636
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
637
+ )
638
+
639
+ # 1. get previous step value
640
+ prev_timeindex = timeindex + 1
641
+ if prev_timeindex < len(self.timesteps):
642
+ prev_timestep = self.timesteps[prev_timeindex]
643
+ else:
644
+ prev_timestep = timestep
645
+
646
+ # 2. compute alphas, betas
647
+ alpha_prod_t = self.alphas_cumprod[timestep]
648
+ alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
649
+
650
+ beta_prod_t = 1 - alpha_prod_t
651
+ beta_prod_t_prev = 1 - alpha_prod_t_prev
652
+
653
+ # 3. Get scalings for boundary conditions
654
+ c_skip, c_out = self.get_scalings_for_boundary_condition_discrete(timestep)
655
+
656
+ # 4. Different Parameterization:
657
+ parameterization = self.config.prediction_type
658
+
659
+ if parameterization == "epsilon": # noise-prediction
660
+ pred_x0 = (sample - beta_prod_t.sqrt() * model_output) / alpha_prod_t.sqrt()
661
+
662
+ elif parameterization == "sample": # x-prediction
663
+ pred_x0 = model_output
664
+
665
+ elif parameterization == "v_prediction": # v-prediction
666
+ pred_x0 = alpha_prod_t.sqrt() * sample - beta_prod_t.sqrt() * model_output
667
+
668
+ # 4. Denoise model output using boundary conditions
669
+ denoised = c_out * pred_x0 + c_skip * sample
670
+
671
+ # 5. Sample z ~ N(0, I), For MultiStep Inference
672
+ # Noise is not used for one-step sampling.
673
+ if len(self.timesteps) > 1:
674
+ noise = torch.randn(model_output.shape).to(model_output.device)
675
+ prev_sample = alpha_prod_t_prev.sqrt() * denoised + beta_prod_t_prev.sqrt() * noise
676
+ else:
677
+ prev_sample = denoised
678
+
679
+ if not return_dict:
680
+ return (prev_sample, denoised)
681
+
682
+ return LCMSchedulerOutput(prev_sample=prev_sample, denoised=denoised)
683
+
684
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.add_noise
685
+ def add_noise(
686
+ self,
687
+ original_samples: torch.FloatTensor,
688
+ noise: torch.FloatTensor,
689
+ timesteps: torch.IntTensor,
690
+ ) -> torch.FloatTensor:
691
+ # Make sure alphas_cumprod and timestep have same device and dtype as original_samples
692
+ alphas_cumprod = self.alphas_cumprod.to(device=original_samples.device, dtype=original_samples.dtype)
693
+ timesteps = timesteps.to(original_samples.device)
694
+
695
+ sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
696
+ sqrt_alpha_prod = sqrt_alpha_prod.flatten()
697
+ while len(sqrt_alpha_prod.shape) < len(original_samples.shape):
698
+ sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
699
+
700
+ sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
701
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
702
+ while len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape):
703
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
704
+
705
+ noisy_samples = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise
706
+ return noisy_samples
707
+
708
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.get_velocity
709
+ def get_velocity(
710
+ self, sample: torch.FloatTensor, noise: torch.FloatTensor, timesteps: torch.IntTensor
711
+ ) -> torch.FloatTensor:
712
+ # Make sure alphas_cumprod and timestep have same device and dtype as sample
713
+ alphas_cumprod = self.alphas_cumprod.to(device=sample.device, dtype=sample.dtype)
714
+ timesteps = timesteps.to(sample.device)
715
+
716
+ sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
717
+ sqrt_alpha_prod = sqrt_alpha_prod.flatten()
718
+ while len(sqrt_alpha_prod.shape) < len(sample.shape):
719
+ sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
720
+
721
+ sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
722
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
723
+ while len(sqrt_one_minus_alpha_prod.shape) < len(sample.shape):
724
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
725
+
726
+ velocity = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample
727
+ return velocity
728
+
729
+ def __len__(self):
730
+ return self.config.num_train_timesteps
v0.22.0/lpw_stable_diffusion.py ADDED
@@ -0,0 +1,1471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import re
3
+ from typing import Any, Callable, Dict, List, Optional, Union
4
+
5
+ import numpy as np
6
+ import PIL.Image
7
+ import torch
8
+ from packaging import version
9
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
10
+
11
+ from diffusers import DiffusionPipeline
12
+ from diffusers.configuration_utils import FrozenDict
13
+ from diffusers.image_processor import VaeImageProcessor
14
+ from diffusers.loaders import FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin
15
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
16
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput, StableDiffusionSafetyChecker
17
+ from diffusers.schedulers import KarrasDiffusionSchedulers
18
+ from diffusers.utils import (
19
+ PIL_INTERPOLATION,
20
+ deprecate,
21
+ is_accelerate_available,
22
+ is_accelerate_version,
23
+ logging,
24
+ )
25
+ from diffusers.utils.torch_utils import randn_tensor
26
+
27
+
28
+ # ------------------------------------------------------------------------------
29
+
30
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
31
+
32
+ re_attention = re.compile(
33
+ r"""
34
+ \\\(|
35
+ \\\)|
36
+ \\\[|
37
+ \\]|
38
+ \\\\|
39
+ \\|
40
+ \(|
41
+ \[|
42
+ :([+-]?[.\d]+)\)|
43
+ \)|
44
+ ]|
45
+ [^\\()\[\]:]+|
46
+ :
47
+ """,
48
+ re.X,
49
+ )
50
+
51
+
52
+ def parse_prompt_attention(text):
53
+ """
54
+ Parses a string with attention tokens and returns a list of pairs: text and its associated weight.
55
+ Accepted tokens are:
56
+ (abc) - increases attention to abc by a multiplier of 1.1
57
+ (abc:3.12) - increases attention to abc by a multiplier of 3.12
58
+ [abc] - decreases attention to abc by a multiplier of 1.1
59
+ \( - literal character '('
60
+ \[ - literal character '['
61
+ \) - literal character ')'
62
+ \] - literal character ']'
63
+ \\ - literal character '\'
64
+ anything else - just text
65
+ >>> parse_prompt_attention('normal text')
66
+ [['normal text', 1.0]]
67
+ >>> parse_prompt_attention('an (important) word')
68
+ [['an ', 1.0], ['important', 1.1], [' word', 1.0]]
69
+ >>> parse_prompt_attention('(unbalanced')
70
+ [['unbalanced', 1.1]]
71
+ >>> parse_prompt_attention('\(literal\]')
72
+ [['(literal]', 1.0]]
73
+ >>> parse_prompt_attention('(unnecessary)(parens)')
74
+ [['unnecessaryparens', 1.1]]
75
+ >>> parse_prompt_attention('a (((house:1.3)) [on] a (hill:0.5), sun, (((sky))).')
76
+ [['a ', 1.0],
77
+ ['house', 1.5730000000000004],
78
+ [' ', 1.1],
79
+ ['on', 1.0],
80
+ [' a ', 1.1],
81
+ ['hill', 0.55],
82
+ [', sun, ', 1.1],
83
+ ['sky', 1.4641000000000006],
84
+ ['.', 1.1]]
85
+ """
86
+
87
+ res = []
88
+ round_brackets = []
89
+ square_brackets = []
90
+
91
+ round_bracket_multiplier = 1.1
92
+ square_bracket_multiplier = 1 / 1.1
93
+
94
+ def multiply_range(start_position, multiplier):
95
+ for p in range(start_position, len(res)):
96
+ res[p][1] *= multiplier
97
+
98
+ for m in re_attention.finditer(text):
99
+ text = m.group(0)
100
+ weight = m.group(1)
101
+
102
+ if text.startswith("\\"):
103
+ res.append([text[1:], 1.0])
104
+ elif text == "(":
105
+ round_brackets.append(len(res))
106
+ elif text == "[":
107
+ square_brackets.append(len(res))
108
+ elif weight is not None and len(round_brackets) > 0:
109
+ multiply_range(round_brackets.pop(), float(weight))
110
+ elif text == ")" and len(round_brackets) > 0:
111
+ multiply_range(round_brackets.pop(), round_bracket_multiplier)
112
+ elif text == "]" and len(square_brackets) > 0:
113
+ multiply_range(square_brackets.pop(), square_bracket_multiplier)
114
+ else:
115
+ res.append([text, 1.0])
116
+
117
+ for pos in round_brackets:
118
+ multiply_range(pos, round_bracket_multiplier)
119
+
120
+ for pos in square_brackets:
121
+ multiply_range(pos, square_bracket_multiplier)
122
+
123
+ if len(res) == 0:
124
+ res = [["", 1.0]]
125
+
126
+ # merge runs of identical weights
127
+ i = 0
128
+ while i + 1 < len(res):
129
+ if res[i][1] == res[i + 1][1]:
130
+ res[i][0] += res[i + 1][0]
131
+ res.pop(i + 1)
132
+ else:
133
+ i += 1
134
+
135
+ return res
136
+
137
+
138
+ def get_prompts_with_weights(pipe: DiffusionPipeline, prompt: List[str], max_length: int):
139
+ r"""
140
+ Tokenize a list of prompts and return its tokens with weights of each token.
141
+
142
+ No padding, starting or ending token is included.
143
+ """
144
+ tokens = []
145
+ weights = []
146
+ truncated = False
147
+ for text in prompt:
148
+ texts_and_weights = parse_prompt_attention(text)
149
+ text_token = []
150
+ text_weight = []
151
+ for word, weight in texts_and_weights:
152
+ # tokenize and discard the starting and the ending token
153
+ token = pipe.tokenizer(word).input_ids[1:-1]
154
+ text_token += token
155
+ # copy the weight by length of token
156
+ text_weight += [weight] * len(token)
157
+ # stop if the text is too long (longer than truncation limit)
158
+ if len(text_token) > max_length:
159
+ truncated = True
160
+ break
161
+ # truncate
162
+ if len(text_token) > max_length:
163
+ truncated = True
164
+ text_token = text_token[:max_length]
165
+ text_weight = text_weight[:max_length]
166
+ tokens.append(text_token)
167
+ weights.append(text_weight)
168
+ if truncated:
169
+ logger.warning("Prompt was truncated. Try to shorten the prompt or increase max_embeddings_multiples")
170
+ return tokens, weights
171
+
172
+
173
+ def pad_tokens_and_weights(tokens, weights, max_length, bos, eos, pad, no_boseos_middle=True, chunk_length=77):
174
+ r"""
175
+ Pad the tokens (with starting and ending tokens) and weights (with 1.0) to max_length.
176
+ """
177
+ max_embeddings_multiples = (max_length - 2) // (chunk_length - 2)
178
+ weights_length = max_length if no_boseos_middle else max_embeddings_multiples * chunk_length
179
+ for i in range(len(tokens)):
180
+ tokens[i] = [bos] + tokens[i] + [pad] * (max_length - 1 - len(tokens[i]) - 1) + [eos]
181
+ if no_boseos_middle:
182
+ weights[i] = [1.0] + weights[i] + [1.0] * (max_length - 1 - len(weights[i]))
183
+ else:
184
+ w = []
185
+ if len(weights[i]) == 0:
186
+ w = [1.0] * weights_length
187
+ else:
188
+ for j in range(max_embeddings_multiples):
189
+ w.append(1.0) # weight for starting token in this chunk
190
+ w += weights[i][j * (chunk_length - 2) : min(len(weights[i]), (j + 1) * (chunk_length - 2))]
191
+ w.append(1.0) # weight for ending token in this chunk
192
+ w += [1.0] * (weights_length - len(w))
193
+ weights[i] = w[:]
194
+
195
+ return tokens, weights
196
+
197
+
198
+ def get_unweighted_text_embeddings(
199
+ pipe: DiffusionPipeline,
200
+ text_input: torch.Tensor,
201
+ chunk_length: int,
202
+ no_boseos_middle: Optional[bool] = True,
203
+ ):
204
+ """
205
+ When the length of tokens is a multiple of the capacity of the text encoder,
206
+ it should be split into chunks and sent to the text encoder individually.
207
+ """
208
+ max_embeddings_multiples = (text_input.shape[1] - 2) // (chunk_length - 2)
209
+ if max_embeddings_multiples > 1:
210
+ text_embeddings = []
211
+ for i in range(max_embeddings_multiples):
212
+ # extract the i-th chunk
213
+ text_input_chunk = text_input[:, i * (chunk_length - 2) : (i + 1) * (chunk_length - 2) + 2].clone()
214
+
215
+ # cover the head and the tail by the starting and the ending tokens
216
+ text_input_chunk[:, 0] = text_input[0, 0]
217
+ text_input_chunk[:, -1] = text_input[0, -1]
218
+ text_embedding = pipe.text_encoder(text_input_chunk)[0]
219
+
220
+ if no_boseos_middle:
221
+ if i == 0:
222
+ # discard the ending token
223
+ text_embedding = text_embedding[:, :-1]
224
+ elif i == max_embeddings_multiples - 1:
225
+ # discard the starting token
226
+ text_embedding = text_embedding[:, 1:]
227
+ else:
228
+ # discard both starting and ending tokens
229
+ text_embedding = text_embedding[:, 1:-1]
230
+
231
+ text_embeddings.append(text_embedding)
232
+ text_embeddings = torch.concat(text_embeddings, axis=1)
233
+ else:
234
+ text_embeddings = pipe.text_encoder(text_input)[0]
235
+ return text_embeddings
236
+
237
+
238
+ def get_weighted_text_embeddings(
239
+ pipe: DiffusionPipeline,
240
+ prompt: Union[str, List[str]],
241
+ uncond_prompt: Optional[Union[str, List[str]]] = None,
242
+ max_embeddings_multiples: Optional[int] = 3,
243
+ no_boseos_middle: Optional[bool] = False,
244
+ skip_parsing: Optional[bool] = False,
245
+ skip_weighting: Optional[bool] = False,
246
+ ):
247
+ r"""
248
+ Prompts can be assigned with local weights using brackets. For example,
249
+ prompt 'A (very beautiful) masterpiece' highlights the words 'very beautiful',
250
+ and the embedding tokens corresponding to the words get multiplied by a constant, 1.1.
251
+
252
+ Also, to regularize of the embedding, the weighted embedding would be scaled to preserve the original mean.
253
+
254
+ Args:
255
+ pipe (`DiffusionPipeline`):
256
+ Pipe to provide access to the tokenizer and the text encoder.
257
+ prompt (`str` or `List[str]`):
258
+ The prompt or prompts to guide the image generation.
259
+ uncond_prompt (`str` or `List[str]`):
260
+ The unconditional prompt or prompts for guide the image generation. If unconditional prompt
261
+ is provided, the embeddings of prompt and uncond_prompt are concatenated.
262
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
263
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
264
+ no_boseos_middle (`bool`, *optional*, defaults to `False`):
265
+ If the length of text token is multiples of the capacity of text encoder, whether reserve the starting and
266
+ ending token in each of the chunk in the middle.
267
+ skip_parsing (`bool`, *optional*, defaults to `False`):
268
+ Skip the parsing of brackets.
269
+ skip_weighting (`bool`, *optional*, defaults to `False`):
270
+ Skip the weighting. When the parsing is skipped, it is forced True.
271
+ """
272
+ max_length = (pipe.tokenizer.model_max_length - 2) * max_embeddings_multiples + 2
273
+ if isinstance(prompt, str):
274
+ prompt = [prompt]
275
+
276
+ if not skip_parsing:
277
+ prompt_tokens, prompt_weights = get_prompts_with_weights(pipe, prompt, max_length - 2)
278
+ if uncond_prompt is not None:
279
+ if isinstance(uncond_prompt, str):
280
+ uncond_prompt = [uncond_prompt]
281
+ uncond_tokens, uncond_weights = get_prompts_with_weights(pipe, uncond_prompt, max_length - 2)
282
+ else:
283
+ prompt_tokens = [
284
+ token[1:-1] for token in pipe.tokenizer(prompt, max_length=max_length, truncation=True).input_ids
285
+ ]
286
+ prompt_weights = [[1.0] * len(token) for token in prompt_tokens]
287
+ if uncond_prompt is not None:
288
+ if isinstance(uncond_prompt, str):
289
+ uncond_prompt = [uncond_prompt]
290
+ uncond_tokens = [
291
+ token[1:-1]
292
+ for token in pipe.tokenizer(uncond_prompt, max_length=max_length, truncation=True).input_ids
293
+ ]
294
+ uncond_weights = [[1.0] * len(token) for token in uncond_tokens]
295
+
296
+ # round up the longest length of tokens to a multiple of (model_max_length - 2)
297
+ max_length = max([len(token) for token in prompt_tokens])
298
+ if uncond_prompt is not None:
299
+ max_length = max(max_length, max([len(token) for token in uncond_tokens]))
300
+
301
+ max_embeddings_multiples = min(
302
+ max_embeddings_multiples,
303
+ (max_length - 1) // (pipe.tokenizer.model_max_length - 2) + 1,
304
+ )
305
+ max_embeddings_multiples = max(1, max_embeddings_multiples)
306
+ max_length = (pipe.tokenizer.model_max_length - 2) * max_embeddings_multiples + 2
307
+
308
+ # pad the length of tokens and weights
309
+ bos = pipe.tokenizer.bos_token_id
310
+ eos = pipe.tokenizer.eos_token_id
311
+ pad = getattr(pipe.tokenizer, "pad_token_id", eos)
312
+ prompt_tokens, prompt_weights = pad_tokens_and_weights(
313
+ prompt_tokens,
314
+ prompt_weights,
315
+ max_length,
316
+ bos,
317
+ eos,
318
+ pad,
319
+ no_boseos_middle=no_boseos_middle,
320
+ chunk_length=pipe.tokenizer.model_max_length,
321
+ )
322
+ prompt_tokens = torch.tensor(prompt_tokens, dtype=torch.long, device=pipe.device)
323
+ if uncond_prompt is not None:
324
+ uncond_tokens, uncond_weights = pad_tokens_and_weights(
325
+ uncond_tokens,
326
+ uncond_weights,
327
+ max_length,
328
+ bos,
329
+ eos,
330
+ pad,
331
+ no_boseos_middle=no_boseos_middle,
332
+ chunk_length=pipe.tokenizer.model_max_length,
333
+ )
334
+ uncond_tokens = torch.tensor(uncond_tokens, dtype=torch.long, device=pipe.device)
335
+
336
+ # get the embeddings
337
+ text_embeddings = get_unweighted_text_embeddings(
338
+ pipe,
339
+ prompt_tokens,
340
+ pipe.tokenizer.model_max_length,
341
+ no_boseos_middle=no_boseos_middle,
342
+ )
343
+ prompt_weights = torch.tensor(prompt_weights, dtype=text_embeddings.dtype, device=text_embeddings.device)
344
+ if uncond_prompt is not None:
345
+ uncond_embeddings = get_unweighted_text_embeddings(
346
+ pipe,
347
+ uncond_tokens,
348
+ pipe.tokenizer.model_max_length,
349
+ no_boseos_middle=no_boseos_middle,
350
+ )
351
+ uncond_weights = torch.tensor(uncond_weights, dtype=uncond_embeddings.dtype, device=uncond_embeddings.device)
352
+
353
+ # assign weights to the prompts and normalize in the sense of mean
354
+ # TODO: should we normalize by chunk or in a whole (current implementation)?
355
+ if (not skip_parsing) and (not skip_weighting):
356
+ previous_mean = text_embeddings.float().mean(axis=[-2, -1]).to(text_embeddings.dtype)
357
+ text_embeddings *= prompt_weights.unsqueeze(-1)
358
+ current_mean = text_embeddings.float().mean(axis=[-2, -1]).to(text_embeddings.dtype)
359
+ text_embeddings *= (previous_mean / current_mean).unsqueeze(-1).unsqueeze(-1)
360
+ if uncond_prompt is not None:
361
+ previous_mean = uncond_embeddings.float().mean(axis=[-2, -1]).to(uncond_embeddings.dtype)
362
+ uncond_embeddings *= uncond_weights.unsqueeze(-1)
363
+ current_mean = uncond_embeddings.float().mean(axis=[-2, -1]).to(uncond_embeddings.dtype)
364
+ uncond_embeddings *= (previous_mean / current_mean).unsqueeze(-1).unsqueeze(-1)
365
+
366
+ if uncond_prompt is not None:
367
+ return text_embeddings, uncond_embeddings
368
+ return text_embeddings, None
369
+
370
+
371
+ def preprocess_image(image, batch_size):
372
+ w, h = image.size
373
+ w, h = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8
374
+ image = image.resize((w, h), resample=PIL_INTERPOLATION["lanczos"])
375
+ image = np.array(image).astype(np.float32) / 255.0
376
+ image = np.vstack([image[None].transpose(0, 3, 1, 2)] * batch_size)
377
+ image = torch.from_numpy(image)
378
+ return 2.0 * image - 1.0
379
+
380
+
381
+ def preprocess_mask(mask, batch_size, scale_factor=8):
382
+ if not isinstance(mask, torch.FloatTensor):
383
+ mask = mask.convert("L")
384
+ w, h = mask.size
385
+ w, h = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8
386
+ mask = mask.resize((w // scale_factor, h // scale_factor), resample=PIL_INTERPOLATION["nearest"])
387
+ mask = np.array(mask).astype(np.float32) / 255.0
388
+ mask = np.tile(mask, (4, 1, 1))
389
+ mask = np.vstack([mask[None]] * batch_size)
390
+ mask = 1 - mask # repaint white, keep black
391
+ mask = torch.from_numpy(mask)
392
+ return mask
393
+
394
+ else:
395
+ valid_mask_channel_sizes = [1, 3]
396
+ # if mask channel is fourth tensor dimension, permute dimensions to pytorch standard (B, C, H, W)
397
+ if mask.shape[3] in valid_mask_channel_sizes:
398
+ mask = mask.permute(0, 3, 1, 2)
399
+ elif mask.shape[1] not in valid_mask_channel_sizes:
400
+ raise ValueError(
401
+ f"Mask channel dimension of size in {valid_mask_channel_sizes} should be second or fourth dimension,"
402
+ f" but received mask of shape {tuple(mask.shape)}"
403
+ )
404
+ # (potentially) reduce mask channel dimension from 3 to 1 for broadcasting to latent shape
405
+ mask = mask.mean(dim=1, keepdim=True)
406
+ h, w = mask.shape[-2:]
407
+ h, w = (x - x % 8 for x in (h, w)) # resize to integer multiple of 8
408
+ mask = torch.nn.functional.interpolate(mask, (h // scale_factor, w // scale_factor))
409
+ return mask
410
+
411
+
412
+ class StableDiffusionLongPromptWeightingPipeline(
413
+ DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, FromSingleFileMixin
414
+ ):
415
+ r"""
416
+ Pipeline for text-to-image generation using Stable Diffusion without tokens length limit, and support parsing
417
+ weighting in prompt.
418
+
419
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
420
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
421
+
422
+ Args:
423
+ vae ([`AutoencoderKL`]):
424
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
425
+ text_encoder ([`CLIPTextModel`]):
426
+ Frozen text-encoder. Stable Diffusion uses the text portion of
427
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
428
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
429
+ tokenizer (`CLIPTokenizer`):
430
+ Tokenizer of class
431
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
432
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
433
+ scheduler ([`SchedulerMixin`]):
434
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
435
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
436
+ safety_checker ([`StableDiffusionSafetyChecker`]):
437
+ Classification module that estimates whether generated images could be considered offensive or harmful.
438
+ Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.
439
+ feature_extractor ([`CLIPImageProcessor`]):
440
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
441
+ """
442
+
443
+ _optional_components = ["safety_checker", "feature_extractor"]
444
+
445
+ def __init__(
446
+ self,
447
+ vae: AutoencoderKL,
448
+ text_encoder: CLIPTextModel,
449
+ tokenizer: CLIPTokenizer,
450
+ unet: UNet2DConditionModel,
451
+ scheduler: KarrasDiffusionSchedulers,
452
+ safety_checker: StableDiffusionSafetyChecker,
453
+ feature_extractor: CLIPImageProcessor,
454
+ requires_safety_checker: bool = True,
455
+ ):
456
+ super().__init__()
457
+
458
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
459
+ deprecation_message = (
460
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
461
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
462
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
463
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
464
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
465
+ " file"
466
+ )
467
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
468
+ new_config = dict(scheduler.config)
469
+ new_config["steps_offset"] = 1
470
+ scheduler._internal_dict = FrozenDict(new_config)
471
+
472
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
473
+ deprecation_message = (
474
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
475
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
476
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
477
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
478
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
479
+ )
480
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
481
+ new_config = dict(scheduler.config)
482
+ new_config["clip_sample"] = False
483
+ scheduler._internal_dict = FrozenDict(new_config)
484
+
485
+ if safety_checker is None and requires_safety_checker:
486
+ logger.warning(
487
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
488
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
489
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
490
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
491
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
492
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
493
+ )
494
+
495
+ if safety_checker is not None and feature_extractor is None:
496
+ raise ValueError(
497
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
498
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
499
+ )
500
+
501
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
502
+ version.parse(unet.config._diffusers_version).base_version
503
+ ) < version.parse("0.9.0.dev0")
504
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
505
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
506
+ deprecation_message = (
507
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
508
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
509
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
510
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
511
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
512
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
513
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
514
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
515
+ " the `unet/config.json` file"
516
+ )
517
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
518
+ new_config = dict(unet.config)
519
+ new_config["sample_size"] = 64
520
+ unet._internal_dict = FrozenDict(new_config)
521
+ self.register_modules(
522
+ vae=vae,
523
+ text_encoder=text_encoder,
524
+ tokenizer=tokenizer,
525
+ unet=unet,
526
+ scheduler=scheduler,
527
+ safety_checker=safety_checker,
528
+ feature_extractor=feature_extractor,
529
+ )
530
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
531
+
532
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
533
+ self.register_to_config(
534
+ requires_safety_checker=requires_safety_checker,
535
+ )
536
+
537
+ def enable_vae_slicing(self):
538
+ r"""
539
+ Enable sliced VAE decoding.
540
+
541
+ When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
542
+ steps. This is useful to save some memory and allow larger batch sizes.
543
+ """
544
+ self.vae.enable_slicing()
545
+
546
+ def disable_vae_slicing(self):
547
+ r"""
548
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to
549
+ computing decoding in one step.
550
+ """
551
+ self.vae.disable_slicing()
552
+
553
+ def enable_vae_tiling(self):
554
+ r"""
555
+ Enable tiled VAE decoding.
556
+
557
+ When this option is enabled, the VAE will split the input tensor into tiles to compute decoding and encoding in
558
+ several steps. This is useful to save a large amount of memory and to allow the processing of larger images.
559
+ """
560
+ self.vae.enable_tiling()
561
+
562
+ def disable_vae_tiling(self):
563
+ r"""
564
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously invoked, this method will go back to
565
+ computing decoding in one step.
566
+ """
567
+ self.vae.disable_tiling()
568
+
569
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_sequential_cpu_offload
570
+ def enable_sequential_cpu_offload(self, gpu_id=0):
571
+ r"""
572
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
573
+ text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
574
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
575
+ Note that offloading happens on a submodule basis. Memory savings are higher than with
576
+ `enable_model_cpu_offload`, but performance is lower.
577
+ """
578
+ if is_accelerate_available() and is_accelerate_version(">=", "0.14.0"):
579
+ from accelerate import cpu_offload
580
+ else:
581
+ raise ImportError("`enable_sequential_cpu_offload` requires `accelerate v0.14.0` or higher")
582
+
583
+ device = torch.device(f"cuda:{gpu_id}")
584
+
585
+ if self.device.type != "cpu":
586
+ self.to("cpu", silence_dtype_warnings=True)
587
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
588
+
589
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]:
590
+ cpu_offload(cpu_offloaded_model, device)
591
+
592
+ if self.safety_checker is not None:
593
+ cpu_offload(self.safety_checker, execution_device=device, offload_buffers=True)
594
+
595
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_model_cpu_offload
596
+ def enable_model_cpu_offload(self, gpu_id=0):
597
+ r"""
598
+ Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
599
+ to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
600
+ method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
601
+ `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
602
+ """
603
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
604
+ from accelerate import cpu_offload_with_hook
605
+ else:
606
+ raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")
607
+
608
+ device = torch.device(f"cuda:{gpu_id}")
609
+
610
+ if self.device.type != "cpu":
611
+ self.to("cpu", silence_dtype_warnings=True)
612
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
613
+
614
+ hook = None
615
+ for cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]:
616
+ _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
617
+
618
+ if self.safety_checker is not None:
619
+ _, hook = cpu_offload_with_hook(self.safety_checker, device, prev_module_hook=hook)
620
+
621
+ # We'll offload the last model manually.
622
+ self.final_offload_hook = hook
623
+
624
+ @property
625
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
626
+ def _execution_device(self):
627
+ r"""
628
+ Returns the device on which the pipeline's models will be executed. After calling
629
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
630
+ hooks.
631
+ """
632
+ if not hasattr(self.unet, "_hf_hook"):
633
+ return self.device
634
+ for module in self.unet.modules():
635
+ if (
636
+ hasattr(module, "_hf_hook")
637
+ and hasattr(module._hf_hook, "execution_device")
638
+ and module._hf_hook.execution_device is not None
639
+ ):
640
+ return torch.device(module._hf_hook.execution_device)
641
+ return self.device
642
+
643
+ def _encode_prompt(
644
+ self,
645
+ prompt,
646
+ device,
647
+ num_images_per_prompt,
648
+ do_classifier_free_guidance,
649
+ negative_prompt=None,
650
+ max_embeddings_multiples=3,
651
+ prompt_embeds: Optional[torch.FloatTensor] = None,
652
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
653
+ ):
654
+ r"""
655
+ Encodes the prompt into text encoder hidden states.
656
+
657
+ Args:
658
+ prompt (`str` or `list(int)`):
659
+ prompt to be encoded
660
+ device: (`torch.device`):
661
+ torch device
662
+ num_images_per_prompt (`int`):
663
+ number of images that should be generated per prompt
664
+ do_classifier_free_guidance (`bool`):
665
+ whether to use classifier free guidance or not
666
+ negative_prompt (`str` or `List[str]`):
667
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
668
+ if `guidance_scale` is less than `1`).
669
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
670
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
671
+ """
672
+ if prompt is not None and isinstance(prompt, str):
673
+ batch_size = 1
674
+ elif prompt is not None and isinstance(prompt, list):
675
+ batch_size = len(prompt)
676
+ else:
677
+ batch_size = prompt_embeds.shape[0]
678
+
679
+ if negative_prompt_embeds is None:
680
+ if negative_prompt is None:
681
+ negative_prompt = [""] * batch_size
682
+ elif isinstance(negative_prompt, str):
683
+ negative_prompt = [negative_prompt] * batch_size
684
+ if batch_size != len(negative_prompt):
685
+ raise ValueError(
686
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
687
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
688
+ " the batch size of `prompt`."
689
+ )
690
+ if prompt_embeds is None or negative_prompt_embeds is None:
691
+ if isinstance(self, TextualInversionLoaderMixin):
692
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
693
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
694
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, self.tokenizer)
695
+
696
+ prompt_embeds1, negative_prompt_embeds1 = get_weighted_text_embeddings(
697
+ pipe=self,
698
+ prompt=prompt,
699
+ uncond_prompt=negative_prompt if do_classifier_free_guidance else None,
700
+ max_embeddings_multiples=max_embeddings_multiples,
701
+ )
702
+ if prompt_embeds is None:
703
+ prompt_embeds = prompt_embeds1
704
+ if negative_prompt_embeds is None:
705
+ negative_prompt_embeds = negative_prompt_embeds1
706
+
707
+ bs_embed, seq_len, _ = prompt_embeds.shape
708
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
709
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
710
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
711
+
712
+ if do_classifier_free_guidance:
713
+ bs_embed, seq_len, _ = negative_prompt_embeds.shape
714
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
715
+ negative_prompt_embeds = negative_prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
716
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
717
+
718
+ return prompt_embeds
719
+
720
+ def check_inputs(
721
+ self,
722
+ prompt,
723
+ height,
724
+ width,
725
+ strength,
726
+ callback_steps,
727
+ negative_prompt=None,
728
+ prompt_embeds=None,
729
+ negative_prompt_embeds=None,
730
+ ):
731
+ if height % 8 != 0 or width % 8 != 0:
732
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
733
+
734
+ if strength < 0 or strength > 1:
735
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
736
+
737
+ if (callback_steps is None) or (
738
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
739
+ ):
740
+ raise ValueError(
741
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
742
+ f" {type(callback_steps)}."
743
+ )
744
+
745
+ if prompt is not None and prompt_embeds is not None:
746
+ raise ValueError(
747
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
748
+ " only forward one of the two."
749
+ )
750
+ elif prompt is None and prompt_embeds is None:
751
+ raise ValueError(
752
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
753
+ )
754
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
755
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
756
+
757
+ if negative_prompt is not None and negative_prompt_embeds is not None:
758
+ raise ValueError(
759
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
760
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
761
+ )
762
+
763
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
764
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
765
+ raise ValueError(
766
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
767
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
768
+ f" {negative_prompt_embeds.shape}."
769
+ )
770
+
771
+ def get_timesteps(self, num_inference_steps, strength, device, is_text2img):
772
+ if is_text2img:
773
+ return self.scheduler.timesteps.to(device), num_inference_steps
774
+ else:
775
+ # get the original timestep using init_timestep
776
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
777
+
778
+ t_start = max(num_inference_steps - init_timestep, 0)
779
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
780
+
781
+ return timesteps, num_inference_steps - t_start
782
+
783
+ def run_safety_checker(self, image, device, dtype):
784
+ if self.safety_checker is not None:
785
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
786
+ image, has_nsfw_concept = self.safety_checker(
787
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
788
+ )
789
+ else:
790
+ has_nsfw_concept = None
791
+ return image, has_nsfw_concept
792
+
793
+ def decode_latents(self, latents):
794
+ latents = 1 / self.vae.config.scaling_factor * latents
795
+ image = self.vae.decode(latents).sample
796
+ image = (image / 2 + 0.5).clamp(0, 1)
797
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
798
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
799
+ return image
800
+
801
+ def prepare_extra_step_kwargs(self, generator, eta):
802
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
803
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
804
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
805
+ # and should be between [0, 1]
806
+
807
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
808
+ extra_step_kwargs = {}
809
+ if accepts_eta:
810
+ extra_step_kwargs["eta"] = eta
811
+
812
+ # check if the scheduler accepts generator
813
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
814
+ if accepts_generator:
815
+ extra_step_kwargs["generator"] = generator
816
+ return extra_step_kwargs
817
+
818
+ def prepare_latents(
819
+ self,
820
+ image,
821
+ timestep,
822
+ num_images_per_prompt,
823
+ batch_size,
824
+ num_channels_latents,
825
+ height,
826
+ width,
827
+ dtype,
828
+ device,
829
+ generator,
830
+ latents=None,
831
+ ):
832
+ if image is None:
833
+ batch_size = batch_size * num_images_per_prompt
834
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
835
+ if isinstance(generator, list) and len(generator) != batch_size:
836
+ raise ValueError(
837
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
838
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
839
+ )
840
+
841
+ if latents is None:
842
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
843
+ else:
844
+ latents = latents.to(device)
845
+
846
+ # scale the initial noise by the standard deviation required by the scheduler
847
+ latents = latents * self.scheduler.init_noise_sigma
848
+ return latents, None, None
849
+ else:
850
+ image = image.to(device=self.device, dtype=dtype)
851
+ init_latent_dist = self.vae.encode(image).latent_dist
852
+ init_latents = init_latent_dist.sample(generator=generator)
853
+ init_latents = self.vae.config.scaling_factor * init_latents
854
+
855
+ # Expand init_latents for batch_size and num_images_per_prompt
856
+ init_latents = torch.cat([init_latents] * num_images_per_prompt, dim=0)
857
+ init_latents_orig = init_latents
858
+
859
+ # add noise to latents using the timesteps
860
+ noise = randn_tensor(init_latents.shape, generator=generator, device=self.device, dtype=dtype)
861
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
862
+ latents = init_latents
863
+ return latents, init_latents_orig, noise
864
+
865
+ @torch.no_grad()
866
+ def __call__(
867
+ self,
868
+ prompt: Union[str, List[str]],
869
+ negative_prompt: Optional[Union[str, List[str]]] = None,
870
+ image: Union[torch.FloatTensor, PIL.Image.Image] = None,
871
+ mask_image: Union[torch.FloatTensor, PIL.Image.Image] = None,
872
+ height: int = 512,
873
+ width: int = 512,
874
+ num_inference_steps: int = 50,
875
+ guidance_scale: float = 7.5,
876
+ strength: float = 0.8,
877
+ num_images_per_prompt: Optional[int] = 1,
878
+ add_predicted_noise: Optional[bool] = False,
879
+ eta: float = 0.0,
880
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
881
+ latents: Optional[torch.FloatTensor] = None,
882
+ prompt_embeds: Optional[torch.FloatTensor] = None,
883
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
884
+ max_embeddings_multiples: Optional[int] = 3,
885
+ output_type: Optional[str] = "pil",
886
+ return_dict: bool = True,
887
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
888
+ is_cancelled_callback: Optional[Callable[[], bool]] = None,
889
+ callback_steps: int = 1,
890
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
891
+ ):
892
+ r"""
893
+ Function invoked when calling the pipeline for generation.
894
+
895
+ Args:
896
+ prompt (`str` or `List[str]`):
897
+ The prompt or prompts to guide the image generation.
898
+ negative_prompt (`str` or `List[str]`, *optional*):
899
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
900
+ if `guidance_scale` is less than `1`).
901
+ image (`torch.FloatTensor` or `PIL.Image.Image`):
902
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
903
+ process.
904
+ mask_image (`torch.FloatTensor` or `PIL.Image.Image`):
905
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
906
+ replaced by noise and therefore repainted, while black pixels will be preserved. If `mask_image` is a
907
+ PIL image, it will be converted to a single channel (luminance) before use. If it's a tensor, it should
908
+ contain one color channel (L) instead of 3, so the expected shape would be `(B, H, W, 1)`.
909
+ height (`int`, *optional*, defaults to 512):
910
+ The height in pixels of the generated image.
911
+ width (`int`, *optional*, defaults to 512):
912
+ The width in pixels of the generated image.
913
+ num_inference_steps (`int`, *optional*, defaults to 50):
914
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
915
+ expense of slower inference.
916
+ guidance_scale (`float`, *optional*, defaults to 7.5):
917
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
918
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
919
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
920
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
921
+ usually at the expense of lower image quality.
922
+ strength (`float`, *optional*, defaults to 0.8):
923
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1.
924
+ `image` will be used as a starting point, adding more noise to it the larger the `strength`. The
925
+ number of denoising steps depends on the amount of noise initially added. When `strength` is 1, added
926
+ noise will be maximum and the denoising process will run for the full number of iterations specified in
927
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
928
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
929
+ The number of images to generate per prompt.
930
+ add_predicted_noise (`bool`, *optional*, defaults to True):
931
+ Use predicted noise instead of random noise when constructing noisy versions of the original image in
932
+ the reverse diffusion process
933
+ eta (`float`, *optional*, defaults to 0.0):
934
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
935
+ [`schedulers.DDIMScheduler`], will be ignored for others.
936
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
937
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
938
+ to make generation deterministic.
939
+ latents (`torch.FloatTensor`, *optional*):
940
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
941
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
942
+ tensor will ge generated by sampling using the supplied random `generator`.
943
+ prompt_embeds (`torch.FloatTensor`, *optional*):
944
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
945
+ provided, text embeddings will be generated from `prompt` input argument.
946
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
947
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
948
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
949
+ argument.
950
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
951
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
952
+ output_type (`str`, *optional*, defaults to `"pil"`):
953
+ The output format of the generate image. Choose between
954
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
955
+ return_dict (`bool`, *optional*, defaults to `True`):
956
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
957
+ plain tuple.
958
+ callback (`Callable`, *optional*):
959
+ A function that will be called every `callback_steps` steps during inference. The function will be
960
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
961
+ is_cancelled_callback (`Callable`, *optional*):
962
+ A function that will be called every `callback_steps` steps during inference. If the function returns
963
+ `True`, the inference will be cancelled.
964
+ callback_steps (`int`, *optional*, defaults to 1):
965
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
966
+ called at every step.
967
+ cross_attention_kwargs (`dict`, *optional*):
968
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
969
+ `self.processor` in
970
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
971
+
972
+ Returns:
973
+ `None` if cancelled by `is_cancelled_callback`,
974
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
975
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
976
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
977
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
978
+ (nsfw) content, according to the `safety_checker`.
979
+ """
980
+ # 0. Default height and width to unet
981
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
982
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
983
+
984
+ # 1. Check inputs. Raise error if not correct
985
+ self.check_inputs(
986
+ prompt, height, width, strength, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds
987
+ )
988
+
989
+ # 2. Define call parameters
990
+ if prompt is not None and isinstance(prompt, str):
991
+ batch_size = 1
992
+ elif prompt is not None and isinstance(prompt, list):
993
+ batch_size = len(prompt)
994
+ else:
995
+ batch_size = prompt_embeds.shape[0]
996
+
997
+ device = self._execution_device
998
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
999
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1000
+ # corresponds to doing no classifier free guidance.
1001
+ do_classifier_free_guidance = guidance_scale > 1.0
1002
+
1003
+ # 3. Encode input prompt
1004
+ prompt_embeds = self._encode_prompt(
1005
+ prompt,
1006
+ device,
1007
+ num_images_per_prompt,
1008
+ do_classifier_free_guidance,
1009
+ negative_prompt,
1010
+ max_embeddings_multiples,
1011
+ prompt_embeds=prompt_embeds,
1012
+ negative_prompt_embeds=negative_prompt_embeds,
1013
+ )
1014
+ dtype = prompt_embeds.dtype
1015
+
1016
+ # 4. Preprocess image and mask
1017
+ if isinstance(image, PIL.Image.Image):
1018
+ image = preprocess_image(image, batch_size)
1019
+ if image is not None:
1020
+ image = image.to(device=self.device, dtype=dtype)
1021
+ if isinstance(mask_image, PIL.Image.Image):
1022
+ mask_image = preprocess_mask(mask_image, batch_size, self.vae_scale_factor)
1023
+ if mask_image is not None:
1024
+ mask = mask_image.to(device=self.device, dtype=dtype)
1025
+ mask = torch.cat([mask] * num_images_per_prompt)
1026
+ else:
1027
+ mask = None
1028
+
1029
+ # 5. set timesteps
1030
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
1031
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device, image is None)
1032
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
1033
+
1034
+ # 6. Prepare latent variables
1035
+ latents, init_latents_orig, noise = self.prepare_latents(
1036
+ image,
1037
+ latent_timestep,
1038
+ num_images_per_prompt,
1039
+ batch_size,
1040
+ self.unet.config.in_channels,
1041
+ height,
1042
+ width,
1043
+ dtype,
1044
+ device,
1045
+ generator,
1046
+ latents,
1047
+ )
1048
+
1049
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1050
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1051
+
1052
+ # 8. Denoising loop
1053
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1054
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1055
+ for i, t in enumerate(timesteps):
1056
+ # expand the latents if we are doing classifier free guidance
1057
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
1058
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1059
+
1060
+ # predict the noise residual
1061
+ noise_pred = self.unet(
1062
+ latent_model_input,
1063
+ t,
1064
+ encoder_hidden_states=prompt_embeds,
1065
+ cross_attention_kwargs=cross_attention_kwargs,
1066
+ ).sample
1067
+
1068
+ # perform guidance
1069
+ if do_classifier_free_guidance:
1070
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1071
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1072
+
1073
+ # compute the previous noisy sample x_t -> x_t-1
1074
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
1075
+
1076
+ if mask is not None:
1077
+ # masking
1078
+ if add_predicted_noise:
1079
+ init_latents_proper = self.scheduler.add_noise(
1080
+ init_latents_orig, noise_pred_uncond, torch.tensor([t])
1081
+ )
1082
+ else:
1083
+ init_latents_proper = self.scheduler.add_noise(init_latents_orig, noise, torch.tensor([t]))
1084
+ latents = (init_latents_proper * mask) + (latents * (1 - mask))
1085
+
1086
+ # call the callback, if provided
1087
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1088
+ progress_bar.update()
1089
+ if i % callback_steps == 0:
1090
+ if callback is not None:
1091
+ step_idx = i // getattr(self.scheduler, "order", 1)
1092
+ callback(step_idx, t, latents)
1093
+ if is_cancelled_callback is not None and is_cancelled_callback():
1094
+ return None
1095
+
1096
+ if output_type == "latent":
1097
+ image = latents
1098
+ has_nsfw_concept = None
1099
+ elif output_type == "pil":
1100
+ # 9. Post-processing
1101
+ image = self.decode_latents(latents)
1102
+
1103
+ # 10. Run safety checker
1104
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1105
+
1106
+ # 11. Convert to PIL
1107
+ image = self.numpy_to_pil(image)
1108
+ else:
1109
+ # 9. Post-processing
1110
+ image = self.decode_latents(latents)
1111
+
1112
+ # 10. Run safety checker
1113
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1114
+
1115
+ # Offload last model to CPU
1116
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
1117
+ self.final_offload_hook.offload()
1118
+
1119
+ if not return_dict:
1120
+ return image, has_nsfw_concept
1121
+
1122
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
1123
+
1124
+ def text2img(
1125
+ self,
1126
+ prompt: Union[str, List[str]],
1127
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1128
+ height: int = 512,
1129
+ width: int = 512,
1130
+ num_inference_steps: int = 50,
1131
+ guidance_scale: float = 7.5,
1132
+ num_images_per_prompt: Optional[int] = 1,
1133
+ eta: float = 0.0,
1134
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1135
+ latents: Optional[torch.FloatTensor] = None,
1136
+ prompt_embeds: Optional[torch.FloatTensor] = None,
1137
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
1138
+ max_embeddings_multiples: Optional[int] = 3,
1139
+ output_type: Optional[str] = "pil",
1140
+ return_dict: bool = True,
1141
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
1142
+ is_cancelled_callback: Optional[Callable[[], bool]] = None,
1143
+ callback_steps: int = 1,
1144
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1145
+ ):
1146
+ r"""
1147
+ Function for text-to-image generation.
1148
+ Args:
1149
+ prompt (`str` or `List[str]`):
1150
+ The prompt or prompts to guide the image generation.
1151
+ negative_prompt (`str` or `List[str]`, *optional*):
1152
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
1153
+ if `guidance_scale` is less than `1`).
1154
+ height (`int`, *optional*, defaults to 512):
1155
+ The height in pixels of the generated image.
1156
+ width (`int`, *optional*, defaults to 512):
1157
+ The width in pixels of the generated image.
1158
+ num_inference_steps (`int`, *optional*, defaults to 50):
1159
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1160
+ expense of slower inference.
1161
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1162
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1163
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1164
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1165
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1166
+ usually at the expense of lower image quality.
1167
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1168
+ The number of images to generate per prompt.
1169
+ eta (`float`, *optional*, defaults to 0.0):
1170
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1171
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1172
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1173
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
1174
+ to make generation deterministic.
1175
+ latents (`torch.FloatTensor`, *optional*):
1176
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
1177
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1178
+ tensor will ge generated by sampling using the supplied random `generator`.
1179
+ prompt_embeds (`torch.FloatTensor`, *optional*):
1180
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
1181
+ provided, text embeddings will be generated from `prompt` input argument.
1182
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
1183
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1184
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
1185
+ argument.
1186
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
1187
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
1188
+ output_type (`str`, *optional*, defaults to `"pil"`):
1189
+ The output format of the generate image. Choose between
1190
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1191
+ return_dict (`bool`, *optional*, defaults to `True`):
1192
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1193
+ plain tuple.
1194
+ callback (`Callable`, *optional*):
1195
+ A function that will be called every `callback_steps` steps during inference. The function will be
1196
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
1197
+ is_cancelled_callback (`Callable`, *optional*):
1198
+ A function that will be called every `callback_steps` steps during inference. If the function returns
1199
+ `True`, the inference will be cancelled.
1200
+ callback_steps (`int`, *optional*, defaults to 1):
1201
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
1202
+ called at every step.
1203
+ cross_attention_kwargs (`dict`, *optional*):
1204
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1205
+ `self.processor` in
1206
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1207
+
1208
+ Returns:
1209
+ `None` if cancelled by `is_cancelled_callback`,
1210
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1211
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
1212
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
1213
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
1214
+ (nsfw) content, according to the `safety_checker`.
1215
+ """
1216
+ return self.__call__(
1217
+ prompt=prompt,
1218
+ negative_prompt=negative_prompt,
1219
+ height=height,
1220
+ width=width,
1221
+ num_inference_steps=num_inference_steps,
1222
+ guidance_scale=guidance_scale,
1223
+ num_images_per_prompt=num_images_per_prompt,
1224
+ eta=eta,
1225
+ generator=generator,
1226
+ latents=latents,
1227
+ prompt_embeds=prompt_embeds,
1228
+ negative_prompt_embeds=negative_prompt_embeds,
1229
+ max_embeddings_multiples=max_embeddings_multiples,
1230
+ output_type=output_type,
1231
+ return_dict=return_dict,
1232
+ callback=callback,
1233
+ is_cancelled_callback=is_cancelled_callback,
1234
+ callback_steps=callback_steps,
1235
+ cross_attention_kwargs=cross_attention_kwargs,
1236
+ )
1237
+
1238
+ def img2img(
1239
+ self,
1240
+ image: Union[torch.FloatTensor, PIL.Image.Image],
1241
+ prompt: Union[str, List[str]],
1242
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1243
+ strength: float = 0.8,
1244
+ num_inference_steps: Optional[int] = 50,
1245
+ guidance_scale: Optional[float] = 7.5,
1246
+ num_images_per_prompt: Optional[int] = 1,
1247
+ eta: Optional[float] = 0.0,
1248
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1249
+ prompt_embeds: Optional[torch.FloatTensor] = None,
1250
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
1251
+ max_embeddings_multiples: Optional[int] = 3,
1252
+ output_type: Optional[str] = "pil",
1253
+ return_dict: bool = True,
1254
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
1255
+ is_cancelled_callback: Optional[Callable[[], bool]] = None,
1256
+ callback_steps: int = 1,
1257
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1258
+ ):
1259
+ r"""
1260
+ Function for image-to-image generation.
1261
+ Args:
1262
+ image (`torch.FloatTensor` or `PIL.Image.Image`):
1263
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
1264
+ process.
1265
+ prompt (`str` or `List[str]`):
1266
+ The prompt or prompts to guide the image generation.
1267
+ negative_prompt (`str` or `List[str]`, *optional*):
1268
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
1269
+ if `guidance_scale` is less than `1`).
1270
+ strength (`float`, *optional*, defaults to 0.8):
1271
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1.
1272
+ `image` will be used as a starting point, adding more noise to it the larger the `strength`. The
1273
+ number of denoising steps depends on the amount of noise initially added. When `strength` is 1, added
1274
+ noise will be maximum and the denoising process will run for the full number of iterations specified in
1275
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
1276
+ num_inference_steps (`int`, *optional*, defaults to 50):
1277
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1278
+ expense of slower inference. This parameter will be modulated by `strength`.
1279
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1280
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1281
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1282
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1283
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1284
+ usually at the expense of lower image quality.
1285
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1286
+ The number of images to generate per prompt.
1287
+ eta (`float`, *optional*, defaults to 0.0):
1288
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1289
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1290
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1291
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
1292
+ to make generation deterministic.
1293
+ prompt_embeds (`torch.FloatTensor`, *optional*):
1294
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
1295
+ provided, text embeddings will be generated from `prompt` input argument.
1296
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
1297
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1298
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
1299
+ argument.
1300
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
1301
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
1302
+ output_type (`str`, *optional*, defaults to `"pil"`):
1303
+ The output format of the generate image. Choose between
1304
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1305
+ return_dict (`bool`, *optional*, defaults to `True`):
1306
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1307
+ plain tuple.
1308
+ callback (`Callable`, *optional*):
1309
+ A function that will be called every `callback_steps` steps during inference. The function will be
1310
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
1311
+ is_cancelled_callback (`Callable`, *optional*):
1312
+ A function that will be called every `callback_steps` steps during inference. If the function returns
1313
+ `True`, the inference will be cancelled.
1314
+ callback_steps (`int`, *optional*, defaults to 1):
1315
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
1316
+ called at every step.
1317
+ cross_attention_kwargs (`dict`, *optional*):
1318
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1319
+ `self.processor` in
1320
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1321
+
1322
+ Returns:
1323
+ `None` if cancelled by `is_cancelled_callback`,
1324
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
1325
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
1326
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
1327
+ (nsfw) content, according to the `safety_checker`.
1328
+ """
1329
+ return self.__call__(
1330
+ prompt=prompt,
1331
+ negative_prompt=negative_prompt,
1332
+ image=image,
1333
+ num_inference_steps=num_inference_steps,
1334
+ guidance_scale=guidance_scale,
1335
+ strength=strength,
1336
+ num_images_per_prompt=num_images_per_prompt,
1337
+ eta=eta,
1338
+ generator=generator,
1339
+ prompt_embeds=prompt_embeds,
1340
+ negative_prompt_embeds=negative_prompt_embeds,
1341
+ max_embeddings_multiples=max_embeddings_multiples,
1342
+ output_type=output_type,
1343
+ return_dict=return_dict,
1344
+ callback=callback,
1345
+ is_cancelled_callback=is_cancelled_callback,
1346
+ callback_steps=callback_steps,
1347
+ cross_attention_kwargs=cross_attention_kwargs,
1348
+ )
1349
+
1350
+ def inpaint(
1351
+ self,
1352
+ image: Union[torch.FloatTensor, PIL.Image.Image],
1353
+ mask_image: Union[torch.FloatTensor, PIL.Image.Image],
1354
+ prompt: Union[str, List[str]],
1355
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1356
+ strength: float = 0.8,
1357
+ num_inference_steps: Optional[int] = 50,
1358
+ guidance_scale: Optional[float] = 7.5,
1359
+ num_images_per_prompt: Optional[int] = 1,
1360
+ add_predicted_noise: Optional[bool] = False,
1361
+ eta: Optional[float] = 0.0,
1362
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1363
+ prompt_embeds: Optional[torch.FloatTensor] = None,
1364
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
1365
+ max_embeddings_multiples: Optional[int] = 3,
1366
+ output_type: Optional[str] = "pil",
1367
+ return_dict: bool = True,
1368
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
1369
+ is_cancelled_callback: Optional[Callable[[], bool]] = None,
1370
+ callback_steps: int = 1,
1371
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1372
+ ):
1373
+ r"""
1374
+ Function for inpaint.
1375
+ Args:
1376
+ image (`torch.FloatTensor` or `PIL.Image.Image`):
1377
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
1378
+ process. This is the image whose masked region will be inpainted.
1379
+ mask_image (`torch.FloatTensor` or `PIL.Image.Image`):
1380
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
1381
+ replaced by noise and therefore repainted, while black pixels will be preserved. If `mask_image` is a
1382
+ PIL image, it will be converted to a single channel (luminance) before use. If it's a tensor, it should
1383
+ contain one color channel (L) instead of 3, so the expected shape would be `(B, H, W, 1)`.
1384
+ prompt (`str` or `List[str]`):
1385
+ The prompt or prompts to guide the image generation.
1386
+ negative_prompt (`str` or `List[str]`, *optional*):
1387
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
1388
+ if `guidance_scale` is less than `1`).
1389
+ strength (`float`, *optional*, defaults to 0.8):
1390
+ Conceptually, indicates how much to inpaint the masked area. Must be between 0 and 1. When `strength`
1391
+ is 1, the denoising process will be run on the masked area for the full number of iterations specified
1392
+ in `num_inference_steps`. `image` will be used as a reference for the masked area, adding more
1393
+ noise to that region the larger the `strength`. If `strength` is 0, no inpainting will occur.
1394
+ num_inference_steps (`int`, *optional*, defaults to 50):
1395
+ The reference number of denoising steps. More denoising steps usually lead to a higher quality image at
1396
+ the expense of slower inference. This parameter will be modulated by `strength`, as explained above.
1397
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1398
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1399
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1400
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1401
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1402
+ usually at the expense of lower image quality.
1403
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1404
+ The number of images to generate per prompt.
1405
+ add_predicted_noise (`bool`, *optional*, defaults to True):
1406
+ Use predicted noise instead of random noise when constructing noisy versions of the original image in
1407
+ the reverse diffusion process
1408
+ eta (`float`, *optional*, defaults to 0.0):
1409
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1410
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1411
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1412
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
1413
+ to make generation deterministic.
1414
+ prompt_embeds (`torch.FloatTensor`, *optional*):
1415
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
1416
+ provided, text embeddings will be generated from `prompt` input argument.
1417
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
1418
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1419
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
1420
+ argument.
1421
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
1422
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
1423
+ output_type (`str`, *optional*, defaults to `"pil"`):
1424
+ The output format of the generate image. Choose between
1425
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1426
+ return_dict (`bool`, *optional*, defaults to `True`):
1427
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1428
+ plain tuple.
1429
+ callback (`Callable`, *optional*):
1430
+ A function that will be called every `callback_steps` steps during inference. The function will be
1431
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
1432
+ is_cancelled_callback (`Callable`, *optional*):
1433
+ A function that will be called every `callback_steps` steps during inference. If the function returns
1434
+ `True`, the inference will be cancelled.
1435
+ callback_steps (`int`, *optional*, defaults to 1):
1436
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
1437
+ called at every step.
1438
+ cross_attention_kwargs (`dict`, *optional*):
1439
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1440
+ `self.processor` in
1441
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1442
+
1443
+ Returns:
1444
+ `None` if cancelled by `is_cancelled_callback`,
1445
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
1446
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
1447
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
1448
+ (nsfw) content, according to the `safety_checker`.
1449
+ """
1450
+ return self.__call__(
1451
+ prompt=prompt,
1452
+ negative_prompt=negative_prompt,
1453
+ image=image,
1454
+ mask_image=mask_image,
1455
+ num_inference_steps=num_inference_steps,
1456
+ guidance_scale=guidance_scale,
1457
+ strength=strength,
1458
+ num_images_per_prompt=num_images_per_prompt,
1459
+ add_predicted_noise=add_predicted_noise,
1460
+ eta=eta,
1461
+ generator=generator,
1462
+ prompt_embeds=prompt_embeds,
1463
+ negative_prompt_embeds=negative_prompt_embeds,
1464
+ max_embeddings_multiples=max_embeddings_multiples,
1465
+ output_type=output_type,
1466
+ return_dict=return_dict,
1467
+ callback=callback,
1468
+ is_cancelled_callback=is_cancelled_callback,
1469
+ callback_steps=callback_steps,
1470
+ cross_attention_kwargs=cross_attention_kwargs,
1471
+ )
v0.22.0/lpw_stable_diffusion_onnx.py ADDED
@@ -0,0 +1,1147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import re
3
+ from typing import Callable, List, Optional, Union
4
+
5
+ import numpy as np
6
+ import PIL.Image
7
+ import torch
8
+ from packaging import version
9
+ from transformers import CLIPImageProcessor, CLIPTokenizer
10
+
11
+ import diffusers
12
+ from diffusers import OnnxRuntimeModel, OnnxStableDiffusionPipeline, SchedulerMixin
13
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
14
+ from diffusers.utils import logging
15
+
16
+
17
+ try:
18
+ from diffusers.pipelines.onnx_utils import ORT_TO_NP_TYPE
19
+ except ImportError:
20
+ ORT_TO_NP_TYPE = {
21
+ "tensor(bool)": np.bool_,
22
+ "tensor(int8)": np.int8,
23
+ "tensor(uint8)": np.uint8,
24
+ "tensor(int16)": np.int16,
25
+ "tensor(uint16)": np.uint16,
26
+ "tensor(int32)": np.int32,
27
+ "tensor(uint32)": np.uint32,
28
+ "tensor(int64)": np.int64,
29
+ "tensor(uint64)": np.uint64,
30
+ "tensor(float16)": np.float16,
31
+ "tensor(float)": np.float32,
32
+ "tensor(double)": np.float64,
33
+ }
34
+
35
+ try:
36
+ from diffusers.utils import PIL_INTERPOLATION
37
+ except ImportError:
38
+ if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
39
+ PIL_INTERPOLATION = {
40
+ "linear": PIL.Image.Resampling.BILINEAR,
41
+ "bilinear": PIL.Image.Resampling.BILINEAR,
42
+ "bicubic": PIL.Image.Resampling.BICUBIC,
43
+ "lanczos": PIL.Image.Resampling.LANCZOS,
44
+ "nearest": PIL.Image.Resampling.NEAREST,
45
+ }
46
+ else:
47
+ PIL_INTERPOLATION = {
48
+ "linear": PIL.Image.LINEAR,
49
+ "bilinear": PIL.Image.BILINEAR,
50
+ "bicubic": PIL.Image.BICUBIC,
51
+ "lanczos": PIL.Image.LANCZOS,
52
+ "nearest": PIL.Image.NEAREST,
53
+ }
54
+ # ------------------------------------------------------------------------------
55
+
56
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
57
+
58
+ re_attention = re.compile(
59
+ r"""
60
+ \\\(|
61
+ \\\)|
62
+ \\\[|
63
+ \\]|
64
+ \\\\|
65
+ \\|
66
+ \(|
67
+ \[|
68
+ :([+-]?[.\d]+)\)|
69
+ \)|
70
+ ]|
71
+ [^\\()\[\]:]+|
72
+ :
73
+ """,
74
+ re.X,
75
+ )
76
+
77
+
78
+ def parse_prompt_attention(text):
79
+ """
80
+ Parses a string with attention tokens and returns a list of pairs: text and its associated weight.
81
+ Accepted tokens are:
82
+ (abc) - increases attention to abc by a multiplier of 1.1
83
+ (abc:3.12) - increases attention to abc by a multiplier of 3.12
84
+ [abc] - decreases attention to abc by a multiplier of 1.1
85
+ \( - literal character '('
86
+ \[ - literal character '['
87
+ \) - literal character ')'
88
+ \] - literal character ']'
89
+ \\ - literal character '\'
90
+ anything else - just text
91
+ >>> parse_prompt_attention('normal text')
92
+ [['normal text', 1.0]]
93
+ >>> parse_prompt_attention('an (important) word')
94
+ [['an ', 1.0], ['important', 1.1], [' word', 1.0]]
95
+ >>> parse_prompt_attention('(unbalanced')
96
+ [['unbalanced', 1.1]]
97
+ >>> parse_prompt_attention('\(literal\]')
98
+ [['(literal]', 1.0]]
99
+ >>> parse_prompt_attention('(unnecessary)(parens)')
100
+ [['unnecessaryparens', 1.1]]
101
+ >>> parse_prompt_attention('a (((house:1.3)) [on] a (hill:0.5), sun, (((sky))).')
102
+ [['a ', 1.0],
103
+ ['house', 1.5730000000000004],
104
+ [' ', 1.1],
105
+ ['on', 1.0],
106
+ [' a ', 1.1],
107
+ ['hill', 0.55],
108
+ [', sun, ', 1.1],
109
+ ['sky', 1.4641000000000006],
110
+ ['.', 1.1]]
111
+ """
112
+
113
+ res = []
114
+ round_brackets = []
115
+ square_brackets = []
116
+
117
+ round_bracket_multiplier = 1.1
118
+ square_bracket_multiplier = 1 / 1.1
119
+
120
+ def multiply_range(start_position, multiplier):
121
+ for p in range(start_position, len(res)):
122
+ res[p][1] *= multiplier
123
+
124
+ for m in re_attention.finditer(text):
125
+ text = m.group(0)
126
+ weight = m.group(1)
127
+
128
+ if text.startswith("\\"):
129
+ res.append([text[1:], 1.0])
130
+ elif text == "(":
131
+ round_brackets.append(len(res))
132
+ elif text == "[":
133
+ square_brackets.append(len(res))
134
+ elif weight is not None and len(round_brackets) > 0:
135
+ multiply_range(round_brackets.pop(), float(weight))
136
+ elif text == ")" and len(round_brackets) > 0:
137
+ multiply_range(round_brackets.pop(), round_bracket_multiplier)
138
+ elif text == "]" and len(square_brackets) > 0:
139
+ multiply_range(square_brackets.pop(), square_bracket_multiplier)
140
+ else:
141
+ res.append([text, 1.0])
142
+
143
+ for pos in round_brackets:
144
+ multiply_range(pos, round_bracket_multiplier)
145
+
146
+ for pos in square_brackets:
147
+ multiply_range(pos, square_bracket_multiplier)
148
+
149
+ if len(res) == 0:
150
+ res = [["", 1.0]]
151
+
152
+ # merge runs of identical weights
153
+ i = 0
154
+ while i + 1 < len(res):
155
+ if res[i][1] == res[i + 1][1]:
156
+ res[i][0] += res[i + 1][0]
157
+ res.pop(i + 1)
158
+ else:
159
+ i += 1
160
+
161
+ return res
162
+
163
+
164
+ def get_prompts_with_weights(pipe, prompt: List[str], max_length: int):
165
+ r"""
166
+ Tokenize a list of prompts and return its tokens with weights of each token.
167
+
168
+ No padding, starting or ending token is included.
169
+ """
170
+ tokens = []
171
+ weights = []
172
+ truncated = False
173
+ for text in prompt:
174
+ texts_and_weights = parse_prompt_attention(text)
175
+ text_token = []
176
+ text_weight = []
177
+ for word, weight in texts_and_weights:
178
+ # tokenize and discard the starting and the ending token
179
+ token = pipe.tokenizer(word, return_tensors="np").input_ids[0, 1:-1]
180
+ text_token += list(token)
181
+ # copy the weight by length of token
182
+ text_weight += [weight] * len(token)
183
+ # stop if the text is too long (longer than truncation limit)
184
+ if len(text_token) > max_length:
185
+ truncated = True
186
+ break
187
+ # truncate
188
+ if len(text_token) > max_length:
189
+ truncated = True
190
+ text_token = text_token[:max_length]
191
+ text_weight = text_weight[:max_length]
192
+ tokens.append(text_token)
193
+ weights.append(text_weight)
194
+ if truncated:
195
+ logger.warning("Prompt was truncated. Try to shorten the prompt or increase max_embeddings_multiples")
196
+ return tokens, weights
197
+
198
+
199
+ def pad_tokens_and_weights(tokens, weights, max_length, bos, eos, pad, no_boseos_middle=True, chunk_length=77):
200
+ r"""
201
+ Pad the tokens (with starting and ending tokens) and weights (with 1.0) to max_length.
202
+ """
203
+ max_embeddings_multiples = (max_length - 2) // (chunk_length - 2)
204
+ weights_length = max_length if no_boseos_middle else max_embeddings_multiples * chunk_length
205
+ for i in range(len(tokens)):
206
+ tokens[i] = [bos] + tokens[i] + [pad] * (max_length - 1 - len(tokens[i]) - 1) + [eos]
207
+ if no_boseos_middle:
208
+ weights[i] = [1.0] + weights[i] + [1.0] * (max_length - 1 - len(weights[i]))
209
+ else:
210
+ w = []
211
+ if len(weights[i]) == 0:
212
+ w = [1.0] * weights_length
213
+ else:
214
+ for j in range(max_embeddings_multiples):
215
+ w.append(1.0) # weight for starting token in this chunk
216
+ w += weights[i][j * (chunk_length - 2) : min(len(weights[i]), (j + 1) * (chunk_length - 2))]
217
+ w.append(1.0) # weight for ending token in this chunk
218
+ w += [1.0] * (weights_length - len(w))
219
+ weights[i] = w[:]
220
+
221
+ return tokens, weights
222
+
223
+
224
+ def get_unweighted_text_embeddings(
225
+ pipe,
226
+ text_input: np.array,
227
+ chunk_length: int,
228
+ no_boseos_middle: Optional[bool] = True,
229
+ ):
230
+ """
231
+ When the length of tokens is a multiple of the capacity of the text encoder,
232
+ it should be split into chunks and sent to the text encoder individually.
233
+ """
234
+ max_embeddings_multiples = (text_input.shape[1] - 2) // (chunk_length - 2)
235
+ if max_embeddings_multiples > 1:
236
+ text_embeddings = []
237
+ for i in range(max_embeddings_multiples):
238
+ # extract the i-th chunk
239
+ text_input_chunk = text_input[:, i * (chunk_length - 2) : (i + 1) * (chunk_length - 2) + 2].copy()
240
+
241
+ # cover the head and the tail by the starting and the ending tokens
242
+ text_input_chunk[:, 0] = text_input[0, 0]
243
+ text_input_chunk[:, -1] = text_input[0, -1]
244
+
245
+ text_embedding = pipe.text_encoder(input_ids=text_input_chunk)[0]
246
+
247
+ if no_boseos_middle:
248
+ if i == 0:
249
+ # discard the ending token
250
+ text_embedding = text_embedding[:, :-1]
251
+ elif i == max_embeddings_multiples - 1:
252
+ # discard the starting token
253
+ text_embedding = text_embedding[:, 1:]
254
+ else:
255
+ # discard both starting and ending tokens
256
+ text_embedding = text_embedding[:, 1:-1]
257
+
258
+ text_embeddings.append(text_embedding)
259
+ text_embeddings = np.concatenate(text_embeddings, axis=1)
260
+ else:
261
+ text_embeddings = pipe.text_encoder(input_ids=text_input)[0]
262
+ return text_embeddings
263
+
264
+
265
+ def get_weighted_text_embeddings(
266
+ pipe,
267
+ prompt: Union[str, List[str]],
268
+ uncond_prompt: Optional[Union[str, List[str]]] = None,
269
+ max_embeddings_multiples: Optional[int] = 4,
270
+ no_boseos_middle: Optional[bool] = False,
271
+ skip_parsing: Optional[bool] = False,
272
+ skip_weighting: Optional[bool] = False,
273
+ **kwargs,
274
+ ):
275
+ r"""
276
+ Prompts can be assigned with local weights using brackets. For example,
277
+ prompt 'A (very beautiful) masterpiece' highlights the words 'very beautiful',
278
+ and the embedding tokens corresponding to the words get multiplied by a constant, 1.1.
279
+
280
+ Also, to regularize of the embedding, the weighted embedding would be scaled to preserve the original mean.
281
+
282
+ Args:
283
+ pipe (`OnnxStableDiffusionPipeline`):
284
+ Pipe to provide access to the tokenizer and the text encoder.
285
+ prompt (`str` or `List[str]`):
286
+ The prompt or prompts to guide the image generation.
287
+ uncond_prompt (`str` or `List[str]`):
288
+ The unconditional prompt or prompts for guide the image generation. If unconditional prompt
289
+ is provided, the embeddings of prompt and uncond_prompt are concatenated.
290
+ max_embeddings_multiples (`int`, *optional*, defaults to `1`):
291
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
292
+ no_boseos_middle (`bool`, *optional*, defaults to `False`):
293
+ If the length of text token is multiples of the capacity of text encoder, whether reserve the starting and
294
+ ending token in each of the chunk in the middle.
295
+ skip_parsing (`bool`, *optional*, defaults to `False`):
296
+ Skip the parsing of brackets.
297
+ skip_weighting (`bool`, *optional*, defaults to `False`):
298
+ Skip the weighting. When the parsing is skipped, it is forced True.
299
+ """
300
+ max_length = (pipe.tokenizer.model_max_length - 2) * max_embeddings_multiples + 2
301
+ if isinstance(prompt, str):
302
+ prompt = [prompt]
303
+
304
+ if not skip_parsing:
305
+ prompt_tokens, prompt_weights = get_prompts_with_weights(pipe, prompt, max_length - 2)
306
+ if uncond_prompt is not None:
307
+ if isinstance(uncond_prompt, str):
308
+ uncond_prompt = [uncond_prompt]
309
+ uncond_tokens, uncond_weights = get_prompts_with_weights(pipe, uncond_prompt, max_length - 2)
310
+ else:
311
+ prompt_tokens = [
312
+ token[1:-1]
313
+ for token in pipe.tokenizer(prompt, max_length=max_length, truncation=True, return_tensors="np").input_ids
314
+ ]
315
+ prompt_weights = [[1.0] * len(token) for token in prompt_tokens]
316
+ if uncond_prompt is not None:
317
+ if isinstance(uncond_prompt, str):
318
+ uncond_prompt = [uncond_prompt]
319
+ uncond_tokens = [
320
+ token[1:-1]
321
+ for token in pipe.tokenizer(
322
+ uncond_prompt,
323
+ max_length=max_length,
324
+ truncation=True,
325
+ return_tensors="np",
326
+ ).input_ids
327
+ ]
328
+ uncond_weights = [[1.0] * len(token) for token in uncond_tokens]
329
+
330
+ # round up the longest length of tokens to a multiple of (model_max_length - 2)
331
+ max_length = max([len(token) for token in prompt_tokens])
332
+ if uncond_prompt is not None:
333
+ max_length = max(max_length, max([len(token) for token in uncond_tokens]))
334
+
335
+ max_embeddings_multiples = min(
336
+ max_embeddings_multiples,
337
+ (max_length - 1) // (pipe.tokenizer.model_max_length - 2) + 1,
338
+ )
339
+ max_embeddings_multiples = max(1, max_embeddings_multiples)
340
+ max_length = (pipe.tokenizer.model_max_length - 2) * max_embeddings_multiples + 2
341
+
342
+ # pad the length of tokens and weights
343
+ bos = pipe.tokenizer.bos_token_id
344
+ eos = pipe.tokenizer.eos_token_id
345
+ pad = getattr(pipe.tokenizer, "pad_token_id", eos)
346
+ prompt_tokens, prompt_weights = pad_tokens_and_weights(
347
+ prompt_tokens,
348
+ prompt_weights,
349
+ max_length,
350
+ bos,
351
+ eos,
352
+ pad,
353
+ no_boseos_middle=no_boseos_middle,
354
+ chunk_length=pipe.tokenizer.model_max_length,
355
+ )
356
+ prompt_tokens = np.array(prompt_tokens, dtype=np.int32)
357
+ if uncond_prompt is not None:
358
+ uncond_tokens, uncond_weights = pad_tokens_and_weights(
359
+ uncond_tokens,
360
+ uncond_weights,
361
+ max_length,
362
+ bos,
363
+ eos,
364
+ pad,
365
+ no_boseos_middle=no_boseos_middle,
366
+ chunk_length=pipe.tokenizer.model_max_length,
367
+ )
368
+ uncond_tokens = np.array(uncond_tokens, dtype=np.int32)
369
+
370
+ # get the embeddings
371
+ text_embeddings = get_unweighted_text_embeddings(
372
+ pipe,
373
+ prompt_tokens,
374
+ pipe.tokenizer.model_max_length,
375
+ no_boseos_middle=no_boseos_middle,
376
+ )
377
+ prompt_weights = np.array(prompt_weights, dtype=text_embeddings.dtype)
378
+ if uncond_prompt is not None:
379
+ uncond_embeddings = get_unweighted_text_embeddings(
380
+ pipe,
381
+ uncond_tokens,
382
+ pipe.tokenizer.model_max_length,
383
+ no_boseos_middle=no_boseos_middle,
384
+ )
385
+ uncond_weights = np.array(uncond_weights, dtype=uncond_embeddings.dtype)
386
+
387
+ # assign weights to the prompts and normalize in the sense of mean
388
+ # TODO: should we normalize by chunk or in a whole (current implementation)?
389
+ if (not skip_parsing) and (not skip_weighting):
390
+ previous_mean = text_embeddings.mean(axis=(-2, -1))
391
+ text_embeddings *= prompt_weights[:, :, None]
392
+ text_embeddings *= (previous_mean / text_embeddings.mean(axis=(-2, -1)))[:, None, None]
393
+ if uncond_prompt is not None:
394
+ previous_mean = uncond_embeddings.mean(axis=(-2, -1))
395
+ uncond_embeddings *= uncond_weights[:, :, None]
396
+ uncond_embeddings *= (previous_mean / uncond_embeddings.mean(axis=(-2, -1)))[:, None, None]
397
+
398
+ # For classifier free guidance, we need to do two forward passes.
399
+ # Here we concatenate the unconditional and text embeddings into a single batch
400
+ # to avoid doing two forward passes
401
+ if uncond_prompt is not None:
402
+ return text_embeddings, uncond_embeddings
403
+
404
+ return text_embeddings
405
+
406
+
407
+ def preprocess_image(image):
408
+ w, h = image.size
409
+ w, h = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32
410
+ image = image.resize((w, h), resample=PIL_INTERPOLATION["lanczos"])
411
+ image = np.array(image).astype(np.float32) / 255.0
412
+ image = image[None].transpose(0, 3, 1, 2)
413
+ return 2.0 * image - 1.0
414
+
415
+
416
+ def preprocess_mask(mask, scale_factor=8):
417
+ mask = mask.convert("L")
418
+ w, h = mask.size
419
+ w, h = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32
420
+ mask = mask.resize((w // scale_factor, h // scale_factor), resample=PIL_INTERPOLATION["nearest"])
421
+ mask = np.array(mask).astype(np.float32) / 255.0
422
+ mask = np.tile(mask, (4, 1, 1))
423
+ mask = mask[None].transpose(0, 1, 2, 3) # what does this step do?
424
+ mask = 1 - mask # repaint white, keep black
425
+ return mask
426
+
427
+
428
+ class OnnxStableDiffusionLongPromptWeightingPipeline(OnnxStableDiffusionPipeline):
429
+ r"""
430
+ Pipeline for text-to-image generation using Stable Diffusion without tokens length limit, and support parsing
431
+ weighting in prompt.
432
+
433
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
434
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
435
+ """
436
+ if version.parse(version.parse(diffusers.__version__).base_version) >= version.parse("0.9.0"):
437
+
438
+ def __init__(
439
+ self,
440
+ vae_encoder: OnnxRuntimeModel,
441
+ vae_decoder: OnnxRuntimeModel,
442
+ text_encoder: OnnxRuntimeModel,
443
+ tokenizer: CLIPTokenizer,
444
+ unet: OnnxRuntimeModel,
445
+ scheduler: SchedulerMixin,
446
+ safety_checker: OnnxRuntimeModel,
447
+ feature_extractor: CLIPImageProcessor,
448
+ requires_safety_checker: bool = True,
449
+ ):
450
+ super().__init__(
451
+ vae_encoder=vae_encoder,
452
+ vae_decoder=vae_decoder,
453
+ text_encoder=text_encoder,
454
+ tokenizer=tokenizer,
455
+ unet=unet,
456
+ scheduler=scheduler,
457
+ safety_checker=safety_checker,
458
+ feature_extractor=feature_extractor,
459
+ requires_safety_checker=requires_safety_checker,
460
+ )
461
+ self.__init__additional__()
462
+
463
+ else:
464
+
465
+ def __init__(
466
+ self,
467
+ vae_encoder: OnnxRuntimeModel,
468
+ vae_decoder: OnnxRuntimeModel,
469
+ text_encoder: OnnxRuntimeModel,
470
+ tokenizer: CLIPTokenizer,
471
+ unet: OnnxRuntimeModel,
472
+ scheduler: SchedulerMixin,
473
+ safety_checker: OnnxRuntimeModel,
474
+ feature_extractor: CLIPImageProcessor,
475
+ ):
476
+ super().__init__(
477
+ vae_encoder=vae_encoder,
478
+ vae_decoder=vae_decoder,
479
+ text_encoder=text_encoder,
480
+ tokenizer=tokenizer,
481
+ unet=unet,
482
+ scheduler=scheduler,
483
+ safety_checker=safety_checker,
484
+ feature_extractor=feature_extractor,
485
+ )
486
+ self.__init__additional__()
487
+
488
+ def __init__additional__(self):
489
+ self.unet.config.in_channels = 4
490
+ self.vae_scale_factor = 8
491
+
492
+ def _encode_prompt(
493
+ self,
494
+ prompt,
495
+ num_images_per_prompt,
496
+ do_classifier_free_guidance,
497
+ negative_prompt,
498
+ max_embeddings_multiples,
499
+ ):
500
+ r"""
501
+ Encodes the prompt into text encoder hidden states.
502
+
503
+ Args:
504
+ prompt (`str` or `list(int)`):
505
+ prompt to be encoded
506
+ num_images_per_prompt (`int`):
507
+ number of images that should be generated per prompt
508
+ do_classifier_free_guidance (`bool`):
509
+ whether to use classifier free guidance or not
510
+ negative_prompt (`str` or `List[str]`):
511
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
512
+ if `guidance_scale` is less than `1`).
513
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
514
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
515
+ """
516
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
517
+
518
+ if negative_prompt is None:
519
+ negative_prompt = [""] * batch_size
520
+ elif isinstance(negative_prompt, str):
521
+ negative_prompt = [negative_prompt] * batch_size
522
+ if batch_size != len(negative_prompt):
523
+ raise ValueError(
524
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
525
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
526
+ " the batch size of `prompt`."
527
+ )
528
+
529
+ text_embeddings, uncond_embeddings = get_weighted_text_embeddings(
530
+ pipe=self,
531
+ prompt=prompt,
532
+ uncond_prompt=negative_prompt if do_classifier_free_guidance else None,
533
+ max_embeddings_multiples=max_embeddings_multiples,
534
+ )
535
+
536
+ text_embeddings = text_embeddings.repeat(num_images_per_prompt, 0)
537
+ if do_classifier_free_guidance:
538
+ uncond_embeddings = uncond_embeddings.repeat(num_images_per_prompt, 0)
539
+ text_embeddings = np.concatenate([uncond_embeddings, text_embeddings])
540
+
541
+ return text_embeddings
542
+
543
+ def check_inputs(self, prompt, height, width, strength, callback_steps):
544
+ if not isinstance(prompt, str) and not isinstance(prompt, list):
545
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
546
+
547
+ if strength < 0 or strength > 1:
548
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
549
+
550
+ if height % 8 != 0 or width % 8 != 0:
551
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
552
+
553
+ if (callback_steps is None) or (
554
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
555
+ ):
556
+ raise ValueError(
557
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
558
+ f" {type(callback_steps)}."
559
+ )
560
+
561
+ def get_timesteps(self, num_inference_steps, strength, is_text2img):
562
+ if is_text2img:
563
+ return self.scheduler.timesteps, num_inference_steps
564
+ else:
565
+ # get the original timestep using init_timestep
566
+ offset = self.scheduler.config.get("steps_offset", 0)
567
+ init_timestep = int(num_inference_steps * strength) + offset
568
+ init_timestep = min(init_timestep, num_inference_steps)
569
+
570
+ t_start = max(num_inference_steps - init_timestep + offset, 0)
571
+ timesteps = self.scheduler.timesteps[t_start:]
572
+ return timesteps, num_inference_steps - t_start
573
+
574
+ def run_safety_checker(self, image):
575
+ if self.safety_checker is not None:
576
+ safety_checker_input = self.feature_extractor(
577
+ self.numpy_to_pil(image), return_tensors="np"
578
+ ).pixel_values.astype(image.dtype)
579
+ # There will throw an error if use safety_checker directly and batchsize>1
580
+ images, has_nsfw_concept = [], []
581
+ for i in range(image.shape[0]):
582
+ image_i, has_nsfw_concept_i = self.safety_checker(
583
+ clip_input=safety_checker_input[i : i + 1], images=image[i : i + 1]
584
+ )
585
+ images.append(image_i)
586
+ has_nsfw_concept.append(has_nsfw_concept_i[0])
587
+ image = np.concatenate(images)
588
+ else:
589
+ has_nsfw_concept = None
590
+ return image, has_nsfw_concept
591
+
592
+ def decode_latents(self, latents):
593
+ latents = 1 / 0.18215 * latents
594
+ # image = self.vae_decoder(latent_sample=latents)[0]
595
+ # it seems likes there is a strange result for using half-precision vae decoder if batchsize>1
596
+ image = np.concatenate(
597
+ [self.vae_decoder(latent_sample=latents[i : i + 1])[0] for i in range(latents.shape[0])]
598
+ )
599
+ image = np.clip(image / 2 + 0.5, 0, 1)
600
+ image = image.transpose((0, 2, 3, 1))
601
+ return image
602
+
603
+ def prepare_extra_step_kwargs(self, generator, eta):
604
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
605
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
606
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
607
+ # and should be between [0, 1]
608
+
609
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
610
+ extra_step_kwargs = {}
611
+ if accepts_eta:
612
+ extra_step_kwargs["eta"] = eta
613
+
614
+ # check if the scheduler accepts generator
615
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
616
+ if accepts_generator:
617
+ extra_step_kwargs["generator"] = generator
618
+ return extra_step_kwargs
619
+
620
+ def prepare_latents(self, image, timestep, batch_size, height, width, dtype, generator, latents=None):
621
+ if image is None:
622
+ shape = (
623
+ batch_size,
624
+ self.unet.config.in_channels,
625
+ height // self.vae_scale_factor,
626
+ width // self.vae_scale_factor,
627
+ )
628
+
629
+ if latents is None:
630
+ latents = torch.randn(shape, generator=generator, device="cpu").numpy().astype(dtype)
631
+ else:
632
+ if latents.shape != shape:
633
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
634
+
635
+ # scale the initial noise by the standard deviation required by the scheduler
636
+ latents = (torch.from_numpy(latents) * self.scheduler.init_noise_sigma).numpy()
637
+ return latents, None, None
638
+ else:
639
+ init_latents = self.vae_encoder(sample=image)[0]
640
+ init_latents = 0.18215 * init_latents
641
+ init_latents = np.concatenate([init_latents] * batch_size, axis=0)
642
+ init_latents_orig = init_latents
643
+ shape = init_latents.shape
644
+
645
+ # add noise to latents using the timesteps
646
+ noise = torch.randn(shape, generator=generator, device="cpu").numpy().astype(dtype)
647
+ latents = self.scheduler.add_noise(
648
+ torch.from_numpy(init_latents), torch.from_numpy(noise), timestep
649
+ ).numpy()
650
+ return latents, init_latents_orig, noise
651
+
652
+ @torch.no_grad()
653
+ def __call__(
654
+ self,
655
+ prompt: Union[str, List[str]],
656
+ negative_prompt: Optional[Union[str, List[str]]] = None,
657
+ image: Union[np.ndarray, PIL.Image.Image] = None,
658
+ mask_image: Union[np.ndarray, PIL.Image.Image] = None,
659
+ height: int = 512,
660
+ width: int = 512,
661
+ num_inference_steps: int = 50,
662
+ guidance_scale: float = 7.5,
663
+ strength: float = 0.8,
664
+ num_images_per_prompt: Optional[int] = 1,
665
+ eta: float = 0.0,
666
+ generator: Optional[torch.Generator] = None,
667
+ latents: Optional[np.ndarray] = None,
668
+ max_embeddings_multiples: Optional[int] = 3,
669
+ output_type: Optional[str] = "pil",
670
+ return_dict: bool = True,
671
+ callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
672
+ is_cancelled_callback: Optional[Callable[[], bool]] = None,
673
+ callback_steps: int = 1,
674
+ **kwargs,
675
+ ):
676
+ r"""
677
+ Function invoked when calling the pipeline for generation.
678
+
679
+ Args:
680
+ prompt (`str` or `List[str]`):
681
+ The prompt or prompts to guide the image generation.
682
+ negative_prompt (`str` or `List[str]`, *optional*):
683
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
684
+ if `guidance_scale` is less than `1`).
685
+ image (`np.ndarray` or `PIL.Image.Image`):
686
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
687
+ process.
688
+ mask_image (`np.ndarray` or `PIL.Image.Image`):
689
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
690
+ replaced by noise and therefore repainted, while black pixels will be preserved. If `mask_image` is a
691
+ PIL image, it will be converted to a single channel (luminance) before use. If it's a tensor, it should
692
+ contain one color channel (L) instead of 3, so the expected shape would be `(B, H, W, 1)`.
693
+ height (`int`, *optional*, defaults to 512):
694
+ The height in pixels of the generated image.
695
+ width (`int`, *optional*, defaults to 512):
696
+ The width in pixels of the generated image.
697
+ num_inference_steps (`int`, *optional*, defaults to 50):
698
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
699
+ expense of slower inference.
700
+ guidance_scale (`float`, *optional*, defaults to 7.5):
701
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
702
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
703
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
704
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
705
+ usually at the expense of lower image quality.
706
+ strength (`float`, *optional*, defaults to 0.8):
707
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1.
708
+ `image` will be used as a starting point, adding more noise to it the larger the `strength`. The
709
+ number of denoising steps depends on the amount of noise initially added. When `strength` is 1, added
710
+ noise will be maximum and the denoising process will run for the full number of iterations specified in
711
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
712
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
713
+ The number of images to generate per prompt.
714
+ eta (`float`, *optional*, defaults to 0.0):
715
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
716
+ [`schedulers.DDIMScheduler`], will be ignored for others.
717
+ generator (`torch.Generator`, *optional*):
718
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
719
+ deterministic.
720
+ latents (`np.ndarray`, *optional*):
721
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
722
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
723
+ tensor will ge generated by sampling using the supplied random `generator`.
724
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
725
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
726
+ output_type (`str`, *optional*, defaults to `"pil"`):
727
+ The output format of the generate image. Choose between
728
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
729
+ return_dict (`bool`, *optional*, defaults to `True`):
730
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
731
+ plain tuple.
732
+ callback (`Callable`, *optional*):
733
+ A function that will be called every `callback_steps` steps during inference. The function will be
734
+ called with the following arguments: `callback(step: int, timestep: int, latents: np.ndarray)`.
735
+ is_cancelled_callback (`Callable`, *optional*):
736
+ A function that will be called every `callback_steps` steps during inference. If the function returns
737
+ `True`, the inference will be cancelled.
738
+ callback_steps (`int`, *optional*, defaults to 1):
739
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
740
+ called at every step.
741
+
742
+ Returns:
743
+ `None` if cancelled by `is_cancelled_callback`,
744
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
745
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
746
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
747
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
748
+ (nsfw) content, according to the `safety_checker`.
749
+ """
750
+ # 0. Default height and width to unet
751
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
752
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
753
+
754
+ # 1. Check inputs. Raise error if not correct
755
+ self.check_inputs(prompt, height, width, strength, callback_steps)
756
+
757
+ # 2. Define call parameters
758
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
759
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
760
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
761
+ # corresponds to doing no classifier free guidance.
762
+ do_classifier_free_guidance = guidance_scale > 1.0
763
+
764
+ # 3. Encode input prompt
765
+ text_embeddings = self._encode_prompt(
766
+ prompt,
767
+ num_images_per_prompt,
768
+ do_classifier_free_guidance,
769
+ negative_prompt,
770
+ max_embeddings_multiples,
771
+ )
772
+ dtype = text_embeddings.dtype
773
+
774
+ # 4. Preprocess image and mask
775
+ if isinstance(image, PIL.Image.Image):
776
+ image = preprocess_image(image)
777
+ if image is not None:
778
+ image = image.astype(dtype)
779
+ if isinstance(mask_image, PIL.Image.Image):
780
+ mask_image = preprocess_mask(mask_image, self.vae_scale_factor)
781
+ if mask_image is not None:
782
+ mask = mask_image.astype(dtype)
783
+ mask = np.concatenate([mask] * batch_size * num_images_per_prompt)
784
+ else:
785
+ mask = None
786
+
787
+ # 5. set timesteps
788
+ self.scheduler.set_timesteps(num_inference_steps)
789
+ timestep_dtype = next(
790
+ (input.type for input in self.unet.model.get_inputs() if input.name == "timestep"), "tensor(float)"
791
+ )
792
+ timestep_dtype = ORT_TO_NP_TYPE[timestep_dtype]
793
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, image is None)
794
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
795
+
796
+ # 6. Prepare latent variables
797
+ latents, init_latents_orig, noise = self.prepare_latents(
798
+ image,
799
+ latent_timestep,
800
+ batch_size * num_images_per_prompt,
801
+ height,
802
+ width,
803
+ dtype,
804
+ generator,
805
+ latents,
806
+ )
807
+
808
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
809
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
810
+
811
+ # 8. Denoising loop
812
+ for i, t in enumerate(self.progress_bar(timesteps)):
813
+ # expand the latents if we are doing classifier free guidance
814
+ latent_model_input = np.concatenate([latents] * 2) if do_classifier_free_guidance else latents
815
+ latent_model_input = self.scheduler.scale_model_input(torch.from_numpy(latent_model_input), t)
816
+ latent_model_input = latent_model_input.numpy()
817
+
818
+ # predict the noise residual
819
+ noise_pred = self.unet(
820
+ sample=latent_model_input,
821
+ timestep=np.array([t], dtype=timestep_dtype),
822
+ encoder_hidden_states=text_embeddings,
823
+ )
824
+ noise_pred = noise_pred[0]
825
+
826
+ # perform guidance
827
+ if do_classifier_free_guidance:
828
+ noise_pred_uncond, noise_pred_text = np.split(noise_pred, 2)
829
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
830
+
831
+ # compute the previous noisy sample x_t -> x_t-1
832
+ scheduler_output = self.scheduler.step(
833
+ torch.from_numpy(noise_pred), t, torch.from_numpy(latents), **extra_step_kwargs
834
+ )
835
+ latents = scheduler_output.prev_sample.numpy()
836
+
837
+ if mask is not None:
838
+ # masking
839
+ init_latents_proper = self.scheduler.add_noise(
840
+ torch.from_numpy(init_latents_orig),
841
+ torch.from_numpy(noise),
842
+ t,
843
+ ).numpy()
844
+ latents = (init_latents_proper * mask) + (latents * (1 - mask))
845
+
846
+ # call the callback, if provided
847
+ if i % callback_steps == 0:
848
+ if callback is not None:
849
+ step_idx = i // getattr(self.scheduler, "order", 1)
850
+ callback(step_idx, t, latents)
851
+ if is_cancelled_callback is not None and is_cancelled_callback():
852
+ return None
853
+
854
+ # 9. Post-processing
855
+ image = self.decode_latents(latents)
856
+
857
+ # 10. Run safety checker
858
+ image, has_nsfw_concept = self.run_safety_checker(image)
859
+
860
+ # 11. Convert to PIL
861
+ if output_type == "pil":
862
+ image = self.numpy_to_pil(image)
863
+
864
+ if not return_dict:
865
+ return image, has_nsfw_concept
866
+
867
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
868
+
869
+ def text2img(
870
+ self,
871
+ prompt: Union[str, List[str]],
872
+ negative_prompt: Optional[Union[str, List[str]]] = None,
873
+ height: int = 512,
874
+ width: int = 512,
875
+ num_inference_steps: int = 50,
876
+ guidance_scale: float = 7.5,
877
+ num_images_per_prompt: Optional[int] = 1,
878
+ eta: float = 0.0,
879
+ generator: Optional[torch.Generator] = None,
880
+ latents: Optional[np.ndarray] = None,
881
+ max_embeddings_multiples: Optional[int] = 3,
882
+ output_type: Optional[str] = "pil",
883
+ return_dict: bool = True,
884
+ callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
885
+ callback_steps: int = 1,
886
+ **kwargs,
887
+ ):
888
+ r"""
889
+ Function for text-to-image generation.
890
+ Args:
891
+ prompt (`str` or `List[str]`):
892
+ The prompt or prompts to guide the image generation.
893
+ negative_prompt (`str` or `List[str]`, *optional*):
894
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
895
+ if `guidance_scale` is less than `1`).
896
+ height (`int`, *optional*, defaults to 512):
897
+ The height in pixels of the generated image.
898
+ width (`int`, *optional*, defaults to 512):
899
+ The width in pixels of the generated image.
900
+ num_inference_steps (`int`, *optional*, defaults to 50):
901
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
902
+ expense of slower inference.
903
+ guidance_scale (`float`, *optional*, defaults to 7.5):
904
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
905
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
906
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
907
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
908
+ usually at the expense of lower image quality.
909
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
910
+ The number of images to generate per prompt.
911
+ eta (`float`, *optional*, defaults to 0.0):
912
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
913
+ [`schedulers.DDIMScheduler`], will be ignored for others.
914
+ generator (`torch.Generator`, *optional*):
915
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
916
+ deterministic.
917
+ latents (`np.ndarray`, *optional*):
918
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
919
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
920
+ tensor will ge generated by sampling using the supplied random `generator`.
921
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
922
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
923
+ output_type (`str`, *optional*, defaults to `"pil"`):
924
+ The output format of the generate image. Choose between
925
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
926
+ return_dict (`bool`, *optional*, defaults to `True`):
927
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
928
+ plain tuple.
929
+ callback (`Callable`, *optional*):
930
+ A function that will be called every `callback_steps` steps during inference. The function will be
931
+ called with the following arguments: `callback(step: int, timestep: int, latents: np.ndarray)`.
932
+ callback_steps (`int`, *optional*, defaults to 1):
933
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
934
+ called at every step.
935
+ Returns:
936
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
937
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
938
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
939
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
940
+ (nsfw) content, according to the `safety_checker`.
941
+ """
942
+ return self.__call__(
943
+ prompt=prompt,
944
+ negative_prompt=negative_prompt,
945
+ height=height,
946
+ width=width,
947
+ num_inference_steps=num_inference_steps,
948
+ guidance_scale=guidance_scale,
949
+ num_images_per_prompt=num_images_per_prompt,
950
+ eta=eta,
951
+ generator=generator,
952
+ latents=latents,
953
+ max_embeddings_multiples=max_embeddings_multiples,
954
+ output_type=output_type,
955
+ return_dict=return_dict,
956
+ callback=callback,
957
+ callback_steps=callback_steps,
958
+ **kwargs,
959
+ )
960
+
961
+ def img2img(
962
+ self,
963
+ image: Union[np.ndarray, PIL.Image.Image],
964
+ prompt: Union[str, List[str]],
965
+ negative_prompt: Optional[Union[str, List[str]]] = None,
966
+ strength: float = 0.8,
967
+ num_inference_steps: Optional[int] = 50,
968
+ guidance_scale: Optional[float] = 7.5,
969
+ num_images_per_prompt: Optional[int] = 1,
970
+ eta: Optional[float] = 0.0,
971
+ generator: Optional[torch.Generator] = None,
972
+ max_embeddings_multiples: Optional[int] = 3,
973
+ output_type: Optional[str] = "pil",
974
+ return_dict: bool = True,
975
+ callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
976
+ callback_steps: int = 1,
977
+ **kwargs,
978
+ ):
979
+ r"""
980
+ Function for image-to-image generation.
981
+ Args:
982
+ image (`np.ndarray` or `PIL.Image.Image`):
983
+ `Image`, or ndarray representing an image batch, that will be used as the starting point for the
984
+ process.
985
+ prompt (`str` or `List[str]`):
986
+ The prompt or prompts to guide the image generation.
987
+ negative_prompt (`str` or `List[str]`, *optional*):
988
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
989
+ if `guidance_scale` is less than `1`).
990
+ strength (`float`, *optional*, defaults to 0.8):
991
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1.
992
+ `image` will be used as a starting point, adding more noise to it the larger the `strength`. The
993
+ number of denoising steps depends on the amount of noise initially added. When `strength` is 1, added
994
+ noise will be maximum and the denoising process will run for the full number of iterations specified in
995
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
996
+ num_inference_steps (`int`, *optional*, defaults to 50):
997
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
998
+ expense of slower inference. This parameter will be modulated by `strength`.
999
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1000
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1001
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1002
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1003
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1004
+ usually at the expense of lower image quality.
1005
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1006
+ The number of images to generate per prompt.
1007
+ eta (`float`, *optional*, defaults to 0.0):
1008
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1009
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1010
+ generator (`torch.Generator`, *optional*):
1011
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
1012
+ deterministic.
1013
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
1014
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
1015
+ output_type (`str`, *optional*, defaults to `"pil"`):
1016
+ The output format of the generate image. Choose between
1017
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1018
+ return_dict (`bool`, *optional*, defaults to `True`):
1019
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1020
+ plain tuple.
1021
+ callback (`Callable`, *optional*):
1022
+ A function that will be called every `callback_steps` steps during inference. The function will be
1023
+ called with the following arguments: `callback(step: int, timestep: int, latents: np.ndarray)`.
1024
+ callback_steps (`int`, *optional*, defaults to 1):
1025
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
1026
+ called at every step.
1027
+ Returns:
1028
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1029
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
1030
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
1031
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
1032
+ (nsfw) content, according to the `safety_checker`.
1033
+ """
1034
+ return self.__call__(
1035
+ prompt=prompt,
1036
+ negative_prompt=negative_prompt,
1037
+ image=image,
1038
+ num_inference_steps=num_inference_steps,
1039
+ guidance_scale=guidance_scale,
1040
+ strength=strength,
1041
+ num_images_per_prompt=num_images_per_prompt,
1042
+ eta=eta,
1043
+ generator=generator,
1044
+ max_embeddings_multiples=max_embeddings_multiples,
1045
+ output_type=output_type,
1046
+ return_dict=return_dict,
1047
+ callback=callback,
1048
+ callback_steps=callback_steps,
1049
+ **kwargs,
1050
+ )
1051
+
1052
+ def inpaint(
1053
+ self,
1054
+ image: Union[np.ndarray, PIL.Image.Image],
1055
+ mask_image: Union[np.ndarray, PIL.Image.Image],
1056
+ prompt: Union[str, List[str]],
1057
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1058
+ strength: float = 0.8,
1059
+ num_inference_steps: Optional[int] = 50,
1060
+ guidance_scale: Optional[float] = 7.5,
1061
+ num_images_per_prompt: Optional[int] = 1,
1062
+ eta: Optional[float] = 0.0,
1063
+ generator: Optional[torch.Generator] = None,
1064
+ max_embeddings_multiples: Optional[int] = 3,
1065
+ output_type: Optional[str] = "pil",
1066
+ return_dict: bool = True,
1067
+ callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
1068
+ callback_steps: int = 1,
1069
+ **kwargs,
1070
+ ):
1071
+ r"""
1072
+ Function for inpaint.
1073
+ Args:
1074
+ image (`np.ndarray` or `PIL.Image.Image`):
1075
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
1076
+ process. This is the image whose masked region will be inpainted.
1077
+ mask_image (`np.ndarray` or `PIL.Image.Image`):
1078
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
1079
+ replaced by noise and therefore repainted, while black pixels will be preserved. If `mask_image` is a
1080
+ PIL image, it will be converted to a single channel (luminance) before use. If it's a tensor, it should
1081
+ contain one color channel (L) instead of 3, so the expected shape would be `(B, H, W, 1)`.
1082
+ prompt (`str` or `List[str]`):
1083
+ The prompt or prompts to guide the image generation.
1084
+ negative_prompt (`str` or `List[str]`, *optional*):
1085
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
1086
+ if `guidance_scale` is less than `1`).
1087
+ strength (`float`, *optional*, defaults to 0.8):
1088
+ Conceptually, indicates how much to inpaint the masked area. Must be between 0 and 1. When `strength`
1089
+ is 1, the denoising process will be run on the masked area for the full number of iterations specified
1090
+ in `num_inference_steps`. `image` will be used as a reference for the masked area, adding more
1091
+ noise to that region the larger the `strength`. If `strength` is 0, no inpainting will occur.
1092
+ num_inference_steps (`int`, *optional*, defaults to 50):
1093
+ The reference number of denoising steps. More denoising steps usually lead to a higher quality image at
1094
+ the expense of slower inference. This parameter will be modulated by `strength`, as explained above.
1095
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1096
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1097
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1098
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1099
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1100
+ usually at the expense of lower image quality.
1101
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1102
+ The number of images to generate per prompt.
1103
+ eta (`float`, *optional*, defaults to 0.0):
1104
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1105
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1106
+ generator (`torch.Generator`, *optional*):
1107
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
1108
+ deterministic.
1109
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
1110
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
1111
+ output_type (`str`, *optional*, defaults to `"pil"`):
1112
+ The output format of the generate image. Choose between
1113
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1114
+ return_dict (`bool`, *optional*, defaults to `True`):
1115
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1116
+ plain tuple.
1117
+ callback (`Callable`, *optional*):
1118
+ A function that will be called every `callback_steps` steps during inference. The function will be
1119
+ called with the following arguments: `callback(step: int, timestep: int, latents: np.ndarray)`.
1120
+ callback_steps (`int`, *optional*, defaults to 1):
1121
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
1122
+ called at every step.
1123
+ Returns:
1124
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1125
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
1126
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
1127
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
1128
+ (nsfw) content, according to the `safety_checker`.
1129
+ """
1130
+ return self.__call__(
1131
+ prompt=prompt,
1132
+ negative_prompt=negative_prompt,
1133
+ image=image,
1134
+ mask_image=mask_image,
1135
+ num_inference_steps=num_inference_steps,
1136
+ guidance_scale=guidance_scale,
1137
+ strength=strength,
1138
+ num_images_per_prompt=num_images_per_prompt,
1139
+ eta=eta,
1140
+ generator=generator,
1141
+ max_embeddings_multiples=max_embeddings_multiples,
1142
+ output_type=output_type,
1143
+ return_dict=return_dict,
1144
+ callback=callback,
1145
+ callback_steps=callback_steps,
1146
+ **kwargs,
1147
+ )
v0.22.0/lpw_stable_diffusion_xl.py ADDED
@@ -0,0 +1,1288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## ----------------------------------------------------------
2
+ # A SDXL pipeline can take unlimited weighted prompt
3
+ #
4
+ # Author: Andrew Zhu
5
+ # Github: https://github.com/xhinker
6
+ # Medium: https://medium.com/@xhinker
7
+ ## -----------------------------------------------------------
8
+
9
+ import inspect
10
+ import os
11
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
12
+
13
+ import torch
14
+ from transformers import CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
15
+
16
+ from diffusers import DiffusionPipeline, StableDiffusionXLPipeline
17
+ from diffusers.image_processor import VaeImageProcessor
18
+ from diffusers.loaders import FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin
19
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
20
+ from diffusers.models.attention_processor import (
21
+ AttnProcessor2_0,
22
+ LoRAAttnProcessor2_0,
23
+ LoRAXFormersAttnProcessor,
24
+ XFormersAttnProcessor,
25
+ )
26
+ from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineOutput
27
+ from diffusers.schedulers import KarrasDiffusionSchedulers
28
+ from diffusers.utils import (
29
+ is_accelerate_available,
30
+ is_accelerate_version,
31
+ is_invisible_watermark_available,
32
+ logging,
33
+ replace_example_docstring,
34
+ )
35
+ from diffusers.utils.torch_utils import randn_tensor
36
+
37
+
38
+ if is_invisible_watermark_available():
39
+ from diffusers.pipelines.stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
40
+
41
+
42
+ def parse_prompt_attention(text):
43
+ """
44
+ Parses a string with attention tokens and returns a list of pairs: text and its associated weight.
45
+ Accepted tokens are:
46
+ (abc) - increases attention to abc by a multiplier of 1.1
47
+ (abc:3.12) - increases attention to abc by a multiplier of 3.12
48
+ [abc] - decreases attention to abc by a multiplier of 1.1
49
+ \( - literal character '('
50
+ \[ - literal character '['
51
+ \) - literal character ')'
52
+ \] - literal character ']'
53
+ \\ - literal character '\'
54
+ anything else - just text
55
+
56
+ >>> parse_prompt_attention('normal text')
57
+ [['normal text', 1.0]]
58
+ >>> parse_prompt_attention('an (important) word')
59
+ [['an ', 1.0], ['important', 1.1], [' word', 1.0]]
60
+ >>> parse_prompt_attention('(unbalanced')
61
+ [['unbalanced', 1.1]]
62
+ >>> parse_prompt_attention('\(literal\]')
63
+ [['(literal]', 1.0]]
64
+ >>> parse_prompt_attention('(unnecessary)(parens)')
65
+ [['unnecessaryparens', 1.1]]
66
+ >>> parse_prompt_attention('a (((house:1.3)) [on] a (hill:0.5), sun, (((sky))).')
67
+ [['a ', 1.0],
68
+ ['house', 1.5730000000000004],
69
+ [' ', 1.1],
70
+ ['on', 1.0],
71
+ [' a ', 1.1],
72
+ ['hill', 0.55],
73
+ [', sun, ', 1.1],
74
+ ['sky', 1.4641000000000006],
75
+ ['.', 1.1]]
76
+ """
77
+ import re
78
+
79
+ re_attention = re.compile(
80
+ r"""
81
+ \\\(|\\\)|\\\[|\\]|\\\\|\\|\(|\[|:([+-]?[.\d]+)\)|
82
+ \)|]|[^\\()\[\]:]+|:
83
+ """,
84
+ re.X,
85
+ )
86
+
87
+ re_break = re.compile(r"\s*\bBREAK\b\s*", re.S)
88
+
89
+ res = []
90
+ round_brackets = []
91
+ square_brackets = []
92
+
93
+ round_bracket_multiplier = 1.1
94
+ square_bracket_multiplier = 1 / 1.1
95
+
96
+ def multiply_range(start_position, multiplier):
97
+ for p in range(start_position, len(res)):
98
+ res[p][1] *= multiplier
99
+
100
+ for m in re_attention.finditer(text):
101
+ text = m.group(0)
102
+ weight = m.group(1)
103
+
104
+ if text.startswith("\\"):
105
+ res.append([text[1:], 1.0])
106
+ elif text == "(":
107
+ round_brackets.append(len(res))
108
+ elif text == "[":
109
+ square_brackets.append(len(res))
110
+ elif weight is not None and len(round_brackets) > 0:
111
+ multiply_range(round_brackets.pop(), float(weight))
112
+ elif text == ")" and len(round_brackets) > 0:
113
+ multiply_range(round_brackets.pop(), round_bracket_multiplier)
114
+ elif text == "]" and len(square_brackets) > 0:
115
+ multiply_range(square_brackets.pop(), square_bracket_multiplier)
116
+ else:
117
+ parts = re.split(re_break, text)
118
+ for i, part in enumerate(parts):
119
+ if i > 0:
120
+ res.append(["BREAK", -1])
121
+ res.append([part, 1.0])
122
+
123
+ for pos in round_brackets:
124
+ multiply_range(pos, round_bracket_multiplier)
125
+
126
+ for pos in square_brackets:
127
+ multiply_range(pos, square_bracket_multiplier)
128
+
129
+ if len(res) == 0:
130
+ res = [["", 1.0]]
131
+
132
+ # merge runs of identical weights
133
+ i = 0
134
+ while i + 1 < len(res):
135
+ if res[i][1] == res[i + 1][1]:
136
+ res[i][0] += res[i + 1][0]
137
+ res.pop(i + 1)
138
+ else:
139
+ i += 1
140
+
141
+ return res
142
+
143
+
144
+ def get_prompts_tokens_with_weights(clip_tokenizer: CLIPTokenizer, prompt: str):
145
+ """
146
+ Get prompt token ids and weights, this function works for both prompt and negative prompt
147
+
148
+ Args:
149
+ pipe (CLIPTokenizer)
150
+ A CLIPTokenizer
151
+ prompt (str)
152
+ A prompt string with weights
153
+
154
+ Returns:
155
+ text_tokens (list)
156
+ A list contains token ids
157
+ text_weight (list)
158
+ A list contains the correspodent weight of token ids
159
+
160
+ Example:
161
+ import torch
162
+ from transformers import CLIPTokenizer
163
+
164
+ clip_tokenizer = CLIPTokenizer.from_pretrained(
165
+ "stablediffusionapi/deliberate-v2"
166
+ , subfolder = "tokenizer"
167
+ , dtype = torch.float16
168
+ )
169
+
170
+ token_id_list, token_weight_list = get_prompts_tokens_with_weights(
171
+ clip_tokenizer = clip_tokenizer
172
+ ,prompt = "a (red:1.5) cat"*70
173
+ )
174
+ """
175
+ texts_and_weights = parse_prompt_attention(prompt)
176
+ text_tokens, text_weights = [], []
177
+ for word, weight in texts_and_weights:
178
+ # tokenize and discard the starting and the ending token
179
+ token = clip_tokenizer(word, truncation=False).input_ids[1:-1] # so that tokenize whatever length prompt
180
+ # the returned token is a 1d list: [320, 1125, 539, 320]
181
+
182
+ # merge the new tokens to the all tokens holder: text_tokens
183
+ text_tokens = [*text_tokens, *token]
184
+
185
+ # each token chunk will come with one weight, like ['red cat', 2.0]
186
+ # need to expand weight for each token.
187
+ chunk_weights = [weight] * len(token)
188
+
189
+ # append the weight back to the weight holder: text_weights
190
+ text_weights = [*text_weights, *chunk_weights]
191
+ return text_tokens, text_weights
192
+
193
+
194
+ def group_tokens_and_weights(token_ids: list, weights: list, pad_last_block=False):
195
+ """
196
+ Produce tokens and weights in groups and pad the missing tokens
197
+
198
+ Args:
199
+ token_ids (list)
200
+ The token ids from tokenizer
201
+ weights (list)
202
+ The weights list from function get_prompts_tokens_with_weights
203
+ pad_last_block (bool)
204
+ Control if fill the last token list to 75 tokens with eos
205
+ Returns:
206
+ new_token_ids (2d list)
207
+ new_weights (2d list)
208
+
209
+ Example:
210
+ token_groups,weight_groups = group_tokens_and_weights(
211
+ token_ids = token_id_list
212
+ , weights = token_weight_list
213
+ )
214
+ """
215
+ bos, eos = 49406, 49407
216
+
217
+ # this will be a 2d list
218
+ new_token_ids = []
219
+ new_weights = []
220
+ while len(token_ids) >= 75:
221
+ # get the first 75 tokens
222
+ head_75_tokens = [token_ids.pop(0) for _ in range(75)]
223
+ head_75_weights = [weights.pop(0) for _ in range(75)]
224
+
225
+ # extract token ids and weights
226
+ temp_77_token_ids = [bos] + head_75_tokens + [eos]
227
+ temp_77_weights = [1.0] + head_75_weights + [1.0]
228
+
229
+ # add 77 token and weights chunk to the holder list
230
+ new_token_ids.append(temp_77_token_ids)
231
+ new_weights.append(temp_77_weights)
232
+
233
+ # padding the left
234
+ if len(token_ids) > 0:
235
+ padding_len = 75 - len(token_ids) if pad_last_block else 0
236
+
237
+ temp_77_token_ids = [bos] + token_ids + [eos] * padding_len + [eos]
238
+ new_token_ids.append(temp_77_token_ids)
239
+
240
+ temp_77_weights = [1.0] + weights + [1.0] * padding_len + [1.0]
241
+ new_weights.append(temp_77_weights)
242
+
243
+ return new_token_ids, new_weights
244
+
245
+
246
+ def get_weighted_text_embeddings_sdxl(
247
+ pipe: StableDiffusionXLPipeline,
248
+ prompt: str = "",
249
+ prompt_2: str = None,
250
+ neg_prompt: str = "",
251
+ neg_prompt_2: str = None,
252
+ ):
253
+ """
254
+ This function can process long prompt with weights, no length limitation
255
+ for Stable Diffusion XL
256
+
257
+ Args:
258
+ pipe (StableDiffusionPipeline)
259
+ prompt (str)
260
+ prompt_2 (str)
261
+ neg_prompt (str)
262
+ neg_prompt_2 (str)
263
+ Returns:
264
+ prompt_embeds (torch.Tensor)
265
+ neg_prompt_embeds (torch.Tensor)
266
+ """
267
+ if prompt_2:
268
+ prompt = f"{prompt} {prompt_2}"
269
+
270
+ if neg_prompt_2:
271
+ neg_prompt = f"{neg_prompt} {neg_prompt_2}"
272
+
273
+ eos = pipe.tokenizer.eos_token_id
274
+
275
+ # tokenizer 1
276
+ prompt_tokens, prompt_weights = get_prompts_tokens_with_weights(pipe.tokenizer, prompt)
277
+
278
+ neg_prompt_tokens, neg_prompt_weights = get_prompts_tokens_with_weights(pipe.tokenizer, neg_prompt)
279
+
280
+ # tokenizer 2
281
+ prompt_tokens_2, prompt_weights_2 = get_prompts_tokens_with_weights(pipe.tokenizer_2, prompt)
282
+
283
+ neg_prompt_tokens_2, neg_prompt_weights_2 = get_prompts_tokens_with_weights(pipe.tokenizer_2, neg_prompt)
284
+
285
+ # padding the shorter one for prompt set 1
286
+ prompt_token_len = len(prompt_tokens)
287
+ neg_prompt_token_len = len(neg_prompt_tokens)
288
+
289
+ if prompt_token_len > neg_prompt_token_len:
290
+ # padding the neg_prompt with eos token
291
+ neg_prompt_tokens = neg_prompt_tokens + [eos] * abs(prompt_token_len - neg_prompt_token_len)
292
+ neg_prompt_weights = neg_prompt_weights + [1.0] * abs(prompt_token_len - neg_prompt_token_len)
293
+ else:
294
+ # padding the prompt
295
+ prompt_tokens = prompt_tokens + [eos] * abs(prompt_token_len - neg_prompt_token_len)
296
+ prompt_weights = prompt_weights + [1.0] * abs(prompt_token_len - neg_prompt_token_len)
297
+
298
+ # padding the shorter one for token set 2
299
+ prompt_token_len_2 = len(prompt_tokens_2)
300
+ neg_prompt_token_len_2 = len(neg_prompt_tokens_2)
301
+
302
+ if prompt_token_len_2 > neg_prompt_token_len_2:
303
+ # padding the neg_prompt with eos token
304
+ neg_prompt_tokens_2 = neg_prompt_tokens_2 + [eos] * abs(prompt_token_len_2 - neg_prompt_token_len_2)
305
+ neg_prompt_weights_2 = neg_prompt_weights_2 + [1.0] * abs(prompt_token_len_2 - neg_prompt_token_len_2)
306
+ else:
307
+ # padding the prompt
308
+ prompt_tokens_2 = prompt_tokens_2 + [eos] * abs(prompt_token_len_2 - neg_prompt_token_len_2)
309
+ prompt_weights_2 = prompt_weights + [1.0] * abs(prompt_token_len_2 - neg_prompt_token_len_2)
310
+
311
+ embeds = []
312
+ neg_embeds = []
313
+
314
+ prompt_token_groups, prompt_weight_groups = group_tokens_and_weights(prompt_tokens.copy(), prompt_weights.copy())
315
+
316
+ neg_prompt_token_groups, neg_prompt_weight_groups = group_tokens_and_weights(
317
+ neg_prompt_tokens.copy(), neg_prompt_weights.copy()
318
+ )
319
+
320
+ prompt_token_groups_2, prompt_weight_groups_2 = group_tokens_and_weights(
321
+ prompt_tokens_2.copy(), prompt_weights_2.copy()
322
+ )
323
+
324
+ neg_prompt_token_groups_2, neg_prompt_weight_groups_2 = group_tokens_and_weights(
325
+ neg_prompt_tokens_2.copy(), neg_prompt_weights_2.copy()
326
+ )
327
+
328
+ # get prompt embeddings one by one is not working.
329
+ for i in range(len(prompt_token_groups)):
330
+ # get positive prompt embeddings with weights
331
+ token_tensor = torch.tensor([prompt_token_groups[i]], dtype=torch.long, device=pipe.device)
332
+ weight_tensor = torch.tensor(prompt_weight_groups[i], dtype=torch.float16, device=pipe.device)
333
+
334
+ token_tensor_2 = torch.tensor([prompt_token_groups_2[i]], dtype=torch.long, device=pipe.device)
335
+
336
+ # use first text encoder
337
+ prompt_embeds_1 = pipe.text_encoder(token_tensor.to(pipe.device), output_hidden_states=True)
338
+ prompt_embeds_1_hidden_states = prompt_embeds_1.hidden_states[-2]
339
+
340
+ # use second text encoder
341
+ prompt_embeds_2 = pipe.text_encoder_2(token_tensor_2.to(pipe.device), output_hidden_states=True)
342
+ prompt_embeds_2_hidden_states = prompt_embeds_2.hidden_states[-2]
343
+ pooled_prompt_embeds = prompt_embeds_2[0]
344
+
345
+ prompt_embeds_list = [prompt_embeds_1_hidden_states, prompt_embeds_2_hidden_states]
346
+ token_embedding = torch.concat(prompt_embeds_list, dim=-1).squeeze(0)
347
+
348
+ for j in range(len(weight_tensor)):
349
+ if weight_tensor[j] != 1.0:
350
+ token_embedding[j] = (
351
+ token_embedding[-1] + (token_embedding[j] - token_embedding[-1]) * weight_tensor[j]
352
+ )
353
+
354
+ token_embedding = token_embedding.unsqueeze(0)
355
+ embeds.append(token_embedding)
356
+
357
+ # get negative prompt embeddings with weights
358
+ neg_token_tensor = torch.tensor([neg_prompt_token_groups[i]], dtype=torch.long, device=pipe.device)
359
+ neg_token_tensor_2 = torch.tensor([neg_prompt_token_groups_2[i]], dtype=torch.long, device=pipe.device)
360
+ neg_weight_tensor = torch.tensor(neg_prompt_weight_groups[i], dtype=torch.float16, device=pipe.device)
361
+
362
+ # use first text encoder
363
+ neg_prompt_embeds_1 = pipe.text_encoder(neg_token_tensor.to(pipe.device), output_hidden_states=True)
364
+ neg_prompt_embeds_1_hidden_states = neg_prompt_embeds_1.hidden_states[-2]
365
+
366
+ # use second text encoder
367
+ neg_prompt_embeds_2 = pipe.text_encoder_2(neg_token_tensor_2.to(pipe.device), output_hidden_states=True)
368
+ neg_prompt_embeds_2_hidden_states = neg_prompt_embeds_2.hidden_states[-2]
369
+ negative_pooled_prompt_embeds = neg_prompt_embeds_2[0]
370
+
371
+ neg_prompt_embeds_list = [neg_prompt_embeds_1_hidden_states, neg_prompt_embeds_2_hidden_states]
372
+ neg_token_embedding = torch.concat(neg_prompt_embeds_list, dim=-1).squeeze(0)
373
+
374
+ for z in range(len(neg_weight_tensor)):
375
+ if neg_weight_tensor[z] != 1.0:
376
+ neg_token_embedding[z] = (
377
+ neg_token_embedding[-1] + (neg_token_embedding[z] - neg_token_embedding[-1]) * neg_weight_tensor[z]
378
+ )
379
+
380
+ neg_token_embedding = neg_token_embedding.unsqueeze(0)
381
+ neg_embeds.append(neg_token_embedding)
382
+
383
+ prompt_embeds = torch.cat(embeds, dim=1)
384
+ negative_prompt_embeds = torch.cat(neg_embeds, dim=1)
385
+
386
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
387
+
388
+
389
+ # -------------------------------------------------------------------------------------------------------------------------------
390
+ # reuse the backbone code from StableDiffusionXLPipeline
391
+ # -------------------------------------------------------------------------------------------------------------------------------
392
+
393
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
394
+
395
+ EXAMPLE_DOC_STRING = """
396
+ Examples:
397
+ ```py
398
+ from diffusers import DiffusionPipeline
399
+ import torch
400
+
401
+ pipe = DiffusionPipeline.from_pretrained(
402
+ "stabilityai/stable-diffusion-xl-base-1.0"
403
+ , torch_dtype = torch.float16
404
+ , use_safetensors = True
405
+ , variant = "fp16"
406
+ , custom_pipeline = "lpw_stable_diffusion_xl",
407
+ )
408
+
409
+ prompt = "a white cat running on the grass"*20
410
+ prompt2 = "play a football"*20
411
+ prompt = f"{prompt},{prompt2}"
412
+ neg_prompt = "blur, low quality"
413
+
414
+ pipe.to("cuda")
415
+ images = pipe(
416
+ prompt = prompt
417
+ , negative_prompt = neg_prompt
418
+ ).images[0]
419
+
420
+ pipe.to("cpu")
421
+ torch.cuda.empty_cache()
422
+ images
423
+ ```
424
+ """
425
+
426
+
427
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
428
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
429
+ """
430
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
431
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
432
+ """
433
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
434
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
435
+ # rescale the results from guidance (fixes overexposure)
436
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
437
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
438
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
439
+ return noise_cfg
440
+
441
+
442
+ class SDXLLongPromptWeightingPipeline(DiffusionPipeline, FromSingleFileMixin, LoraLoaderMixin):
443
+ r"""
444
+ Pipeline for text-to-image generation using Stable Diffusion XL.
445
+
446
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
447
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
448
+
449
+ In addition the pipeline inherits the following loading methods:
450
+ - *LoRA*: [`StableDiffusionXLPipeline.load_lora_weights`]
451
+ - *Ckpt*: [`loaders.FromSingleFileMixin.from_single_file`]
452
+
453
+ as well as the following saving methods:
454
+ - *LoRA*: [`loaders.StableDiffusionXLPipeline.save_lora_weights`]
455
+
456
+ Args:
457
+ vae ([`AutoencoderKL`]):
458
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
459
+ text_encoder ([`CLIPTextModel`]):
460
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
461
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
462
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
463
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
464
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
465
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
466
+ specifically the
467
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
468
+ variant.
469
+ tokenizer (`CLIPTokenizer`):
470
+ Tokenizer of class
471
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
472
+ tokenizer_2 (`CLIPTokenizer`):
473
+ Second Tokenizer of class
474
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
475
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
476
+ scheduler ([`SchedulerMixin`]):
477
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
478
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
479
+ """
480
+
481
+ def __init__(
482
+ self,
483
+ vae: AutoencoderKL,
484
+ text_encoder: CLIPTextModel,
485
+ text_encoder_2: CLIPTextModelWithProjection,
486
+ tokenizer: CLIPTokenizer,
487
+ tokenizer_2: CLIPTokenizer,
488
+ unet: UNet2DConditionModel,
489
+ scheduler: KarrasDiffusionSchedulers,
490
+ force_zeros_for_empty_prompt: bool = True,
491
+ add_watermarker: Optional[bool] = None,
492
+ ):
493
+ super().__init__()
494
+
495
+ self.register_modules(
496
+ vae=vae,
497
+ text_encoder=text_encoder,
498
+ text_encoder_2=text_encoder_2,
499
+ tokenizer=tokenizer,
500
+ tokenizer_2=tokenizer_2,
501
+ unet=unet,
502
+ scheduler=scheduler,
503
+ )
504
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
505
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
506
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
507
+ self.default_sample_size = self.unet.config.sample_size
508
+
509
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
510
+
511
+ if add_watermarker:
512
+ self.watermark = StableDiffusionXLWatermarker()
513
+ else:
514
+ self.watermark = None
515
+
516
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing
517
+ def enable_vae_slicing(self):
518
+ r"""
519
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
520
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
521
+ """
522
+ self.vae.enable_slicing()
523
+
524
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing
525
+ def disable_vae_slicing(self):
526
+ r"""
527
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
528
+ computing decoding in one step.
529
+ """
530
+ self.vae.disable_slicing()
531
+
532
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling
533
+ def enable_vae_tiling(self):
534
+ r"""
535
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
536
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
537
+ processing larger images.
538
+ """
539
+ self.vae.enable_tiling()
540
+
541
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling
542
+ def disable_vae_tiling(self):
543
+ r"""
544
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
545
+ computing decoding in one step.
546
+ """
547
+ self.vae.disable_tiling()
548
+
549
+ def enable_model_cpu_offload(self, gpu_id=0):
550
+ r"""
551
+ Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
552
+ to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
553
+ method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
554
+ `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
555
+ """
556
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
557
+ from accelerate import cpu_offload_with_hook
558
+ else:
559
+ raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")
560
+
561
+ device = torch.device(f"cuda:{gpu_id}")
562
+
563
+ if self.device.type != "cpu":
564
+ self.to("cpu", silence_dtype_warnings=True)
565
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
566
+
567
+ model_sequence = (
568
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
569
+ )
570
+ model_sequence.extend([self.unet, self.vae])
571
+
572
+ hook = None
573
+ for cpu_offloaded_model in model_sequence:
574
+ _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
575
+
576
+ # We'll offload the last model manually.
577
+ self.final_offload_hook = hook
578
+
579
+ def encode_prompt(
580
+ self,
581
+ prompt: str,
582
+ prompt_2: Optional[str] = None,
583
+ device: Optional[torch.device] = None,
584
+ num_images_per_prompt: int = 1,
585
+ do_classifier_free_guidance: bool = True,
586
+ negative_prompt: Optional[str] = None,
587
+ negative_prompt_2: Optional[str] = None,
588
+ prompt_embeds: Optional[torch.FloatTensor] = None,
589
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
590
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
591
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
592
+ lora_scale: Optional[float] = None,
593
+ ):
594
+ r"""
595
+ Encodes the prompt into text encoder hidden states.
596
+
597
+ Args:
598
+ prompt (`str` or `List[str]`, *optional*):
599
+ prompt to be encoded
600
+ prompt_2 (`str` or `List[str]`, *optional*):
601
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
602
+ used in both text-encoders
603
+ device: (`torch.device`):
604
+ torch device
605
+ num_images_per_prompt (`int`):
606
+ number of images that should be generated per prompt
607
+ do_classifier_free_guidance (`bool`):
608
+ whether to use classifier free guidance or not
609
+ negative_prompt (`str` or `List[str]`, *optional*):
610
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
611
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
612
+ less than `1`).
613
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
614
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
615
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
616
+ prompt_embeds (`torch.FloatTensor`, *optional*):
617
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
618
+ provided, text embeddings will be generated from `prompt` input argument.
619
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
620
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
621
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
622
+ argument.
623
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
624
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
625
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
626
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
627
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
628
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
629
+ input argument.
630
+ lora_scale (`float`, *optional*):
631
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
632
+ """
633
+ device = device or self._execution_device
634
+
635
+ # set lora scale so that monkey patched LoRA
636
+ # function of text encoder can correctly access it
637
+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):
638
+ self._lora_scale = lora_scale
639
+
640
+ if prompt is not None and isinstance(prompt, str):
641
+ batch_size = 1
642
+ elif prompt is not None and isinstance(prompt, list):
643
+ batch_size = len(prompt)
644
+ else:
645
+ batch_size = prompt_embeds.shape[0]
646
+
647
+ # Define tokenizers and text encoders
648
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
649
+ text_encoders = (
650
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
651
+ )
652
+
653
+ if prompt_embeds is None:
654
+ prompt_2 = prompt_2 or prompt
655
+ # textual inversion: procecss multi-vector tokens if necessary
656
+ prompt_embeds_list = []
657
+ prompts = [prompt, prompt_2]
658
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
659
+ if isinstance(self, TextualInversionLoaderMixin):
660
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
661
+
662
+ text_inputs = tokenizer(
663
+ prompt,
664
+ padding="max_length",
665
+ max_length=tokenizer.model_max_length,
666
+ truncation=True,
667
+ return_tensors="pt",
668
+ )
669
+
670
+ text_input_ids = text_inputs.input_ids
671
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
672
+
673
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
674
+ text_input_ids, untruncated_ids
675
+ ):
676
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
677
+ logger.warning(
678
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
679
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
680
+ )
681
+
682
+ prompt_embeds = text_encoder(
683
+ text_input_ids.to(device),
684
+ output_hidden_states=True,
685
+ )
686
+
687
+ # We are only ALWAYS interested in the pooled output of the final text encoder
688
+ pooled_prompt_embeds = prompt_embeds[0]
689
+ prompt_embeds = prompt_embeds.hidden_states[-2]
690
+
691
+ prompt_embeds_list.append(prompt_embeds)
692
+
693
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
694
+
695
+ # get unconditional embeddings for classifier free guidance
696
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
697
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
698
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
699
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
700
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
701
+ negative_prompt = negative_prompt or ""
702
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
703
+
704
+ uncond_tokens: List[str]
705
+ if prompt is not None and type(prompt) is not type(negative_prompt):
706
+ raise TypeError(
707
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
708
+ f" {type(prompt)}."
709
+ )
710
+ elif isinstance(negative_prompt, str):
711
+ uncond_tokens = [negative_prompt, negative_prompt_2]
712
+ elif batch_size != len(negative_prompt):
713
+ raise ValueError(
714
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
715
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
716
+ " the batch size of `prompt`."
717
+ )
718
+ else:
719
+ uncond_tokens = [negative_prompt, negative_prompt_2]
720
+
721
+ negative_prompt_embeds_list = []
722
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
723
+ if isinstance(self, TextualInversionLoaderMixin):
724
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
725
+
726
+ max_length = prompt_embeds.shape[1]
727
+ uncond_input = tokenizer(
728
+ negative_prompt,
729
+ padding="max_length",
730
+ max_length=max_length,
731
+ truncation=True,
732
+ return_tensors="pt",
733
+ )
734
+
735
+ negative_prompt_embeds = text_encoder(
736
+ uncond_input.input_ids.to(device),
737
+ output_hidden_states=True,
738
+ )
739
+ # We are only ALWAYS interested in the pooled output of the final text encoder
740
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
741
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
742
+
743
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
744
+
745
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
746
+
747
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
748
+ bs_embed, seq_len, _ = prompt_embeds.shape
749
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
750
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
751
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
752
+
753
+ if do_classifier_free_guidance:
754
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
755
+ seq_len = negative_prompt_embeds.shape[1]
756
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
757
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
758
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
759
+
760
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
761
+ bs_embed * num_images_per_prompt, -1
762
+ )
763
+ if do_classifier_free_guidance:
764
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
765
+ bs_embed * num_images_per_prompt, -1
766
+ )
767
+
768
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
769
+
770
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
771
+ def prepare_extra_step_kwargs(self, generator, eta):
772
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
773
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
774
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
775
+ # and should be between [0, 1]
776
+
777
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
778
+ extra_step_kwargs = {}
779
+ if accepts_eta:
780
+ extra_step_kwargs["eta"] = eta
781
+
782
+ # check if the scheduler accepts generator
783
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
784
+ if accepts_generator:
785
+ extra_step_kwargs["generator"] = generator
786
+ return extra_step_kwargs
787
+
788
+ def check_inputs(
789
+ self,
790
+ prompt,
791
+ prompt_2,
792
+ height,
793
+ width,
794
+ callback_steps,
795
+ negative_prompt=None,
796
+ negative_prompt_2=None,
797
+ prompt_embeds=None,
798
+ negative_prompt_embeds=None,
799
+ pooled_prompt_embeds=None,
800
+ negative_pooled_prompt_embeds=None,
801
+ ):
802
+ if height % 8 != 0 or width % 8 != 0:
803
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
804
+
805
+ if (callback_steps is None) or (
806
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
807
+ ):
808
+ raise ValueError(
809
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
810
+ f" {type(callback_steps)}."
811
+ )
812
+
813
+ if prompt is not None and prompt_embeds is not None:
814
+ raise ValueError(
815
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
816
+ " only forward one of the two."
817
+ )
818
+ elif prompt_2 is not None and prompt_embeds is not None:
819
+ raise ValueError(
820
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
821
+ " only forward one of the two."
822
+ )
823
+ elif prompt is None and prompt_embeds is None:
824
+ raise ValueError(
825
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
826
+ )
827
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
828
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
829
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
830
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
831
+
832
+ if negative_prompt is not None and negative_prompt_embeds is not None:
833
+ raise ValueError(
834
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
835
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
836
+ )
837
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
838
+ raise ValueError(
839
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
840
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
841
+ )
842
+
843
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
844
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
845
+ raise ValueError(
846
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
847
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
848
+ f" {negative_prompt_embeds.shape}."
849
+ )
850
+
851
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
852
+ raise ValueError(
853
+ "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
854
+ )
855
+
856
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
857
+ raise ValueError(
858
+ "If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
859
+ )
860
+
861
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
862
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
863
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
864
+ if isinstance(generator, list) and len(generator) != batch_size:
865
+ raise ValueError(
866
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
867
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
868
+ )
869
+
870
+ if latents is None:
871
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
872
+ else:
873
+ latents = latents.to(device)
874
+
875
+ # scale the initial noise by the standard deviation required by the scheduler
876
+ latents = latents * self.scheduler.init_noise_sigma
877
+ return latents
878
+
879
+ def _get_add_time_ids(self, original_size, crops_coords_top_left, target_size, dtype):
880
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
881
+
882
+ passed_add_embed_dim = (
883
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + self.text_encoder_2.config.projection_dim
884
+ )
885
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
886
+
887
+ if expected_add_embed_dim != passed_add_embed_dim:
888
+ raise ValueError(
889
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
890
+ )
891
+
892
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
893
+ return add_time_ids
894
+
895
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
896
+ def upcast_vae(self):
897
+ dtype = self.vae.dtype
898
+ self.vae.to(dtype=torch.float32)
899
+ use_torch_2_0_or_xformers = isinstance(
900
+ self.vae.decoder.mid_block.attentions[0].processor,
901
+ (
902
+ AttnProcessor2_0,
903
+ XFormersAttnProcessor,
904
+ LoRAXFormersAttnProcessor,
905
+ LoRAAttnProcessor2_0,
906
+ ),
907
+ )
908
+ # if xformers or torch_2_0 is used attention block does not need
909
+ # to be in float32 which can save lots of memory
910
+ if use_torch_2_0_or_xformers:
911
+ self.vae.post_quant_conv.to(dtype)
912
+ self.vae.decoder.conv_in.to(dtype)
913
+ self.vae.decoder.mid_block.to(dtype)
914
+
915
+ @torch.no_grad()
916
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
917
+ def __call__(
918
+ self,
919
+ prompt: str = None,
920
+ prompt_2: Optional[str] = None,
921
+ height: Optional[int] = None,
922
+ width: Optional[int] = None,
923
+ num_inference_steps: int = 50,
924
+ denoising_end: Optional[float] = None,
925
+ guidance_scale: float = 5.0,
926
+ negative_prompt: Optional[str] = None,
927
+ negative_prompt_2: Optional[str] = None,
928
+ num_images_per_prompt: Optional[int] = 1,
929
+ eta: float = 0.0,
930
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
931
+ latents: Optional[torch.FloatTensor] = None,
932
+ prompt_embeds: Optional[torch.FloatTensor] = None,
933
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
934
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
935
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
936
+ output_type: Optional[str] = "pil",
937
+ return_dict: bool = True,
938
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
939
+ callback_steps: int = 1,
940
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
941
+ guidance_rescale: float = 0.0,
942
+ original_size: Optional[Tuple[int, int]] = None,
943
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
944
+ target_size: Optional[Tuple[int, int]] = None,
945
+ ):
946
+ r"""
947
+ Function invoked when calling the pipeline for generation.
948
+
949
+ Args:
950
+ prompt (`str`):
951
+ The prompt to guide the image generation. If not defined, one has to pass `prompt_embeds`.
952
+ instead.
953
+ prompt_2 (`str`):
954
+ The prompt to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
955
+ used in both text-encoders
956
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
957
+ The height in pixels of the generated image.
958
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
959
+ The width in pixels of the generated image.
960
+ num_inference_steps (`int`, *optional*, defaults to 50):
961
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
962
+ expense of slower inference.
963
+ denoising_end (`float`, *optional*):
964
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
965
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
966
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
967
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
968
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
969
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
970
+ guidance_scale (`float`, *optional*, defaults to 5.0):
971
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
972
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
973
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
974
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
975
+ usually at the expense of lower image quality.
976
+ negative_prompt (`str`):
977
+ The prompt not to guide the image generation. If not defined, one has to pass
978
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
979
+ less than `1`).
980
+ negative_prompt_2 (`str`):
981
+ The prompt not to guide the image generation to be sent to `tokenizer_2` and
982
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
983
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
984
+ The number of images to generate per prompt.
985
+ eta (`float`, *optional*, defaults to 0.0):
986
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
987
+ [`schedulers.DDIMScheduler`], will be ignored for others.
988
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
989
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
990
+ to make generation deterministic.
991
+ latents (`torch.FloatTensor`, *optional*):
992
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
993
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
994
+ tensor will ge generated by sampling using the supplied random `generator`.
995
+ prompt_embeds (`torch.FloatTensor`, *optional*):
996
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
997
+ provided, text embeddings will be generated from `prompt` input argument.
998
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
999
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1000
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
1001
+ argument.
1002
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
1003
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
1004
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
1005
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
1006
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1007
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
1008
+ input argument.
1009
+ output_type (`str`, *optional*, defaults to `"pil"`):
1010
+ The output format of the generate image. Choose between
1011
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1012
+ return_dict (`bool`, *optional*, defaults to `True`):
1013
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
1014
+ of a plain tuple.
1015
+ callback (`Callable`, *optional*):
1016
+ A function that will be called every `callback_steps` steps during inference. The function will be
1017
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
1018
+ callback_steps (`int`, *optional*, defaults to 1):
1019
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
1020
+ called at every step.
1021
+ cross_attention_kwargs (`dict`, *optional*):
1022
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1023
+ `self.processor` in
1024
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1025
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
1026
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
1027
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
1028
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
1029
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
1030
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1031
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
1032
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
1033
+ explained in section 2.2 of
1034
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1035
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1036
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
1037
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
1038
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
1039
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1040
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1041
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
1042
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
1043
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1044
+
1045
+ Examples:
1046
+
1047
+ Returns:
1048
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
1049
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
1050
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
1051
+ """
1052
+ # 0. Default height and width to unet
1053
+ height = height or self.default_sample_size * self.vae_scale_factor
1054
+ width = width or self.default_sample_size * self.vae_scale_factor
1055
+
1056
+ original_size = original_size or (height, width)
1057
+ target_size = target_size or (height, width)
1058
+
1059
+ # 1. Check inputs. Raise error if not correct
1060
+ self.check_inputs(
1061
+ prompt,
1062
+ prompt_2,
1063
+ height,
1064
+ width,
1065
+ callback_steps,
1066
+ negative_prompt,
1067
+ negative_prompt_2,
1068
+ prompt_embeds,
1069
+ negative_prompt_embeds,
1070
+ pooled_prompt_embeds,
1071
+ negative_pooled_prompt_embeds,
1072
+ )
1073
+
1074
+ # 2. Define call parameters
1075
+ if prompt is not None and isinstance(prompt, str):
1076
+ batch_size = 1
1077
+ elif prompt is not None and isinstance(prompt, list):
1078
+ batch_size = len(prompt)
1079
+ else:
1080
+ batch_size = prompt_embeds.shape[0]
1081
+
1082
+ device = self._execution_device
1083
+
1084
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1085
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1086
+ # corresponds to doing no classifier free guidance.
1087
+ do_classifier_free_guidance = guidance_scale > 1.0
1088
+
1089
+ # 3. Encode input prompt
1090
+ (cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None)
1091
+
1092
+ negative_prompt = negative_prompt if negative_prompt is not None else ""
1093
+
1094
+ (
1095
+ prompt_embeds,
1096
+ negative_prompt_embeds,
1097
+ pooled_prompt_embeds,
1098
+ negative_pooled_prompt_embeds,
1099
+ ) = get_weighted_text_embeddings_sdxl(pipe=self, prompt=prompt, neg_prompt=negative_prompt)
1100
+
1101
+ # 4. Prepare timesteps
1102
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
1103
+
1104
+ timesteps = self.scheduler.timesteps
1105
+
1106
+ # 5. Prepare latent variables
1107
+ num_channels_latents = self.unet.config.in_channels
1108
+ latents = self.prepare_latents(
1109
+ batch_size * num_images_per_prompt,
1110
+ num_channels_latents,
1111
+ height,
1112
+ width,
1113
+ prompt_embeds.dtype,
1114
+ device,
1115
+ generator,
1116
+ latents,
1117
+ )
1118
+
1119
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1120
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1121
+
1122
+ # 7. Prepare added time ids & embeddings
1123
+ add_text_embeds = pooled_prompt_embeds
1124
+ add_time_ids = self._get_add_time_ids(
1125
+ original_size, crops_coords_top_left, target_size, dtype=prompt_embeds.dtype
1126
+ )
1127
+
1128
+ if do_classifier_free_guidance:
1129
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1130
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1131
+ add_time_ids = torch.cat([add_time_ids, add_time_ids], dim=0)
1132
+
1133
+ prompt_embeds = prompt_embeds.to(device)
1134
+ add_text_embeds = add_text_embeds.to(device)
1135
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
1136
+
1137
+ # 8. Denoising loop
1138
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1139
+
1140
+ # 7.1 Apply denoising_end
1141
+ if denoising_end is not None and isinstance(denoising_end, float) and denoising_end > 0 and denoising_end < 1:
1142
+ discrete_timestep_cutoff = int(
1143
+ round(
1144
+ self.scheduler.config.num_train_timesteps
1145
+ - (denoising_end * self.scheduler.config.num_train_timesteps)
1146
+ )
1147
+ )
1148
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1149
+ timesteps = timesteps[:num_inference_steps]
1150
+
1151
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1152
+ for i, t in enumerate(timesteps):
1153
+ # expand the latents if we are doing classifier free guidance
1154
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
1155
+
1156
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1157
+
1158
+ # predict the noise residual
1159
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1160
+ noise_pred = self.unet(
1161
+ latent_model_input,
1162
+ t,
1163
+ encoder_hidden_states=prompt_embeds,
1164
+ cross_attention_kwargs=cross_attention_kwargs,
1165
+ added_cond_kwargs=added_cond_kwargs,
1166
+ return_dict=False,
1167
+ )[0]
1168
+
1169
+ # perform guidance
1170
+ if do_classifier_free_guidance:
1171
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1172
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1173
+
1174
+ if do_classifier_free_guidance and guidance_rescale > 0.0:
1175
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1176
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
1177
+
1178
+ # compute the previous noisy sample x_t -> x_t-1
1179
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1180
+
1181
+ # call the callback, if provided
1182
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1183
+ progress_bar.update()
1184
+ if callback is not None and i % callback_steps == 0:
1185
+ step_idx = i // getattr(self.scheduler, "order", 1)
1186
+ callback(step_idx, t, latents)
1187
+
1188
+ if not output_type == "latent":
1189
+ # make sure the VAE is in float32 mode, as it overflows in float16
1190
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1191
+
1192
+ if needs_upcasting:
1193
+ self.upcast_vae()
1194
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1195
+
1196
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1197
+
1198
+ # cast back to fp16 if needed
1199
+ if needs_upcasting:
1200
+ self.vae.to(dtype=torch.float16)
1201
+ else:
1202
+ image = latents
1203
+ return StableDiffusionXLPipelineOutput(images=image)
1204
+
1205
+ # apply watermark if available
1206
+ if self.watermark is not None:
1207
+ image = self.watermark.apply_watermark(image)
1208
+
1209
+ image = self.image_processor.postprocess(image, output_type=output_type)
1210
+
1211
+ # Offload last model to CPU
1212
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
1213
+ self.final_offload_hook.offload()
1214
+
1215
+ if not return_dict:
1216
+ return (image,)
1217
+
1218
+ return StableDiffusionXLPipelineOutput(images=image)
1219
+
1220
+ # Overrride to properly handle the loading and unloading of the additional text encoder.
1221
+ def load_lora_weights(self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], **kwargs):
1222
+ # We could have accessed the unet config from `lora_state_dict()` too. We pass
1223
+ # it here explicitly to be able to tell that it's coming from an SDXL
1224
+ # pipeline.
1225
+ state_dict, network_alphas = self.lora_state_dict(
1226
+ pretrained_model_name_or_path_or_dict,
1227
+ unet_config=self.unet.config,
1228
+ **kwargs,
1229
+ )
1230
+ self.load_lora_into_unet(state_dict, network_alphas=network_alphas, unet=self.unet)
1231
+
1232
+ text_encoder_state_dict = {k: v for k, v in state_dict.items() if "text_encoder." in k}
1233
+ if len(text_encoder_state_dict) > 0:
1234
+ self.load_lora_into_text_encoder(
1235
+ text_encoder_state_dict,
1236
+ network_alphas=network_alphas,
1237
+ text_encoder=self.text_encoder,
1238
+ prefix="text_encoder",
1239
+ lora_scale=self.lora_scale,
1240
+ )
1241
+
1242
+ text_encoder_2_state_dict = {k: v for k, v in state_dict.items() if "text_encoder_2." in k}
1243
+ if len(text_encoder_2_state_dict) > 0:
1244
+ self.load_lora_into_text_encoder(
1245
+ text_encoder_2_state_dict,
1246
+ network_alphas=network_alphas,
1247
+ text_encoder=self.text_encoder_2,
1248
+ prefix="text_encoder_2",
1249
+ lora_scale=self.lora_scale,
1250
+ )
1251
+
1252
+ @classmethod
1253
+ def save_lora_weights(
1254
+ self,
1255
+ save_directory: Union[str, os.PathLike],
1256
+ unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1257
+ text_encoder_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1258
+ text_encoder_2_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1259
+ is_main_process: bool = True,
1260
+ weight_name: str = None,
1261
+ save_function: Callable = None,
1262
+ safe_serialization: bool = False,
1263
+ ):
1264
+ state_dict = {}
1265
+
1266
+ def pack_weights(layers, prefix):
1267
+ layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
1268
+ layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
1269
+ return layers_state_dict
1270
+
1271
+ state_dict.update(pack_weights(unet_lora_layers, "unet"))
1272
+
1273
+ if text_encoder_lora_layers and text_encoder_2_lora_layers:
1274
+ state_dict.update(pack_weights(text_encoder_lora_layers, "text_encoder"))
1275
+ state_dict.update(pack_weights(text_encoder_2_lora_layers, "text_encoder_2"))
1276
+
1277
+ self.write_lora_layers(
1278
+ state_dict=state_dict,
1279
+ save_directory=save_directory,
1280
+ is_main_process=is_main_process,
1281
+ weight_name=weight_name,
1282
+ save_function=save_function,
1283
+ safe_serialization=safe_serialization,
1284
+ )
1285
+
1286
+ def _remove_text_encoder_monkey_patch(self):
1287
+ self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder)
1288
+ self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder_2)
v0.22.0/magic_mix.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union
2
+
3
+ import torch
4
+ from PIL import Image
5
+ from torchvision import transforms as tfms
6
+ from tqdm.auto import tqdm
7
+ from transformers import CLIPTextModel, CLIPTokenizer
8
+
9
+ from diffusers import (
10
+ AutoencoderKL,
11
+ DDIMScheduler,
12
+ DiffusionPipeline,
13
+ LMSDiscreteScheduler,
14
+ PNDMScheduler,
15
+ UNet2DConditionModel,
16
+ )
17
+
18
+
19
+ class MagicMixPipeline(DiffusionPipeline):
20
+ def __init__(
21
+ self,
22
+ vae: AutoencoderKL,
23
+ text_encoder: CLIPTextModel,
24
+ tokenizer: CLIPTokenizer,
25
+ unet: UNet2DConditionModel,
26
+ scheduler: Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler],
27
+ ):
28
+ super().__init__()
29
+
30
+ self.register_modules(vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, unet=unet, scheduler=scheduler)
31
+
32
+ # convert PIL image to latents
33
+ def encode(self, img):
34
+ with torch.no_grad():
35
+ latent = self.vae.encode(tfms.ToTensor()(img).unsqueeze(0).to(self.device) * 2 - 1)
36
+ latent = 0.18215 * latent.latent_dist.sample()
37
+ return latent
38
+
39
+ # convert latents to PIL image
40
+ def decode(self, latent):
41
+ latent = (1 / 0.18215) * latent
42
+ with torch.no_grad():
43
+ img = self.vae.decode(latent).sample
44
+ img = (img / 2 + 0.5).clamp(0, 1)
45
+ img = img.detach().cpu().permute(0, 2, 3, 1).numpy()
46
+ img = (img * 255).round().astype("uint8")
47
+ return Image.fromarray(img[0])
48
+
49
+ # convert prompt into text embeddings, also unconditional embeddings
50
+ def prep_text(self, prompt):
51
+ text_input = self.tokenizer(
52
+ prompt,
53
+ padding="max_length",
54
+ max_length=self.tokenizer.model_max_length,
55
+ truncation=True,
56
+ return_tensors="pt",
57
+ )
58
+
59
+ text_embedding = self.text_encoder(text_input.input_ids.to(self.device))[0]
60
+
61
+ uncond_input = self.tokenizer(
62
+ "",
63
+ padding="max_length",
64
+ max_length=self.tokenizer.model_max_length,
65
+ truncation=True,
66
+ return_tensors="pt",
67
+ )
68
+
69
+ uncond_embedding = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
70
+
71
+ return torch.cat([uncond_embedding, text_embedding])
72
+
73
+ def __call__(
74
+ self,
75
+ img: Image.Image,
76
+ prompt: str,
77
+ kmin: float = 0.3,
78
+ kmax: float = 0.6,
79
+ mix_factor: float = 0.5,
80
+ seed: int = 42,
81
+ steps: int = 50,
82
+ guidance_scale: float = 7.5,
83
+ ) -> Image.Image:
84
+ tmin = steps - int(kmin * steps)
85
+ tmax = steps - int(kmax * steps)
86
+
87
+ text_embeddings = self.prep_text(prompt)
88
+
89
+ self.scheduler.set_timesteps(steps)
90
+
91
+ width, height = img.size
92
+ encoded = self.encode(img)
93
+
94
+ torch.manual_seed(seed)
95
+ noise = torch.randn(
96
+ (1, self.unet.config.in_channels, height // 8, width // 8),
97
+ ).to(self.device)
98
+
99
+ latents = self.scheduler.add_noise(
100
+ encoded,
101
+ noise,
102
+ timesteps=self.scheduler.timesteps[tmax],
103
+ )
104
+
105
+ input = torch.cat([latents] * 2)
106
+
107
+ input = self.scheduler.scale_model_input(input, self.scheduler.timesteps[tmax])
108
+
109
+ with torch.no_grad():
110
+ pred = self.unet(
111
+ input,
112
+ self.scheduler.timesteps[tmax],
113
+ encoder_hidden_states=text_embeddings,
114
+ ).sample
115
+
116
+ pred_uncond, pred_text = pred.chunk(2)
117
+ pred = pred_uncond + guidance_scale * (pred_text - pred_uncond)
118
+
119
+ latents = self.scheduler.step(pred, self.scheduler.timesteps[tmax], latents).prev_sample
120
+
121
+ for i, t in enumerate(tqdm(self.scheduler.timesteps)):
122
+ if i > tmax:
123
+ if i < tmin: # layout generation phase
124
+ orig_latents = self.scheduler.add_noise(
125
+ encoded,
126
+ noise,
127
+ timesteps=t,
128
+ )
129
+
130
+ input = (mix_factor * latents) + (
131
+ 1 - mix_factor
132
+ ) * orig_latents # interpolating between layout noise and conditionally generated noise to preserve layout sematics
133
+ input = torch.cat([input] * 2)
134
+
135
+ else: # content generation phase
136
+ input = torch.cat([latents] * 2)
137
+
138
+ input = self.scheduler.scale_model_input(input, t)
139
+
140
+ with torch.no_grad():
141
+ pred = self.unet(
142
+ input,
143
+ t,
144
+ encoder_hidden_states=text_embeddings,
145
+ ).sample
146
+
147
+ pred_uncond, pred_text = pred.chunk(2)
148
+ pred = pred_uncond + guidance_scale * (pred_text - pred_uncond)
149
+
150
+ latents = self.scheduler.step(pred, t, latents).prev_sample
151
+
152
+ return self.decode(latents)
v0.22.0/masked_stable_diffusion_img2img.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, Dict, List, Optional, Union
2
+
3
+ import numpy as np
4
+ import PIL.Image
5
+ import torch
6
+
7
+ from diffusers import StableDiffusionImg2ImgPipeline
8
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
9
+
10
+
11
+ class MaskedStableDiffusionImg2ImgPipeline(StableDiffusionImg2ImgPipeline):
12
+ debug_save = False
13
+
14
+ @torch.no_grad()
15
+ def __call__(
16
+ self,
17
+ prompt: Union[str, List[str]] = None,
18
+ image: Union[
19
+ torch.FloatTensor,
20
+ PIL.Image.Image,
21
+ np.ndarray,
22
+ List[torch.FloatTensor],
23
+ List[PIL.Image.Image],
24
+ List[np.ndarray],
25
+ ] = None,
26
+ strength: float = 0.8,
27
+ num_inference_steps: Optional[int] = 50,
28
+ guidance_scale: Optional[float] = 7.5,
29
+ negative_prompt: Optional[Union[str, List[str]]] = None,
30
+ num_images_per_prompt: Optional[int] = 1,
31
+ eta: Optional[float] = 0.0,
32
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
33
+ prompt_embeds: Optional[torch.FloatTensor] = None,
34
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
35
+ output_type: Optional[str] = "pil",
36
+ return_dict: bool = True,
37
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
38
+ callback_steps: int = 1,
39
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
40
+ mask: Union[
41
+ torch.FloatTensor,
42
+ PIL.Image.Image,
43
+ np.ndarray,
44
+ List[torch.FloatTensor],
45
+ List[PIL.Image.Image],
46
+ List[np.ndarray],
47
+ ] = None,
48
+ ):
49
+ r"""
50
+ The call function to the pipeline for generation.
51
+
52
+ Args:
53
+ prompt (`str` or `List[str]`, *optional*):
54
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
55
+ image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
56
+ `Image` or tensor representing an image batch to be used as the starting point. Can also accept image
57
+ latents as `image`, but if passing latents directly it is not encoded again.
58
+ strength (`float`, *optional*, defaults to 0.8):
59
+ Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
60
+ starting point and more noise is added the higher the `strength`. The number of denoising steps depends
61
+ on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
62
+ process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
63
+ essentially ignores `image`.
64
+ num_inference_steps (`int`, *optional*, defaults to 50):
65
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
66
+ expense of slower inference. This parameter is modulated by `strength`.
67
+ guidance_scale (`float`, *optional*, defaults to 7.5):
68
+ A higher guidance scale value encourages the model to generate images closely linked to the text
69
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
70
+ negative_prompt (`str` or `List[str]`, *optional*):
71
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
72
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
73
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
74
+ The number of images to generate per prompt.
75
+ eta (`float`, *optional*, defaults to 0.0):
76
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
77
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
78
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
79
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
80
+ generation deterministic.
81
+ prompt_embeds (`torch.FloatTensor`, *optional*):
82
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
83
+ provided, text embeddings are generated from the `prompt` input argument.
84
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
85
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
86
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
87
+ output_type (`str`, *optional*, defaults to `"pil"`):
88
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
89
+ return_dict (`bool`, *optional*, defaults to `True`):
90
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
91
+ plain tuple.
92
+ callback (`Callable`, *optional*):
93
+ A function that calls every `callback_steps` steps during inference. The function is called with the
94
+ following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
95
+ callback_steps (`int`, *optional*, defaults to 1):
96
+ The frequency at which the `callback` function is called. If not specified, the callback is called at
97
+ every step.
98
+ cross_attention_kwargs (`dict`, *optional*):
99
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
100
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
101
+ mask (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`, *optional*):
102
+ A mask with non-zero elements for the area to be inpainted. If not specified, no mask is applied.
103
+ Examples:
104
+
105
+ Returns:
106
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
107
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
108
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
109
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
110
+ "not-safe-for-work" (nsfw) content.
111
+ """
112
+ # code adapted from parent class StableDiffusionImg2ImgPipeline
113
+
114
+ # 0. Check inputs. Raise error if not correct
115
+ self.check_inputs(prompt, strength, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds)
116
+
117
+ # 1. Define call parameters
118
+ if prompt is not None and isinstance(prompt, str):
119
+ batch_size = 1
120
+ elif prompt is not None and isinstance(prompt, list):
121
+ batch_size = len(prompt)
122
+ else:
123
+ batch_size = prompt_embeds.shape[0]
124
+ device = self._execution_device
125
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
126
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
127
+ # corresponds to doing no classifier free guidance.
128
+ do_classifier_free_guidance = guidance_scale > 1.0
129
+
130
+ # 2. Encode input prompt
131
+ text_encoder_lora_scale = (
132
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
133
+ )
134
+ prompt_embeds = self._encode_prompt(
135
+ prompt,
136
+ device,
137
+ num_images_per_prompt,
138
+ do_classifier_free_guidance,
139
+ negative_prompt,
140
+ prompt_embeds=prompt_embeds,
141
+ negative_prompt_embeds=negative_prompt_embeds,
142
+ lora_scale=text_encoder_lora_scale,
143
+ )
144
+
145
+ # 3. Preprocess image
146
+ image = self.image_processor.preprocess(image)
147
+
148
+ # 4. set timesteps
149
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
150
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
151
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
152
+
153
+ # 5. Prepare latent variables
154
+ # it is sampled from the latent distribution of the VAE
155
+ latents = self.prepare_latents(
156
+ image, latent_timestep, batch_size, num_images_per_prompt, prompt_embeds.dtype, device, generator
157
+ )
158
+
159
+ # mean of the latent distribution
160
+ init_latents = [
161
+ self.vae.encode(image.to(device=device, dtype=prompt_embeds.dtype)[i : i + 1]).latent_dist.mean
162
+ for i in range(batch_size)
163
+ ]
164
+ init_latents = torch.cat(init_latents, dim=0)
165
+
166
+ # 6. create latent mask
167
+ latent_mask = self._make_latent_mask(latents, mask)
168
+
169
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
170
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
171
+
172
+ # 8. Denoising loop
173
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
174
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
175
+ for i, t in enumerate(timesteps):
176
+ # expand the latents if we are doing classifier free guidance
177
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
178
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
179
+
180
+ # predict the noise residual
181
+ noise_pred = self.unet(
182
+ latent_model_input,
183
+ t,
184
+ encoder_hidden_states=prompt_embeds,
185
+ cross_attention_kwargs=cross_attention_kwargs,
186
+ return_dict=False,
187
+ )[0]
188
+
189
+ # perform guidance
190
+ if do_classifier_free_guidance:
191
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
192
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
193
+
194
+ if latent_mask is not None:
195
+ latents = torch.lerp(init_latents * self.vae.config.scaling_factor, latents, latent_mask)
196
+ noise_pred = torch.lerp(torch.zeros_like(noise_pred), noise_pred, latent_mask)
197
+
198
+ # compute the previous noisy sample x_t -> x_t-1
199
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
200
+
201
+ # call the callback, if provided
202
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
203
+ progress_bar.update()
204
+ if callback is not None and i % callback_steps == 0:
205
+ step_idx = i // getattr(self.scheduler, "order", 1)
206
+ callback(step_idx, t, latents)
207
+
208
+ if not output_type == "latent":
209
+ scaled = latents / self.vae.config.scaling_factor
210
+ if latent_mask is not None:
211
+ # scaled = latents / self.vae.config.scaling_factor * latent_mask + init_latents * (1 - latent_mask)
212
+ scaled = torch.lerp(init_latents, scaled, latent_mask)
213
+ image = self.vae.decode(scaled, return_dict=False)[0]
214
+ if self.debug_save:
215
+ image_gen = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
216
+ image_gen = self.image_processor.postprocess(image_gen, output_type=output_type, do_denormalize=[True])
217
+ image_gen[0].save("from_latent.png")
218
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
219
+ else:
220
+ image = latents
221
+ has_nsfw_concept = None
222
+
223
+ if has_nsfw_concept is None:
224
+ do_denormalize = [True] * image.shape[0]
225
+ else:
226
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
227
+
228
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
229
+
230
+ # Offload last model to CPU
231
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
232
+ self.final_offload_hook.offload()
233
+
234
+ if not return_dict:
235
+ return (image, has_nsfw_concept)
236
+
237
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
238
+
239
+ def _make_latent_mask(self, latents, mask):
240
+ if mask is not None:
241
+ latent_mask = []
242
+ if not isinstance(mask, list):
243
+ tmp_mask = [mask]
244
+ else:
245
+ tmp_mask = mask
246
+ _, l_channels, l_height, l_width = latents.shape
247
+ for m in tmp_mask:
248
+ if not isinstance(m, PIL.Image.Image):
249
+ if len(m.shape) == 2:
250
+ m = m[..., np.newaxis]
251
+ if m.max() > 1:
252
+ m = m / 255.0
253
+ m = self.image_processor.numpy_to_pil(m)[0]
254
+ if m.mode != "L":
255
+ m = m.convert("L")
256
+ resized = self.image_processor.resize(m, l_height, l_width)
257
+ if self.debug_save:
258
+ resized.save("latent_mask.png")
259
+ latent_mask.append(np.repeat(np.array(resized)[np.newaxis, :, :], l_channels, axis=0))
260
+ latent_mask = torch.as_tensor(np.stack(latent_mask)).to(latents)
261
+ latent_mask = latent_mask / latent_mask.max()
262
+ return latent_mask
v0.22.0/mixture_canvas.py ADDED
@@ -0,0 +1,503 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from copy import deepcopy
3
+ from dataclasses import asdict, dataclass
4
+ from enum import Enum
5
+ from typing import List, Optional, Union
6
+
7
+ import numpy as np
8
+ import torch
9
+ from numpy import exp, pi, sqrt
10
+ from torchvision.transforms.functional import resize
11
+ from tqdm.auto import tqdm
12
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
13
+
14
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
15
+ from diffusers.pipeline_utils import DiffusionPipeline
16
+ from diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker
17
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
18
+
19
+
20
+ def preprocess_image(image):
21
+ from PIL import Image
22
+
23
+ """Preprocess an input image
24
+
25
+ Same as
26
+ https://github.com/huggingface/diffusers/blob/1138d63b519e37f0ce04e027b9f4a3261d27c628/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py#L44
27
+ """
28
+ w, h = image.size
29
+ w, h = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32
30
+ image = image.resize((w, h), resample=Image.LANCZOS)
31
+ image = np.array(image).astype(np.float32) / 255.0
32
+ image = image[None].transpose(0, 3, 1, 2)
33
+ image = torch.from_numpy(image)
34
+ return 2.0 * image - 1.0
35
+
36
+
37
+ @dataclass
38
+ class CanvasRegion:
39
+ """Class defining a rectangular region in the canvas"""
40
+
41
+ row_init: int # Region starting row in pixel space (included)
42
+ row_end: int # Region end row in pixel space (not included)
43
+ col_init: int # Region starting column in pixel space (included)
44
+ col_end: int # Region end column in pixel space (not included)
45
+ region_seed: int = None # Seed for random operations in this region
46
+ noise_eps: float = 0.0 # Deviation of a zero-mean gaussian noise to be applied over the latents in this region. Useful for slightly "rerolling" latents
47
+
48
+ def __post_init__(self):
49
+ # Initialize arguments if not specified
50
+ if self.region_seed is None:
51
+ self.region_seed = np.random.randint(9999999999)
52
+ # Check coordinates are non-negative
53
+ for coord in [self.row_init, self.row_end, self.col_init, self.col_end]:
54
+ if coord < 0:
55
+ raise ValueError(
56
+ f"A CanvasRegion must be defined with non-negative indices, found ({self.row_init}, {self.row_end}, {self.col_init}, {self.col_end})"
57
+ )
58
+ # Check coordinates are divisible by 8, else we end up with nasty rounding error when mapping to latent space
59
+ for coord in [self.row_init, self.row_end, self.col_init, self.col_end]:
60
+ if coord // 8 != coord / 8:
61
+ raise ValueError(
62
+ f"A CanvasRegion must be defined with locations divisible by 8, found ({self.row_init}-{self.row_end}, {self.col_init}-{self.col_end})"
63
+ )
64
+ # Check noise eps is non-negative
65
+ if self.noise_eps < 0:
66
+ raise ValueError(f"A CanvasRegion must be defined noises eps non-negative, found {self.noise_eps}")
67
+ # Compute coordinates for this region in latent space
68
+ self.latent_row_init = self.row_init // 8
69
+ self.latent_row_end = self.row_end // 8
70
+ self.latent_col_init = self.col_init // 8
71
+ self.latent_col_end = self.col_end // 8
72
+
73
+ @property
74
+ def width(self):
75
+ return self.col_end - self.col_init
76
+
77
+ @property
78
+ def height(self):
79
+ return self.row_end - self.row_init
80
+
81
+ def get_region_generator(self, device="cpu"):
82
+ """Creates a torch.Generator based on the random seed of this region"""
83
+ # Initialize region generator
84
+ return torch.Generator(device).manual_seed(self.region_seed)
85
+
86
+ @property
87
+ def __dict__(self):
88
+ return asdict(self)
89
+
90
+
91
+ class MaskModes(Enum):
92
+ """Modes in which the influence of diffuser is masked"""
93
+
94
+ CONSTANT = "constant"
95
+ GAUSSIAN = "gaussian"
96
+ QUARTIC = "quartic" # See https://en.wikipedia.org/wiki/Kernel_(statistics)
97
+
98
+
99
+ @dataclass
100
+ class DiffusionRegion(CanvasRegion):
101
+ """Abstract class defining a region where some class of diffusion process is acting"""
102
+
103
+ pass
104
+
105
+
106
+ @dataclass
107
+ class Text2ImageRegion(DiffusionRegion):
108
+ """Class defining a region where a text guided diffusion process is acting"""
109
+
110
+ prompt: str = "" # Text prompt guiding the diffuser in this region
111
+ guidance_scale: float = 7.5 # Guidance scale of the diffuser in this region. If None, randomize
112
+ mask_type: MaskModes = MaskModes.GAUSSIAN.value # Kind of weight mask applied to this region
113
+ mask_weight: float = 1.0 # Global weights multiplier of the mask
114
+ tokenized_prompt = None # Tokenized prompt
115
+ encoded_prompt = None # Encoded prompt
116
+
117
+ def __post_init__(self):
118
+ super().__post_init__()
119
+ # Mask weight cannot be negative
120
+ if self.mask_weight < 0:
121
+ raise ValueError(
122
+ f"A Text2ImageRegion must be defined with non-negative mask weight, found {self.mask_weight}"
123
+ )
124
+ # Mask type must be an actual known mask
125
+ if self.mask_type not in [e.value for e in MaskModes]:
126
+ raise ValueError(
127
+ f"A Text2ImageRegion was defined with mask {self.mask_type}, which is not an accepted mask ({[e.value for e in MaskModes]})"
128
+ )
129
+ # Randomize arguments if given as None
130
+ if self.guidance_scale is None:
131
+ self.guidance_scale = np.random.randint(5, 30)
132
+ # Clean prompt
133
+ self.prompt = re.sub(" +", " ", self.prompt).replace("\n", " ")
134
+
135
+ def tokenize_prompt(self, tokenizer):
136
+ """Tokenizes the prompt for this diffusion region using a given tokenizer"""
137
+ self.tokenized_prompt = tokenizer(
138
+ self.prompt,
139
+ padding="max_length",
140
+ max_length=tokenizer.model_max_length,
141
+ truncation=True,
142
+ return_tensors="pt",
143
+ )
144
+
145
+ def encode_prompt(self, text_encoder, device):
146
+ """Encodes the previously tokenized prompt for this diffusion region using a given encoder"""
147
+ assert self.tokenized_prompt is not None, ValueError(
148
+ "Prompt in diffusion region must be tokenized before encoding"
149
+ )
150
+ self.encoded_prompt = text_encoder(self.tokenized_prompt.input_ids.to(device))[0]
151
+
152
+
153
+ @dataclass
154
+ class Image2ImageRegion(DiffusionRegion):
155
+ """Class defining a region where an image guided diffusion process is acting"""
156
+
157
+ reference_image: torch.FloatTensor = None
158
+ strength: float = 0.8 # Strength of the image
159
+
160
+ def __post_init__(self):
161
+ super().__post_init__()
162
+ if self.reference_image is None:
163
+ raise ValueError("Must provide a reference image when creating an Image2ImageRegion")
164
+ if self.strength < 0 or self.strength > 1:
165
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {self.strength}")
166
+ # Rescale image to region shape
167
+ self.reference_image = resize(self.reference_image, size=[self.height, self.width])
168
+
169
+ def encode_reference_image(self, encoder, device, generator, cpu_vae=False):
170
+ """Encodes the reference image for this Image2Image region into the latent space"""
171
+ # Place encoder in CPU or not following the parameter cpu_vae
172
+ if cpu_vae:
173
+ # Note here we use mean instead of sample, to avoid moving also generator to CPU, which is troublesome
174
+ self.reference_latents = encoder.cpu().encode(self.reference_image).latent_dist.mean.to(device)
175
+ else:
176
+ self.reference_latents = encoder.encode(self.reference_image.to(device)).latent_dist.sample(
177
+ generator=generator
178
+ )
179
+ self.reference_latents = 0.18215 * self.reference_latents
180
+
181
+ @property
182
+ def __dict__(self):
183
+ # This class requires special casting to dict because of the reference_image tensor. Otherwise it cannot be casted to JSON
184
+
185
+ # Get all basic fields from parent class
186
+ super_fields = {key: getattr(self, key) for key in DiffusionRegion.__dataclass_fields__.keys()}
187
+ # Pack other fields
188
+ return {**super_fields, "reference_image": self.reference_image.cpu().tolist(), "strength": self.strength}
189
+
190
+
191
+ class RerollModes(Enum):
192
+ """Modes in which the reroll regions operate"""
193
+
194
+ RESET = "reset" # Completely reset the random noise in the region
195
+ EPSILON = "epsilon" # Alter slightly the latents in the region
196
+
197
+
198
+ @dataclass
199
+ class RerollRegion(CanvasRegion):
200
+ """Class defining a rectangular canvas region in which initial latent noise will be rerolled"""
201
+
202
+ reroll_mode: RerollModes = RerollModes.RESET.value
203
+
204
+
205
+ @dataclass
206
+ class MaskWeightsBuilder:
207
+ """Auxiliary class to compute a tensor of weights for a given diffusion region"""
208
+
209
+ latent_space_dim: int # Size of the U-net latent space
210
+ nbatch: int = 1 # Batch size in the U-net
211
+
212
+ def compute_mask_weights(self, region: DiffusionRegion) -> torch.tensor:
213
+ """Computes a tensor of weights for a given diffusion region"""
214
+ MASK_BUILDERS = {
215
+ MaskModes.CONSTANT.value: self._constant_weights,
216
+ MaskModes.GAUSSIAN.value: self._gaussian_weights,
217
+ MaskModes.QUARTIC.value: self._quartic_weights,
218
+ }
219
+ return MASK_BUILDERS[region.mask_type](region)
220
+
221
+ def _constant_weights(self, region: DiffusionRegion) -> torch.tensor:
222
+ """Computes a tensor of constant for a given diffusion region"""
223
+ latent_width = region.latent_col_end - region.latent_col_init
224
+ latent_height = region.latent_row_end - region.latent_row_init
225
+ return torch.ones(self.nbatch, self.latent_space_dim, latent_height, latent_width) * region.mask_weight
226
+
227
+ def _gaussian_weights(self, region: DiffusionRegion) -> torch.tensor:
228
+ """Generates a gaussian mask of weights for tile contributions"""
229
+ latent_width = region.latent_col_end - region.latent_col_init
230
+ latent_height = region.latent_row_end - region.latent_row_init
231
+
232
+ var = 0.01
233
+ midpoint = (latent_width - 1) / 2 # -1 because index goes from 0 to latent_width - 1
234
+ x_probs = [
235
+ exp(-(x - midpoint) * (x - midpoint) / (latent_width * latent_width) / (2 * var)) / sqrt(2 * pi * var)
236
+ for x in range(latent_width)
237
+ ]
238
+ midpoint = (latent_height - 1) / 2
239
+ y_probs = [
240
+ exp(-(y - midpoint) * (y - midpoint) / (latent_height * latent_height) / (2 * var)) / sqrt(2 * pi * var)
241
+ for y in range(latent_height)
242
+ ]
243
+
244
+ weights = np.outer(y_probs, x_probs) * region.mask_weight
245
+ return torch.tile(torch.tensor(weights), (self.nbatch, self.latent_space_dim, 1, 1))
246
+
247
+ def _quartic_weights(self, region: DiffusionRegion) -> torch.tensor:
248
+ """Generates a quartic mask of weights for tile contributions
249
+
250
+ The quartic kernel has bounded support over the diffusion region, and a smooth decay to the region limits.
251
+ """
252
+ quartic_constant = 15.0 / 16.0
253
+
254
+ support = (np.array(range(region.latent_col_init, region.latent_col_end)) - region.latent_col_init) / (
255
+ region.latent_col_end - region.latent_col_init - 1
256
+ ) * 1.99 - (1.99 / 2.0)
257
+ x_probs = quartic_constant * np.square(1 - np.square(support))
258
+ support = (np.array(range(region.latent_row_init, region.latent_row_end)) - region.latent_row_init) / (
259
+ region.latent_row_end - region.latent_row_init - 1
260
+ ) * 1.99 - (1.99 / 2.0)
261
+ y_probs = quartic_constant * np.square(1 - np.square(support))
262
+
263
+ weights = np.outer(y_probs, x_probs) * region.mask_weight
264
+ return torch.tile(torch.tensor(weights), (self.nbatch, self.latent_space_dim, 1, 1))
265
+
266
+
267
+ class StableDiffusionCanvasPipeline(DiffusionPipeline):
268
+ """Stable Diffusion pipeline that mixes several diffusers in the same canvas"""
269
+
270
+ def __init__(
271
+ self,
272
+ vae: AutoencoderKL,
273
+ text_encoder: CLIPTextModel,
274
+ tokenizer: CLIPTokenizer,
275
+ unet: UNet2DConditionModel,
276
+ scheduler: Union[DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler],
277
+ safety_checker: StableDiffusionSafetyChecker,
278
+ feature_extractor: CLIPFeatureExtractor,
279
+ ):
280
+ super().__init__()
281
+ self.register_modules(
282
+ vae=vae,
283
+ text_encoder=text_encoder,
284
+ tokenizer=tokenizer,
285
+ unet=unet,
286
+ scheduler=scheduler,
287
+ safety_checker=safety_checker,
288
+ feature_extractor=feature_extractor,
289
+ )
290
+
291
+ def decode_latents(self, latents, cpu_vae=False):
292
+ """Decodes a given array of latents into pixel space"""
293
+ # scale and decode the image latents with vae
294
+ if cpu_vae:
295
+ lat = deepcopy(latents).cpu()
296
+ vae = deepcopy(self.vae).cpu()
297
+ else:
298
+ lat = latents
299
+ vae = self.vae
300
+
301
+ lat = 1 / 0.18215 * lat
302
+ image = vae.decode(lat).sample
303
+
304
+ image = (image / 2 + 0.5).clamp(0, 1)
305
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
306
+
307
+ return self.numpy_to_pil(image)
308
+
309
+ def get_latest_timestep_img2img(self, num_inference_steps, strength):
310
+ """Finds the latest timesteps where an img2img strength does not impose latents anymore"""
311
+ # get the original timestep using init_timestep
312
+ offset = self.scheduler.config.get("steps_offset", 0)
313
+ init_timestep = int(num_inference_steps * (1 - strength)) + offset
314
+ init_timestep = min(init_timestep, num_inference_steps)
315
+
316
+ t_start = min(max(num_inference_steps - init_timestep + offset, 0), num_inference_steps - 1)
317
+ latest_timestep = self.scheduler.timesteps[t_start]
318
+
319
+ return latest_timestep
320
+
321
+ @torch.no_grad()
322
+ def __call__(
323
+ self,
324
+ canvas_height: int,
325
+ canvas_width: int,
326
+ regions: List[DiffusionRegion],
327
+ num_inference_steps: Optional[int] = 50,
328
+ seed: Optional[int] = 12345,
329
+ reroll_regions: Optional[List[RerollRegion]] = None,
330
+ cpu_vae: Optional[bool] = False,
331
+ decode_steps: Optional[bool] = False,
332
+ ):
333
+ if reroll_regions is None:
334
+ reroll_regions = []
335
+ batch_size = 1
336
+
337
+ if decode_steps:
338
+ steps_images = []
339
+
340
+ # Prepare scheduler
341
+ self.scheduler.set_timesteps(num_inference_steps, device=self.device)
342
+
343
+ # Split diffusion regions by their kind
344
+ text2image_regions = [region for region in regions if isinstance(region, Text2ImageRegion)]
345
+ image2image_regions = [region for region in regions if isinstance(region, Image2ImageRegion)]
346
+
347
+ # Prepare text embeddings
348
+ for region in text2image_regions:
349
+ region.tokenize_prompt(self.tokenizer)
350
+ region.encode_prompt(self.text_encoder, self.device)
351
+
352
+ # Create original noisy latents using the timesteps
353
+ latents_shape = (batch_size, self.unet.config.in_channels, canvas_height // 8, canvas_width // 8)
354
+ generator = torch.Generator(self.device).manual_seed(seed)
355
+ init_noise = torch.randn(latents_shape, generator=generator, device=self.device)
356
+
357
+ # Reset latents in seed reroll regions, if requested
358
+ for region in reroll_regions:
359
+ if region.reroll_mode == RerollModes.RESET.value:
360
+ region_shape = (
361
+ latents_shape[0],
362
+ latents_shape[1],
363
+ region.latent_row_end - region.latent_row_init,
364
+ region.latent_col_end - region.latent_col_init,
365
+ )
366
+ init_noise[
367
+ :,
368
+ :,
369
+ region.latent_row_init : region.latent_row_end,
370
+ region.latent_col_init : region.latent_col_end,
371
+ ] = torch.randn(region_shape, generator=region.get_region_generator(self.device), device=self.device)
372
+
373
+ # Apply epsilon noise to regions: first diffusion regions, then reroll regions
374
+ all_eps_rerolls = regions + [r for r in reroll_regions if r.reroll_mode == RerollModes.EPSILON.value]
375
+ for region in all_eps_rerolls:
376
+ if region.noise_eps > 0:
377
+ region_noise = init_noise[
378
+ :,
379
+ :,
380
+ region.latent_row_init : region.latent_row_end,
381
+ region.latent_col_init : region.latent_col_end,
382
+ ]
383
+ eps_noise = (
384
+ torch.randn(
385
+ region_noise.shape, generator=region.get_region_generator(self.device), device=self.device
386
+ )
387
+ * region.noise_eps
388
+ )
389
+ init_noise[
390
+ :,
391
+ :,
392
+ region.latent_row_init : region.latent_row_end,
393
+ region.latent_col_init : region.latent_col_end,
394
+ ] += eps_noise
395
+
396
+ # scale the initial noise by the standard deviation required by the scheduler
397
+ latents = init_noise * self.scheduler.init_noise_sigma
398
+
399
+ # Get unconditional embeddings for classifier free guidance in text2image regions
400
+ for region in text2image_regions:
401
+ max_length = region.tokenized_prompt.input_ids.shape[-1]
402
+ uncond_input = self.tokenizer(
403
+ [""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
404
+ )
405
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
406
+
407
+ # For classifier free guidance, we need to do two forward passes.
408
+ # Here we concatenate the unconditional and text embeddings into a single batch
409
+ # to avoid doing two forward passes
410
+ region.encoded_prompt = torch.cat([uncond_embeddings, region.encoded_prompt])
411
+
412
+ # Prepare image latents
413
+ for region in image2image_regions:
414
+ region.encode_reference_image(self.vae, device=self.device, generator=generator)
415
+
416
+ # Prepare mask of weights for each region
417
+ mask_builder = MaskWeightsBuilder(latent_space_dim=self.unet.config.in_channels, nbatch=batch_size)
418
+ mask_weights = [mask_builder.compute_mask_weights(region).to(self.device) for region in text2image_regions]
419
+
420
+ # Diffusion timesteps
421
+ for i, t in tqdm(enumerate(self.scheduler.timesteps)):
422
+ # Diffuse each region
423
+ noise_preds_regions = []
424
+
425
+ # text2image regions
426
+ for region in text2image_regions:
427
+ region_latents = latents[
428
+ :,
429
+ :,
430
+ region.latent_row_init : region.latent_row_end,
431
+ region.latent_col_init : region.latent_col_end,
432
+ ]
433
+ # expand the latents if we are doing classifier free guidance
434
+ latent_model_input = torch.cat([region_latents] * 2)
435
+ # scale model input following scheduler rules
436
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
437
+ # predict the noise residual
438
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=region.encoded_prompt)["sample"]
439
+ # perform guidance
440
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
441
+ noise_pred_region = noise_pred_uncond + region.guidance_scale * (noise_pred_text - noise_pred_uncond)
442
+ noise_preds_regions.append(noise_pred_region)
443
+
444
+ # Merge noise predictions for all tiles
445
+ noise_pred = torch.zeros(latents.shape, device=self.device)
446
+ contributors = torch.zeros(latents.shape, device=self.device)
447
+ # Add each tile contribution to overall latents
448
+ for region, noise_pred_region, mask_weights_region in zip(
449
+ text2image_regions, noise_preds_regions, mask_weights
450
+ ):
451
+ noise_pred[
452
+ :,
453
+ :,
454
+ region.latent_row_init : region.latent_row_end,
455
+ region.latent_col_init : region.latent_col_end,
456
+ ] += (
457
+ noise_pred_region * mask_weights_region
458
+ )
459
+ contributors[
460
+ :,
461
+ :,
462
+ region.latent_row_init : region.latent_row_end,
463
+ region.latent_col_init : region.latent_col_end,
464
+ ] += mask_weights_region
465
+ # Average overlapping areas with more than 1 contributor
466
+ noise_pred /= contributors
467
+ noise_pred = torch.nan_to_num(
468
+ noise_pred
469
+ ) # Replace NaNs by zeros: NaN can appear if a position is not covered by any DiffusionRegion
470
+
471
+ # compute the previous noisy sample x_t -> x_t-1
472
+ latents = self.scheduler.step(noise_pred, t, latents).prev_sample
473
+
474
+ # Image2Image regions: override latents generated by the scheduler
475
+ for region in image2image_regions:
476
+ influence_step = self.get_latest_timestep_img2img(num_inference_steps, region.strength)
477
+ # Only override in the timesteps before the last influence step of the image (given by its strength)
478
+ if t > influence_step:
479
+ timestep = t.repeat(batch_size)
480
+ region_init_noise = init_noise[
481
+ :,
482
+ :,
483
+ region.latent_row_init : region.latent_row_end,
484
+ region.latent_col_init : region.latent_col_end,
485
+ ]
486
+ region_latents = self.scheduler.add_noise(region.reference_latents, region_init_noise, timestep)
487
+ latents[
488
+ :,
489
+ :,
490
+ region.latent_row_init : region.latent_row_end,
491
+ region.latent_col_init : region.latent_col_end,
492
+ ] = region_latents
493
+
494
+ if decode_steps:
495
+ steps_images.append(self.decode_latents(latents, cpu_vae))
496
+
497
+ # scale and decode the image latents with vae
498
+ image = self.decode_latents(latents, cpu_vae)
499
+
500
+ output = {"images": image}
501
+ if decode_steps:
502
+ output = {**output, "steps_images": steps_images}
503
+ return output
v0.22.0/mixture_tiling.py ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from copy import deepcopy
3
+ from enum import Enum
4
+ from typing import List, Optional, Tuple, Union
5
+
6
+ import torch
7
+ from tqdm.auto import tqdm
8
+
9
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
10
+ from diffusers.pipeline_utils import DiffusionPipeline
11
+ from diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker
12
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
13
+ from diffusers.utils import logging
14
+
15
+
16
+ try:
17
+ from ligo.segments import segment
18
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
19
+ except ImportError:
20
+ raise ImportError("Please install transformers and ligo-segments to use the mixture pipeline")
21
+
22
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
23
+
24
+ EXAMPLE_DOC_STRING = """
25
+ Examples:
26
+ ```py
27
+ >>> from diffusers import LMSDiscreteScheduler, DiffusionPipeline
28
+
29
+ >>> scheduler = LMSDiscreteScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000)
30
+ >>> pipeline = DiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", scheduler=scheduler, custom_pipeline="mixture_tiling")
31
+ >>> pipeline.to("cuda")
32
+
33
+ >>> image = pipeline(
34
+ >>> prompt=[[
35
+ >>> "A charming house in the countryside, by jakub rozalski, sunset lighting, elegant, highly detailed, smooth, sharp focus, artstation, stunning masterpiece",
36
+ >>> "A dirt road in the countryside crossing pastures, by jakub rozalski, sunset lighting, elegant, highly detailed, smooth, sharp focus, artstation, stunning masterpiece",
37
+ >>> "An old and rusty giant robot lying on a dirt road, by jakub rozalski, dark sunset lighting, elegant, highly detailed, smooth, sharp focus, artstation, stunning masterpiece"
38
+ >>> ]],
39
+ >>> tile_height=640,
40
+ >>> tile_width=640,
41
+ >>> tile_row_overlap=0,
42
+ >>> tile_col_overlap=256,
43
+ >>> guidance_scale=8,
44
+ >>> seed=7178915308,
45
+ >>> num_inference_steps=50,
46
+ >>> )["images"][0]
47
+ ```
48
+ """
49
+
50
+
51
+ def _tile2pixel_indices(tile_row, tile_col, tile_width, tile_height, tile_row_overlap, tile_col_overlap):
52
+ """Given a tile row and column numbers returns the range of pixels affected by that tiles in the overall image
53
+
54
+ Returns a tuple with:
55
+ - Starting coordinates of rows in pixel space
56
+ - Ending coordinates of rows in pixel space
57
+ - Starting coordinates of columns in pixel space
58
+ - Ending coordinates of columns in pixel space
59
+ """
60
+ px_row_init = 0 if tile_row == 0 else tile_row * (tile_height - tile_row_overlap)
61
+ px_row_end = px_row_init + tile_height
62
+ px_col_init = 0 if tile_col == 0 else tile_col * (tile_width - tile_col_overlap)
63
+ px_col_end = px_col_init + tile_width
64
+ return px_row_init, px_row_end, px_col_init, px_col_end
65
+
66
+
67
+ def _pixel2latent_indices(px_row_init, px_row_end, px_col_init, px_col_end):
68
+ """Translates coordinates in pixel space to coordinates in latent space"""
69
+ return px_row_init // 8, px_row_end // 8, px_col_init // 8, px_col_end // 8
70
+
71
+
72
+ def _tile2latent_indices(tile_row, tile_col, tile_width, tile_height, tile_row_overlap, tile_col_overlap):
73
+ """Given a tile row and column numbers returns the range of latents affected by that tiles in the overall image
74
+
75
+ Returns a tuple with:
76
+ - Starting coordinates of rows in latent space
77
+ - Ending coordinates of rows in latent space
78
+ - Starting coordinates of columns in latent space
79
+ - Ending coordinates of columns in latent space
80
+ """
81
+ px_row_init, px_row_end, px_col_init, px_col_end = _tile2pixel_indices(
82
+ tile_row, tile_col, tile_width, tile_height, tile_row_overlap, tile_col_overlap
83
+ )
84
+ return _pixel2latent_indices(px_row_init, px_row_end, px_col_init, px_col_end)
85
+
86
+
87
+ def _tile2latent_exclusive_indices(
88
+ tile_row, tile_col, tile_width, tile_height, tile_row_overlap, tile_col_overlap, rows, columns
89
+ ):
90
+ """Given a tile row and column numbers returns the range of latents affected only by that tile in the overall image
91
+
92
+ Returns a tuple with:
93
+ - Starting coordinates of rows in latent space
94
+ - Ending coordinates of rows in latent space
95
+ - Starting coordinates of columns in latent space
96
+ - Ending coordinates of columns in latent space
97
+ """
98
+ row_init, row_end, col_init, col_end = _tile2latent_indices(
99
+ tile_row, tile_col, tile_width, tile_height, tile_row_overlap, tile_col_overlap
100
+ )
101
+ row_segment = segment(row_init, row_end)
102
+ col_segment = segment(col_init, col_end)
103
+ # Iterate over the rest of tiles, clipping the region for the current tile
104
+ for row in range(rows):
105
+ for column in range(columns):
106
+ if row != tile_row and column != tile_col:
107
+ clip_row_init, clip_row_end, clip_col_init, clip_col_end = _tile2latent_indices(
108
+ row, column, tile_width, tile_height, tile_row_overlap, tile_col_overlap
109
+ )
110
+ row_segment = row_segment - segment(clip_row_init, clip_row_end)
111
+ col_segment = col_segment - segment(clip_col_init, clip_col_end)
112
+ # return row_init, row_end, col_init, col_end
113
+ return row_segment[0], row_segment[1], col_segment[0], col_segment[1]
114
+
115
+
116
+ class StableDiffusionExtrasMixin:
117
+ """Mixin providing additional convenience method to Stable Diffusion pipelines"""
118
+
119
+ def decode_latents(self, latents, cpu_vae=False):
120
+ """Decodes a given array of latents into pixel space"""
121
+ # scale and decode the image latents with vae
122
+ if cpu_vae:
123
+ lat = deepcopy(latents).cpu()
124
+ vae = deepcopy(self.vae).cpu()
125
+ else:
126
+ lat = latents
127
+ vae = self.vae
128
+
129
+ lat = 1 / 0.18215 * lat
130
+ image = vae.decode(lat).sample
131
+
132
+ image = (image / 2 + 0.5).clamp(0, 1)
133
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
134
+
135
+ return self.numpy_to_pil(image)
136
+
137
+
138
+ class StableDiffusionTilingPipeline(DiffusionPipeline, StableDiffusionExtrasMixin):
139
+ def __init__(
140
+ self,
141
+ vae: AutoencoderKL,
142
+ text_encoder: CLIPTextModel,
143
+ tokenizer: CLIPTokenizer,
144
+ unet: UNet2DConditionModel,
145
+ scheduler: Union[DDIMScheduler, PNDMScheduler],
146
+ safety_checker: StableDiffusionSafetyChecker,
147
+ feature_extractor: CLIPFeatureExtractor,
148
+ ):
149
+ super().__init__()
150
+ self.register_modules(
151
+ vae=vae,
152
+ text_encoder=text_encoder,
153
+ tokenizer=tokenizer,
154
+ unet=unet,
155
+ scheduler=scheduler,
156
+ safety_checker=safety_checker,
157
+ feature_extractor=feature_extractor,
158
+ )
159
+
160
+ class SeedTilesMode(Enum):
161
+ """Modes in which the latents of a particular tile can be re-seeded"""
162
+
163
+ FULL = "full"
164
+ EXCLUSIVE = "exclusive"
165
+
166
+ @torch.no_grad()
167
+ def __call__(
168
+ self,
169
+ prompt: Union[str, List[List[str]]],
170
+ num_inference_steps: Optional[int] = 50,
171
+ guidance_scale: Optional[float] = 7.5,
172
+ eta: Optional[float] = 0.0,
173
+ seed: Optional[int] = None,
174
+ tile_height: Optional[int] = 512,
175
+ tile_width: Optional[int] = 512,
176
+ tile_row_overlap: Optional[int] = 256,
177
+ tile_col_overlap: Optional[int] = 256,
178
+ guidance_scale_tiles: Optional[List[List[float]]] = None,
179
+ seed_tiles: Optional[List[List[int]]] = None,
180
+ seed_tiles_mode: Optional[Union[str, List[List[str]]]] = "full",
181
+ seed_reroll_regions: Optional[List[Tuple[int, int, int, int, int]]] = None,
182
+ cpu_vae: Optional[bool] = False,
183
+ ):
184
+ r"""
185
+ Function to run the diffusion pipeline with tiling support.
186
+
187
+ Args:
188
+ prompt: either a single string (no tiling) or a list of lists with all the prompts to use (one list for each row of tiles). This will also define the tiling structure.
189
+ num_inference_steps: number of diffusions steps.
190
+ guidance_scale: classifier-free guidance.
191
+ seed: general random seed to initialize latents.
192
+ tile_height: height in pixels of each grid tile.
193
+ tile_width: width in pixels of each grid tile.
194
+ tile_row_overlap: number of overlap pixels between tiles in consecutive rows.
195
+ tile_col_overlap: number of overlap pixels between tiles in consecutive columns.
196
+ guidance_scale_tiles: specific weights for classifier-free guidance in each tile.
197
+ guidance_scale_tiles: specific weights for classifier-free guidance in each tile. If None, the value provided in guidance_scale will be used.
198
+ seed_tiles: specific seeds for the initialization latents in each tile. These will override the latents generated for the whole canvas using the standard seed parameter.
199
+ seed_tiles_mode: either "full" "exclusive". If "full", all the latents affected by the tile be overriden. If "exclusive", only the latents that are affected exclusively by this tile (and no other tiles) will be overrriden.
200
+ seed_reroll_regions: a list of tuples in the form (start row, end row, start column, end column, seed) defining regions in pixel space for which the latents will be overriden using the given seed. Takes priority over seed_tiles.
201
+ cpu_vae: the decoder from latent space to pixel space can require too mucho GPU RAM for large images. If you find out of memory errors at the end of the generation process, try setting this parameter to True to run the decoder in CPU. Slower, but should run without memory issues.
202
+
203
+ Examples:
204
+
205
+ Returns:
206
+ A PIL image with the generated image.
207
+
208
+ """
209
+ if not isinstance(prompt, list) or not all(isinstance(row, list) for row in prompt):
210
+ raise ValueError(f"`prompt` has to be a list of lists but is {type(prompt)}")
211
+ grid_rows = len(prompt)
212
+ grid_cols = len(prompt[0])
213
+ if not all(len(row) == grid_cols for row in prompt):
214
+ raise ValueError("All prompt rows must have the same number of prompt columns")
215
+ if not isinstance(seed_tiles_mode, str) and (
216
+ not isinstance(seed_tiles_mode, list) or not all(isinstance(row, list) for row in seed_tiles_mode)
217
+ ):
218
+ raise ValueError(f"`seed_tiles_mode` has to be a string or list of lists but is {type(prompt)}")
219
+ if isinstance(seed_tiles_mode, str):
220
+ seed_tiles_mode = [[seed_tiles_mode for _ in range(len(row))] for row in prompt]
221
+
222
+ modes = [mode.value for mode in self.SeedTilesMode]
223
+ if any(mode not in modes for row in seed_tiles_mode for mode in row):
224
+ raise ValueError(f"Seed tiles mode must be one of {modes}")
225
+ if seed_reroll_regions is None:
226
+ seed_reroll_regions = []
227
+ batch_size = 1
228
+
229
+ # create original noisy latents using the timesteps
230
+ height = tile_height + (grid_rows - 1) * (tile_height - tile_row_overlap)
231
+ width = tile_width + (grid_cols - 1) * (tile_width - tile_col_overlap)
232
+ latents_shape = (batch_size, self.unet.config.in_channels, height // 8, width // 8)
233
+ generator = torch.Generator("cuda").manual_seed(seed)
234
+ latents = torch.randn(latents_shape, generator=generator, device=self.device)
235
+
236
+ # overwrite latents for specific tiles if provided
237
+ if seed_tiles is not None:
238
+ for row in range(grid_rows):
239
+ for col in range(grid_cols):
240
+ if (seed_tile := seed_tiles[row][col]) is not None:
241
+ mode = seed_tiles_mode[row][col]
242
+ if mode == self.SeedTilesMode.FULL.value:
243
+ row_init, row_end, col_init, col_end = _tile2latent_indices(
244
+ row, col, tile_width, tile_height, tile_row_overlap, tile_col_overlap
245
+ )
246
+ else:
247
+ row_init, row_end, col_init, col_end = _tile2latent_exclusive_indices(
248
+ row,
249
+ col,
250
+ tile_width,
251
+ tile_height,
252
+ tile_row_overlap,
253
+ tile_col_overlap,
254
+ grid_rows,
255
+ grid_cols,
256
+ )
257
+ tile_generator = torch.Generator("cuda").manual_seed(seed_tile)
258
+ tile_shape = (latents_shape[0], latents_shape[1], row_end - row_init, col_end - col_init)
259
+ latents[:, :, row_init:row_end, col_init:col_end] = torch.randn(
260
+ tile_shape, generator=tile_generator, device=self.device
261
+ )
262
+
263
+ # overwrite again for seed reroll regions
264
+ for row_init, row_end, col_init, col_end, seed_reroll in seed_reroll_regions:
265
+ row_init, row_end, col_init, col_end = _pixel2latent_indices(
266
+ row_init, row_end, col_init, col_end
267
+ ) # to latent space coordinates
268
+ reroll_generator = torch.Generator("cuda").manual_seed(seed_reroll)
269
+ region_shape = (latents_shape[0], latents_shape[1], row_end - row_init, col_end - col_init)
270
+ latents[:, :, row_init:row_end, col_init:col_end] = torch.randn(
271
+ region_shape, generator=reroll_generator, device=self.device
272
+ )
273
+
274
+ # Prepare scheduler
275
+ accepts_offset = "offset" in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys())
276
+ extra_set_kwargs = {}
277
+ if accepts_offset:
278
+ extra_set_kwargs["offset"] = 1
279
+ self.scheduler.set_timesteps(num_inference_steps, **extra_set_kwargs)
280
+ # if we use LMSDiscreteScheduler, let's make sure latents are multiplied by sigmas
281
+ if isinstance(self.scheduler, LMSDiscreteScheduler):
282
+ latents = latents * self.scheduler.sigmas[0]
283
+
284
+ # get prompts text embeddings
285
+ text_input = [
286
+ [
287
+ self.tokenizer(
288
+ col,
289
+ padding="max_length",
290
+ max_length=self.tokenizer.model_max_length,
291
+ truncation=True,
292
+ return_tensors="pt",
293
+ )
294
+ for col in row
295
+ ]
296
+ for row in prompt
297
+ ]
298
+ text_embeddings = [[self.text_encoder(col.input_ids.to(self.device))[0] for col in row] for row in text_input]
299
+
300
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
301
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
302
+ # corresponds to doing no classifier free guidance.
303
+ do_classifier_free_guidance = guidance_scale > 1.0 # TODO: also active if any tile has guidance scale
304
+ # get unconditional embeddings for classifier free guidance
305
+ if do_classifier_free_guidance:
306
+ for i in range(grid_rows):
307
+ for j in range(grid_cols):
308
+ max_length = text_input[i][j].input_ids.shape[-1]
309
+ uncond_input = self.tokenizer(
310
+ [""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
311
+ )
312
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
313
+
314
+ # For classifier free guidance, we need to do two forward passes.
315
+ # Here we concatenate the unconditional and text embeddings into a single batch
316
+ # to avoid doing two forward passes
317
+ text_embeddings[i][j] = torch.cat([uncond_embeddings, text_embeddings[i][j]])
318
+
319
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
320
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
321
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
322
+ # and should be between [0, 1]
323
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
324
+ extra_step_kwargs = {}
325
+ if accepts_eta:
326
+ extra_step_kwargs["eta"] = eta
327
+
328
+ # Mask for tile weights strenght
329
+ tile_weights = self._gaussian_weights(tile_width, tile_height, batch_size)
330
+
331
+ # Diffusion timesteps
332
+ for i, t in tqdm(enumerate(self.scheduler.timesteps)):
333
+ # Diffuse each tile
334
+ noise_preds = []
335
+ for row in range(grid_rows):
336
+ noise_preds_row = []
337
+ for col in range(grid_cols):
338
+ px_row_init, px_row_end, px_col_init, px_col_end = _tile2latent_indices(
339
+ row, col, tile_width, tile_height, tile_row_overlap, tile_col_overlap
340
+ )
341
+ tile_latents = latents[:, :, px_row_init:px_row_end, px_col_init:px_col_end]
342
+ # expand the latents if we are doing classifier free guidance
343
+ latent_model_input = torch.cat([tile_latents] * 2) if do_classifier_free_guidance else tile_latents
344
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
345
+ # predict the noise residual
346
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings[row][col])[
347
+ "sample"
348
+ ]
349
+ # perform guidance
350
+ if do_classifier_free_guidance:
351
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
352
+ guidance = (
353
+ guidance_scale
354
+ if guidance_scale_tiles is None or guidance_scale_tiles[row][col] is None
355
+ else guidance_scale_tiles[row][col]
356
+ )
357
+ noise_pred_tile = noise_pred_uncond + guidance * (noise_pred_text - noise_pred_uncond)
358
+ noise_preds_row.append(noise_pred_tile)
359
+ noise_preds.append(noise_preds_row)
360
+ # Stitch noise predictions for all tiles
361
+ noise_pred = torch.zeros(latents.shape, device=self.device)
362
+ contributors = torch.zeros(latents.shape, device=self.device)
363
+ # Add each tile contribution to overall latents
364
+ for row in range(grid_rows):
365
+ for col in range(grid_cols):
366
+ px_row_init, px_row_end, px_col_init, px_col_end = _tile2latent_indices(
367
+ row, col, tile_width, tile_height, tile_row_overlap, tile_col_overlap
368
+ )
369
+ noise_pred[:, :, px_row_init:px_row_end, px_col_init:px_col_end] += (
370
+ noise_preds[row][col] * tile_weights
371
+ )
372
+ contributors[:, :, px_row_init:px_row_end, px_col_init:px_col_end] += tile_weights
373
+ # Average overlapping areas with more than 1 contributor
374
+ noise_pred /= contributors
375
+
376
+ # compute the previous noisy sample x_t -> x_t-1
377
+ latents = self.scheduler.step(noise_pred, t, latents).prev_sample
378
+
379
+ # scale and decode the image latents with vae
380
+ image = self.decode_latents(latents, cpu_vae)
381
+
382
+ return {"images": image}
383
+
384
+ def _gaussian_weights(self, tile_width, tile_height, nbatches):
385
+ """Generates a gaussian mask of weights for tile contributions"""
386
+ import numpy as np
387
+ from numpy import exp, pi, sqrt
388
+
389
+ latent_width = tile_width // 8
390
+ latent_height = tile_height // 8
391
+
392
+ var = 0.01
393
+ midpoint = (latent_width - 1) / 2 # -1 because index goes from 0 to latent_width - 1
394
+ x_probs = [
395
+ exp(-(x - midpoint) * (x - midpoint) / (latent_width * latent_width) / (2 * var)) / sqrt(2 * pi * var)
396
+ for x in range(latent_width)
397
+ ]
398
+ midpoint = latent_height / 2
399
+ y_probs = [
400
+ exp(-(y - midpoint) * (y - midpoint) / (latent_height * latent_height) / (2 * var)) / sqrt(2 * pi * var)
401
+ for y in range(latent_height)
402
+ ]
403
+
404
+ weights = np.outer(y_probs, x_probs)
405
+ return torch.tile(torch.tensor(weights, device=self.device), (nbatches, self.unet.config.in_channels, 1, 1))
v0.22.0/multilingual_stable_diffusion.py ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import Callable, List, Optional, Union
3
+
4
+ import torch
5
+ from transformers import (
6
+ CLIPImageProcessor,
7
+ CLIPTextModel,
8
+ CLIPTokenizer,
9
+ MBart50TokenizerFast,
10
+ MBartForConditionalGeneration,
11
+ pipeline,
12
+ )
13
+
14
+ from diffusers import DiffusionPipeline
15
+ from diffusers.configuration_utils import FrozenDict
16
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
17
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
18
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
19
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
20
+ from diffusers.utils import deprecate, logging
21
+
22
+
23
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
24
+
25
+
26
+ def detect_language(pipe, prompt, batch_size):
27
+ """helper function to detect language(s) of prompt"""
28
+
29
+ if batch_size == 1:
30
+ preds = pipe(prompt, top_k=1, truncation=True, max_length=128)
31
+ return preds[0]["label"]
32
+ else:
33
+ detected_languages = []
34
+ for p in prompt:
35
+ preds = pipe(p, top_k=1, truncation=True, max_length=128)
36
+ detected_languages.append(preds[0]["label"])
37
+
38
+ return detected_languages
39
+
40
+
41
+ def translate_prompt(prompt, translation_tokenizer, translation_model, device):
42
+ """helper function to translate prompt to English"""
43
+
44
+ encoded_prompt = translation_tokenizer(prompt, return_tensors="pt").to(device)
45
+ generated_tokens = translation_model.generate(**encoded_prompt, max_new_tokens=1000)
46
+ en_trans = translation_tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
47
+
48
+ return en_trans[0]
49
+
50
+
51
+ class MultilingualStableDiffusion(DiffusionPipeline):
52
+ r"""
53
+ Pipeline for text-to-image generation using Stable Diffusion in different languages.
54
+
55
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
56
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
57
+
58
+ Args:
59
+ detection_pipeline ([`pipeline`]):
60
+ Transformers pipeline to detect prompt's language.
61
+ translation_model ([`MBartForConditionalGeneration`]):
62
+ Model to translate prompt to English, if necessary. Please refer to the
63
+ [model card](https://huggingface.co/docs/transformers/model_doc/mbart) for details.
64
+ translation_tokenizer ([`MBart50TokenizerFast`]):
65
+ Tokenizer of the translation model.
66
+ vae ([`AutoencoderKL`]):
67
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
68
+ text_encoder ([`CLIPTextModel`]):
69
+ Frozen text-encoder. Stable Diffusion uses the text portion of
70
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
71
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
72
+ tokenizer (`CLIPTokenizer`):
73
+ Tokenizer of class
74
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
75
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
76
+ scheduler ([`SchedulerMixin`]):
77
+ A scheduler to be used in combination with `unet` to denoise the encoded image latens. Can be one of
78
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
79
+ safety_checker ([`StableDiffusionSafetyChecker`]):
80
+ Classification module that estimates whether generated images could be considered offensive or harmful.
81
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
82
+ feature_extractor ([`CLIPImageProcessor`]):
83
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
84
+ """
85
+
86
+ def __init__(
87
+ self,
88
+ detection_pipeline: pipeline,
89
+ translation_model: MBartForConditionalGeneration,
90
+ translation_tokenizer: MBart50TokenizerFast,
91
+ vae: AutoencoderKL,
92
+ text_encoder: CLIPTextModel,
93
+ tokenizer: CLIPTokenizer,
94
+ unet: UNet2DConditionModel,
95
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
96
+ safety_checker: StableDiffusionSafetyChecker,
97
+ feature_extractor: CLIPImageProcessor,
98
+ ):
99
+ super().__init__()
100
+
101
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
102
+ deprecation_message = (
103
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
104
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
105
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
106
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
107
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
108
+ " file"
109
+ )
110
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
111
+ new_config = dict(scheduler.config)
112
+ new_config["steps_offset"] = 1
113
+ scheduler._internal_dict = FrozenDict(new_config)
114
+
115
+ if safety_checker is None:
116
+ logger.warning(
117
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
118
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
119
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
120
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
121
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
122
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
123
+ )
124
+
125
+ self.register_modules(
126
+ detection_pipeline=detection_pipeline,
127
+ translation_model=translation_model,
128
+ translation_tokenizer=translation_tokenizer,
129
+ vae=vae,
130
+ text_encoder=text_encoder,
131
+ tokenizer=tokenizer,
132
+ unet=unet,
133
+ scheduler=scheduler,
134
+ safety_checker=safety_checker,
135
+ feature_extractor=feature_extractor,
136
+ )
137
+
138
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
139
+ r"""
140
+ Enable sliced attention computation.
141
+
142
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
143
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
144
+
145
+ Args:
146
+ slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
147
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
148
+ a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
149
+ `attention_head_dim` must be a multiple of `slice_size`.
150
+ """
151
+ if slice_size == "auto":
152
+ # half the attention head size is usually a good trade-off between
153
+ # speed and memory
154
+ slice_size = self.unet.config.attention_head_dim // 2
155
+ self.unet.set_attention_slice(slice_size)
156
+
157
+ def disable_attention_slicing(self):
158
+ r"""
159
+ Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
160
+ back to computing attention in one step.
161
+ """
162
+ # set slice_size = `None` to disable `attention slicing`
163
+ self.enable_attention_slicing(None)
164
+
165
+ @torch.no_grad()
166
+ def __call__(
167
+ self,
168
+ prompt: Union[str, List[str]],
169
+ height: int = 512,
170
+ width: int = 512,
171
+ num_inference_steps: int = 50,
172
+ guidance_scale: float = 7.5,
173
+ negative_prompt: Optional[Union[str, List[str]]] = None,
174
+ num_images_per_prompt: Optional[int] = 1,
175
+ eta: float = 0.0,
176
+ generator: Optional[torch.Generator] = None,
177
+ latents: Optional[torch.FloatTensor] = None,
178
+ output_type: Optional[str] = "pil",
179
+ return_dict: bool = True,
180
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
181
+ callback_steps: int = 1,
182
+ **kwargs,
183
+ ):
184
+ r"""
185
+ Function invoked when calling the pipeline for generation.
186
+
187
+ Args:
188
+ prompt (`str` or `List[str]`):
189
+ The prompt or prompts to guide the image generation. Can be in different languages.
190
+ height (`int`, *optional*, defaults to 512):
191
+ The height in pixels of the generated image.
192
+ width (`int`, *optional*, defaults to 512):
193
+ The width in pixels of the generated image.
194
+ num_inference_steps (`int`, *optional*, defaults to 50):
195
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
196
+ expense of slower inference.
197
+ guidance_scale (`float`, *optional*, defaults to 7.5):
198
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
199
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
200
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
201
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
202
+ usually at the expense of lower image quality.
203
+ negative_prompt (`str` or `List[str]`, *optional*):
204
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
205
+ if `guidance_scale` is less than `1`).
206
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
207
+ The number of images to generate per prompt.
208
+ eta (`float`, *optional*, defaults to 0.0):
209
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
210
+ [`schedulers.DDIMScheduler`], will be ignored for others.
211
+ generator (`torch.Generator`, *optional*):
212
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
213
+ deterministic.
214
+ latents (`torch.FloatTensor`, *optional*):
215
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
216
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
217
+ tensor will ge generated by sampling using the supplied random `generator`.
218
+ output_type (`str`, *optional*, defaults to `"pil"`):
219
+ The output format of the generate image. Choose between
220
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
221
+ return_dict (`bool`, *optional*, defaults to `True`):
222
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
223
+ plain tuple.
224
+ callback (`Callable`, *optional*):
225
+ A function that will be called every `callback_steps` steps during inference. The function will be
226
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
227
+ callback_steps (`int`, *optional*, defaults to 1):
228
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
229
+ called at every step.
230
+
231
+ Returns:
232
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
233
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
234
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
235
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
236
+ (nsfw) content, according to the `safety_checker`.
237
+ """
238
+ if isinstance(prompt, str):
239
+ batch_size = 1
240
+ elif isinstance(prompt, list):
241
+ batch_size = len(prompt)
242
+ else:
243
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
244
+
245
+ if height % 8 != 0 or width % 8 != 0:
246
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
247
+
248
+ if (callback_steps is None) or (
249
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
250
+ ):
251
+ raise ValueError(
252
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
253
+ f" {type(callback_steps)}."
254
+ )
255
+
256
+ # detect language and translate if necessary
257
+ prompt_language = detect_language(self.detection_pipeline, prompt, batch_size)
258
+ if batch_size == 1 and prompt_language != "en":
259
+ prompt = translate_prompt(prompt, self.translation_tokenizer, self.translation_model, self.device)
260
+
261
+ if isinstance(prompt, list):
262
+ for index in range(batch_size):
263
+ if prompt_language[index] != "en":
264
+ p = translate_prompt(
265
+ prompt[index], self.translation_tokenizer, self.translation_model, self.device
266
+ )
267
+ prompt[index] = p
268
+
269
+ # get prompt text embeddings
270
+ text_inputs = self.tokenizer(
271
+ prompt,
272
+ padding="max_length",
273
+ max_length=self.tokenizer.model_max_length,
274
+ return_tensors="pt",
275
+ )
276
+ text_input_ids = text_inputs.input_ids
277
+
278
+ if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
279
+ removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :])
280
+ logger.warning(
281
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
282
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
283
+ )
284
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
285
+ text_embeddings = self.text_encoder(text_input_ids.to(self.device))[0]
286
+
287
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
288
+ bs_embed, seq_len, _ = text_embeddings.shape
289
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
290
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
291
+
292
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
293
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
294
+ # corresponds to doing no classifier free guidance.
295
+ do_classifier_free_guidance = guidance_scale > 1.0
296
+ # get unconditional embeddings for classifier free guidance
297
+ if do_classifier_free_guidance:
298
+ uncond_tokens: List[str]
299
+ if negative_prompt is None:
300
+ uncond_tokens = [""] * batch_size
301
+ elif type(prompt) is not type(negative_prompt):
302
+ raise TypeError(
303
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
304
+ f" {type(prompt)}."
305
+ )
306
+ elif isinstance(negative_prompt, str):
307
+ # detect language and translate it if necessary
308
+ negative_prompt_language = detect_language(self.detection_pipeline, negative_prompt, batch_size)
309
+ if negative_prompt_language != "en":
310
+ negative_prompt = translate_prompt(
311
+ negative_prompt, self.translation_tokenizer, self.translation_model, self.device
312
+ )
313
+ if isinstance(negative_prompt, str):
314
+ uncond_tokens = [negative_prompt]
315
+ elif batch_size != len(negative_prompt):
316
+ raise ValueError(
317
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
318
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
319
+ " the batch size of `prompt`."
320
+ )
321
+ else:
322
+ # detect language and translate it if necessary
323
+ if isinstance(negative_prompt, list):
324
+ negative_prompt_languages = detect_language(self.detection_pipeline, negative_prompt, batch_size)
325
+ for index in range(batch_size):
326
+ if negative_prompt_languages[index] != "en":
327
+ p = translate_prompt(
328
+ negative_prompt[index], self.translation_tokenizer, self.translation_model, self.device
329
+ )
330
+ negative_prompt[index] = p
331
+ uncond_tokens = negative_prompt
332
+
333
+ max_length = text_input_ids.shape[-1]
334
+ uncond_input = self.tokenizer(
335
+ uncond_tokens,
336
+ padding="max_length",
337
+ max_length=max_length,
338
+ truncation=True,
339
+ return_tensors="pt",
340
+ )
341
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
342
+
343
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
344
+ seq_len = uncond_embeddings.shape[1]
345
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
346
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
347
+
348
+ # For classifier free guidance, we need to do two forward passes.
349
+ # Here we concatenate the unconditional and text embeddings into a single batch
350
+ # to avoid doing two forward passes
351
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
352
+
353
+ # get the initial random noise unless the user supplied it
354
+
355
+ # Unlike in other pipelines, latents need to be generated in the target device
356
+ # for 1-to-1 results reproducibility with the CompVis implementation.
357
+ # However this currently doesn't work in `mps`.
358
+ latents_shape = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
359
+ latents_dtype = text_embeddings.dtype
360
+ if latents is None:
361
+ if self.device.type == "mps":
362
+ # randn does not work reproducibly on mps
363
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
364
+ self.device
365
+ )
366
+ else:
367
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
368
+ else:
369
+ if latents.shape != latents_shape:
370
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
371
+ latents = latents.to(self.device)
372
+
373
+ # set timesteps
374
+ self.scheduler.set_timesteps(num_inference_steps)
375
+
376
+ # Some schedulers like PNDM have timesteps as arrays
377
+ # It's more optimized to move all timesteps to correct device beforehand
378
+ timesteps_tensor = self.scheduler.timesteps.to(self.device)
379
+
380
+ # scale the initial noise by the standard deviation required by the scheduler
381
+ latents = latents * self.scheduler.init_noise_sigma
382
+
383
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
384
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
385
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
386
+ # and should be between [0, 1]
387
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
388
+ extra_step_kwargs = {}
389
+ if accepts_eta:
390
+ extra_step_kwargs["eta"] = eta
391
+
392
+ for i, t in enumerate(self.progress_bar(timesteps_tensor)):
393
+ # expand the latents if we are doing classifier free guidance
394
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
395
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
396
+
397
+ # predict the noise residual
398
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
399
+
400
+ # perform guidance
401
+ if do_classifier_free_guidance:
402
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
403
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
404
+
405
+ # compute the previous noisy sample x_t -> x_t-1
406
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
407
+
408
+ # call the callback, if provided
409
+ if callback is not None and i % callback_steps == 0:
410
+ step_idx = i // getattr(self.scheduler, "order", 1)
411
+ callback(step_idx, t, latents)
412
+
413
+ latents = 1 / 0.18215 * latents
414
+ image = self.vae.decode(latents).sample
415
+
416
+ image = (image / 2 + 0.5).clamp(0, 1)
417
+
418
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
419
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
420
+
421
+ if self.safety_checker is not None:
422
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(
423
+ self.device
424
+ )
425
+ image, has_nsfw_concept = self.safety_checker(
426
+ images=image, clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype)
427
+ )
428
+ else:
429
+ has_nsfw_concept = None
430
+
431
+ if output_type == "pil":
432
+ image = self.numpy_to_pil(image)
433
+
434
+ if not return_dict:
435
+ return (image, has_nsfw_concept)
436
+
437
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.22.0/one_step_unet.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import torch
3
+
4
+ from diffusers import DiffusionPipeline
5
+
6
+
7
+ class UnetSchedulerOneForwardPipeline(DiffusionPipeline):
8
+ def __init__(self, unet, scheduler):
9
+ super().__init__()
10
+
11
+ self.register_modules(unet=unet, scheduler=scheduler)
12
+
13
+ def __call__(self):
14
+ image = torch.randn(
15
+ (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size),
16
+ )
17
+ timestep = 1
18
+
19
+ model_output = self.unet(image, timestep).sample
20
+ scheduler_output = self.scheduler.step(model_output, timestep, image).prev_sample
21
+
22
+ result = scheduler_output - scheduler_output + torch.ones_like(scheduler_output)
23
+
24
+ return result
v0.22.0/pipeline_fabric.py ADDED
@@ -0,0 +1,751 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 FABRIC authors and 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
+ from typing import List, Optional, Union
15
+
16
+ import torch
17
+ from diffuser.utils.torch_utils import randn_tensor
18
+ from packaging import version
19
+ from PIL import Image
20
+ from transformers import CLIPTextModel, CLIPTokenizer
21
+
22
+ from diffusers import AutoencoderKL, UNet2DConditionModel
23
+ from diffusers.configuration_utils import FrozenDict
24
+ from diffusers.image_processor import VaeImageProcessor
25
+ from diffusers.loaders import LoraLoaderMixin, TextualInversionLoaderMixin
26
+ from diffusers.models.attention import BasicTransformerBlock
27
+ from diffusers.models.attention_processor import LoRAAttnProcessor
28
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
29
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
30
+ from diffusers.schedulers import EulerAncestralDiscreteScheduler, KarrasDiffusionSchedulers
31
+ from diffusers.utils import (
32
+ deprecate,
33
+ logging,
34
+ replace_example_docstring,
35
+ )
36
+
37
+
38
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
39
+
40
+ EXAMPLE_DOC_STRING = """
41
+ Examples:
42
+ ```py
43
+ >>> from diffusers import DiffusionPipeline
44
+ >>> import torch
45
+
46
+ >>> model_id = "dreamlike-art/dreamlike-photoreal-2.0"
47
+ >>> pipe = DiffusionPipeline(model_id, torch_dtype=torch.float16, custom_pipeline="pipeline_fabric")
48
+ >>> pipe = pipe.to("cuda")
49
+ >>> prompt = "a giant standing in a fantasy landscape best quality"
50
+ >>> liked = [] # list of images for positive feedback
51
+ >>> disliked = [] # list of images for negative feedback
52
+ >>> image = pipe(prompt, num_images=4, liked=liked, disliked=disliked).images[0]
53
+ ```
54
+ """
55
+
56
+
57
+ class FabricCrossAttnProcessor:
58
+ def __init__(self):
59
+ self.attntion_probs = None
60
+
61
+ def __call__(
62
+ self,
63
+ attn,
64
+ hidden_states,
65
+ encoder_hidden_states=None,
66
+ attention_mask=None,
67
+ weights=None,
68
+ lora_scale=1.0,
69
+ ):
70
+ batch_size, sequence_length, _ = (
71
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
72
+ )
73
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
74
+
75
+ if isinstance(attn.processor, LoRAAttnProcessor):
76
+ query = attn.to_q(hidden_states) + lora_scale * attn.processor.to_q_lora(hidden_states)
77
+ else:
78
+ query = attn.to_q(hidden_states)
79
+
80
+ if encoder_hidden_states is None:
81
+ encoder_hidden_states = hidden_states
82
+ elif attn.norm_cross:
83
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
84
+
85
+ if isinstance(attn.processor, LoRAAttnProcessor):
86
+ key = attn.to_k(encoder_hidden_states) + lora_scale * attn.processor.to_k_lora(encoder_hidden_states)
87
+ value = attn.to_v(encoder_hidden_states) + lora_scale * attn.processor.to_v_lora(encoder_hidden_states)
88
+ else:
89
+ key = attn.to_k(encoder_hidden_states)
90
+ value = attn.to_v(encoder_hidden_states)
91
+
92
+ query = attn.head_to_batch_dim(query)
93
+ key = attn.head_to_batch_dim(key)
94
+ value = attn.head_to_batch_dim(value)
95
+
96
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
97
+
98
+ if weights is not None:
99
+ if weights.shape[0] != 1:
100
+ weights = weights.repeat_interleave(attn.heads, dim=0)
101
+ attention_probs = attention_probs * weights[:, None]
102
+ attention_probs = attention_probs / attention_probs.sum(dim=-1, keepdim=True)
103
+
104
+ hidden_states = torch.bmm(attention_probs, value)
105
+ hidden_states = attn.batch_to_head_dim(hidden_states)
106
+
107
+ # linear proj
108
+ if isinstance(attn.processor, LoRAAttnProcessor):
109
+ hidden_states = attn.to_out[0](hidden_states) + lora_scale * attn.processor.to_out_lora(hidden_states)
110
+ else:
111
+ hidden_states = attn.to_out[0](hidden_states)
112
+ # dropout
113
+ hidden_states = attn.to_out[1](hidden_states)
114
+
115
+ return hidden_states
116
+
117
+
118
+ class FabricPipeline(DiffusionPipeline):
119
+ r"""
120
+ Pipeline for text-to-image generation using Stable Diffusion and conditioning the results using feedback images.
121
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
122
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
123
+
124
+ Args:
125
+ vae ([`AutoencoderKL`]):
126
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
127
+ text_encoder ([`~transformers.CLIPTextModel`]):
128
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
129
+ tokenizer ([`~transformers.CLIPTokenizer`]):
130
+ A `CLIPTokenizer` to tokenize text.
131
+ unet ([`UNet2DConditionModel`]):
132
+ A `UNet2DConditionModel` to denoise the encoded image latents.
133
+ scheduler ([`EulerAncestralDiscreteScheduler`]):
134
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
135
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
136
+ safety_checker ([`StableDiffusionSafetyChecker`]):
137
+ Classification module that estimates whether generated images could be considered offensive or harmful.
138
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
139
+ about a model's potential harms.
140
+ """
141
+
142
+ def __init__(
143
+ self,
144
+ vae: AutoencoderKL,
145
+ text_encoder: CLIPTextModel,
146
+ tokenizer: CLIPTokenizer,
147
+ unet: UNet2DConditionModel,
148
+ scheduler: KarrasDiffusionSchedulers,
149
+ requires_safety_checker: bool = True,
150
+ ):
151
+ super().__init__()
152
+
153
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
154
+ version.parse(unet.config._diffusers_version).base_version
155
+ ) < version.parse("0.9.0.dev0")
156
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
157
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
158
+ deprecation_message = (
159
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
160
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
161
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
162
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
163
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
164
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
165
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
166
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
167
+ " the `unet/config.json` file"
168
+ )
169
+
170
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
171
+ new_config = dict(unet.config)
172
+ new_config["sample_size"] = 64
173
+ unet._internal_dict = FrozenDict(new_config)
174
+
175
+ self.register_modules(
176
+ unet=unet,
177
+ vae=vae,
178
+ text_encoder=text_encoder,
179
+ tokenizer=tokenizer,
180
+ scheduler=scheduler,
181
+ )
182
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
183
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
184
+
185
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt
186
+ def _encode_prompt(
187
+ self,
188
+ prompt,
189
+ device,
190
+ num_images_per_prompt,
191
+ do_classifier_free_guidance,
192
+ negative_prompt=None,
193
+ prompt_embeds: Optional[torch.FloatTensor] = None,
194
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
195
+ lora_scale: Optional[float] = None,
196
+ ):
197
+ r"""
198
+ Encodes the prompt into text encoder hidden states.
199
+
200
+ Args:
201
+ prompt (`str` or `List[str]`, *optional*):
202
+ prompt to be encoded
203
+ device: (`torch.device`):
204
+ torch device
205
+ num_images_per_prompt (`int`):
206
+ number of images that should be generated per prompt
207
+ do_classifier_free_guidance (`bool`):
208
+ whether to use classifier free guidance or not
209
+ negative_prompt (`str` or `List[str]`, *optional*):
210
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
211
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
212
+ less than `1`).
213
+ prompt_embeds (`torch.FloatTensor`, *optional*):
214
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
215
+ provided, text embeddings will be generated from `prompt` input argument.
216
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
217
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
218
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
219
+ argument.
220
+ lora_scale (`float`, *optional*):
221
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
222
+ """
223
+ # set lora scale so that monkey patched LoRA
224
+ # function of text encoder can correctly access it
225
+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):
226
+ self._lora_scale = lora_scale
227
+
228
+ if prompt is not None and isinstance(prompt, str):
229
+ batch_size = 1
230
+ elif prompt is not None and isinstance(prompt, list):
231
+ batch_size = len(prompt)
232
+ else:
233
+ batch_size = prompt_embeds.shape[0]
234
+
235
+ if prompt_embeds is None:
236
+ # textual inversion: procecss multi-vector tokens if necessary
237
+ if isinstance(self, TextualInversionLoaderMixin):
238
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
239
+
240
+ text_inputs = self.tokenizer(
241
+ prompt,
242
+ padding="max_length",
243
+ max_length=self.tokenizer.model_max_length,
244
+ truncation=True,
245
+ return_tensors="pt",
246
+ )
247
+ text_input_ids = text_inputs.input_ids
248
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
249
+
250
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
251
+ text_input_ids, untruncated_ids
252
+ ):
253
+ removed_text = self.tokenizer.batch_decode(
254
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
255
+ )
256
+ logger.warning(
257
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
258
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
259
+ )
260
+
261
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
262
+ attention_mask = text_inputs.attention_mask.to(device)
263
+ else:
264
+ attention_mask = None
265
+
266
+ prompt_embeds = self.text_encoder(
267
+ text_input_ids.to(device),
268
+ attention_mask=attention_mask,
269
+ )
270
+ prompt_embeds = prompt_embeds[0]
271
+
272
+ if self.text_encoder is not None:
273
+ prompt_embeds_dtype = self.text_encoder.dtype
274
+ elif self.unet is not None:
275
+ prompt_embeds_dtype = self.unet.dtype
276
+ else:
277
+ prompt_embeds_dtype = prompt_embeds.dtype
278
+
279
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
280
+
281
+ bs_embed, seq_len, _ = prompt_embeds.shape
282
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
283
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
284
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
285
+
286
+ # get unconditional embeddings for classifier free guidance
287
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
288
+ uncond_tokens: List[str]
289
+ if negative_prompt is None:
290
+ uncond_tokens = [""] * batch_size
291
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
292
+ raise TypeError(
293
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
294
+ f" {type(prompt)}."
295
+ )
296
+ elif isinstance(negative_prompt, str):
297
+ uncond_tokens = [negative_prompt]
298
+ elif batch_size != len(negative_prompt):
299
+ raise ValueError(
300
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
301
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
302
+ " the batch size of `prompt`."
303
+ )
304
+ else:
305
+ uncond_tokens = negative_prompt
306
+
307
+ # textual inversion: procecss multi-vector tokens if necessary
308
+ if isinstance(self, TextualInversionLoaderMixin):
309
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
310
+
311
+ max_length = prompt_embeds.shape[1]
312
+ uncond_input = self.tokenizer(
313
+ uncond_tokens,
314
+ padding="max_length",
315
+ max_length=max_length,
316
+ truncation=True,
317
+ return_tensors="pt",
318
+ )
319
+
320
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
321
+ attention_mask = uncond_input.attention_mask.to(device)
322
+ else:
323
+ attention_mask = None
324
+
325
+ negative_prompt_embeds = self.text_encoder(
326
+ uncond_input.input_ids.to(device),
327
+ attention_mask=attention_mask,
328
+ )
329
+ negative_prompt_embeds = negative_prompt_embeds[0]
330
+
331
+ if do_classifier_free_guidance:
332
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
333
+ seq_len = negative_prompt_embeds.shape[1]
334
+
335
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
336
+
337
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
338
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
339
+
340
+ # For classifier free guidance, we need to do two forward passes.
341
+ # Here we concatenate the unconditional and text embeddings into a single batch
342
+ # to avoid doing two forward passes
343
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
344
+
345
+ return prompt_embeds
346
+
347
+ def get_unet_hidden_states(self, z_all, t, prompt_embd):
348
+ cached_hidden_states = []
349
+ for module in self.unet.modules():
350
+ if isinstance(module, BasicTransformerBlock):
351
+
352
+ def new_forward(self, hidden_states, *args, **kwargs):
353
+ cached_hidden_states.append(hidden_states.clone().detach().cpu())
354
+ return self.old_forward(hidden_states, *args, **kwargs)
355
+
356
+ module.attn1.old_forward = module.attn1.forward
357
+ module.attn1.forward = new_forward.__get__(module.attn1)
358
+
359
+ # run forward pass to cache hidden states, output can be discarded
360
+ _ = self.unet(z_all, t, encoder_hidden_states=prompt_embd)
361
+
362
+ # restore original forward pass
363
+ for module in self.unet.modules():
364
+ if isinstance(module, BasicTransformerBlock):
365
+ module.attn1.forward = module.attn1.old_forward
366
+ del module.attn1.old_forward
367
+
368
+ return cached_hidden_states
369
+
370
+ def unet_forward_with_cached_hidden_states(
371
+ self,
372
+ z_all,
373
+ t,
374
+ prompt_embd,
375
+ cached_pos_hiddens: Optional[List[torch.Tensor]] = None,
376
+ cached_neg_hiddens: Optional[List[torch.Tensor]] = None,
377
+ pos_weights=(0.8, 0.8),
378
+ neg_weights=(0.5, 0.5),
379
+ ):
380
+ if cached_pos_hiddens is None and cached_neg_hiddens is None:
381
+ return self.unet(z_all, t, encoder_hidden_states=prompt_embd)
382
+
383
+ local_pos_weights = torch.linspace(*pos_weights, steps=len(self.unet.down_blocks) + 1)[:-1].tolist()
384
+ local_neg_weights = torch.linspace(*neg_weights, steps=len(self.unet.down_blocks) + 1)[:-1].tolist()
385
+ for block, pos_weight, neg_weight in zip(
386
+ self.unet.down_blocks + [self.unet.mid_block] + self.unet.up_blocks,
387
+ local_pos_weights + [pos_weights[1]] + local_pos_weights[::-1],
388
+ local_neg_weights + [neg_weights[1]] + local_neg_weights[::-1],
389
+ ):
390
+ for module in block.modules():
391
+ if isinstance(module, BasicTransformerBlock):
392
+
393
+ def new_forward(
394
+ self,
395
+ hidden_states,
396
+ pos_weight=pos_weight,
397
+ neg_weight=neg_weight,
398
+ **kwargs,
399
+ ):
400
+ cond_hiddens, uncond_hiddens = hidden_states.chunk(2, dim=0)
401
+ batch_size, d_model = cond_hiddens.shape[:2]
402
+ device, dtype = hidden_states.device, hidden_states.dtype
403
+
404
+ weights = torch.ones(batch_size, d_model, device=device, dtype=dtype)
405
+ out_pos = self.old_forward(hidden_states)
406
+ out_neg = self.old_forward(hidden_states)
407
+
408
+ if cached_pos_hiddens is not None:
409
+ cached_pos_hs = cached_pos_hiddens.pop(0).to(hidden_states.device)
410
+ cond_pos_hs = torch.cat([cond_hiddens, cached_pos_hs], dim=1)
411
+ pos_weights = weights.clone().repeat(1, 1 + cached_pos_hs.shape[1] // d_model)
412
+ pos_weights[:, d_model:] = pos_weight
413
+ attn_with_weights = FabricCrossAttnProcessor()
414
+ out_pos = attn_with_weights(
415
+ self,
416
+ cond_hiddens,
417
+ encoder_hidden_states=cond_pos_hs,
418
+ weights=pos_weights,
419
+ )
420
+ else:
421
+ out_pos = self.old_forward(cond_hiddens)
422
+
423
+ if cached_neg_hiddens is not None:
424
+ cached_neg_hs = cached_neg_hiddens.pop(0).to(hidden_states.device)
425
+ uncond_neg_hs = torch.cat([uncond_hiddens, cached_neg_hs], dim=1)
426
+ neg_weights = weights.clone().repeat(1, 1 + cached_neg_hs.shape[1] // d_model)
427
+ neg_weights[:, d_model:] = neg_weight
428
+ attn_with_weights = FabricCrossAttnProcessor()
429
+ out_neg = attn_with_weights(
430
+ self,
431
+ uncond_hiddens,
432
+ encoder_hidden_states=uncond_neg_hs,
433
+ weights=neg_weights,
434
+ )
435
+ else:
436
+ out_neg = self.old_forward(uncond_hiddens)
437
+
438
+ out = torch.cat([out_pos, out_neg], dim=0)
439
+ return out
440
+
441
+ module.attn1.old_forward = module.attn1.forward
442
+ module.attn1.forward = new_forward.__get__(module.attn1)
443
+
444
+ out = self.unet(z_all, t, encoder_hidden_states=prompt_embd)
445
+
446
+ # restore original forward pass
447
+ for module in self.unet.modules():
448
+ if isinstance(module, BasicTransformerBlock):
449
+ module.attn1.forward = module.attn1.old_forward
450
+ del module.attn1.old_forward
451
+
452
+ return out
453
+
454
+ def preprocess_feedback_images(self, images, vae, dim, device, dtype, generator) -> torch.tensor:
455
+ images_t = [self.image_to_tensor(img, dim, dtype) for img in images]
456
+ images_t = torch.stack(images_t).to(device)
457
+ latents = vae.config.scaling_factor * vae.encode(images_t).latent_dist.sample(generator)
458
+
459
+ return torch.cat([latents], dim=0)
460
+
461
+ def check_inputs(
462
+ self,
463
+ prompt,
464
+ negative_prompt=None,
465
+ liked=None,
466
+ disliked=None,
467
+ height=None,
468
+ width=None,
469
+ ):
470
+ if prompt is None:
471
+ raise ValueError("Provide `prompt`. Cannot leave both `prompt` undefined.")
472
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
473
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
474
+
475
+ if negative_prompt is not None and (
476
+ not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
477
+ ):
478
+ raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")
479
+
480
+ if liked is not None and not isinstance(liked, list):
481
+ raise ValueError(f"`liked` has to be of type `list` but is {type(liked)}")
482
+
483
+ if disliked is not None and not isinstance(disliked, list):
484
+ raise ValueError(f"`disliked` has to be of type `list` but is {type(disliked)}")
485
+
486
+ if height is not None and not isinstance(height, int):
487
+ raise ValueError(f"`height` has to be of type `int` but is {type(height)}")
488
+
489
+ if width is not None and not isinstance(width, int):
490
+ raise ValueError(f"`width` has to be of type `int` but is {type(width)}")
491
+
492
+ @torch.no_grad()
493
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
494
+ def __call__(
495
+ self,
496
+ prompt: Optional[Union[str, List[str]]] = "",
497
+ negative_prompt: Optional[Union[str, List[str]]] = "lowres, bad anatomy, bad hands, cropped, worst quality",
498
+ liked: Optional[Union[List[str], List[Image.Image]]] = [],
499
+ disliked: Optional[Union[List[str], List[Image.Image]]] = [],
500
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
501
+ height: int = 512,
502
+ width: int = 512,
503
+ return_dict: bool = True,
504
+ num_images: int = 4,
505
+ guidance_scale: float = 7.0,
506
+ num_inference_steps: int = 20,
507
+ output_type: Optional[str] = "pil",
508
+ feedback_start_ratio: float = 0.33,
509
+ feedback_end_ratio: float = 0.66,
510
+ min_weight: float = 0.05,
511
+ max_weight: float = 0.8,
512
+ neg_scale: float = 0.5,
513
+ pos_bottleneck_scale: float = 1.0,
514
+ neg_bottleneck_scale: float = 1.0,
515
+ latents: Optional[torch.FloatTensor] = None,
516
+ ):
517
+ r"""
518
+ The call function to the pipeline for generation. Generate a trajectory of images with binary feedback. The
519
+ feedback can be given as a list of liked and disliked images.
520
+
521
+ Args:
522
+ prompt (`str` or `List[str]`, *optional*):
523
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`
524
+ instead.
525
+ negative_prompt (`str` or `List[str]`, *optional*):
526
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
527
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
528
+ liked (`List[Image.Image]` or `List[str]`, *optional*):
529
+ Encourages images with liked features.
530
+ disliked (`List[Image.Image]` or `List[str]`, *optional*):
531
+ Discourages images with disliked features.
532
+ generator (`torch.Generator` or `List[torch.Generator]` or `int`, *optional*):
533
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) or an `int` to
534
+ make generation deterministic.
535
+ height (`int`, *optional*, defaults to 512):
536
+ Height of the generated image.
537
+ width (`int`, *optional*, defaults to 512):
538
+ Width of the generated image.
539
+ num_images (`int`, *optional*, defaults to 4):
540
+ The number of images to generate per prompt.
541
+ guidance_scale (`float`, *optional*, defaults to 7.0):
542
+ A higher guidance scale value encourages the model to generate images closely linked to the text
543
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
544
+ num_inference_steps (`int`, *optional*, defaults to 20):
545
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
546
+ expense of slower inference.
547
+ output_type (`str`, *optional*, defaults to `"pil"`):
548
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
549
+ return_dict (`bool`, *optional*, defaults to `True`):
550
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
551
+ plain tuple.
552
+ feedback_start_ratio (`float`, *optional*, defaults to `.33`):
553
+ Start point for providing feedback (between 0 and 1).
554
+ feedback_end_ratio (`float`, *optional*, defaults to `.66`):
555
+ End point for providing feedback (between 0 and 1).
556
+ min_weight (`float`, *optional*, defaults to `.05`):
557
+ Minimum weight for feedback.
558
+ max_weight (`float`, *optional*, defults tp `1.0`):
559
+ Maximum weight for feedback.
560
+ neg_scale (`float`, *optional*, defaults to `.5`):
561
+ Scale factor for negative feedback.
562
+
563
+ Examples:
564
+
565
+ Returns:
566
+ [`~pipelines.fabric.FabricPipelineOutput`] or `tuple`:
567
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
568
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
569
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
570
+ "not-safe-for-work" (nsfw) content.
571
+
572
+ """
573
+
574
+ self.check_inputs(prompt, negative_prompt, liked, disliked)
575
+
576
+ device = self._execution_device
577
+ dtype = self.unet.dtype
578
+
579
+ if isinstance(prompt, str) and prompt is not None:
580
+ batch_size = 1
581
+ elif isinstance(prompt, list) and prompt is not None:
582
+ batch_size = len(prompt)
583
+ else:
584
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
585
+
586
+ if isinstance(negative_prompt, str):
587
+ negative_prompt = negative_prompt
588
+ elif isinstance(negative_prompt, list):
589
+ negative_prompt = negative_prompt
590
+ else:
591
+ assert len(negative_prompt) == batch_size
592
+
593
+ shape = (
594
+ batch_size * num_images,
595
+ self.unet.config.in_channels,
596
+ height // self.vae_scale_factor,
597
+ width // self.vae_scale_factor,
598
+ )
599
+ latent_noise = randn_tensor(
600
+ shape,
601
+ device=device,
602
+ dtype=dtype,
603
+ generator=generator,
604
+ )
605
+
606
+ positive_latents = (
607
+ self.preprocess_feedback_images(liked, self.vae, (height, width), device, dtype, generator)
608
+ if liked and len(liked) > 0
609
+ else torch.tensor(
610
+ [],
611
+ device=device,
612
+ dtype=dtype,
613
+ )
614
+ )
615
+ negative_latents = (
616
+ self.preprocess_feedback_images(disliked, self.vae, (height, width), device, dtype, generator)
617
+ if disliked and len(disliked) > 0
618
+ else torch.tensor(
619
+ [],
620
+ device=device,
621
+ dtype=dtype,
622
+ )
623
+ )
624
+
625
+ do_classifier_free_guidance = guidance_scale > 0.1
626
+
627
+ (prompt_neg_embs, prompt_pos_embs) = self._encode_prompt(
628
+ prompt,
629
+ device,
630
+ num_images,
631
+ do_classifier_free_guidance,
632
+ negative_prompt,
633
+ ).split([num_images * batch_size, num_images * batch_size])
634
+
635
+ batched_prompt_embd = torch.cat([prompt_pos_embs, prompt_neg_embs], dim=0)
636
+
637
+ null_tokens = self.tokenizer(
638
+ [""],
639
+ return_tensors="pt",
640
+ max_length=self.tokenizer.model_max_length,
641
+ padding="max_length",
642
+ truncation=True,
643
+ )
644
+
645
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
646
+ attention_mask = null_tokens.attention_mask.to(device)
647
+ else:
648
+ attention_mask = None
649
+
650
+ null_prompt_emb = self.text_encoder(
651
+ input_ids=null_tokens.input_ids.to(device),
652
+ attention_mask=attention_mask,
653
+ ).last_hidden_state
654
+
655
+ null_prompt_emb = null_prompt_emb.to(device=device, dtype=dtype)
656
+
657
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
658
+ timesteps = self.scheduler.timesteps
659
+ latent_noise = latent_noise * self.scheduler.init_noise_sigma
660
+
661
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
662
+
663
+ ref_start_idx = round(len(timesteps) * feedback_start_ratio)
664
+ ref_end_idx = round(len(timesteps) * feedback_end_ratio)
665
+
666
+ with self.progress_bar(total=num_inference_steps) as pbar:
667
+ for i, t in enumerate(timesteps):
668
+ sigma = self.scheduler.sigma_t[t] if hasattr(self.scheduler, "sigma_t") else 0
669
+ if hasattr(self.scheduler, "sigmas"):
670
+ sigma = self.scheduler.sigmas[i]
671
+
672
+ alpha_hat = 1 / (sigma**2 + 1)
673
+
674
+ z_single = self.scheduler.scale_model_input(latent_noise, t)
675
+ z_all = torch.cat([z_single] * 2, dim=0)
676
+ z_ref = torch.cat([positive_latents, negative_latents], dim=0)
677
+
678
+ if i >= ref_start_idx and i <= ref_end_idx:
679
+ weight_factor = max_weight
680
+ else:
681
+ weight_factor = min_weight
682
+
683
+ pos_ws = (weight_factor, weight_factor * pos_bottleneck_scale)
684
+ neg_ws = (weight_factor * neg_scale, weight_factor * neg_scale * neg_bottleneck_scale)
685
+
686
+ if z_ref.size(0) > 0 and weight_factor > 0:
687
+ noise = torch.randn_like(z_ref)
688
+ if isinstance(self.scheduler, EulerAncestralDiscreteScheduler):
689
+ z_ref_noised = (alpha_hat**0.5 * z_ref + (1 - alpha_hat) ** 0.5 * noise).type(dtype)
690
+ else:
691
+ z_ref_noised = self.scheduler.add_noise(z_ref, noise, t)
692
+
693
+ ref_prompt_embd = torch.cat(
694
+ [null_prompt_emb] * (len(positive_latents) + len(negative_latents)), dim=0
695
+ )
696
+ cached_hidden_states = self.get_unet_hidden_states(z_ref_noised, t, ref_prompt_embd)
697
+
698
+ n_pos, n_neg = positive_latents.shape[0], negative_latents.shape[0]
699
+ cached_pos_hs, cached_neg_hs = [], []
700
+ for hs in cached_hidden_states:
701
+ cached_pos, cached_neg = hs.split([n_pos, n_neg], dim=0)
702
+ cached_pos = cached_pos.view(1, -1, *cached_pos.shape[2:]).expand(num_images, -1, -1)
703
+ cached_neg = cached_neg.view(1, -1, *cached_neg.shape[2:]).expand(num_images, -1, -1)
704
+ cached_pos_hs.append(cached_pos)
705
+ cached_neg_hs.append(cached_neg)
706
+
707
+ if n_pos == 0:
708
+ cached_pos_hs = None
709
+ if n_neg == 0:
710
+ cached_neg_hs = None
711
+ else:
712
+ cached_pos_hs, cached_neg_hs = None, None
713
+ unet_out = self.unet_forward_with_cached_hidden_states(
714
+ z_all,
715
+ t,
716
+ prompt_embd=batched_prompt_embd,
717
+ cached_pos_hiddens=cached_pos_hs,
718
+ cached_neg_hiddens=cached_neg_hs,
719
+ pos_weights=pos_ws,
720
+ neg_weights=neg_ws,
721
+ )[0]
722
+
723
+ noise_cond, noise_uncond = unet_out.chunk(2)
724
+ guidance = noise_cond - noise_uncond
725
+ noise_pred = noise_uncond + guidance_scale * guidance
726
+ latent_noise = self.scheduler.step(noise_pred, t, latent_noise)[0]
727
+
728
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
729
+ pbar.update()
730
+
731
+ y = self.vae.decode(latent_noise / self.vae.config.scaling_factor, return_dict=False)[0]
732
+ imgs = self.image_processor.postprocess(
733
+ y,
734
+ output_type=output_type,
735
+ )
736
+
737
+ if not return_dict:
738
+ return imgs
739
+
740
+ return StableDiffusionPipelineOutput(imgs, False)
741
+
742
+ def image_to_tensor(self, image: Union[str, Image.Image], dim: tuple, dtype):
743
+ """
744
+ Convert latent PIL image to a torch tensor for further processing.
745
+ """
746
+ if isinstance(image, str):
747
+ image = Image.open(image)
748
+ if not image.mode == "RGB":
749
+ image = image.convert("RGB")
750
+ image = self.image_processor.preprocess(image, height=dim[0], width=dim[1])[0]
751
+ return image.type(dtype)
v0.22.0/pipeline_prompt2prompt.py ADDED
@@ -0,0 +1,860 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from __future__ import annotations
16
+
17
+ import abc
18
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
19
+
20
+ import numpy as np
21
+ import torch
22
+ import torch.nn.functional as F
23
+
24
+ from ...src.diffusers.models.attention import Attention
25
+ from ...src.diffusers.pipelines.stable_diffusion import StableDiffusionPipeline, StableDiffusionPipelineOutput
26
+
27
+
28
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
29
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
30
+ """
31
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
32
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
33
+ """
34
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
35
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
36
+ # rescale the results from guidance (fixes overexposure)
37
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
38
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
39
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
40
+ return noise_cfg
41
+
42
+
43
+ class Prompt2PromptPipeline(StableDiffusionPipeline):
44
+ r"""
45
+ Args:
46
+ Prompt-to-Prompt-Pipeline for text-to-image generation using Stable Diffusion. This model inherits from
47
+ [`StableDiffusionPipeline`]. Check the superclass documentation for the generic methods the library implements for
48
+ all the pipelines (such as downloading or saving, running on a particular device, etc.)
49
+ vae ([`AutoencoderKL`]):
50
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
51
+ text_encoder ([`CLIPTextModel`]):
52
+ Frozen text-encoder. Stable Diffusion uses the text portion of
53
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
54
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
55
+ tokenizer (`CLIPTokenizer`):
56
+ Tokenizer of class
57
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
58
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents. scheduler
59
+ ([`SchedulerMixin`]):
60
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
61
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
62
+ safety_checker ([`StableDiffusionSafetyChecker`]):
63
+ Classification module that estimates whether generated images could be considered offensive or harmful.
64
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
65
+ feature_extractor ([`CLIPFeatureExtractor`]):
66
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
67
+ """
68
+ _optional_components = ["safety_checker", "feature_extractor"]
69
+
70
+ @torch.no_grad()
71
+ def __call__(
72
+ self,
73
+ prompt: Union[str, List[str]],
74
+ height: Optional[int] = None,
75
+ width: Optional[int] = None,
76
+ num_inference_steps: int = 50,
77
+ guidance_scale: float = 7.5,
78
+ negative_prompt: Optional[Union[str, List[str]]] = None,
79
+ num_images_per_prompt: Optional[int] = 1,
80
+ eta: float = 0.0,
81
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
82
+ latents: Optional[torch.FloatTensor] = None,
83
+ prompt_embeds: Optional[torch.FloatTensor] = None,
84
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
85
+ output_type: Optional[str] = "pil",
86
+ return_dict: bool = True,
87
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
88
+ callback_steps: Optional[int] = 1,
89
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
90
+ guidance_rescale: float = 0.0,
91
+ ):
92
+ r"""
93
+ Function invoked when calling the pipeline for generation.
94
+
95
+ Args:
96
+ prompt (`str` or `List[str]`):
97
+ The prompt or prompts to guide the image generation.
98
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
99
+ The height in pixels of the generated image.
100
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
101
+ The width in pixels of the generated image.
102
+ num_inference_steps (`int`, *optional*, defaults to 50):
103
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
104
+ expense of slower inference.
105
+ guidance_scale (`float`, *optional*, defaults to 7.5):
106
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
107
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
108
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
109
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
110
+ usually at the expense of lower image quality.
111
+ negative_prompt (`str` or `List[str]`, *optional*):
112
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
113
+ if `guidance_scale` is less than `1`).
114
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
115
+ The number of images to generate per prompt.
116
+ eta (`float`, *optional*, defaults to 0.0):
117
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
118
+ [`schedulers.DDIMScheduler`], will be ignored for others.
119
+ generator (`torch.Generator`, *optional*):
120
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
121
+ to make generation deterministic.
122
+ latents (`torch.FloatTensor`, *optional*):
123
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
124
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
125
+ tensor will ge generated by sampling using the supplied random `generator`.
126
+ output_type (`str`, *optional*, defaults to `"pil"`):
127
+ The output format of the generate image. Choose between
128
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
129
+ return_dict (`bool`, *optional*, defaults to `True`):
130
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
131
+ plain tuple.
132
+ callback (`Callable`, *optional*):
133
+ A function that will be called every `callback_steps` steps during inference. The function will be
134
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
135
+ callback_steps (`int`, *optional*, defaults to 1):
136
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
137
+ called at every step.
138
+ cross_attention_kwargs (`dict`, *optional*):
139
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
140
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
141
+
142
+ The keyword arguments to configure the edit are:
143
+ - edit_type (`str`). The edit type to apply. Can be either of `replace`, `refine`, `reweight`.
144
+ - n_cross_replace (`int`): Number of diffusion steps in which cross attention should be replaced
145
+ - n_self_replace (`int`): Number of diffusion steps in which self attention should be replaced
146
+ - local_blend_words(`List[str]`, *optional*, default to `None`): Determines which area should be
147
+ changed. If None, then the whole image can be changed.
148
+ - equalizer_words(`List[str]`, *optional*, default to `None`): Required for edit type `reweight`.
149
+ Determines which words should be enhanced.
150
+ - equalizer_strengths (`List[float]`, *optional*, default to `None`) Required for edit type `reweight`.
151
+ Determines which how much the words in `equalizer_words` should be enhanced.
152
+
153
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
154
+ Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
155
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
156
+ using zero terminal SNR.
157
+
158
+ Returns:
159
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
160
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
161
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
162
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
163
+ (nsfw) content, according to the `safety_checker`.
164
+ """
165
+
166
+ self.controller = create_controller(
167
+ prompt, cross_attention_kwargs, num_inference_steps, tokenizer=self.tokenizer, device=self.device
168
+ )
169
+ self.register_attention_control(self.controller) # add attention controller
170
+
171
+ # 0. Default height and width to unet
172
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
173
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
174
+
175
+ # 1. Check inputs. Raise error if not correct
176
+ self.check_inputs(prompt, height, width, callback_steps)
177
+
178
+ # 2. Define call parameters
179
+ if prompt is not None and isinstance(prompt, str):
180
+ batch_size = 1
181
+ elif prompt is not None and isinstance(prompt, list):
182
+ batch_size = len(prompt)
183
+ else:
184
+ batch_size = prompt_embeds.shape[0]
185
+
186
+ device = self._execution_device
187
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
188
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
189
+ # corresponds to doing no classifier free guidance.
190
+ do_classifier_free_guidance = guidance_scale > 1.0
191
+
192
+ # 3. Encode input prompt
193
+ text_encoder_lora_scale = (
194
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
195
+ )
196
+ prompt_embeds = self._encode_prompt(
197
+ prompt,
198
+ device,
199
+ num_images_per_prompt,
200
+ do_classifier_free_guidance,
201
+ negative_prompt,
202
+ prompt_embeds=prompt_embeds,
203
+ negative_prompt_embeds=negative_prompt_embeds,
204
+ lora_scale=text_encoder_lora_scale,
205
+ )
206
+
207
+ # 4. Prepare timesteps
208
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
209
+ timesteps = self.scheduler.timesteps
210
+
211
+ # 5. Prepare latent variables
212
+ num_channels_latents = self.unet.config.in_channels
213
+ latents = self.prepare_latents(
214
+ batch_size * num_images_per_prompt,
215
+ num_channels_latents,
216
+ height,
217
+ width,
218
+ prompt_embeds.dtype,
219
+ device,
220
+ generator,
221
+ latents,
222
+ )
223
+
224
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
225
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
226
+
227
+ # 7. Denoising loop
228
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
229
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
230
+ for i, t in enumerate(timesteps):
231
+ # expand the latents if we are doing classifier free guidance
232
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
233
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
234
+
235
+ # predict the noise residual
236
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=prompt_embeds).sample
237
+
238
+ # perform guidance
239
+ if do_classifier_free_guidance:
240
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
241
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
242
+
243
+ if do_classifier_free_guidance and guidance_rescale > 0.0:
244
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
245
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
246
+
247
+ # compute the previous noisy sample x_t -> x_t-1
248
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
249
+
250
+ # step callback
251
+ latents = self.controller.step_callback(latents)
252
+
253
+ # call the callback, if provided
254
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
255
+ progress_bar.update()
256
+ if callback is not None and i % callback_steps == 0:
257
+ step_idx = i // getattr(self.scheduler, "order", 1)
258
+ callback(step_idx, t, latents)
259
+
260
+ # 8. Post-processing
261
+ if not output_type == "latent":
262
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
263
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
264
+ else:
265
+ image = latents
266
+ has_nsfw_concept = None
267
+
268
+ # 9. Run safety checker
269
+ if has_nsfw_concept is None:
270
+ do_denormalize = [True] * image.shape[0]
271
+ else:
272
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
273
+
274
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
275
+
276
+ # Offload last model to CPU
277
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
278
+ self.final_offload_hook.offload()
279
+
280
+ if not return_dict:
281
+ return (image, has_nsfw_concept)
282
+
283
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
284
+
285
+ def register_attention_control(self, controller):
286
+ attn_procs = {}
287
+ cross_att_count = 0
288
+ for name in self.unet.attn_processors.keys():
289
+ None if name.endswith("attn1.processor") else self.unet.config.cross_attention_dim
290
+ if name.startswith("mid_block"):
291
+ self.unet.config.block_out_channels[-1]
292
+ place_in_unet = "mid"
293
+ elif name.startswith("up_blocks"):
294
+ block_id = int(name[len("up_blocks.")])
295
+ list(reversed(self.unet.config.block_out_channels))[block_id]
296
+ place_in_unet = "up"
297
+ elif name.startswith("down_blocks"):
298
+ block_id = int(name[len("down_blocks.")])
299
+ self.unet.config.block_out_channels[block_id]
300
+ place_in_unet = "down"
301
+ else:
302
+ continue
303
+ cross_att_count += 1
304
+ attn_procs[name] = P2PCrossAttnProcessor(controller=controller, place_in_unet=place_in_unet)
305
+
306
+ self.unet.set_attn_processor(attn_procs)
307
+ controller.num_att_layers = cross_att_count
308
+
309
+
310
+ class P2PCrossAttnProcessor:
311
+ def __init__(self, controller, place_in_unet):
312
+ super().__init__()
313
+ self.controller = controller
314
+ self.place_in_unet = place_in_unet
315
+
316
+ def __call__(self, attn: Attention, hidden_states, encoder_hidden_states=None, attention_mask=None):
317
+ batch_size, sequence_length, _ = hidden_states.shape
318
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
319
+
320
+ query = attn.to_q(hidden_states)
321
+
322
+ is_cross = encoder_hidden_states is not None
323
+ encoder_hidden_states = encoder_hidden_states if encoder_hidden_states is not None else hidden_states
324
+ key = attn.to_k(encoder_hidden_states)
325
+ value = attn.to_v(encoder_hidden_states)
326
+
327
+ query = attn.head_to_batch_dim(query)
328
+ key = attn.head_to_batch_dim(key)
329
+ value = attn.head_to_batch_dim(value)
330
+
331
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
332
+
333
+ # one line change
334
+ self.controller(attention_probs, is_cross, self.place_in_unet)
335
+
336
+ hidden_states = torch.bmm(attention_probs, value)
337
+ hidden_states = attn.batch_to_head_dim(hidden_states)
338
+
339
+ # linear proj
340
+ hidden_states = attn.to_out[0](hidden_states)
341
+ # dropout
342
+ hidden_states = attn.to_out[1](hidden_states)
343
+
344
+ return hidden_states
345
+
346
+
347
+ def create_controller(
348
+ prompts: List[str], cross_attention_kwargs: Dict, num_inference_steps: int, tokenizer, device
349
+ ) -> AttentionControl:
350
+ edit_type = cross_attention_kwargs.get("edit_type", None)
351
+ local_blend_words = cross_attention_kwargs.get("local_blend_words", None)
352
+ equalizer_words = cross_attention_kwargs.get("equalizer_words", None)
353
+ equalizer_strengths = cross_attention_kwargs.get("equalizer_strengths", None)
354
+ n_cross_replace = cross_attention_kwargs.get("n_cross_replace", 0.4)
355
+ n_self_replace = cross_attention_kwargs.get("n_self_replace", 0.4)
356
+
357
+ # only replace
358
+ if edit_type == "replace" and local_blend_words is None:
359
+ return AttentionReplace(
360
+ prompts, num_inference_steps, n_cross_replace, n_self_replace, tokenizer=tokenizer, device=device
361
+ )
362
+
363
+ # replace + localblend
364
+ if edit_type == "replace" and local_blend_words is not None:
365
+ lb = LocalBlend(prompts, local_blend_words, tokenizer=tokenizer, device=device)
366
+ return AttentionReplace(
367
+ prompts, num_inference_steps, n_cross_replace, n_self_replace, lb, tokenizer=tokenizer, device=device
368
+ )
369
+
370
+ # only refine
371
+ if edit_type == "refine" and local_blend_words is None:
372
+ return AttentionRefine(
373
+ prompts, num_inference_steps, n_cross_replace, n_self_replace, tokenizer=tokenizer, device=device
374
+ )
375
+
376
+ # refine + localblend
377
+ if edit_type == "refine" and local_blend_words is not None:
378
+ lb = LocalBlend(prompts, local_blend_words, tokenizer=tokenizer, device=device)
379
+ return AttentionRefine(
380
+ prompts, num_inference_steps, n_cross_replace, n_self_replace, lb, tokenizer=tokenizer, device=device
381
+ )
382
+
383
+ # reweight
384
+ if edit_type == "reweight":
385
+ assert (
386
+ equalizer_words is not None and equalizer_strengths is not None
387
+ ), "To use reweight edit, please specify equalizer_words and equalizer_strengths."
388
+ assert len(equalizer_words) == len(
389
+ equalizer_strengths
390
+ ), "equalizer_words and equalizer_strengths must be of same length."
391
+ equalizer = get_equalizer(prompts[1], equalizer_words, equalizer_strengths, tokenizer=tokenizer)
392
+ return AttentionReweight(
393
+ prompts,
394
+ num_inference_steps,
395
+ n_cross_replace,
396
+ n_self_replace,
397
+ tokenizer=tokenizer,
398
+ device=device,
399
+ equalizer=equalizer,
400
+ )
401
+
402
+ raise ValueError(f"Edit type {edit_type} not recognized. Use one of: replace, refine, reweight.")
403
+
404
+
405
+ class AttentionControl(abc.ABC):
406
+ def step_callback(self, x_t):
407
+ return x_t
408
+
409
+ def between_steps(self):
410
+ return
411
+
412
+ @property
413
+ def num_uncond_att_layers(self):
414
+ return 0
415
+
416
+ @abc.abstractmethod
417
+ def forward(self, attn, is_cross: bool, place_in_unet: str):
418
+ raise NotImplementedError
419
+
420
+ def __call__(self, attn, is_cross: bool, place_in_unet: str):
421
+ if self.cur_att_layer >= self.num_uncond_att_layers:
422
+ h = attn.shape[0]
423
+ attn[h // 2 :] = self.forward(attn[h // 2 :], is_cross, place_in_unet)
424
+ self.cur_att_layer += 1
425
+ if self.cur_att_layer == self.num_att_layers + self.num_uncond_att_layers:
426
+ self.cur_att_layer = 0
427
+ self.cur_step += 1
428
+ self.between_steps()
429
+ return attn
430
+
431
+ def reset(self):
432
+ self.cur_step = 0
433
+ self.cur_att_layer = 0
434
+
435
+ def __init__(self):
436
+ self.cur_step = 0
437
+ self.num_att_layers = -1
438
+ self.cur_att_layer = 0
439
+
440
+
441
+ class EmptyControl(AttentionControl):
442
+ def forward(self, attn, is_cross: bool, place_in_unet: str):
443
+ return attn
444
+
445
+
446
+ class AttentionStore(AttentionControl):
447
+ @staticmethod
448
+ def get_empty_store():
449
+ return {"down_cross": [], "mid_cross": [], "up_cross": [], "down_self": [], "mid_self": [], "up_self": []}
450
+
451
+ def forward(self, attn, is_cross: bool, place_in_unet: str):
452
+ key = f"{place_in_unet}_{'cross' if is_cross else 'self'}"
453
+ if attn.shape[1] <= 32**2: # avoid memory overhead
454
+ self.step_store[key].append(attn)
455
+ return attn
456
+
457
+ def between_steps(self):
458
+ if len(self.attention_store) == 0:
459
+ self.attention_store = self.step_store
460
+ else:
461
+ for key in self.attention_store:
462
+ for i in range(len(self.attention_store[key])):
463
+ self.attention_store[key][i] += self.step_store[key][i]
464
+ self.step_store = self.get_empty_store()
465
+
466
+ def get_average_attention(self):
467
+ average_attention = {
468
+ key: [item / self.cur_step for item in self.attention_store[key]] for key in self.attention_store
469
+ }
470
+ return average_attention
471
+
472
+ def reset(self):
473
+ super(AttentionStore, self).reset()
474
+ self.step_store = self.get_empty_store()
475
+ self.attention_store = {}
476
+
477
+ def __init__(self):
478
+ super(AttentionStore, self).__init__()
479
+ self.step_store = self.get_empty_store()
480
+ self.attention_store = {}
481
+
482
+
483
+ class LocalBlend:
484
+ def __call__(self, x_t, attention_store):
485
+ k = 1
486
+ maps = attention_store["down_cross"][2:4] + attention_store["up_cross"][:3]
487
+ maps = [item.reshape(self.alpha_layers.shape[0], -1, 1, 16, 16, self.max_num_words) for item in maps]
488
+ maps = torch.cat(maps, dim=1)
489
+ maps = (maps * self.alpha_layers).sum(-1).mean(1)
490
+ mask = F.max_pool2d(maps, (k * 2 + 1, k * 2 + 1), (1, 1), padding=(k, k))
491
+ mask = F.interpolate(mask, size=(x_t.shape[2:]))
492
+ mask = mask / mask.max(2, keepdims=True)[0].max(3, keepdims=True)[0]
493
+ mask = mask.gt(self.threshold)
494
+ mask = (mask[:1] + mask[1:]).float()
495
+ x_t = x_t[:1] + mask * (x_t - x_t[:1])
496
+ return x_t
497
+
498
+ def __init__(
499
+ self, prompts: List[str], words: [List[List[str]]], tokenizer, device, threshold=0.3, max_num_words=77
500
+ ):
501
+ self.max_num_words = 77
502
+
503
+ alpha_layers = torch.zeros(len(prompts), 1, 1, 1, 1, self.max_num_words)
504
+ for i, (prompt, words_) in enumerate(zip(prompts, words)):
505
+ if isinstance(words_, str):
506
+ words_ = [words_]
507
+ for word in words_:
508
+ ind = get_word_inds(prompt, word, tokenizer)
509
+ alpha_layers[i, :, :, :, :, ind] = 1
510
+ self.alpha_layers = alpha_layers.to(device)
511
+ self.threshold = threshold
512
+
513
+
514
+ class AttentionControlEdit(AttentionStore, abc.ABC):
515
+ def step_callback(self, x_t):
516
+ if self.local_blend is not None:
517
+ x_t = self.local_blend(x_t, self.attention_store)
518
+ return x_t
519
+
520
+ def replace_self_attention(self, attn_base, att_replace):
521
+ if att_replace.shape[2] <= 16**2:
522
+ return attn_base.unsqueeze(0).expand(att_replace.shape[0], *attn_base.shape)
523
+ else:
524
+ return att_replace
525
+
526
+ @abc.abstractmethod
527
+ def replace_cross_attention(self, attn_base, att_replace):
528
+ raise NotImplementedError
529
+
530
+ def forward(self, attn, is_cross: bool, place_in_unet: str):
531
+ super(AttentionControlEdit, self).forward(attn, is_cross, place_in_unet)
532
+ # FIXME not replace correctly
533
+ if is_cross or (self.num_self_replace[0] <= self.cur_step < self.num_self_replace[1]):
534
+ h = attn.shape[0] // (self.batch_size)
535
+ attn = attn.reshape(self.batch_size, h, *attn.shape[1:])
536
+ attn_base, attn_repalce = attn[0], attn[1:]
537
+ if is_cross:
538
+ alpha_words = self.cross_replace_alpha[self.cur_step]
539
+ attn_repalce_new = (
540
+ self.replace_cross_attention(attn_base, attn_repalce) * alpha_words
541
+ + (1 - alpha_words) * attn_repalce
542
+ )
543
+ attn[1:] = attn_repalce_new
544
+ else:
545
+ attn[1:] = self.replace_self_attention(attn_base, attn_repalce)
546
+ attn = attn.reshape(self.batch_size * h, *attn.shape[2:])
547
+ return attn
548
+
549
+ def __init__(
550
+ self,
551
+ prompts,
552
+ num_steps: int,
553
+ cross_replace_steps: Union[float, Tuple[float, float], Dict[str, Tuple[float, float]]],
554
+ self_replace_steps: Union[float, Tuple[float, float]],
555
+ local_blend: Optional[LocalBlend],
556
+ tokenizer,
557
+ device,
558
+ ):
559
+ super(AttentionControlEdit, self).__init__()
560
+ # add tokenizer and device here
561
+
562
+ self.tokenizer = tokenizer
563
+ self.device = device
564
+
565
+ self.batch_size = len(prompts)
566
+ self.cross_replace_alpha = get_time_words_attention_alpha(
567
+ prompts, num_steps, cross_replace_steps, self.tokenizer
568
+ ).to(self.device)
569
+ if isinstance(self_replace_steps, float):
570
+ self_replace_steps = 0, self_replace_steps
571
+ self.num_self_replace = int(num_steps * self_replace_steps[0]), int(num_steps * self_replace_steps[1])
572
+ self.local_blend = local_blend # 在外面定义后传进来
573
+
574
+
575
+ class AttentionReplace(AttentionControlEdit):
576
+ def replace_cross_attention(self, attn_base, att_replace):
577
+ return torch.einsum("hpw,bwn->bhpn", attn_base, self.mapper)
578
+
579
+ def __init__(
580
+ self,
581
+ prompts,
582
+ num_steps: int,
583
+ cross_replace_steps: float,
584
+ self_replace_steps: float,
585
+ local_blend: Optional[LocalBlend] = None,
586
+ tokenizer=None,
587
+ device=None,
588
+ ):
589
+ super(AttentionReplace, self).__init__(
590
+ prompts, num_steps, cross_replace_steps, self_replace_steps, local_blend, tokenizer, device
591
+ )
592
+ self.mapper = get_replacement_mapper(prompts, self.tokenizer).to(self.device)
593
+
594
+
595
+ class AttentionRefine(AttentionControlEdit):
596
+ def replace_cross_attention(self, attn_base, att_replace):
597
+ attn_base_replace = attn_base[:, :, self.mapper].permute(2, 0, 1, 3)
598
+ attn_replace = attn_base_replace * self.alphas + att_replace * (1 - self.alphas)
599
+ return attn_replace
600
+
601
+ def __init__(
602
+ self,
603
+ prompts,
604
+ num_steps: int,
605
+ cross_replace_steps: float,
606
+ self_replace_steps: float,
607
+ local_blend: Optional[LocalBlend] = None,
608
+ tokenizer=None,
609
+ device=None,
610
+ ):
611
+ super(AttentionRefine, self).__init__(
612
+ prompts, num_steps, cross_replace_steps, self_replace_steps, local_blend, tokenizer, device
613
+ )
614
+ self.mapper, alphas = get_refinement_mapper(prompts, self.tokenizer)
615
+ self.mapper, alphas = self.mapper.to(self.device), alphas.to(self.device)
616
+ self.alphas = alphas.reshape(alphas.shape[0], 1, 1, alphas.shape[1])
617
+
618
+
619
+ class AttentionReweight(AttentionControlEdit):
620
+ def replace_cross_attention(self, attn_base, att_replace):
621
+ if self.prev_controller is not None:
622
+ attn_base = self.prev_controller.replace_cross_attention(attn_base, att_replace)
623
+ attn_replace = attn_base[None, :, :, :] * self.equalizer[:, None, None, :]
624
+ return attn_replace
625
+
626
+ def __init__(
627
+ self,
628
+ prompts,
629
+ num_steps: int,
630
+ cross_replace_steps: float,
631
+ self_replace_steps: float,
632
+ equalizer,
633
+ local_blend: Optional[LocalBlend] = None,
634
+ controller: Optional[AttentionControlEdit] = None,
635
+ tokenizer=None,
636
+ device=None,
637
+ ):
638
+ super(AttentionReweight, self).__init__(
639
+ prompts, num_steps, cross_replace_steps, self_replace_steps, local_blend, tokenizer, device
640
+ )
641
+ self.equalizer = equalizer.to(self.device)
642
+ self.prev_controller = controller
643
+
644
+
645
+ ### util functions for all Edits
646
+ def update_alpha_time_word(
647
+ alpha, bounds: Union[float, Tuple[float, float]], prompt_ind: int, word_inds: Optional[torch.Tensor] = None
648
+ ):
649
+ if isinstance(bounds, float):
650
+ bounds = 0, bounds
651
+ start, end = int(bounds[0] * alpha.shape[0]), int(bounds[1] * alpha.shape[0])
652
+ if word_inds is None:
653
+ word_inds = torch.arange(alpha.shape[2])
654
+ alpha[:start, prompt_ind, word_inds] = 0
655
+ alpha[start:end, prompt_ind, word_inds] = 1
656
+ alpha[end:, prompt_ind, word_inds] = 0
657
+ return alpha
658
+
659
+
660
+ def get_time_words_attention_alpha(
661
+ prompts, num_steps, cross_replace_steps: Union[float, Dict[str, Tuple[float, float]]], tokenizer, max_num_words=77
662
+ ):
663
+ if not isinstance(cross_replace_steps, dict):
664
+ cross_replace_steps = {"default_": cross_replace_steps}
665
+ if "default_" not in cross_replace_steps:
666
+ cross_replace_steps["default_"] = (0.0, 1.0)
667
+ alpha_time_words = torch.zeros(num_steps + 1, len(prompts) - 1, max_num_words)
668
+ for i in range(len(prompts) - 1):
669
+ alpha_time_words = update_alpha_time_word(alpha_time_words, cross_replace_steps["default_"], i)
670
+ for key, item in cross_replace_steps.items():
671
+ if key != "default_":
672
+ inds = [get_word_inds(prompts[i], key, tokenizer) for i in range(1, len(prompts))]
673
+ for i, ind in enumerate(inds):
674
+ if len(ind) > 0:
675
+ alpha_time_words = update_alpha_time_word(alpha_time_words, item, i, ind)
676
+ alpha_time_words = alpha_time_words.reshape(num_steps + 1, len(prompts) - 1, 1, 1, max_num_words)
677
+ return alpha_time_words
678
+
679
+
680
+ ### util functions for LocalBlend and ReplacementEdit
681
+ def get_word_inds(text: str, word_place: int, tokenizer):
682
+ split_text = text.split(" ")
683
+ if isinstance(word_place, str):
684
+ word_place = [i for i, word in enumerate(split_text) if word_place == word]
685
+ elif isinstance(word_place, int):
686
+ word_place = [word_place]
687
+ out = []
688
+ if len(word_place) > 0:
689
+ words_encode = [tokenizer.decode([item]).strip("#") for item in tokenizer.encode(text)][1:-1]
690
+ cur_len, ptr = 0, 0
691
+
692
+ for i in range(len(words_encode)):
693
+ cur_len += len(words_encode[i])
694
+ if ptr in word_place:
695
+ out.append(i + 1)
696
+ if cur_len >= len(split_text[ptr]):
697
+ ptr += 1
698
+ cur_len = 0
699
+ return np.array(out)
700
+
701
+
702
+ ### util functions for ReplacementEdit
703
+ def get_replacement_mapper_(x: str, y: str, tokenizer, max_len=77):
704
+ words_x = x.split(" ")
705
+ words_y = y.split(" ")
706
+ if len(words_x) != len(words_y):
707
+ raise ValueError(
708
+ f"attention replacement edit can only be applied on prompts with the same length"
709
+ f" but prompt A has {len(words_x)} words and prompt B has {len(words_y)} words."
710
+ )
711
+ inds_replace = [i for i in range(len(words_y)) if words_y[i] != words_x[i]]
712
+ inds_source = [get_word_inds(x, i, tokenizer) for i in inds_replace]
713
+ inds_target = [get_word_inds(y, i, tokenizer) for i in inds_replace]
714
+ mapper = np.zeros((max_len, max_len))
715
+ i = j = 0
716
+ cur_inds = 0
717
+ while i < max_len and j < max_len:
718
+ if cur_inds < len(inds_source) and inds_source[cur_inds][0] == i:
719
+ inds_source_, inds_target_ = inds_source[cur_inds], inds_target[cur_inds]
720
+ if len(inds_source_) == len(inds_target_):
721
+ mapper[inds_source_, inds_target_] = 1
722
+ else:
723
+ ratio = 1 / len(inds_target_)
724
+ for i_t in inds_target_:
725
+ mapper[inds_source_, i_t] = ratio
726
+ cur_inds += 1
727
+ i += len(inds_source_)
728
+ j += len(inds_target_)
729
+ elif cur_inds < len(inds_source):
730
+ mapper[i, j] = 1
731
+ i += 1
732
+ j += 1
733
+ else:
734
+ mapper[j, j] = 1
735
+ i += 1
736
+ j += 1
737
+
738
+ return torch.from_numpy(mapper).float()
739
+
740
+
741
+ def get_replacement_mapper(prompts, tokenizer, max_len=77):
742
+ x_seq = prompts[0]
743
+ mappers = []
744
+ for i in range(1, len(prompts)):
745
+ mapper = get_replacement_mapper_(x_seq, prompts[i], tokenizer, max_len)
746
+ mappers.append(mapper)
747
+ return torch.stack(mappers)
748
+
749
+
750
+ ### util functions for ReweightEdit
751
+ def get_equalizer(
752
+ text: str, word_select: Union[int, Tuple[int, ...]], values: Union[List[float], Tuple[float, ...]], tokenizer
753
+ ):
754
+ if isinstance(word_select, (int, str)):
755
+ word_select = (word_select,)
756
+ equalizer = torch.ones(len(values), 77)
757
+ values = torch.tensor(values, dtype=torch.float32)
758
+ for word in word_select:
759
+ inds = get_word_inds(text, word, tokenizer)
760
+ equalizer[:, inds] = values
761
+ return equalizer
762
+
763
+
764
+ ### util functions for RefinementEdit
765
+ class ScoreParams:
766
+ def __init__(self, gap, match, mismatch):
767
+ self.gap = gap
768
+ self.match = match
769
+ self.mismatch = mismatch
770
+
771
+ def mis_match_char(self, x, y):
772
+ if x != y:
773
+ return self.mismatch
774
+ else:
775
+ return self.match
776
+
777
+
778
+ def get_matrix(size_x, size_y, gap):
779
+ matrix = np.zeros((size_x + 1, size_y + 1), dtype=np.int32)
780
+ matrix[0, 1:] = (np.arange(size_y) + 1) * gap
781
+ matrix[1:, 0] = (np.arange(size_x) + 1) * gap
782
+ return matrix
783
+
784
+
785
+ def get_traceback_matrix(size_x, size_y):
786
+ matrix = np.zeros((size_x + 1, size_y + 1), dtype=np.int32)
787
+ matrix[0, 1:] = 1
788
+ matrix[1:, 0] = 2
789
+ matrix[0, 0] = 4
790
+ return matrix
791
+
792
+
793
+ def global_align(x, y, score):
794
+ matrix = get_matrix(len(x), len(y), score.gap)
795
+ trace_back = get_traceback_matrix(len(x), len(y))
796
+ for i in range(1, len(x) + 1):
797
+ for j in range(1, len(y) + 1):
798
+ left = matrix[i, j - 1] + score.gap
799
+ up = matrix[i - 1, j] + score.gap
800
+ diag = matrix[i - 1, j - 1] + score.mis_match_char(x[i - 1], y[j - 1])
801
+ matrix[i, j] = max(left, up, diag)
802
+ if matrix[i, j] == left:
803
+ trace_back[i, j] = 1
804
+ elif matrix[i, j] == up:
805
+ trace_back[i, j] = 2
806
+ else:
807
+ trace_back[i, j] = 3
808
+ return matrix, trace_back
809
+
810
+
811
+ def get_aligned_sequences(x, y, trace_back):
812
+ x_seq = []
813
+ y_seq = []
814
+ i = len(x)
815
+ j = len(y)
816
+ mapper_y_to_x = []
817
+ while i > 0 or j > 0:
818
+ if trace_back[i, j] == 3:
819
+ x_seq.append(x[i - 1])
820
+ y_seq.append(y[j - 1])
821
+ i = i - 1
822
+ j = j - 1
823
+ mapper_y_to_x.append((j, i))
824
+ elif trace_back[i][j] == 1:
825
+ x_seq.append("-")
826
+ y_seq.append(y[j - 1])
827
+ j = j - 1
828
+ mapper_y_to_x.append((j, -1))
829
+ elif trace_back[i][j] == 2:
830
+ x_seq.append(x[i - 1])
831
+ y_seq.append("-")
832
+ i = i - 1
833
+ elif trace_back[i][j] == 4:
834
+ break
835
+ mapper_y_to_x.reverse()
836
+ return x_seq, y_seq, torch.tensor(mapper_y_to_x, dtype=torch.int64)
837
+
838
+
839
+ def get_mapper(x: str, y: str, tokenizer, max_len=77):
840
+ x_seq = tokenizer.encode(x)
841
+ y_seq = tokenizer.encode(y)
842
+ score = ScoreParams(0, 1, -1)
843
+ matrix, trace_back = global_align(x_seq, y_seq, score)
844
+ mapper_base = get_aligned_sequences(x_seq, y_seq, trace_back)[-1]
845
+ alphas = torch.ones(max_len)
846
+ alphas[: mapper_base.shape[0]] = mapper_base[:, 1].ne(-1).float()
847
+ mapper = torch.zeros(max_len, dtype=torch.int64)
848
+ mapper[: mapper_base.shape[0]] = mapper_base[:, 1]
849
+ mapper[mapper_base.shape[0] :] = len(y_seq) + torch.arange(max_len - len(y_seq))
850
+ return mapper, alphas
851
+
852
+
853
+ def get_refinement_mapper(prompts, tokenizer, max_len=77):
854
+ x_seq = prompts[0]
855
+ mappers, alphas = [], []
856
+ for i in range(1, len(prompts)):
857
+ mapper, alpha = get_mapper(x_seq, prompts[i], tokenizer, max_len)
858
+ mappers.append(mapper)
859
+ alphas.append(alpha)
860
+ return torch.stack(mappers), torch.stack(alphas)
v0.22.0/pipeline_zero1to3.py ADDED
@@ -0,0 +1,891 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # A diffuser version implementation of Zero1to3 (https://github.com/cvlab-columbia/zero123), ICCV 2023
2
+ # by Xin Kong
3
+
4
+ import inspect
5
+ from typing import Any, Callable, Dict, List, Optional, Union
6
+
7
+ import kornia
8
+ import numpy as np
9
+ import PIL.Image
10
+ import torch
11
+ from packaging import version
12
+ from transformers import CLIPFeatureExtractor, CLIPVisionModelWithProjection
13
+
14
+ # from ...configuration_utils import FrozenDict
15
+ # from ...models import AutoencoderKL, UNet2DConditionModel
16
+ # from ...schedulers import KarrasDiffusionSchedulers
17
+ # from ...utils import (
18
+ # deprecate,
19
+ # is_accelerate_available,
20
+ # is_accelerate_version,
21
+ # logging,
22
+ # randn_tensor,
23
+ # replace_example_docstring,
24
+ # )
25
+ # from ..pipeline_utils import DiffusionPipeline
26
+ # from . import StableDiffusionPipelineOutput
27
+ # from .safety_checker import StableDiffusionSafetyChecker
28
+ from diffusers import AutoencoderKL, DiffusionPipeline, UNet2DConditionModel
29
+ from diffusers.configuration_utils import ConfigMixin, FrozenDict
30
+ from diffusers.models.modeling_utils import ModelMixin
31
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput, StableDiffusionSafetyChecker
32
+ from diffusers.schedulers import KarrasDiffusionSchedulers
33
+ from diffusers.utils import (
34
+ deprecate,
35
+ is_accelerate_available,
36
+ is_accelerate_version,
37
+ logging,
38
+ replace_example_docstring,
39
+ )
40
+ from diffusers.utils.torch_utils import randn_tensor
41
+
42
+
43
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
44
+ # todo
45
+ EXAMPLE_DOC_STRING = """
46
+ Examples:
47
+ ```py
48
+ >>> import torch
49
+ >>> from diffusers import StableDiffusionPipeline
50
+
51
+ >>> pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)
52
+ >>> pipe = pipe.to("cuda")
53
+
54
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
55
+ >>> image = pipe(prompt).images[0]
56
+ ```
57
+ """
58
+
59
+
60
+ class CCProjection(ModelMixin, ConfigMixin):
61
+ def __init__(self, in_channel=772, out_channel=768):
62
+ super().__init__()
63
+ self.in_channel = in_channel
64
+ self.out_channel = out_channel
65
+ self.projection = torch.nn.Linear(in_channel, out_channel)
66
+
67
+ def forward(self, x):
68
+ return self.projection(x)
69
+
70
+
71
+ class Zero1to3StableDiffusionPipeline(DiffusionPipeline):
72
+ r"""
73
+ Pipeline for single view conditioned novel view generation using Zero1to3.
74
+
75
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
76
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
77
+
78
+ Args:
79
+ vae ([`AutoencoderKL`]):
80
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
81
+ image_encoder ([`CLIPVisionModelWithProjection`]):
82
+ Frozen CLIP image-encoder. Stable Diffusion Image Variation uses the vision portion of
83
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPVisionModelWithProjection),
84
+ specifically the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
85
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
86
+ scheduler ([`SchedulerMixin`]):
87
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
88
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
89
+ safety_checker ([`StableDiffusionSafetyChecker`]):
90
+ Classification module that estimates whether generated images could be considered offensive or harmful.
91
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
92
+ feature_extractor ([`CLIPFeatureExtractor`]):
93
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
94
+ cc_projection ([`CCProjection`]):
95
+ Projection layer to project the concated CLIP features and pose embeddings to the original CLIP feature size.
96
+ """
97
+ _optional_components = ["safety_checker", "feature_extractor"]
98
+
99
+ def __init__(
100
+ self,
101
+ vae: AutoencoderKL,
102
+ image_encoder: CLIPVisionModelWithProjection,
103
+ unet: UNet2DConditionModel,
104
+ scheduler: KarrasDiffusionSchedulers,
105
+ safety_checker: StableDiffusionSafetyChecker,
106
+ feature_extractor: CLIPFeatureExtractor,
107
+ cc_projection: CCProjection,
108
+ requires_safety_checker: bool = True,
109
+ ):
110
+ super().__init__()
111
+
112
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
113
+ deprecation_message = (
114
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
115
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
116
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
117
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
118
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
119
+ " file"
120
+ )
121
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
122
+ new_config = dict(scheduler.config)
123
+ new_config["steps_offset"] = 1
124
+ scheduler._internal_dict = FrozenDict(new_config)
125
+
126
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
127
+ deprecation_message = (
128
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
129
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
130
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
131
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
132
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
133
+ )
134
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
135
+ new_config = dict(scheduler.config)
136
+ new_config["clip_sample"] = False
137
+ scheduler._internal_dict = FrozenDict(new_config)
138
+
139
+ if safety_checker is None and requires_safety_checker:
140
+ logger.warning(
141
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
142
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
143
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
144
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
145
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
146
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
147
+ )
148
+
149
+ if safety_checker is not None and feature_extractor is None:
150
+ raise ValueError(
151
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
152
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
153
+ )
154
+
155
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
156
+ version.parse(unet.config._diffusers_version).base_version
157
+ ) < version.parse("0.9.0.dev0")
158
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
159
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
160
+ deprecation_message = (
161
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
162
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
163
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
164
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
165
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
166
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
167
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
168
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
169
+ " the `unet/config.json` file"
170
+ )
171
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
172
+ new_config = dict(unet.config)
173
+ new_config["sample_size"] = 64
174
+ unet._internal_dict = FrozenDict(new_config)
175
+
176
+ self.register_modules(
177
+ vae=vae,
178
+ image_encoder=image_encoder,
179
+ unet=unet,
180
+ scheduler=scheduler,
181
+ safety_checker=safety_checker,
182
+ feature_extractor=feature_extractor,
183
+ cc_projection=cc_projection,
184
+ )
185
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
186
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
187
+ # self.model_mode = None
188
+
189
+ def enable_vae_slicing(self):
190
+ r"""
191
+ Enable sliced VAE decoding.
192
+
193
+ When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
194
+ steps. This is useful to save some memory and allow larger batch sizes.
195
+ """
196
+ self.vae.enable_slicing()
197
+
198
+ def disable_vae_slicing(self):
199
+ r"""
200
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to
201
+ computing decoding in one step.
202
+ """
203
+ self.vae.disable_slicing()
204
+
205
+ def enable_vae_tiling(self):
206
+ r"""
207
+ Enable tiled VAE decoding.
208
+
209
+ When this option is enabled, the VAE will split the input tensor into tiles to compute decoding and encoding in
210
+ several steps. This is useful to save a large amount of memory and to allow the processing of larger images.
211
+ """
212
+ self.vae.enable_tiling()
213
+
214
+ def disable_vae_tiling(self):
215
+ r"""
216
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously invoked, this method will go back to
217
+ computing decoding in one step.
218
+ """
219
+ self.vae.disable_tiling()
220
+
221
+ def enable_sequential_cpu_offload(self, gpu_id=0):
222
+ r"""
223
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
224
+ text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
225
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
226
+ Note that offloading happens on a submodule basis. Memory savings are higher than with
227
+ `enable_model_cpu_offload`, but performance is lower.
228
+ """
229
+ if is_accelerate_available() and is_accelerate_version(">=", "0.14.0"):
230
+ from accelerate import cpu_offload
231
+ else:
232
+ raise ImportError("`enable_sequential_cpu_offload` requires `accelerate v0.14.0` or higher")
233
+
234
+ device = torch.device(f"cuda:{gpu_id}")
235
+
236
+ if self.device.type != "cpu":
237
+ self.to("cpu", silence_dtype_warnings=True)
238
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
239
+
240
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]:
241
+ cpu_offload(cpu_offloaded_model, device)
242
+
243
+ if self.safety_checker is not None:
244
+ cpu_offload(self.safety_checker, execution_device=device, offload_buffers=True)
245
+
246
+ def enable_model_cpu_offload(self, gpu_id=0):
247
+ r"""
248
+ Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
249
+ to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
250
+ method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
251
+ `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
252
+ """
253
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
254
+ from accelerate import cpu_offload_with_hook
255
+ else:
256
+ raise ImportError("`enable_model_offload` requires `accelerate v0.17.0` or higher.")
257
+
258
+ device = torch.device(f"cuda:{gpu_id}")
259
+
260
+ if self.device.type != "cpu":
261
+ self.to("cpu", silence_dtype_warnings=True)
262
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
263
+
264
+ hook = None
265
+ for cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]:
266
+ _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
267
+
268
+ if self.safety_checker is not None:
269
+ _, hook = cpu_offload_with_hook(self.safety_checker, device, prev_module_hook=hook)
270
+
271
+ # We'll offload the last model manually.
272
+ self.final_offload_hook = hook
273
+
274
+ @property
275
+ def _execution_device(self):
276
+ r"""
277
+ Returns the device on which the pipeline's models will be executed. After calling
278
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
279
+ hooks.
280
+ """
281
+ if not hasattr(self.unet, "_hf_hook"):
282
+ return self.device
283
+ for module in self.unet.modules():
284
+ if (
285
+ hasattr(module, "_hf_hook")
286
+ and hasattr(module._hf_hook, "execution_device")
287
+ and module._hf_hook.execution_device is not None
288
+ ):
289
+ return torch.device(module._hf_hook.execution_device)
290
+ return self.device
291
+
292
+ def _encode_prompt(
293
+ self,
294
+ prompt,
295
+ device,
296
+ num_images_per_prompt,
297
+ do_classifier_free_guidance,
298
+ negative_prompt=None,
299
+ prompt_embeds: Optional[torch.FloatTensor] = None,
300
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
301
+ ):
302
+ r"""
303
+ Encodes the prompt into text encoder hidden states.
304
+
305
+ Args:
306
+ prompt (`str` or `List[str]`, *optional*):
307
+ prompt to be encoded
308
+ device: (`torch.device`):
309
+ torch device
310
+ num_images_per_prompt (`int`):
311
+ number of images that should be generated per prompt
312
+ do_classifier_free_guidance (`bool`):
313
+ whether to use classifier free guidance or not
314
+ negative_prompt (`str` or `List[str]`, *optional*):
315
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
316
+ `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
317
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
318
+ prompt_embeds (`torch.FloatTensor`, *optional*):
319
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
320
+ provided, text embeddings will be generated from `prompt` input argument.
321
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
322
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
323
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
324
+ argument.
325
+ """
326
+ if prompt is not None and isinstance(prompt, str):
327
+ batch_size = 1
328
+ elif prompt is not None and isinstance(prompt, list):
329
+ batch_size = len(prompt)
330
+ else:
331
+ batch_size = prompt_embeds.shape[0]
332
+
333
+ if prompt_embeds is None:
334
+ text_inputs = self.tokenizer(
335
+ prompt,
336
+ padding="max_length",
337
+ max_length=self.tokenizer.model_max_length,
338
+ truncation=True,
339
+ return_tensors="pt",
340
+ )
341
+ text_input_ids = text_inputs.input_ids
342
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
343
+
344
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
345
+ text_input_ids, untruncated_ids
346
+ ):
347
+ removed_text = self.tokenizer.batch_decode(
348
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
349
+ )
350
+ logger.warning(
351
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
352
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
353
+ )
354
+
355
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
356
+ attention_mask = text_inputs.attention_mask.to(device)
357
+ else:
358
+ attention_mask = None
359
+
360
+ prompt_embeds = self.text_encoder(
361
+ text_input_ids.to(device),
362
+ attention_mask=attention_mask,
363
+ )
364
+ prompt_embeds = prompt_embeds[0]
365
+
366
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
367
+
368
+ bs_embed, seq_len, _ = prompt_embeds.shape
369
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
370
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
371
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
372
+
373
+ # get unconditional embeddings for classifier free guidance
374
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
375
+ uncond_tokens: List[str]
376
+ if negative_prompt is None:
377
+ uncond_tokens = [""] * batch_size
378
+ elif type(prompt) is not type(negative_prompt):
379
+ raise TypeError(
380
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
381
+ f" {type(prompt)}."
382
+ )
383
+ elif isinstance(negative_prompt, str):
384
+ uncond_tokens = [negative_prompt]
385
+ elif batch_size != len(negative_prompt):
386
+ raise ValueError(
387
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
388
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
389
+ " the batch size of `prompt`."
390
+ )
391
+ else:
392
+ uncond_tokens = negative_prompt
393
+
394
+ max_length = prompt_embeds.shape[1]
395
+ uncond_input = self.tokenizer(
396
+ uncond_tokens,
397
+ padding="max_length",
398
+ max_length=max_length,
399
+ truncation=True,
400
+ return_tensors="pt",
401
+ )
402
+
403
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
404
+ attention_mask = uncond_input.attention_mask.to(device)
405
+ else:
406
+ attention_mask = None
407
+
408
+ negative_prompt_embeds = self.text_encoder(
409
+ uncond_input.input_ids.to(device),
410
+ attention_mask=attention_mask,
411
+ )
412
+ negative_prompt_embeds = negative_prompt_embeds[0]
413
+
414
+ if do_classifier_free_guidance:
415
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
416
+ seq_len = negative_prompt_embeds.shape[1]
417
+
418
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
419
+
420
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
421
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
422
+
423
+ # For classifier free guidance, we need to do two forward passes.
424
+ # Here we concatenate the unconditional and text embeddings into a single batch
425
+ # to avoid doing two forward passes
426
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
427
+
428
+ return prompt_embeds
429
+
430
+ def CLIP_preprocess(self, x):
431
+ dtype = x.dtype
432
+ # following openai's implementation
433
+ # TODO HF OpenAI CLIP preprocessing issue https://github.com/huggingface/transformers/issues/22505#issuecomment-1650170741
434
+ # follow openai preprocessing to keep exact same, input tensor [-1, 1], otherwise the preprocessing will be different, https://github.com/huggingface/transformers/pull/22608
435
+ if isinstance(x, torch.Tensor):
436
+ if x.min() < -1.0 or x.max() > 1.0:
437
+ raise ValueError("Expected input tensor to have values in the range [-1, 1]")
438
+ x = kornia.geometry.resize(
439
+ x.to(torch.float32), (224, 224), interpolation="bicubic", align_corners=True, antialias=False
440
+ ).to(dtype=dtype)
441
+ x = (x + 1.0) / 2.0
442
+ # renormalize according to clip
443
+ x = kornia.enhance.normalize(
444
+ x, torch.Tensor([0.48145466, 0.4578275, 0.40821073]), torch.Tensor([0.26862954, 0.26130258, 0.27577711])
445
+ )
446
+ return x
447
+
448
+ # from image_variation
449
+ def _encode_image(self, image, device, num_images_per_prompt, do_classifier_free_guidance):
450
+ dtype = next(self.image_encoder.parameters()).dtype
451
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
452
+ raise ValueError(
453
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
454
+ )
455
+
456
+ if isinstance(image, torch.Tensor):
457
+ # Batch single image
458
+ if image.ndim == 3:
459
+ assert image.shape[0] == 3, "Image outside a batch should be of shape (3, H, W)"
460
+ image = image.unsqueeze(0)
461
+
462
+ assert image.ndim == 4, "Image must have 4 dimensions"
463
+
464
+ # Check image is in [-1, 1]
465
+ if image.min() < -1 or image.max() > 1:
466
+ raise ValueError("Image should be in [-1, 1] range")
467
+ else:
468
+ # preprocess image
469
+ if isinstance(image, (PIL.Image.Image, np.ndarray)):
470
+ image = [image]
471
+
472
+ if isinstance(image, list) and isinstance(image[0], PIL.Image.Image):
473
+ image = [np.array(i.convert("RGB"))[None, :] for i in image]
474
+ image = np.concatenate(image, axis=0)
475
+ elif isinstance(image, list) and isinstance(image[0], np.ndarray):
476
+ image = np.concatenate([i[None, :] for i in image], axis=0)
477
+
478
+ image = image.transpose(0, 3, 1, 2)
479
+ image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
480
+
481
+ image = image.to(device=device, dtype=dtype)
482
+
483
+ image = self.CLIP_preprocess(image)
484
+ # if not isinstance(image, torch.Tensor):
485
+ # # 0-255
486
+ # print("Warning: image is processed by hf's preprocess, which is different from openai original's.")
487
+ # image = self.feature_extractor(images=image, return_tensors="pt").pixel_values
488
+ image_embeddings = self.image_encoder(image).image_embeds.to(dtype=dtype)
489
+ image_embeddings = image_embeddings.unsqueeze(1)
490
+
491
+ # duplicate image embeddings for each generation per prompt, using mps friendly method
492
+ bs_embed, seq_len, _ = image_embeddings.shape
493
+ image_embeddings = image_embeddings.repeat(1, num_images_per_prompt, 1)
494
+ image_embeddings = image_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
495
+
496
+ if do_classifier_free_guidance:
497
+ negative_prompt_embeds = torch.zeros_like(image_embeddings)
498
+
499
+ # For classifier free guidance, we need to do two forward passes.
500
+ # Here we concatenate the unconditional and text embeddings into a single batch
501
+ # to avoid doing two forward passes
502
+ image_embeddings = torch.cat([negative_prompt_embeds, image_embeddings])
503
+
504
+ return image_embeddings
505
+
506
+ def _encode_pose(self, pose, device, num_images_per_prompt, do_classifier_free_guidance):
507
+ dtype = next(self.cc_projection.parameters()).dtype
508
+ if isinstance(pose, torch.Tensor):
509
+ pose_embeddings = pose.unsqueeze(1).to(device=device, dtype=dtype)
510
+ else:
511
+ if isinstance(pose[0], list):
512
+ pose = torch.Tensor(pose)
513
+ else:
514
+ pose = torch.Tensor([pose])
515
+ x, y, z = pose[:, 0].unsqueeze(1), pose[:, 1].unsqueeze(1), pose[:, 2].unsqueeze(1)
516
+ pose_embeddings = (
517
+ torch.cat([torch.deg2rad(x), torch.sin(torch.deg2rad(y)), torch.cos(torch.deg2rad(y)), z], dim=-1)
518
+ .unsqueeze(1)
519
+ .to(device=device, dtype=dtype)
520
+ ) # B, 1, 4
521
+ # duplicate pose embeddings for each generation per prompt, using mps friendly method
522
+ bs_embed, seq_len, _ = pose_embeddings.shape
523
+ pose_embeddings = pose_embeddings.repeat(1, num_images_per_prompt, 1)
524
+ pose_embeddings = pose_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
525
+ if do_classifier_free_guidance:
526
+ negative_prompt_embeds = torch.zeros_like(pose_embeddings)
527
+
528
+ # For classifier free guidance, we need to do two forward passes.
529
+ # Here we concatenate the unconditional and text embeddings into a single batch
530
+ # to avoid doing two forward passes
531
+ pose_embeddings = torch.cat([negative_prompt_embeds, pose_embeddings])
532
+ return pose_embeddings
533
+
534
+ def _encode_image_with_pose(self, image, pose, device, num_images_per_prompt, do_classifier_free_guidance):
535
+ img_prompt_embeds = self._encode_image(image, device, num_images_per_prompt, False)
536
+ pose_prompt_embeds = self._encode_pose(pose, device, num_images_per_prompt, False)
537
+ prompt_embeds = torch.cat([img_prompt_embeds, pose_prompt_embeds], dim=-1)
538
+ prompt_embeds = self.cc_projection(prompt_embeds)
539
+ # prompt_embeds = img_prompt_embeds
540
+ # follow 0123, add negative prompt, after projection
541
+ if do_classifier_free_guidance:
542
+ negative_prompt = torch.zeros_like(prompt_embeds)
543
+ prompt_embeds = torch.cat([negative_prompt, prompt_embeds])
544
+ return prompt_embeds
545
+
546
+ def run_safety_checker(self, image, device, dtype):
547
+ if self.safety_checker is not None:
548
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
549
+ image, has_nsfw_concept = self.safety_checker(
550
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
551
+ )
552
+ else:
553
+ has_nsfw_concept = None
554
+ return image, has_nsfw_concept
555
+
556
+ def decode_latents(self, latents):
557
+ latents = 1 / self.vae.config.scaling_factor * latents
558
+ image = self.vae.decode(latents).sample
559
+ image = (image / 2 + 0.5).clamp(0, 1)
560
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
561
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
562
+ return image
563
+
564
+ def prepare_extra_step_kwargs(self, generator, eta):
565
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
566
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
567
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
568
+ # and should be between [0, 1]
569
+
570
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
571
+ extra_step_kwargs = {}
572
+ if accepts_eta:
573
+ extra_step_kwargs["eta"] = eta
574
+
575
+ # check if the scheduler accepts generator
576
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
577
+ if accepts_generator:
578
+ extra_step_kwargs["generator"] = generator
579
+ return extra_step_kwargs
580
+
581
+ def check_inputs(self, image, height, width, callback_steps):
582
+ if (
583
+ not isinstance(image, torch.Tensor)
584
+ and not isinstance(image, PIL.Image.Image)
585
+ and not isinstance(image, list)
586
+ ):
587
+ raise ValueError(
588
+ "`image` has to be of type `torch.FloatTensor` or `PIL.Image.Image` or `List[PIL.Image.Image]` but is"
589
+ f" {type(image)}"
590
+ )
591
+
592
+ if height % 8 != 0 or width % 8 != 0:
593
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
594
+
595
+ if (callback_steps is None) or (
596
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
597
+ ):
598
+ raise ValueError(
599
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
600
+ f" {type(callback_steps)}."
601
+ )
602
+
603
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
604
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
605
+ if isinstance(generator, list) and len(generator) != batch_size:
606
+ raise ValueError(
607
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
608
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
609
+ )
610
+
611
+ if latents is None:
612
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
613
+ else:
614
+ latents = latents.to(device)
615
+
616
+ # scale the initial noise by the standard deviation required by the scheduler
617
+ latents = latents * self.scheduler.init_noise_sigma
618
+ return latents
619
+
620
+ def prepare_img_latents(self, image, batch_size, dtype, device, generator=None, do_classifier_free_guidance=False):
621
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
622
+ raise ValueError(
623
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
624
+ )
625
+
626
+ if isinstance(image, torch.Tensor):
627
+ # Batch single image
628
+ if image.ndim == 3:
629
+ assert image.shape[0] == 3, "Image outside a batch should be of shape (3, H, W)"
630
+ image = image.unsqueeze(0)
631
+
632
+ assert image.ndim == 4, "Image must have 4 dimensions"
633
+
634
+ # Check image is in [-1, 1]
635
+ if image.min() < -1 or image.max() > 1:
636
+ raise ValueError("Image should be in [-1, 1] range")
637
+ else:
638
+ # preprocess image
639
+ if isinstance(image, (PIL.Image.Image, np.ndarray)):
640
+ image = [image]
641
+
642
+ if isinstance(image, list) and isinstance(image[0], PIL.Image.Image):
643
+ image = [np.array(i.convert("RGB"))[None, :] for i in image]
644
+ image = np.concatenate(image, axis=0)
645
+ elif isinstance(image, list) and isinstance(image[0], np.ndarray):
646
+ image = np.concatenate([i[None, :] for i in image], axis=0)
647
+
648
+ image = image.transpose(0, 3, 1, 2)
649
+ image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
650
+
651
+ image = image.to(device=device, dtype=dtype)
652
+
653
+ if isinstance(generator, list) and len(generator) != batch_size:
654
+ raise ValueError(
655
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
656
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
657
+ )
658
+
659
+ if isinstance(generator, list):
660
+ init_latents = [
661
+ self.vae.encode(image[i : i + 1]).latent_dist.mode(generator[i]) for i in range(batch_size) # sample
662
+ ]
663
+ init_latents = torch.cat(init_latents, dim=0)
664
+ else:
665
+ init_latents = self.vae.encode(image).latent_dist.mode()
666
+
667
+ # init_latents = self.vae.config.scaling_factor * init_latents # todo in original zero123's inference gradio_new.py, model.encode_first_stage() is not scaled by scaling_factor
668
+ if batch_size > init_latents.shape[0]:
669
+ # init_latents = init_latents.repeat(batch_size // init_latents.shape[0], 1, 1, 1)
670
+ num_images_per_prompt = batch_size // init_latents.shape[0]
671
+ # duplicate image latents for each generation per prompt, using mps friendly method
672
+ bs_embed, emb_c, emb_h, emb_w = init_latents.shape
673
+ init_latents = init_latents.unsqueeze(1)
674
+ init_latents = init_latents.repeat(1, num_images_per_prompt, 1, 1, 1)
675
+ init_latents = init_latents.view(bs_embed * num_images_per_prompt, emb_c, emb_h, emb_w)
676
+
677
+ # init_latents = torch.cat([init_latents]*2) if do_classifier_free_guidance else init_latents # follow zero123
678
+ init_latents = (
679
+ torch.cat([torch.zeros_like(init_latents), init_latents]) if do_classifier_free_guidance else init_latents
680
+ )
681
+
682
+ init_latents = init_latents.to(device=device, dtype=dtype)
683
+ return init_latents
684
+
685
+ # def load_cc_projection(self, pretrained_weights=None):
686
+ # self.cc_projection = torch.nn.Linear(772, 768)
687
+ # torch.nn.init.eye_(list(self.cc_projection.parameters())[0][:768, :768])
688
+ # torch.nn.init.zeros_(list(self.cc_projection.parameters())[1])
689
+ # if pretrained_weights is not None:
690
+ # self.cc_projection.load_state_dict(pretrained_weights)
691
+
692
+ @torch.no_grad()
693
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
694
+ def __call__(
695
+ self,
696
+ input_imgs: Union[torch.FloatTensor, PIL.Image.Image] = None,
697
+ prompt_imgs: Union[torch.FloatTensor, PIL.Image.Image] = None,
698
+ poses: Union[List[float], List[List[float]]] = None,
699
+ torch_dtype=torch.float32,
700
+ height: Optional[int] = None,
701
+ width: Optional[int] = None,
702
+ num_inference_steps: int = 50,
703
+ guidance_scale: float = 3.0,
704
+ negative_prompt: Optional[Union[str, List[str]]] = None,
705
+ num_images_per_prompt: Optional[int] = 1,
706
+ eta: float = 0.0,
707
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
708
+ latents: Optional[torch.FloatTensor] = None,
709
+ prompt_embeds: Optional[torch.FloatTensor] = None,
710
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
711
+ output_type: Optional[str] = "pil",
712
+ return_dict: bool = True,
713
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
714
+ callback_steps: int = 1,
715
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
716
+ controlnet_conditioning_scale: float = 1.0,
717
+ ):
718
+ r"""
719
+ Function invoked when calling the pipeline for generation.
720
+
721
+ Args:
722
+ input_imgs (`PIL` or `List[PIL]`, *optional*):
723
+ The single input image for each 3D object
724
+ prompt_imgs (`PIL` or `List[PIL]`, *optional*):
725
+ Same as input_imgs, but will be used later as an image prompt condition, encoded by CLIP feature
726
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
727
+ The height in pixels of the generated image.
728
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
729
+ The width in pixels of the generated image.
730
+ num_inference_steps (`int`, *optional*, defaults to 50):
731
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
732
+ expense of slower inference.
733
+ guidance_scale (`float`, *optional*, defaults to 7.5):
734
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
735
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
736
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
737
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
738
+ usually at the expense of lower image quality.
739
+ negative_prompt (`str` or `List[str]`, *optional*):
740
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
741
+ `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
742
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
743
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
744
+ The number of images to generate per prompt.
745
+ eta (`float`, *optional*, defaults to 0.0):
746
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
747
+ [`schedulers.DDIMScheduler`], will be ignored for others.
748
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
749
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
750
+ to make generation deterministic.
751
+ latents (`torch.FloatTensor`, *optional*):
752
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
753
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
754
+ tensor will ge generated by sampling using the supplied random `generator`.
755
+ prompt_embeds (`torch.FloatTensor`, *optional*):
756
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
757
+ provided, text embeddings will be generated from `prompt` input argument.
758
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
759
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
760
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
761
+ argument.
762
+ output_type (`str`, *optional*, defaults to `"pil"`):
763
+ The output format of the generate image. Choose between
764
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
765
+ return_dict (`bool`, *optional*, defaults to `True`):
766
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
767
+ plain tuple.
768
+ callback (`Callable`, *optional*):
769
+ A function that will be called every `callback_steps` steps during inference. The function will be
770
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
771
+ callback_steps (`int`, *optional*, defaults to 1):
772
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
773
+ called at every step.
774
+ cross_attention_kwargs (`dict`, *optional*):
775
+ A kwargs dictionary that if specified is passed along to the `AttnProcessor` as defined under
776
+ `self.processor` in
777
+ [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
778
+
779
+ Examples:
780
+
781
+ Returns:
782
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
783
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
784
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
785
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
786
+ (nsfw) content, according to the `safety_checker`.
787
+ """
788
+ # 0. Default height and width to unet
789
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
790
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
791
+
792
+ # 1. Check inputs. Raise error if not correct
793
+ # input_image = hint_imgs
794
+ self.check_inputs(input_imgs, height, width, callback_steps)
795
+
796
+ # 2. Define call parameters
797
+ if isinstance(input_imgs, PIL.Image.Image):
798
+ batch_size = 1
799
+ elif isinstance(input_imgs, list):
800
+ batch_size = len(input_imgs)
801
+ else:
802
+ batch_size = input_imgs.shape[0]
803
+ device = self._execution_device
804
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
805
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
806
+ # corresponds to doing no classifier free guidance.
807
+ do_classifier_free_guidance = guidance_scale > 1.0
808
+
809
+ # 3. Encode input image with pose as prompt
810
+ prompt_embeds = self._encode_image_with_pose(
811
+ prompt_imgs, poses, device, num_images_per_prompt, do_classifier_free_guidance
812
+ )
813
+
814
+ # 4. Prepare timesteps
815
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
816
+ timesteps = self.scheduler.timesteps
817
+
818
+ # 5. Prepare latent variables
819
+ latents = self.prepare_latents(
820
+ batch_size * num_images_per_prompt,
821
+ 4,
822
+ height,
823
+ width,
824
+ prompt_embeds.dtype,
825
+ device,
826
+ generator,
827
+ latents,
828
+ )
829
+
830
+ # 6. Prepare image latents
831
+ img_latents = self.prepare_img_latents(
832
+ input_imgs,
833
+ batch_size * num_images_per_prompt,
834
+ prompt_embeds.dtype,
835
+ device,
836
+ generator,
837
+ do_classifier_free_guidance,
838
+ )
839
+
840
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
841
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
842
+
843
+ # 7. Denoising loop
844
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
845
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
846
+ for i, t in enumerate(timesteps):
847
+ # expand the latents if we are doing classifier free guidance
848
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
849
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
850
+ latent_model_input = torch.cat([latent_model_input, img_latents], dim=1)
851
+
852
+ # predict the noise residual
853
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=prompt_embeds).sample
854
+
855
+ # perform guidance
856
+ if do_classifier_free_guidance:
857
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
858
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
859
+
860
+ # compute the previous noisy sample x_t -> x_t-1
861
+ # latents = self.scheduler.step(noise_pred.to(dtype=torch.float32), t, latents.to(dtype=torch.float32)).prev_sample.to(prompt_embeds.dtype)
862
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
863
+
864
+ # call the callback, if provided
865
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
866
+ progress_bar.update()
867
+ if callback is not None and i % callback_steps == 0:
868
+ step_idx = i // getattr(self.scheduler, "order", 1)
869
+ callback(step_idx, t, latents)
870
+
871
+ # 8. Post-processing
872
+ has_nsfw_concept = None
873
+ if output_type == "latent":
874
+ image = latents
875
+ elif output_type == "pil":
876
+ # 8. Post-processing
877
+ image = self.decode_latents(latents)
878
+ # 10. Convert to PIL
879
+ image = self.numpy_to_pil(image)
880
+ else:
881
+ # 8. Post-processing
882
+ image = self.decode_latents(latents)
883
+
884
+ # Offload last model to CPU
885
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
886
+ self.final_offload_hook.offload()
887
+
888
+ if not return_dict:
889
+ return (image, has_nsfw_concept)
890
+
891
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.22.0/run_onnx_controlnet.py ADDED
@@ -0,0 +1,910 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import inspect
3
+ import os
4
+ import time
5
+ import warnings
6
+ from typing import Any, Callable, Dict, List, Optional, Union
7
+
8
+ import numpy as np
9
+ import PIL.Image
10
+ import torch
11
+ from PIL import Image
12
+ from transformers import CLIPTokenizer
13
+
14
+ from diffusers import OnnxRuntimeModel, StableDiffusionImg2ImgPipeline, UniPCMultistepScheduler
15
+ from diffusers.image_processor import VaeImageProcessor
16
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
17
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
18
+ from diffusers.schedulers import KarrasDiffusionSchedulers
19
+ from diffusers.utils import (
20
+ deprecate,
21
+ logging,
22
+ replace_example_docstring,
23
+ )
24
+ from diffusers.utils.torch_utils import randn_tensor
25
+
26
+
27
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
28
+
29
+
30
+ EXAMPLE_DOC_STRING = """
31
+ Examples:
32
+ ```py
33
+ >>> # !pip install opencv-python transformers accelerate
34
+ >>> from diffusers import StableDiffusionControlNetImg2ImgPipeline, ControlNetModel, UniPCMultistepScheduler
35
+ >>> from diffusers.utils import load_image
36
+ >>> import numpy as np
37
+ >>> import torch
38
+
39
+ >>> import cv2
40
+ >>> from PIL import Image
41
+
42
+ >>> # download an image
43
+ >>> image = load_image(
44
+ ... "https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png"
45
+ ... )
46
+ >>> np_image = np.array(image)
47
+
48
+ >>> # get canny image
49
+ >>> np_image = cv2.Canny(np_image, 100, 200)
50
+ >>> np_image = np_image[:, :, None]
51
+ >>> np_image = np.concatenate([np_image, np_image, np_image], axis=2)
52
+ >>> canny_image = Image.fromarray(np_image)
53
+
54
+ >>> # load control net and stable diffusion v1-5
55
+ >>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
56
+ >>> pipe = StableDiffusionControlNetImg2ImgPipeline.from_pretrained(
57
+ ... "runwayml/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16
58
+ ... )
59
+
60
+ >>> # speed up diffusion process with faster scheduler and memory optimization
61
+ >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
62
+ >>> pipe.enable_model_cpu_offload()
63
+
64
+ >>> # generate image
65
+ >>> generator = torch.manual_seed(0)
66
+ >>> image = pipe(
67
+ ... "futuristic-looking woman",
68
+ ... num_inference_steps=20,
69
+ ... generator=generator,
70
+ ... image=image,
71
+ ... control_image=canny_image,
72
+ ... ).images[0]
73
+ ```
74
+ """
75
+
76
+
77
+ def prepare_image(image):
78
+ if isinstance(image, torch.Tensor):
79
+ # Batch single image
80
+ if image.ndim == 3:
81
+ image = image.unsqueeze(0)
82
+
83
+ image = image.to(dtype=torch.float32)
84
+ else:
85
+ # preprocess image
86
+ if isinstance(image, (PIL.Image.Image, np.ndarray)):
87
+ image = [image]
88
+
89
+ if isinstance(image, list) and isinstance(image[0], PIL.Image.Image):
90
+ image = [np.array(i.convert("RGB"))[None, :] for i in image]
91
+ image = np.concatenate(image, axis=0)
92
+ elif isinstance(image, list) and isinstance(image[0], np.ndarray):
93
+ image = np.concatenate([i[None, :] for i in image], axis=0)
94
+
95
+ image = image.transpose(0, 3, 1, 2)
96
+ image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
97
+
98
+ return image
99
+
100
+
101
+ class OnnxStableDiffusionControlNetImg2ImgPipeline(DiffusionPipeline):
102
+ vae_encoder: OnnxRuntimeModel
103
+ vae_decoder: OnnxRuntimeModel
104
+ text_encoder: OnnxRuntimeModel
105
+ tokenizer: CLIPTokenizer
106
+ unet: OnnxRuntimeModel
107
+ scheduler: KarrasDiffusionSchedulers
108
+
109
+ def __init__(
110
+ self,
111
+ vae_encoder: OnnxRuntimeModel,
112
+ vae_decoder: OnnxRuntimeModel,
113
+ text_encoder: OnnxRuntimeModel,
114
+ tokenizer: CLIPTokenizer,
115
+ unet: OnnxRuntimeModel,
116
+ scheduler: KarrasDiffusionSchedulers,
117
+ ):
118
+ super().__init__()
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
+ )
128
+ self.vae_scale_factor = 2 ** (4 - 1)
129
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True)
130
+ self.control_image_processor = VaeImageProcessor(
131
+ vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
132
+ )
133
+
134
+ def _encode_prompt(
135
+ self,
136
+ prompt: Union[str, List[str]],
137
+ num_images_per_prompt: Optional[int],
138
+ do_classifier_free_guidance: bool,
139
+ negative_prompt: Optional[str],
140
+ prompt_embeds: Optional[np.ndarray] = None,
141
+ negative_prompt_embeds: Optional[np.ndarray] = None,
142
+ ):
143
+ r"""
144
+ Encodes the prompt into text encoder hidden states.
145
+
146
+ Args:
147
+ prompt (`str` or `List[str]`):
148
+ prompt to be encoded
149
+ num_images_per_prompt (`int`):
150
+ number of images that should be generated per prompt
151
+ do_classifier_free_guidance (`bool`):
152
+ whether to use classifier free guidance or not
153
+ negative_prompt (`str` or `List[str]`):
154
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
155
+ if `guidance_scale` is less than `1`).
156
+ prompt_embeds (`np.ndarray`, *optional*):
157
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
158
+ provided, text embeddings will be generated from `prompt` input argument.
159
+ negative_prompt_embeds (`np.ndarray`, *optional*):
160
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
161
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
162
+ argument.
163
+ """
164
+ if prompt is not None and isinstance(prompt, str):
165
+ batch_size = 1
166
+ elif prompt is not None and isinstance(prompt, list):
167
+ batch_size = len(prompt)
168
+ else:
169
+ batch_size = prompt_embeds.shape[0]
170
+
171
+ if prompt_embeds is None:
172
+ # get prompt text embeddings
173
+ text_inputs = self.tokenizer(
174
+ prompt,
175
+ padding="max_length",
176
+ max_length=self.tokenizer.model_max_length,
177
+ truncation=True,
178
+ return_tensors="np",
179
+ )
180
+ text_input_ids = text_inputs.input_ids
181
+ untruncated_ids = self.tokenizer(prompt, padding="max_length", return_tensors="np").input_ids
182
+
183
+ if not np.array_equal(text_input_ids, untruncated_ids):
184
+ removed_text = self.tokenizer.batch_decode(
185
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
186
+ )
187
+ logger.warning(
188
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
189
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
190
+ )
191
+
192
+ prompt_embeds = self.text_encoder(input_ids=text_input_ids.astype(np.int32))[0]
193
+
194
+ prompt_embeds = np.repeat(prompt_embeds, num_images_per_prompt, axis=0)
195
+
196
+ # get unconditional embeddings for classifier free guidance
197
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
198
+ uncond_tokens: List[str]
199
+ if negative_prompt is None:
200
+ uncond_tokens = [""] * batch_size
201
+ elif type(prompt) is not type(negative_prompt):
202
+ raise TypeError(
203
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
204
+ f" {type(prompt)}."
205
+ )
206
+ elif isinstance(negative_prompt, str):
207
+ uncond_tokens = [negative_prompt] * batch_size
208
+ elif batch_size != len(negative_prompt):
209
+ raise ValueError(
210
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
211
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
212
+ " the batch size of `prompt`."
213
+ )
214
+ else:
215
+ uncond_tokens = negative_prompt
216
+
217
+ max_length = prompt_embeds.shape[1]
218
+ uncond_input = self.tokenizer(
219
+ uncond_tokens,
220
+ padding="max_length",
221
+ max_length=max_length,
222
+ truncation=True,
223
+ return_tensors="np",
224
+ )
225
+ negative_prompt_embeds = self.text_encoder(input_ids=uncond_input.input_ids.astype(np.int32))[0]
226
+
227
+ if do_classifier_free_guidance:
228
+ negative_prompt_embeds = np.repeat(negative_prompt_embeds, num_images_per_prompt, axis=0)
229
+
230
+ # For classifier free guidance, we need to do two forward passes.
231
+ # Here we concatenate the unconditional and text embeddings into a single batch
232
+ # to avoid doing two forward passes
233
+ prompt_embeds = np.concatenate([negative_prompt_embeds, prompt_embeds])
234
+
235
+ return prompt_embeds
236
+
237
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents
238
+ def decode_latents(self, latents):
239
+ warnings.warn(
240
+ "The decode_latents method is deprecated and will be removed in a future version. Please"
241
+ " use VaeImageProcessor instead",
242
+ FutureWarning,
243
+ )
244
+ latents = 1 / self.vae.config.scaling_factor * latents
245
+ image = self.vae.decode(latents, return_dict=False)[0]
246
+ image = (image / 2 + 0.5).clamp(0, 1)
247
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
248
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
249
+ return image
250
+
251
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
252
+ def prepare_extra_step_kwargs(self, generator, eta):
253
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
254
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
255
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
256
+ # and should be between [0, 1]
257
+
258
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
259
+ extra_step_kwargs = {}
260
+ if accepts_eta:
261
+ extra_step_kwargs["eta"] = eta
262
+
263
+ # check if the scheduler accepts generator
264
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
265
+ if accepts_generator:
266
+ extra_step_kwargs["generator"] = generator
267
+ return extra_step_kwargs
268
+
269
+ def check_inputs(
270
+ self,
271
+ num_controlnet,
272
+ prompt,
273
+ image,
274
+ callback_steps,
275
+ negative_prompt=None,
276
+ prompt_embeds=None,
277
+ negative_prompt_embeds=None,
278
+ controlnet_conditioning_scale=1.0,
279
+ control_guidance_start=0.0,
280
+ control_guidance_end=1.0,
281
+ ):
282
+ if (callback_steps is None) or (
283
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
284
+ ):
285
+ raise ValueError(
286
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
287
+ f" {type(callback_steps)}."
288
+ )
289
+
290
+ if prompt is not None and prompt_embeds is not None:
291
+ raise ValueError(
292
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
293
+ " only forward one of the two."
294
+ )
295
+ elif prompt is None and prompt_embeds is None:
296
+ raise ValueError(
297
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
298
+ )
299
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
300
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
301
+
302
+ if negative_prompt is not None and negative_prompt_embeds is not None:
303
+ raise ValueError(
304
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
305
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
306
+ )
307
+
308
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
309
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
310
+ raise ValueError(
311
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
312
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
313
+ f" {negative_prompt_embeds.shape}."
314
+ )
315
+
316
+ # Check `image`
317
+ if num_controlnet == 1:
318
+ self.check_image(image, prompt, prompt_embeds)
319
+ elif num_controlnet > 1:
320
+ if not isinstance(image, list):
321
+ raise TypeError("For multiple controlnets: `image` must be type `list`")
322
+
323
+ # When `image` is a nested list:
324
+ # (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])
325
+ elif any(isinstance(i, list) for i in image):
326
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
327
+ elif len(image) != num_controlnet:
328
+ raise ValueError(
329
+ f"For multiple controlnets: `image` must have the same length as the number of controlnets, but got {len(image)} images and {num_controlnet} ControlNets."
330
+ )
331
+
332
+ for image_ in image:
333
+ self.check_image(image_, prompt, prompt_embeds)
334
+ else:
335
+ assert False
336
+
337
+ # Check `controlnet_conditioning_scale`
338
+ if num_controlnet == 1:
339
+ if not isinstance(controlnet_conditioning_scale, float):
340
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
341
+ elif num_controlnet > 1:
342
+ if isinstance(controlnet_conditioning_scale, list):
343
+ if any(isinstance(i, list) for i in controlnet_conditioning_scale):
344
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
345
+ elif (
346
+ isinstance(controlnet_conditioning_scale, list)
347
+ and len(controlnet_conditioning_scale) != num_controlnet
348
+ ):
349
+ raise ValueError(
350
+ "For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
351
+ " the same length as the number of controlnets"
352
+ )
353
+ else:
354
+ assert False
355
+
356
+ if len(control_guidance_start) != len(control_guidance_end):
357
+ raise ValueError(
358
+ f"`control_guidance_start` has {len(control_guidance_start)} elements, but `control_guidance_end` has {len(control_guidance_end)} elements. Make sure to provide the same number of elements to each list."
359
+ )
360
+
361
+ if num_controlnet > 1:
362
+ if len(control_guidance_start) != num_controlnet:
363
+ raise ValueError(
364
+ f"`control_guidance_start`: {control_guidance_start} has {len(control_guidance_start)} elements but there are {num_controlnet} controlnets available. Make sure to provide {num_controlnet}."
365
+ )
366
+
367
+ for start, end in zip(control_guidance_start, control_guidance_end):
368
+ if start >= end:
369
+ raise ValueError(
370
+ f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
371
+ )
372
+ if start < 0.0:
373
+ raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
374
+ if end > 1.0:
375
+ raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
376
+
377
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.check_image
378
+ def check_image(self, image, prompt, prompt_embeds):
379
+ image_is_pil = isinstance(image, PIL.Image.Image)
380
+ image_is_tensor = isinstance(image, torch.Tensor)
381
+ image_is_np = isinstance(image, np.ndarray)
382
+ image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
383
+ image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
384
+ image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
385
+
386
+ if (
387
+ not image_is_pil
388
+ and not image_is_tensor
389
+ and not image_is_np
390
+ and not image_is_pil_list
391
+ and not image_is_tensor_list
392
+ and not image_is_np_list
393
+ ):
394
+ raise TypeError(
395
+ f"image must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(image)}"
396
+ )
397
+
398
+ if image_is_pil:
399
+ image_batch_size = 1
400
+ else:
401
+ image_batch_size = len(image)
402
+
403
+ if prompt is not None and isinstance(prompt, str):
404
+ prompt_batch_size = 1
405
+ elif prompt is not None and isinstance(prompt, list):
406
+ prompt_batch_size = len(prompt)
407
+ elif prompt_embeds is not None:
408
+ prompt_batch_size = prompt_embeds.shape[0]
409
+
410
+ if image_batch_size != 1 and image_batch_size != prompt_batch_size:
411
+ raise ValueError(
412
+ f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
413
+ )
414
+
415
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.prepare_image
416
+ def prepare_control_image(
417
+ self,
418
+ image,
419
+ width,
420
+ height,
421
+ batch_size,
422
+ num_images_per_prompt,
423
+ device,
424
+ dtype,
425
+ do_classifier_free_guidance=False,
426
+ guess_mode=False,
427
+ ):
428
+ image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
429
+ image_batch_size = image.shape[0]
430
+
431
+ if image_batch_size == 1:
432
+ repeat_by = batch_size
433
+ else:
434
+ # image batch size is the same as prompt batch size
435
+ repeat_by = num_images_per_prompt
436
+
437
+ image = image.repeat_interleave(repeat_by, dim=0)
438
+
439
+ image = image.to(device=device, dtype=dtype)
440
+
441
+ if do_classifier_free_guidance and not guess_mode:
442
+ image = torch.cat([image] * 2)
443
+
444
+ return image
445
+
446
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.get_timesteps
447
+ def get_timesteps(self, num_inference_steps, strength, device):
448
+ # get the original timestep using init_timestep
449
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
450
+
451
+ t_start = max(num_inference_steps - init_timestep, 0)
452
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
453
+
454
+ return timesteps, num_inference_steps - t_start
455
+
456
+ def prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None):
457
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
458
+ raise ValueError(
459
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
460
+ )
461
+
462
+ image = image.to(device=device, dtype=dtype)
463
+
464
+ batch_size = batch_size * num_images_per_prompt
465
+
466
+ if image.shape[1] == 4:
467
+ init_latents = image
468
+
469
+ else:
470
+ _image = image.cpu().detach().numpy()
471
+ init_latents = self.vae_encoder(sample=_image)[0]
472
+ init_latents = torch.from_numpy(init_latents).to(device=device, dtype=dtype)
473
+ init_latents = 0.18215 * init_latents
474
+
475
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
476
+ # expand init_latents for batch_size
477
+ deprecation_message = (
478
+ f"You have passed {batch_size} text prompts (`prompt`), but only {init_latents.shape[0]} initial"
479
+ " images (`image`). Initial images are now duplicating to match the number of text prompts. Note"
480
+ " that this behavior is deprecated and will be removed in a version 1.0.0. Please make sure to update"
481
+ " your script to pass as many initial images as text prompts to suppress this warning."
482
+ )
483
+ deprecate("len(prompt) != len(image)", "1.0.0", deprecation_message, standard_warn=False)
484
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
485
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
486
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
487
+ raise ValueError(
488
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
489
+ )
490
+ else:
491
+ init_latents = torch.cat([init_latents], dim=0)
492
+
493
+ shape = init_latents.shape
494
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
495
+
496
+ # get latents
497
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
498
+ latents = init_latents
499
+
500
+ return latents
501
+
502
+ @torch.no_grad()
503
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
504
+ def __call__(
505
+ self,
506
+ num_controlnet: int,
507
+ fp16: bool = True,
508
+ prompt: Union[str, List[str]] = None,
509
+ image: Union[
510
+ torch.FloatTensor,
511
+ PIL.Image.Image,
512
+ np.ndarray,
513
+ List[torch.FloatTensor],
514
+ List[PIL.Image.Image],
515
+ List[np.ndarray],
516
+ ] = None,
517
+ control_image: Union[
518
+ torch.FloatTensor,
519
+ PIL.Image.Image,
520
+ np.ndarray,
521
+ List[torch.FloatTensor],
522
+ List[PIL.Image.Image],
523
+ List[np.ndarray],
524
+ ] = None,
525
+ height: Optional[int] = None,
526
+ width: Optional[int] = None,
527
+ strength: float = 0.8,
528
+ num_inference_steps: int = 50,
529
+ guidance_scale: float = 7.5,
530
+ negative_prompt: Optional[Union[str, List[str]]] = None,
531
+ num_images_per_prompt: Optional[int] = 1,
532
+ eta: float = 0.0,
533
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
534
+ latents: Optional[torch.FloatTensor] = None,
535
+ prompt_embeds: Optional[torch.FloatTensor] = None,
536
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
537
+ output_type: Optional[str] = "pil",
538
+ return_dict: bool = True,
539
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
540
+ callback_steps: int = 1,
541
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
542
+ controlnet_conditioning_scale: Union[float, List[float]] = 0.8,
543
+ guess_mode: bool = False,
544
+ control_guidance_start: Union[float, List[float]] = 0.0,
545
+ control_guidance_end: Union[float, List[float]] = 1.0,
546
+ ):
547
+ r"""
548
+ Function invoked when calling the pipeline for generation.
549
+
550
+ Args:
551
+ prompt (`str` or `List[str]`, *optional*):
552
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
553
+ instead.
554
+ image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
555
+ `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
556
+ The initial image will be used as the starting point for the image generation process. Can also accept
557
+ image latents as `image`, if passing latents directly, it will not be encoded again.
558
+ control_image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
559
+ `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
560
+ The ControlNet input condition. ControlNet uses this input condition to generate guidance to Unet. If
561
+ the type is specified as `Torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can
562
+ also be accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If
563
+ height and/or width are passed, `image` is resized according to them. If multiple ControlNets are
564
+ specified in init, images must be passed as a list such that each element of the list can be correctly
565
+ batched for input to a single controlnet.
566
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
567
+ The height in pixels of the generated image.
568
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
569
+ The width in pixels of the generated image.
570
+ num_inference_steps (`int`, *optional*, defaults to 50):
571
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
572
+ expense of slower inference.
573
+ guidance_scale (`float`, *optional*, defaults to 7.5):
574
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
575
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
576
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
577
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
578
+ usually at the expense of lower image quality.
579
+ negative_prompt (`str` or `List[str]`, *optional*):
580
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
581
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
582
+ less than `1`).
583
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
584
+ The number of images to generate per prompt.
585
+ eta (`float`, *optional*, defaults to 0.0):
586
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
587
+ [`schedulers.DDIMScheduler`], will be ignored for others.
588
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
589
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
590
+ to make generation deterministic.
591
+ latents (`torch.FloatTensor`, *optional*):
592
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
593
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
594
+ tensor will ge generated by sampling using the supplied random `generator`.
595
+ prompt_embeds (`torch.FloatTensor`, *optional*):
596
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
597
+ provided, text embeddings will be generated from `prompt` input argument.
598
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
599
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
600
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
601
+ argument.
602
+ output_type (`str`, *optional*, defaults to `"pil"`):
603
+ The output format of the generate image. Choose between
604
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
605
+ return_dict (`bool`, *optional*, defaults to `True`):
606
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
607
+ plain tuple.
608
+ callback (`Callable`, *optional*):
609
+ A function that will be called every `callback_steps` steps during inference. The function will be
610
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
611
+ callback_steps (`int`, *optional*, defaults to 1):
612
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
613
+ called at every step.
614
+ cross_attention_kwargs (`dict`, *optional*):
615
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
616
+ `self.processor` in
617
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
618
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
619
+ The outputs of the controlnet are multiplied by `controlnet_conditioning_scale` before they are added
620
+ to the residual in the original unet. If multiple ControlNets are specified in init, you can set the
621
+ corresponding scale as a list. Note that by default, we use a smaller conditioning scale for inpainting
622
+ than for [`~StableDiffusionControlNetPipeline.__call__`].
623
+ guess_mode (`bool`, *optional*, defaults to `False`):
624
+ In this mode, the ControlNet encoder will try best to recognize the content of the input image even if
625
+ you remove all prompts. The `guidance_scale` between 3.0 and 5.0 is recommended.
626
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
627
+ The percentage of total steps at which the controlnet starts applying.
628
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
629
+ The percentage of total steps at which the controlnet stops applying.
630
+
631
+ Examples:
632
+
633
+ Returns:
634
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
635
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
636
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
637
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
638
+ (nsfw) content, according to the `safety_checker`.
639
+ """
640
+ if fp16:
641
+ torch_dtype = torch.float16
642
+ np_dtype = np.float16
643
+ else:
644
+ torch_dtype = torch.float32
645
+ np_dtype = np.float32
646
+
647
+ # align format for control guidance
648
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
649
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
650
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
651
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
652
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
653
+ mult = num_controlnet
654
+ control_guidance_start, control_guidance_end = mult * [control_guidance_start], mult * [
655
+ control_guidance_end
656
+ ]
657
+
658
+ # 1. Check inputs. Raise error if not correct
659
+ self.check_inputs(
660
+ num_controlnet,
661
+ prompt,
662
+ control_image,
663
+ callback_steps,
664
+ negative_prompt,
665
+ prompt_embeds,
666
+ negative_prompt_embeds,
667
+ controlnet_conditioning_scale,
668
+ control_guidance_start,
669
+ control_guidance_end,
670
+ )
671
+
672
+ # 2. Define call parameters
673
+ if prompt is not None and isinstance(prompt, str):
674
+ batch_size = 1
675
+ elif prompt is not None and isinstance(prompt, list):
676
+ batch_size = len(prompt)
677
+ else:
678
+ batch_size = prompt_embeds.shape[0]
679
+
680
+ device = self._execution_device
681
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
682
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
683
+ # corresponds to doing no classifier free guidance.
684
+ do_classifier_free_guidance = guidance_scale > 1.0
685
+
686
+ if num_controlnet > 1 and isinstance(controlnet_conditioning_scale, float):
687
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * num_controlnet
688
+
689
+ # 3. Encode input prompt
690
+ prompt_embeds = self._encode_prompt(
691
+ prompt,
692
+ num_images_per_prompt,
693
+ do_classifier_free_guidance,
694
+ negative_prompt,
695
+ prompt_embeds=prompt_embeds,
696
+ negative_prompt_embeds=negative_prompt_embeds,
697
+ )
698
+ # 4. Prepare image
699
+ image = self.image_processor.preprocess(image).to(dtype=torch.float32)
700
+
701
+ # 5. Prepare controlnet_conditioning_image
702
+ if num_controlnet == 1:
703
+ control_image = self.prepare_control_image(
704
+ image=control_image,
705
+ width=width,
706
+ height=height,
707
+ batch_size=batch_size * num_images_per_prompt,
708
+ num_images_per_prompt=num_images_per_prompt,
709
+ device=device,
710
+ dtype=torch_dtype,
711
+ do_classifier_free_guidance=do_classifier_free_guidance,
712
+ guess_mode=guess_mode,
713
+ )
714
+ elif num_controlnet > 1:
715
+ control_images = []
716
+
717
+ for control_image_ in control_image:
718
+ control_image_ = self.prepare_control_image(
719
+ image=control_image_,
720
+ width=width,
721
+ height=height,
722
+ batch_size=batch_size * num_images_per_prompt,
723
+ num_images_per_prompt=num_images_per_prompt,
724
+ device=device,
725
+ dtype=torch_dtype,
726
+ do_classifier_free_guidance=do_classifier_free_guidance,
727
+ guess_mode=guess_mode,
728
+ )
729
+
730
+ control_images.append(control_image_)
731
+
732
+ control_image = control_images
733
+ else:
734
+ assert False
735
+
736
+ # 5. Prepare timesteps
737
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
738
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
739
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
740
+
741
+ # 6. Prepare latent variables
742
+ latents = self.prepare_latents(
743
+ image,
744
+ latent_timestep,
745
+ batch_size,
746
+ num_images_per_prompt,
747
+ torch_dtype,
748
+ device,
749
+ generator,
750
+ )
751
+
752
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
753
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
754
+
755
+ # 7.1 Create tensor stating which controlnets to keep
756
+ controlnet_keep = []
757
+ for i in range(len(timesteps)):
758
+ keeps = [
759
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
760
+ for s, e in zip(control_guidance_start, control_guidance_end)
761
+ ]
762
+ controlnet_keep.append(keeps[0] if num_controlnet == 1 else keeps)
763
+
764
+ # 8. Denoising loop
765
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
766
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
767
+ for i, t in enumerate(timesteps):
768
+ # expand the latents if we are doing classifier free guidance
769
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
770
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
771
+
772
+ if isinstance(controlnet_keep[i], list):
773
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
774
+ else:
775
+ controlnet_cond_scale = controlnet_conditioning_scale
776
+ if isinstance(controlnet_cond_scale, list):
777
+ controlnet_cond_scale = controlnet_cond_scale[0]
778
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
779
+
780
+ # predict the noise residual
781
+ _latent_model_input = latent_model_input.cpu().detach().numpy()
782
+ _prompt_embeds = np.array(prompt_embeds, dtype=np_dtype)
783
+ _t = np.array([t.cpu().detach().numpy()], dtype=np_dtype)
784
+
785
+ if num_controlnet == 1:
786
+ control_images = np.array([control_image], dtype=np_dtype)
787
+ else:
788
+ control_images = []
789
+ for _control_img in control_image:
790
+ _control_img = _control_img.cpu().detach().numpy()
791
+ control_images.append(_control_img)
792
+ control_images = np.array(control_images, dtype=np_dtype)
793
+
794
+ control_scales = np.array(cond_scale, dtype=np_dtype)
795
+ control_scales = np.resize(control_scales, (num_controlnet, 1))
796
+
797
+ noise_pred = self.unet(
798
+ sample=_latent_model_input,
799
+ timestep=_t,
800
+ encoder_hidden_states=_prompt_embeds,
801
+ controlnet_conds=control_images,
802
+ conditioning_scales=control_scales,
803
+ )[0]
804
+ noise_pred = torch.from_numpy(noise_pred).to(device)
805
+
806
+ # perform guidance
807
+ if do_classifier_free_guidance:
808
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
809
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
810
+
811
+ # compute the previous noisy sample x_t -> x_t-1
812
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
813
+
814
+ # call the callback, if provided
815
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
816
+ progress_bar.update()
817
+ if callback is not None and i % callback_steps == 0:
818
+ step_idx = i // getattr(self.scheduler, "order", 1)
819
+ callback(step_idx, t, latents)
820
+
821
+ if not output_type == "latent":
822
+ _latents = latents.cpu().detach().numpy() / 0.18215
823
+ _latents = np.array(_latents, dtype=np_dtype)
824
+ image = self.vae_decoder(latent_sample=_latents)[0]
825
+ image = torch.from_numpy(image).to(device, dtype=torch.float32)
826
+ has_nsfw_concept = None
827
+ else:
828
+ image = latents
829
+ has_nsfw_concept = None
830
+
831
+ if has_nsfw_concept is None:
832
+ do_denormalize = [True] * image.shape[0]
833
+ else:
834
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
835
+
836
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
837
+
838
+ if not return_dict:
839
+ return (image, has_nsfw_concept)
840
+
841
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
842
+
843
+
844
+ if __name__ == "__main__":
845
+ parser = argparse.ArgumentParser()
846
+
847
+ parser.add_argument(
848
+ "--sd_model",
849
+ type=str,
850
+ required=True,
851
+ help="Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).",
852
+ )
853
+
854
+ parser.add_argument(
855
+ "--onnx_model_dir",
856
+ type=str,
857
+ required=True,
858
+ help="Path to the ONNX directory",
859
+ )
860
+
861
+ parser.add_argument("--qr_img_path", type=str, required=True, help="Path to the qr code image")
862
+
863
+ args = parser.parse_args()
864
+
865
+ qr_image = Image.open(args.qr_img_path)
866
+ qr_image = qr_image.resize((512, 512))
867
+
868
+ # init stable diffusion pipeline
869
+ pipeline = StableDiffusionImg2ImgPipeline.from_pretrained(args.sd_model)
870
+ pipeline.scheduler = UniPCMultistepScheduler.from_config(pipeline.scheduler.config)
871
+
872
+ provider = ["CUDAExecutionProvider", "CPUExecutionProvider"]
873
+ onnx_pipeline = OnnxStableDiffusionControlNetImg2ImgPipeline(
874
+ vae_encoder=OnnxRuntimeModel.from_pretrained(
875
+ os.path.join(args.onnx_model_dir, "vae_encoder"), provider=provider
876
+ ),
877
+ vae_decoder=OnnxRuntimeModel.from_pretrained(
878
+ os.path.join(args.onnx_model_dir, "vae_decoder"), provider=provider
879
+ ),
880
+ text_encoder=OnnxRuntimeModel.from_pretrained(
881
+ os.path.join(args.onnx_model_dir, "text_encoder"), provider=provider
882
+ ),
883
+ tokenizer=pipeline.tokenizer,
884
+ unet=OnnxRuntimeModel.from_pretrained(os.path.join(args.onnx_model_dir, "unet"), provider=provider),
885
+ scheduler=pipeline.scheduler,
886
+ )
887
+ onnx_pipeline = onnx_pipeline.to("cuda")
888
+
889
+ prompt = "a cute cat fly to the moon"
890
+ negative_prompt = "paintings, sketches, worst quality, low quality, normal quality, lowres, normal quality, monochrome, grayscale, skin spots, acnes, skin blemishes, age spot, glans, nsfw, nipples, necklace, worst quality, low quality, watermark, username, signature, multiple breasts, lowres, bad anatomy, bad hands, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry, bad feet, single color, ugly, duplicate, morbid, mutilated, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, ugly, blurry, bad anatomy, bad proportions, extra limbs, disfigured, bad anatomy, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, mutated hands, fused fingers, too many fingers, long neck, bad body perspect"
891
+
892
+ for i in range(10):
893
+ start_time = time.time()
894
+ image = onnx_pipeline(
895
+ num_controlnet=2,
896
+ prompt=prompt,
897
+ negative_prompt=negative_prompt,
898
+ image=qr_image,
899
+ control_image=[qr_image, qr_image],
900
+ width=512,
901
+ height=512,
902
+ strength=0.75,
903
+ num_inference_steps=20,
904
+ num_images_per_prompt=1,
905
+ controlnet_conditioning_scale=[0.8, 0.8],
906
+ control_guidance_start=[0.3, 0.3],
907
+ control_guidance_end=[0.9, 0.9],
908
+ ).images[0]
909
+ print(time.time() - start_time)
910
+ image.save("output_qr_code.png")
v0.22.0/run_tensorrt_controlnet.py ADDED
@@ -0,0 +1,1021 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import atexit
3
+ import inspect
4
+ import os
5
+ import time
6
+ import warnings
7
+ from typing import Any, Callable, Dict, List, Optional, Union
8
+
9
+ import numpy as np
10
+ import PIL.Image
11
+ import pycuda.driver as cuda
12
+ import tensorrt as trt
13
+ import torch
14
+ from PIL import Image
15
+ from pycuda.tools import make_default_context
16
+ from transformers import CLIPTokenizer
17
+
18
+ from diffusers import OnnxRuntimeModel, StableDiffusionImg2ImgPipeline, UniPCMultistepScheduler
19
+ from diffusers.image_processor import VaeImageProcessor
20
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
21
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
22
+ from diffusers.schedulers import KarrasDiffusionSchedulers
23
+ from diffusers.utils import (
24
+ deprecate,
25
+ logging,
26
+ replace_example_docstring,
27
+ )
28
+ from diffusers.utils.torch_utils import randn_tensor
29
+
30
+
31
+ # Initialize CUDA
32
+ cuda.init()
33
+ context = make_default_context()
34
+ device = context.get_device()
35
+ atexit.register(context.pop)
36
+
37
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
38
+
39
+
40
+ def load_engine(trt_runtime, engine_path):
41
+ with open(engine_path, "rb") as f:
42
+ engine_data = f.read()
43
+ engine = trt_runtime.deserialize_cuda_engine(engine_data)
44
+ return engine
45
+
46
+
47
+ class TensorRTModel:
48
+ def __init__(
49
+ self,
50
+ trt_engine_path,
51
+ **kwargs,
52
+ ):
53
+ cuda.init()
54
+ stream = cuda.Stream()
55
+ TRT_LOGGER = trt.Logger(trt.Logger.VERBOSE)
56
+ trt.init_libnvinfer_plugins(TRT_LOGGER, "")
57
+ trt_runtime = trt.Runtime(TRT_LOGGER)
58
+ engine = load_engine(trt_runtime, trt_engine_path)
59
+ context = engine.create_execution_context()
60
+
61
+ # allocates memory for network inputs/outputs on both CPU and GPU
62
+ host_inputs = []
63
+ cuda_inputs = []
64
+ host_outputs = []
65
+ cuda_outputs = []
66
+ bindings = []
67
+ input_names = []
68
+ output_names = []
69
+
70
+ for binding in engine:
71
+ datatype = engine.get_binding_dtype(binding)
72
+ if datatype == trt.DataType.HALF:
73
+ dtype = np.float16
74
+ else:
75
+ dtype = np.float32
76
+
77
+ shape = tuple(engine.get_binding_shape(binding))
78
+ host_mem = cuda.pagelocked_empty(shape, dtype)
79
+ cuda_mem = cuda.mem_alloc(host_mem.nbytes)
80
+ bindings.append(int(cuda_mem))
81
+
82
+ if engine.binding_is_input(binding):
83
+ host_inputs.append(host_mem)
84
+ cuda_inputs.append(cuda_mem)
85
+ input_names.append(binding)
86
+ else:
87
+ host_outputs.append(host_mem)
88
+ cuda_outputs.append(cuda_mem)
89
+ output_names.append(binding)
90
+
91
+ self.stream = stream
92
+ self.context = context
93
+ self.engine = engine
94
+
95
+ self.host_inputs = host_inputs
96
+ self.cuda_inputs = cuda_inputs
97
+ self.host_outputs = host_outputs
98
+ self.cuda_outputs = cuda_outputs
99
+ self.bindings = bindings
100
+ self.batch_size = engine.max_batch_size
101
+
102
+ self.input_names = input_names
103
+ self.output_names = output_names
104
+
105
+ def __call__(self, **kwargs):
106
+ context = self.context
107
+ stream = self.stream
108
+ bindings = self.bindings
109
+
110
+ host_inputs = self.host_inputs
111
+ cuda_inputs = self.cuda_inputs
112
+ host_outputs = self.host_outputs
113
+ cuda_outputs = self.cuda_outputs
114
+
115
+ for idx, input_name in enumerate(self.input_names):
116
+ _input = kwargs[input_name]
117
+ np.copyto(host_inputs[idx], _input)
118
+ # transfer input data to the GPU
119
+ cuda.memcpy_htod_async(cuda_inputs[idx], host_inputs[idx], stream)
120
+
121
+ context.execute_async_v2(bindings=bindings, stream_handle=stream.handle)
122
+
123
+ result = {}
124
+ for idx, output_name in enumerate(self.output_names):
125
+ # transfer predictions back from the GPU
126
+ cuda.memcpy_dtoh_async(host_outputs[idx], cuda_outputs[idx], stream)
127
+ result[output_name] = host_outputs[idx]
128
+
129
+ stream.synchronize()
130
+
131
+ return result
132
+
133
+
134
+ EXAMPLE_DOC_STRING = """
135
+ Examples:
136
+ ```py
137
+ >>> # !pip install opencv-python transformers accelerate
138
+ >>> from diffusers import StableDiffusionControlNetImg2ImgPipeline, ControlNetModel, UniPCMultistepScheduler
139
+ >>> from diffusers.utils import load_image
140
+ >>> import numpy as np
141
+ >>> import torch
142
+
143
+ >>> import cv2
144
+ >>> from PIL import Image
145
+
146
+ >>> # download an image
147
+ >>> image = load_image(
148
+ ... "https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png"
149
+ ... )
150
+ >>> np_image = np.array(image)
151
+
152
+ >>> # get canny image
153
+ >>> np_image = cv2.Canny(np_image, 100, 200)
154
+ >>> np_image = np_image[:, :, None]
155
+ >>> np_image = np.concatenate([np_image, np_image, np_image], axis=2)
156
+ >>> canny_image = Image.fromarray(np_image)
157
+
158
+ >>> # load control net and stable diffusion v1-5
159
+ >>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
160
+ >>> pipe = StableDiffusionControlNetImg2ImgPipeline.from_pretrained(
161
+ ... "runwayml/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16
162
+ ... )
163
+
164
+ >>> # speed up diffusion process with faster scheduler and memory optimization
165
+ >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
166
+ >>> pipe.enable_model_cpu_offload()
167
+
168
+ >>> # generate image
169
+ >>> generator = torch.manual_seed(0)
170
+ >>> image = pipe(
171
+ ... "futuristic-looking woman",
172
+ ... num_inference_steps=20,
173
+ ... generator=generator,
174
+ ... image=image,
175
+ ... control_image=canny_image,
176
+ ... ).images[0]
177
+ ```
178
+ """
179
+
180
+
181
+ def prepare_image(image):
182
+ if isinstance(image, torch.Tensor):
183
+ # Batch single image
184
+ if image.ndim == 3:
185
+ image = image.unsqueeze(0)
186
+
187
+ image = image.to(dtype=torch.float32)
188
+ else:
189
+ # preprocess image
190
+ if isinstance(image, (PIL.Image.Image, np.ndarray)):
191
+ image = [image]
192
+
193
+ if isinstance(image, list) and isinstance(image[0], PIL.Image.Image):
194
+ image = [np.array(i.convert("RGB"))[None, :] for i in image]
195
+ image = np.concatenate(image, axis=0)
196
+ elif isinstance(image, list) and isinstance(image[0], np.ndarray):
197
+ image = np.concatenate([i[None, :] for i in image], axis=0)
198
+
199
+ image = image.transpose(0, 3, 1, 2)
200
+ image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
201
+
202
+ return image
203
+
204
+
205
+ class TensorRTStableDiffusionControlNetImg2ImgPipeline(DiffusionPipeline):
206
+ vae_encoder: OnnxRuntimeModel
207
+ vae_decoder: OnnxRuntimeModel
208
+ text_encoder: OnnxRuntimeModel
209
+ tokenizer: CLIPTokenizer
210
+ unet: TensorRTModel
211
+ scheduler: KarrasDiffusionSchedulers
212
+
213
+ def __init__(
214
+ self,
215
+ vae_encoder: OnnxRuntimeModel,
216
+ vae_decoder: OnnxRuntimeModel,
217
+ text_encoder: OnnxRuntimeModel,
218
+ tokenizer: CLIPTokenizer,
219
+ unet: TensorRTModel,
220
+ scheduler: KarrasDiffusionSchedulers,
221
+ ):
222
+ super().__init__()
223
+
224
+ self.register_modules(
225
+ vae_encoder=vae_encoder,
226
+ vae_decoder=vae_decoder,
227
+ text_encoder=text_encoder,
228
+ tokenizer=tokenizer,
229
+ unet=unet,
230
+ scheduler=scheduler,
231
+ )
232
+ self.vae_scale_factor = 2 ** (4 - 1)
233
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True)
234
+ self.control_image_processor = VaeImageProcessor(
235
+ vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
236
+ )
237
+
238
+ def _encode_prompt(
239
+ self,
240
+ prompt: Union[str, List[str]],
241
+ num_images_per_prompt: Optional[int],
242
+ do_classifier_free_guidance: bool,
243
+ negative_prompt: Optional[str],
244
+ prompt_embeds: Optional[np.ndarray] = None,
245
+ negative_prompt_embeds: Optional[np.ndarray] = None,
246
+ ):
247
+ r"""
248
+ Encodes the prompt into text encoder hidden states.
249
+
250
+ Args:
251
+ prompt (`str` or `List[str]`):
252
+ prompt to be encoded
253
+ num_images_per_prompt (`int`):
254
+ number of images that should be generated per prompt
255
+ do_classifier_free_guidance (`bool`):
256
+ whether to use classifier free guidance or not
257
+ negative_prompt (`str` or `List[str]`):
258
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
259
+ if `guidance_scale` is less than `1`).
260
+ prompt_embeds (`np.ndarray`, *optional*):
261
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
262
+ provided, text embeddings will be generated from `prompt` input argument.
263
+ negative_prompt_embeds (`np.ndarray`, *optional*):
264
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
265
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
266
+ argument.
267
+ """
268
+ if prompt is not None and isinstance(prompt, str):
269
+ batch_size = 1
270
+ elif prompt is not None and isinstance(prompt, list):
271
+ batch_size = len(prompt)
272
+ else:
273
+ batch_size = prompt_embeds.shape[0]
274
+
275
+ if prompt_embeds is None:
276
+ # get prompt text embeddings
277
+ text_inputs = self.tokenizer(
278
+ prompt,
279
+ padding="max_length",
280
+ max_length=self.tokenizer.model_max_length,
281
+ truncation=True,
282
+ return_tensors="np",
283
+ )
284
+ text_input_ids = text_inputs.input_ids
285
+ untruncated_ids = self.tokenizer(prompt, padding="max_length", return_tensors="np").input_ids
286
+
287
+ if not np.array_equal(text_input_ids, untruncated_ids):
288
+ removed_text = self.tokenizer.batch_decode(
289
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
290
+ )
291
+ logger.warning(
292
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
293
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
294
+ )
295
+
296
+ prompt_embeds = self.text_encoder(input_ids=text_input_ids.astype(np.int32))[0]
297
+
298
+ prompt_embeds = np.repeat(prompt_embeds, num_images_per_prompt, axis=0)
299
+
300
+ # get unconditional embeddings for classifier free guidance
301
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
302
+ uncond_tokens: List[str]
303
+ if negative_prompt is None:
304
+ uncond_tokens = [""] * batch_size
305
+ elif type(prompt) is not type(negative_prompt):
306
+ raise TypeError(
307
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
308
+ f" {type(prompt)}."
309
+ )
310
+ elif isinstance(negative_prompt, str):
311
+ uncond_tokens = [negative_prompt] * batch_size
312
+ elif batch_size != len(negative_prompt):
313
+ raise ValueError(
314
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
315
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
316
+ " the batch size of `prompt`."
317
+ )
318
+ else:
319
+ uncond_tokens = negative_prompt
320
+
321
+ max_length = prompt_embeds.shape[1]
322
+ uncond_input = self.tokenizer(
323
+ uncond_tokens,
324
+ padding="max_length",
325
+ max_length=max_length,
326
+ truncation=True,
327
+ return_tensors="np",
328
+ )
329
+ negative_prompt_embeds = self.text_encoder(input_ids=uncond_input.input_ids.astype(np.int32))[0]
330
+
331
+ if do_classifier_free_guidance:
332
+ negative_prompt_embeds = np.repeat(negative_prompt_embeds, num_images_per_prompt, axis=0)
333
+
334
+ # For classifier free guidance, we need to do two forward passes.
335
+ # Here we concatenate the unconditional and text embeddings into a single batch
336
+ # to avoid doing two forward passes
337
+ prompt_embeds = np.concatenate([negative_prompt_embeds, prompt_embeds])
338
+
339
+ return prompt_embeds
340
+
341
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents
342
+ def decode_latents(self, latents):
343
+ warnings.warn(
344
+ "The decode_latents method is deprecated and will be removed in a future version. Please"
345
+ " use VaeImageProcessor instead",
346
+ FutureWarning,
347
+ )
348
+ latents = 1 / self.vae.config.scaling_factor * latents
349
+ image = self.vae.decode(latents, return_dict=False)[0]
350
+ image = (image / 2 + 0.5).clamp(0, 1)
351
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
352
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
353
+ return image
354
+
355
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
356
+ def prepare_extra_step_kwargs(self, generator, eta):
357
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
358
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
359
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
360
+ # and should be between [0, 1]
361
+
362
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
363
+ extra_step_kwargs = {}
364
+ if accepts_eta:
365
+ extra_step_kwargs["eta"] = eta
366
+
367
+ # check if the scheduler accepts generator
368
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
369
+ if accepts_generator:
370
+ extra_step_kwargs["generator"] = generator
371
+ return extra_step_kwargs
372
+
373
+ def check_inputs(
374
+ self,
375
+ num_controlnet,
376
+ prompt,
377
+ image,
378
+ callback_steps,
379
+ negative_prompt=None,
380
+ prompt_embeds=None,
381
+ negative_prompt_embeds=None,
382
+ controlnet_conditioning_scale=1.0,
383
+ control_guidance_start=0.0,
384
+ control_guidance_end=1.0,
385
+ ):
386
+ if (callback_steps is None) or (
387
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
388
+ ):
389
+ raise ValueError(
390
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
391
+ f" {type(callback_steps)}."
392
+ )
393
+
394
+ if prompt is not None and prompt_embeds is not None:
395
+ raise ValueError(
396
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
397
+ " only forward one of the two."
398
+ )
399
+ elif prompt is None and prompt_embeds is None:
400
+ raise ValueError(
401
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
402
+ )
403
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
404
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
405
+
406
+ if negative_prompt is not None and negative_prompt_embeds is not None:
407
+ raise ValueError(
408
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
409
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
410
+ )
411
+
412
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
413
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
414
+ raise ValueError(
415
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
416
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
417
+ f" {negative_prompt_embeds.shape}."
418
+ )
419
+
420
+ # Check `image`
421
+ if num_controlnet == 1:
422
+ self.check_image(image, prompt, prompt_embeds)
423
+ elif num_controlnet > 1:
424
+ if not isinstance(image, list):
425
+ raise TypeError("For multiple controlnets: `image` must be type `list`")
426
+
427
+ # When `image` is a nested list:
428
+ # (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])
429
+ elif any(isinstance(i, list) for i in image):
430
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
431
+ elif len(image) != num_controlnet:
432
+ raise ValueError(
433
+ f"For multiple controlnets: `image` must have the same length as the number of controlnets, but got {len(image)} images and {num_controlnet} ControlNets."
434
+ )
435
+
436
+ for image_ in image:
437
+ self.check_image(image_, prompt, prompt_embeds)
438
+ else:
439
+ assert False
440
+
441
+ # Check `controlnet_conditioning_scale`
442
+ if num_controlnet == 1:
443
+ if not isinstance(controlnet_conditioning_scale, float):
444
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
445
+ elif num_controlnet > 1:
446
+ if isinstance(controlnet_conditioning_scale, list):
447
+ if any(isinstance(i, list) for i in controlnet_conditioning_scale):
448
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
449
+ elif (
450
+ isinstance(controlnet_conditioning_scale, list)
451
+ and len(controlnet_conditioning_scale) != num_controlnet
452
+ ):
453
+ raise ValueError(
454
+ "For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
455
+ " the same length as the number of controlnets"
456
+ )
457
+ else:
458
+ assert False
459
+
460
+ if len(control_guidance_start) != len(control_guidance_end):
461
+ raise ValueError(
462
+ f"`control_guidance_start` has {len(control_guidance_start)} elements, but `control_guidance_end` has {len(control_guidance_end)} elements. Make sure to provide the same number of elements to each list."
463
+ )
464
+
465
+ if num_controlnet > 1:
466
+ if len(control_guidance_start) != num_controlnet:
467
+ raise ValueError(
468
+ f"`control_guidance_start`: {control_guidance_start} has {len(control_guidance_start)} elements but there are {num_controlnet} controlnets available. Make sure to provide {num_controlnet}."
469
+ )
470
+
471
+ for start, end in zip(control_guidance_start, control_guidance_end):
472
+ if start >= end:
473
+ raise ValueError(
474
+ f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
475
+ )
476
+ if start < 0.0:
477
+ raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
478
+ if end > 1.0:
479
+ raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
480
+
481
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.check_image
482
+ def check_image(self, image, prompt, prompt_embeds):
483
+ image_is_pil = isinstance(image, PIL.Image.Image)
484
+ image_is_tensor = isinstance(image, torch.Tensor)
485
+ image_is_np = isinstance(image, np.ndarray)
486
+ image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
487
+ image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
488
+ image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
489
+
490
+ if (
491
+ not image_is_pil
492
+ and not image_is_tensor
493
+ and not image_is_np
494
+ and not image_is_pil_list
495
+ and not image_is_tensor_list
496
+ and not image_is_np_list
497
+ ):
498
+ raise TypeError(
499
+ f"image must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(image)}"
500
+ )
501
+
502
+ if image_is_pil:
503
+ image_batch_size = 1
504
+ else:
505
+ image_batch_size = len(image)
506
+
507
+ if prompt is not None and isinstance(prompt, str):
508
+ prompt_batch_size = 1
509
+ elif prompt is not None and isinstance(prompt, list):
510
+ prompt_batch_size = len(prompt)
511
+ elif prompt_embeds is not None:
512
+ prompt_batch_size = prompt_embeds.shape[0]
513
+
514
+ if image_batch_size != 1 and image_batch_size != prompt_batch_size:
515
+ raise ValueError(
516
+ f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
517
+ )
518
+
519
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.prepare_image
520
+ def prepare_control_image(
521
+ self,
522
+ image,
523
+ width,
524
+ height,
525
+ batch_size,
526
+ num_images_per_prompt,
527
+ device,
528
+ dtype,
529
+ do_classifier_free_guidance=False,
530
+ guess_mode=False,
531
+ ):
532
+ image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
533
+ image_batch_size = image.shape[0]
534
+
535
+ if image_batch_size == 1:
536
+ repeat_by = batch_size
537
+ else:
538
+ # image batch size is the same as prompt batch size
539
+ repeat_by = num_images_per_prompt
540
+
541
+ image = image.repeat_interleave(repeat_by, dim=0)
542
+
543
+ image = image.to(device=device, dtype=dtype)
544
+
545
+ if do_classifier_free_guidance and not guess_mode:
546
+ image = torch.cat([image] * 2)
547
+
548
+ return image
549
+
550
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.get_timesteps
551
+ def get_timesteps(self, num_inference_steps, strength, device):
552
+ # get the original timestep using init_timestep
553
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
554
+
555
+ t_start = max(num_inference_steps - init_timestep, 0)
556
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
557
+
558
+ return timesteps, num_inference_steps - t_start
559
+
560
+ def prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None):
561
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
562
+ raise ValueError(
563
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
564
+ )
565
+
566
+ image = image.to(device=device, dtype=dtype)
567
+
568
+ batch_size = batch_size * num_images_per_prompt
569
+
570
+ if image.shape[1] == 4:
571
+ init_latents = image
572
+
573
+ else:
574
+ _image = image.cpu().detach().numpy()
575
+ init_latents = self.vae_encoder(sample=_image)[0]
576
+ init_latents = torch.from_numpy(init_latents).to(device=device, dtype=dtype)
577
+ init_latents = 0.18215 * init_latents
578
+
579
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
580
+ # expand init_latents for batch_size
581
+ deprecation_message = (
582
+ f"You have passed {batch_size} text prompts (`prompt`), but only {init_latents.shape[0]} initial"
583
+ " images (`image`). Initial images are now duplicating to match the number of text prompts. Note"
584
+ " that this behavior is deprecated and will be removed in a version 1.0.0. Please make sure to update"
585
+ " your script to pass as many initial images as text prompts to suppress this warning."
586
+ )
587
+ deprecate("len(prompt) != len(image)", "1.0.0", deprecation_message, standard_warn=False)
588
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
589
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
590
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
591
+ raise ValueError(
592
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
593
+ )
594
+ else:
595
+ init_latents = torch.cat([init_latents], dim=0)
596
+
597
+ shape = init_latents.shape
598
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
599
+
600
+ # get latents
601
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
602
+ latents = init_latents
603
+
604
+ return latents
605
+
606
+ @torch.no_grad()
607
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
608
+ def __call__(
609
+ self,
610
+ num_controlnet: int,
611
+ fp16: bool = True,
612
+ prompt: Union[str, List[str]] = None,
613
+ image: Union[
614
+ torch.FloatTensor,
615
+ PIL.Image.Image,
616
+ np.ndarray,
617
+ List[torch.FloatTensor],
618
+ List[PIL.Image.Image],
619
+ List[np.ndarray],
620
+ ] = None,
621
+ control_image: Union[
622
+ torch.FloatTensor,
623
+ PIL.Image.Image,
624
+ np.ndarray,
625
+ List[torch.FloatTensor],
626
+ List[PIL.Image.Image],
627
+ List[np.ndarray],
628
+ ] = None,
629
+ height: Optional[int] = None,
630
+ width: Optional[int] = None,
631
+ strength: float = 0.8,
632
+ num_inference_steps: int = 50,
633
+ guidance_scale: float = 7.5,
634
+ negative_prompt: Optional[Union[str, List[str]]] = None,
635
+ num_images_per_prompt: Optional[int] = 1,
636
+ eta: float = 0.0,
637
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
638
+ latents: Optional[torch.FloatTensor] = None,
639
+ prompt_embeds: Optional[torch.FloatTensor] = None,
640
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
641
+ output_type: Optional[str] = "pil",
642
+ return_dict: bool = True,
643
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
644
+ callback_steps: int = 1,
645
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
646
+ controlnet_conditioning_scale: Union[float, List[float]] = 0.8,
647
+ guess_mode: bool = False,
648
+ control_guidance_start: Union[float, List[float]] = 0.0,
649
+ control_guidance_end: Union[float, List[float]] = 1.0,
650
+ ):
651
+ r"""
652
+ Function invoked when calling the pipeline for generation.
653
+
654
+ Args:
655
+ prompt (`str` or `List[str]`, *optional*):
656
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
657
+ instead.
658
+ image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
659
+ `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
660
+ The initial image will be used as the starting point for the image generation process. Can also accept
661
+ image latents as `image`, if passing latents directly, it will not be encoded again.
662
+ control_image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
663
+ `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
664
+ The ControlNet input condition. ControlNet uses this input condition to generate guidance to Unet. If
665
+ the type is specified as `Torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can
666
+ also be accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If
667
+ height and/or width are passed, `image` is resized according to them. If multiple ControlNets are
668
+ specified in init, images must be passed as a list such that each element of the list can be correctly
669
+ batched for input to a single controlnet.
670
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
671
+ The height in pixels of the generated image.
672
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
673
+ The width in pixels of the generated image.
674
+ num_inference_steps (`int`, *optional*, defaults to 50):
675
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
676
+ expense of slower inference.
677
+ guidance_scale (`float`, *optional*, defaults to 7.5):
678
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
679
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
680
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
681
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
682
+ usually at the expense of lower image quality.
683
+ negative_prompt (`str` or `List[str]`, *optional*):
684
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
685
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
686
+ less than `1`).
687
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
688
+ The number of images to generate per prompt.
689
+ eta (`float`, *optional*, defaults to 0.0):
690
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
691
+ [`schedulers.DDIMScheduler`], will be ignored for others.
692
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
693
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
694
+ to make generation deterministic.
695
+ latents (`torch.FloatTensor`, *optional*):
696
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
697
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
698
+ tensor will ge generated by sampling using the supplied random `generator`.
699
+ prompt_embeds (`torch.FloatTensor`, *optional*):
700
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
701
+ provided, text embeddings will be generated from `prompt` input argument.
702
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
703
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
704
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
705
+ argument.
706
+ output_type (`str`, *optional*, defaults to `"pil"`):
707
+ The output format of the generate image. Choose between
708
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
709
+ return_dict (`bool`, *optional*, defaults to `True`):
710
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
711
+ plain tuple.
712
+ callback (`Callable`, *optional*):
713
+ A function that will be called every `callback_steps` steps during inference. The function will be
714
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
715
+ callback_steps (`int`, *optional*, defaults to 1):
716
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
717
+ called at every step.
718
+ cross_attention_kwargs (`dict`, *optional*):
719
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
720
+ `self.processor` in
721
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
722
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
723
+ The outputs of the controlnet are multiplied by `controlnet_conditioning_scale` before they are added
724
+ to the residual in the original unet. If multiple ControlNets are specified in init, you can set the
725
+ corresponding scale as a list. Note that by default, we use a smaller conditioning scale for inpainting
726
+ than for [`~StableDiffusionControlNetPipeline.__call__`].
727
+ guess_mode (`bool`, *optional*, defaults to `False`):
728
+ In this mode, the ControlNet encoder will try best to recognize the content of the input image even if
729
+ you remove all prompts. The `guidance_scale` between 3.0 and 5.0 is recommended.
730
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
731
+ The percentage of total steps at which the controlnet starts applying.
732
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
733
+ The percentage of total steps at which the controlnet stops applying.
734
+
735
+ Examples:
736
+
737
+ Returns:
738
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
739
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
740
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
741
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
742
+ (nsfw) content, according to the `safety_checker`.
743
+ """
744
+ if fp16:
745
+ torch_dtype = torch.float16
746
+ np_dtype = np.float16
747
+ else:
748
+ torch_dtype = torch.float32
749
+ np_dtype = np.float32
750
+
751
+ # align format for control guidance
752
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
753
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
754
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
755
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
756
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
757
+ mult = num_controlnet
758
+ control_guidance_start, control_guidance_end = mult * [control_guidance_start], mult * [
759
+ control_guidance_end
760
+ ]
761
+
762
+ # 1. Check inputs. Raise error if not correct
763
+ self.check_inputs(
764
+ num_controlnet,
765
+ prompt,
766
+ control_image,
767
+ callback_steps,
768
+ negative_prompt,
769
+ prompt_embeds,
770
+ negative_prompt_embeds,
771
+ controlnet_conditioning_scale,
772
+ control_guidance_start,
773
+ control_guidance_end,
774
+ )
775
+
776
+ # 2. Define call parameters
777
+ if prompt is not None and isinstance(prompt, str):
778
+ batch_size = 1
779
+ elif prompt is not None and isinstance(prompt, list):
780
+ batch_size = len(prompt)
781
+ else:
782
+ batch_size = prompt_embeds.shape[0]
783
+
784
+ device = self._execution_device
785
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
786
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
787
+ # corresponds to doing no classifier free guidance.
788
+ do_classifier_free_guidance = guidance_scale > 1.0
789
+
790
+ if num_controlnet > 1 and isinstance(controlnet_conditioning_scale, float):
791
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * num_controlnet
792
+
793
+ # 3. Encode input prompt
794
+ prompt_embeds = self._encode_prompt(
795
+ prompt,
796
+ num_images_per_prompt,
797
+ do_classifier_free_guidance,
798
+ negative_prompt,
799
+ prompt_embeds=prompt_embeds,
800
+ negative_prompt_embeds=negative_prompt_embeds,
801
+ )
802
+ # 4. Prepare image
803
+ image = self.image_processor.preprocess(image).to(dtype=torch.float32)
804
+
805
+ # 5. Prepare controlnet_conditioning_image
806
+ if num_controlnet == 1:
807
+ control_image = self.prepare_control_image(
808
+ image=control_image,
809
+ width=width,
810
+ height=height,
811
+ batch_size=batch_size * num_images_per_prompt,
812
+ num_images_per_prompt=num_images_per_prompt,
813
+ device=device,
814
+ dtype=torch_dtype,
815
+ do_classifier_free_guidance=do_classifier_free_guidance,
816
+ guess_mode=guess_mode,
817
+ )
818
+ elif num_controlnet > 1:
819
+ control_images = []
820
+
821
+ for control_image_ in control_image:
822
+ control_image_ = self.prepare_control_image(
823
+ image=control_image_,
824
+ width=width,
825
+ height=height,
826
+ batch_size=batch_size * num_images_per_prompt,
827
+ num_images_per_prompt=num_images_per_prompt,
828
+ device=device,
829
+ dtype=torch_dtype,
830
+ do_classifier_free_guidance=do_classifier_free_guidance,
831
+ guess_mode=guess_mode,
832
+ )
833
+
834
+ control_images.append(control_image_)
835
+
836
+ control_image = control_images
837
+ else:
838
+ assert False
839
+
840
+ # 5. Prepare timesteps
841
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
842
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
843
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
844
+
845
+ # 6. Prepare latent variables
846
+ latents = self.prepare_latents(
847
+ image,
848
+ latent_timestep,
849
+ batch_size,
850
+ num_images_per_prompt,
851
+ torch_dtype,
852
+ device,
853
+ generator,
854
+ )
855
+
856
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
857
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
858
+
859
+ # 7.1 Create tensor stating which controlnets to keep
860
+ controlnet_keep = []
861
+ for i in range(len(timesteps)):
862
+ keeps = [
863
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
864
+ for s, e in zip(control_guidance_start, control_guidance_end)
865
+ ]
866
+ controlnet_keep.append(keeps[0] if num_controlnet == 1 else keeps)
867
+
868
+ # 8. Denoising loop
869
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
870
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
871
+ for i, t in enumerate(timesteps):
872
+ # expand the latents if we are doing classifier free guidance
873
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
874
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
875
+
876
+ if isinstance(controlnet_keep[i], list):
877
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
878
+ else:
879
+ controlnet_cond_scale = controlnet_conditioning_scale
880
+ if isinstance(controlnet_cond_scale, list):
881
+ controlnet_cond_scale = controlnet_cond_scale[0]
882
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
883
+
884
+ # predict the noise residual
885
+ _latent_model_input = latent_model_input.cpu().detach().numpy()
886
+ _prompt_embeds = np.array(prompt_embeds, dtype=np_dtype)
887
+ _t = np.array([t.cpu().detach().numpy()], dtype=np_dtype)
888
+
889
+ if num_controlnet == 1:
890
+ control_images = np.array([control_image], dtype=np_dtype)
891
+ else:
892
+ control_images = []
893
+ for _control_img in control_image:
894
+ _control_img = _control_img.cpu().detach().numpy()
895
+ control_images.append(_control_img)
896
+ control_images = np.array(control_images, dtype=np_dtype)
897
+
898
+ control_scales = np.array(cond_scale, dtype=np_dtype)
899
+ control_scales = np.resize(control_scales, (num_controlnet, 1))
900
+
901
+ noise_pred = self.unet(
902
+ sample=_latent_model_input,
903
+ timestep=_t,
904
+ encoder_hidden_states=_prompt_embeds,
905
+ controlnet_conds=control_images,
906
+ conditioning_scales=control_scales,
907
+ )["noise_pred"]
908
+ noise_pred = torch.from_numpy(noise_pred).to(device)
909
+
910
+ # perform guidance
911
+ if do_classifier_free_guidance:
912
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
913
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
914
+
915
+ # compute the previous noisy sample x_t -> x_t-1
916
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
917
+
918
+ # call the callback, if provided
919
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
920
+ progress_bar.update()
921
+ if callback is not None and i % callback_steps == 0:
922
+ step_idx = i // getattr(self.scheduler, "order", 1)
923
+ callback(step_idx, t, latents)
924
+
925
+ if not output_type == "latent":
926
+ _latents = latents.cpu().detach().numpy() / 0.18215
927
+ _latents = np.array(_latents, dtype=np_dtype)
928
+ image = self.vae_decoder(latent_sample=_latents)[0]
929
+ image = torch.from_numpy(image).to(device, dtype=torch.float32)
930
+ has_nsfw_concept = None
931
+ else:
932
+ image = latents
933
+ has_nsfw_concept = None
934
+
935
+ if has_nsfw_concept is None:
936
+ do_denormalize = [True] * image.shape[0]
937
+ else:
938
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
939
+
940
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
941
+
942
+ if not return_dict:
943
+ return (image, has_nsfw_concept)
944
+
945
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
946
+
947
+
948
+ if __name__ == "__main__":
949
+ parser = argparse.ArgumentParser()
950
+
951
+ parser.add_argument(
952
+ "--sd_model",
953
+ type=str,
954
+ required=True,
955
+ help="Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).",
956
+ )
957
+
958
+ parser.add_argument(
959
+ "--onnx_model_dir",
960
+ type=str,
961
+ required=True,
962
+ help="Path to the ONNX directory",
963
+ )
964
+
965
+ parser.add_argument(
966
+ "--unet_engine_path",
967
+ type=str,
968
+ required=True,
969
+ help="Path to the unet + controlnet tensorrt model",
970
+ )
971
+
972
+ parser.add_argument("--qr_img_path", type=str, required=True, help="Path to the qr code image")
973
+
974
+ args = parser.parse_args()
975
+
976
+ qr_image = Image.open(args.qr_img_path)
977
+ qr_image = qr_image.resize((512, 512))
978
+
979
+ # init stable diffusion pipeline
980
+ pipeline = StableDiffusionImg2ImgPipeline.from_pretrained(args.sd_model)
981
+ pipeline.scheduler = UniPCMultistepScheduler.from_config(pipeline.scheduler.config)
982
+
983
+ provider = ["CUDAExecutionProvider", "CPUExecutionProvider"]
984
+ onnx_pipeline = TensorRTStableDiffusionControlNetImg2ImgPipeline(
985
+ vae_encoder=OnnxRuntimeModel.from_pretrained(
986
+ os.path.join(args.onnx_model_dir, "vae_encoder"), provider=provider
987
+ ),
988
+ vae_decoder=OnnxRuntimeModel.from_pretrained(
989
+ os.path.join(args.onnx_model_dir, "vae_decoder"), provider=provider
990
+ ),
991
+ text_encoder=OnnxRuntimeModel.from_pretrained(
992
+ os.path.join(args.onnx_model_dir, "text_encoder"), provider=provider
993
+ ),
994
+ tokenizer=pipeline.tokenizer,
995
+ unet=TensorRTModel(args.unet_engine_path),
996
+ scheduler=pipeline.scheduler,
997
+ )
998
+ onnx_pipeline = onnx_pipeline.to("cuda")
999
+
1000
+ prompt = "a cute cat fly to the moon"
1001
+ negative_prompt = "paintings, sketches, worst quality, low quality, normal quality, lowres, normal quality, monochrome, grayscale, skin spots, acnes, skin blemishes, age spot, glans, nsfw, nipples, necklace, worst quality, low quality, watermark, username, signature, multiple breasts, lowres, bad anatomy, bad hands, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry, bad feet, single color, ugly, duplicate, morbid, mutilated, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, ugly, blurry, bad anatomy, bad proportions, extra limbs, disfigured, bad anatomy, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, mutated hands, fused fingers, too many fingers, long neck, bad body perspect"
1002
+
1003
+ for i in range(10):
1004
+ start_time = time.time()
1005
+ image = onnx_pipeline(
1006
+ num_controlnet=2,
1007
+ prompt=prompt,
1008
+ negative_prompt=negative_prompt,
1009
+ image=qr_image,
1010
+ control_image=[qr_image, qr_image],
1011
+ width=512,
1012
+ height=512,
1013
+ strength=0.75,
1014
+ num_inference_steps=20,
1015
+ num_images_per_prompt=1,
1016
+ controlnet_conditioning_scale=[0.8, 0.8],
1017
+ control_guidance_start=[0.3, 0.3],
1018
+ control_guidance_end=[0.9, 0.9],
1019
+ ).images[0]
1020
+ print(time.time() - start_time)
1021
+ image.save("output_qr_code.png")
v0.22.0/sd_text2img_k_diffusion.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 importlib
16
+ import warnings
17
+ from typing import Callable, List, Optional, Union
18
+
19
+ import torch
20
+ from k_diffusion.external import CompVisDenoiser, CompVisVDenoiser
21
+
22
+ from diffusers import DiffusionPipeline, LMSDiscreteScheduler
23
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
24
+ from diffusers.utils import is_accelerate_available, logging
25
+
26
+
27
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
28
+
29
+
30
+ class ModelWrapper:
31
+ def __init__(self, model, alphas_cumprod):
32
+ self.model = model
33
+ self.alphas_cumprod = alphas_cumprod
34
+
35
+ def apply_model(self, *args, **kwargs):
36
+ if len(args) == 3:
37
+ encoder_hidden_states = args[-1]
38
+ args = args[:2]
39
+ if kwargs.get("cond", None) is not None:
40
+ encoder_hidden_states = kwargs.pop("cond")
41
+ return self.model(*args, encoder_hidden_states=encoder_hidden_states, **kwargs).sample
42
+
43
+
44
+ class StableDiffusionPipeline(DiffusionPipeline):
45
+ r"""
46
+ Pipeline for text-to-image generation using Stable Diffusion.
47
+
48
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
49
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
50
+
51
+ Args:
52
+ vae ([`AutoencoderKL`]):
53
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
54
+ text_encoder ([`CLIPTextModel`]):
55
+ Frozen text-encoder. Stable Diffusion uses the text portion of
56
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
57
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
58
+ tokenizer (`CLIPTokenizer`):
59
+ Tokenizer of class
60
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
61
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
62
+ scheduler ([`SchedulerMixin`]):
63
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
64
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
65
+ safety_checker ([`StableDiffusionSafetyChecker`]):
66
+ Classification module that estimates whether generated images could be considered offensive or harmful.
67
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
68
+ feature_extractor ([`CLIPImageProcessor`]):
69
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
70
+ """
71
+ _optional_components = ["safety_checker", "feature_extractor"]
72
+
73
+ def __init__(
74
+ self,
75
+ vae,
76
+ text_encoder,
77
+ tokenizer,
78
+ unet,
79
+ scheduler,
80
+ safety_checker,
81
+ feature_extractor,
82
+ ):
83
+ super().__init__()
84
+
85
+ if safety_checker is None:
86
+ logger.warning(
87
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
88
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
89
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
90
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
91
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
92
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
93
+ )
94
+
95
+ # get correct sigmas from LMS
96
+ scheduler = LMSDiscreteScheduler.from_config(scheduler.config)
97
+ self.register_modules(
98
+ vae=vae,
99
+ text_encoder=text_encoder,
100
+ tokenizer=tokenizer,
101
+ unet=unet,
102
+ scheduler=scheduler,
103
+ safety_checker=safety_checker,
104
+ feature_extractor=feature_extractor,
105
+ )
106
+
107
+ model = ModelWrapper(unet, scheduler.alphas_cumprod)
108
+ if scheduler.config.prediction_type == "v_prediction":
109
+ self.k_diffusion_model = CompVisVDenoiser(model)
110
+ else:
111
+ self.k_diffusion_model = CompVisDenoiser(model)
112
+
113
+ def set_sampler(self, scheduler_type: str):
114
+ warnings.warn("The `set_sampler` method is deprecated, please use `set_scheduler` instead.")
115
+ return self.set_scheduler(scheduler_type)
116
+
117
+ def set_scheduler(self, scheduler_type: str):
118
+ library = importlib.import_module("k_diffusion")
119
+ sampling = getattr(library, "sampling")
120
+ self.sampler = getattr(sampling, scheduler_type)
121
+
122
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
123
+ r"""
124
+ Enable sliced attention computation.
125
+
126
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
127
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
128
+
129
+ Args:
130
+ slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
131
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
132
+ a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
133
+ `attention_head_dim` must be a multiple of `slice_size`.
134
+ """
135
+ if slice_size == "auto":
136
+ # half the attention head size is usually a good trade-off between
137
+ # speed and memory
138
+ slice_size = self.unet.config.attention_head_dim // 2
139
+ self.unet.set_attention_slice(slice_size)
140
+
141
+ def disable_attention_slicing(self):
142
+ r"""
143
+ Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
144
+ back to computing attention in one step.
145
+ """
146
+ # set slice_size = `None` to disable `attention slicing`
147
+ self.enable_attention_slicing(None)
148
+
149
+ def enable_sequential_cpu_offload(self, gpu_id=0):
150
+ r"""
151
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
152
+ text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
153
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
154
+ """
155
+ if is_accelerate_available():
156
+ from accelerate import cpu_offload
157
+ else:
158
+ raise ImportError("Please install accelerate via `pip install accelerate`")
159
+
160
+ device = torch.device(f"cuda:{gpu_id}")
161
+
162
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]:
163
+ if cpu_offloaded_model is not None:
164
+ cpu_offload(cpu_offloaded_model, device)
165
+
166
+ @property
167
+ def _execution_device(self):
168
+ r"""
169
+ Returns the device on which the pipeline's models will be executed. After calling
170
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
171
+ hooks.
172
+ """
173
+ if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"):
174
+ return self.device
175
+ for module in self.unet.modules():
176
+ if (
177
+ hasattr(module, "_hf_hook")
178
+ and hasattr(module._hf_hook, "execution_device")
179
+ and module._hf_hook.execution_device is not None
180
+ ):
181
+ return torch.device(module._hf_hook.execution_device)
182
+ return self.device
183
+
184
+ def _encode_prompt(self, prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt):
185
+ r"""
186
+ Encodes the prompt into text encoder hidden states.
187
+
188
+ Args:
189
+ prompt (`str` or `list(int)`):
190
+ prompt to be encoded
191
+ device: (`torch.device`):
192
+ torch device
193
+ num_images_per_prompt (`int`):
194
+ number of images that should be generated per prompt
195
+ do_classifier_free_guidance (`bool`):
196
+ whether to use classifier free guidance or not
197
+ negative_prompt (`str` or `List[str]`):
198
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
199
+ if `guidance_scale` is less than `1`).
200
+ """
201
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
202
+
203
+ text_inputs = self.tokenizer(
204
+ prompt,
205
+ padding="max_length",
206
+ max_length=self.tokenizer.model_max_length,
207
+ truncation=True,
208
+ return_tensors="pt",
209
+ )
210
+ text_input_ids = text_inputs.input_ids
211
+ untruncated_ids = self.tokenizer(prompt, padding="max_length", return_tensors="pt").input_ids
212
+
213
+ if not torch.equal(text_input_ids, untruncated_ids):
214
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
215
+ logger.warning(
216
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
217
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
218
+ )
219
+
220
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
221
+ attention_mask = text_inputs.attention_mask.to(device)
222
+ else:
223
+ attention_mask = None
224
+
225
+ text_embeddings = self.text_encoder(
226
+ text_input_ids.to(device),
227
+ attention_mask=attention_mask,
228
+ )
229
+ text_embeddings = text_embeddings[0]
230
+
231
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
232
+ bs_embed, seq_len, _ = text_embeddings.shape
233
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
234
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
235
+
236
+ # get unconditional embeddings for classifier free guidance
237
+ if do_classifier_free_guidance:
238
+ uncond_tokens: List[str]
239
+ if negative_prompt is None:
240
+ uncond_tokens = [""] * batch_size
241
+ elif type(prompt) is not type(negative_prompt):
242
+ raise TypeError(
243
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
244
+ f" {type(prompt)}."
245
+ )
246
+ elif isinstance(negative_prompt, str):
247
+ uncond_tokens = [negative_prompt]
248
+ elif batch_size != len(negative_prompt):
249
+ raise ValueError(
250
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
251
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
252
+ " the batch size of `prompt`."
253
+ )
254
+ else:
255
+ uncond_tokens = negative_prompt
256
+
257
+ max_length = text_input_ids.shape[-1]
258
+ uncond_input = self.tokenizer(
259
+ uncond_tokens,
260
+ padding="max_length",
261
+ max_length=max_length,
262
+ truncation=True,
263
+ return_tensors="pt",
264
+ )
265
+
266
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
267
+ attention_mask = uncond_input.attention_mask.to(device)
268
+ else:
269
+ attention_mask = None
270
+
271
+ uncond_embeddings = self.text_encoder(
272
+ uncond_input.input_ids.to(device),
273
+ attention_mask=attention_mask,
274
+ )
275
+ uncond_embeddings = uncond_embeddings[0]
276
+
277
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
278
+ seq_len = uncond_embeddings.shape[1]
279
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
280
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
281
+
282
+ # For classifier free guidance, we need to do two forward passes.
283
+ # Here we concatenate the unconditional and text embeddings into a single batch
284
+ # to avoid doing two forward passes
285
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
286
+
287
+ return text_embeddings
288
+
289
+ def run_safety_checker(self, image, device, dtype):
290
+ if self.safety_checker is not None:
291
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
292
+ image, has_nsfw_concept = self.safety_checker(
293
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
294
+ )
295
+ else:
296
+ has_nsfw_concept = None
297
+ return image, has_nsfw_concept
298
+
299
+ def decode_latents(self, latents):
300
+ latents = 1 / 0.18215 * latents
301
+ image = self.vae.decode(latents).sample
302
+ image = (image / 2 + 0.5).clamp(0, 1)
303
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
304
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
305
+ return image
306
+
307
+ def check_inputs(self, prompt, height, width, callback_steps):
308
+ if not isinstance(prompt, str) and not isinstance(prompt, list):
309
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
310
+
311
+ if height % 8 != 0 or width % 8 != 0:
312
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
313
+
314
+ if (callback_steps is None) or (
315
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
316
+ ):
317
+ raise ValueError(
318
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
319
+ f" {type(callback_steps)}."
320
+ )
321
+
322
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
323
+ shape = (batch_size, num_channels_latents, height // 8, width // 8)
324
+ if latents is None:
325
+ if device.type == "mps":
326
+ # randn does not work reproducibly on mps
327
+ latents = torch.randn(shape, generator=generator, device="cpu", dtype=dtype).to(device)
328
+ else:
329
+ latents = torch.randn(shape, generator=generator, device=device, dtype=dtype)
330
+ else:
331
+ if latents.shape != shape:
332
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
333
+ latents = latents.to(device)
334
+
335
+ # scale the initial noise by the standard deviation required by the scheduler
336
+ return latents
337
+
338
+ @torch.no_grad()
339
+ def __call__(
340
+ self,
341
+ prompt: Union[str, List[str]],
342
+ height: int = 512,
343
+ width: int = 512,
344
+ num_inference_steps: int = 50,
345
+ guidance_scale: float = 7.5,
346
+ negative_prompt: Optional[Union[str, List[str]]] = None,
347
+ num_images_per_prompt: Optional[int] = 1,
348
+ eta: float = 0.0,
349
+ generator: Optional[torch.Generator] = None,
350
+ latents: Optional[torch.FloatTensor] = None,
351
+ output_type: Optional[str] = "pil",
352
+ return_dict: bool = True,
353
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
354
+ callback_steps: int = 1,
355
+ **kwargs,
356
+ ):
357
+ r"""
358
+ Function invoked when calling the pipeline for generation.
359
+
360
+ Args:
361
+ prompt (`str` or `List[str]`):
362
+ The prompt or prompts to guide the image generation.
363
+ height (`int`, *optional*, defaults to 512):
364
+ The height in pixels of the generated image.
365
+ width (`int`, *optional*, defaults to 512):
366
+ The width in pixels of the generated image.
367
+ num_inference_steps (`int`, *optional*, defaults to 50):
368
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
369
+ expense of slower inference.
370
+ guidance_scale (`float`, *optional*, defaults to 7.5):
371
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
372
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
373
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
374
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
375
+ usually at the expense of lower image quality.
376
+ negative_prompt (`str` or `List[str]`, *optional*):
377
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
378
+ if `guidance_scale` is less than `1`).
379
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
380
+ The number of images to generate per prompt.
381
+ eta (`float`, *optional*, defaults to 0.0):
382
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
383
+ [`schedulers.DDIMScheduler`], will be ignored for others.
384
+ generator (`torch.Generator`, *optional*):
385
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
386
+ deterministic.
387
+ latents (`torch.FloatTensor`, *optional*):
388
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
389
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
390
+ tensor will ge generated by sampling using the supplied random `generator`.
391
+ output_type (`str`, *optional*, defaults to `"pil"`):
392
+ The output format of the generate image. Choose between
393
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
394
+ return_dict (`bool`, *optional*, defaults to `True`):
395
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
396
+ plain tuple.
397
+ callback (`Callable`, *optional*):
398
+ A function that will be called every `callback_steps` steps during inference. The function will be
399
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
400
+ callback_steps (`int`, *optional*, defaults to 1):
401
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
402
+ called at every step.
403
+
404
+ Returns:
405
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
406
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
407
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
408
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
409
+ (nsfw) content, according to the `safety_checker`.
410
+ """
411
+
412
+ # 1. Check inputs. Raise error if not correct
413
+ self.check_inputs(prompt, height, width, callback_steps)
414
+
415
+ # 2. Define call parameters
416
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
417
+ device = self._execution_device
418
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
419
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
420
+ # corresponds to doing no classifier free guidance.
421
+ do_classifier_free_guidance = True
422
+ if guidance_scale <= 1.0:
423
+ raise ValueError("has to use guidance_scale")
424
+
425
+ # 3. Encode input prompt
426
+ text_embeddings = self._encode_prompt(
427
+ prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt
428
+ )
429
+
430
+ # 4. Prepare timesteps
431
+ self.scheduler.set_timesteps(num_inference_steps, device=text_embeddings.device)
432
+ sigmas = self.scheduler.sigmas
433
+ sigmas = sigmas.to(text_embeddings.dtype)
434
+
435
+ # 5. Prepare latent variables
436
+ num_channels_latents = self.unet.config.in_channels
437
+ latents = self.prepare_latents(
438
+ batch_size * num_images_per_prompt,
439
+ num_channels_latents,
440
+ height,
441
+ width,
442
+ text_embeddings.dtype,
443
+ device,
444
+ generator,
445
+ latents,
446
+ )
447
+ latents = latents * sigmas[0]
448
+ self.k_diffusion_model.sigmas = self.k_diffusion_model.sigmas.to(latents.device)
449
+ self.k_diffusion_model.log_sigmas = self.k_diffusion_model.log_sigmas.to(latents.device)
450
+
451
+ def model_fn(x, t):
452
+ latent_model_input = torch.cat([x] * 2)
453
+
454
+ noise_pred = self.k_diffusion_model(latent_model_input, t, cond=text_embeddings)
455
+
456
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
457
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
458
+ return noise_pred
459
+
460
+ latents = self.sampler(model_fn, latents, sigmas)
461
+
462
+ # 8. Post-processing
463
+ image = self.decode_latents(latents)
464
+
465
+ # 9. Run safety checker
466
+ image, has_nsfw_concept = self.run_safety_checker(image, device, text_embeddings.dtype)
467
+
468
+ # 10. Convert to PIL
469
+ if output_type == "pil":
470
+ image = self.numpy_to_pil(image)
471
+
472
+ if not return_dict:
473
+ return (image, has_nsfw_concept)
474
+
475
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.22.0/seed_resize_stable_diffusion.py ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ modified based on diffusion library from Huggingface: https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py
3
+ """
4
+ import inspect
5
+ from typing import Callable, List, Optional, Union
6
+
7
+ import torch
8
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
9
+
10
+ from diffusers import DiffusionPipeline
11
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
12
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
13
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
14
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
15
+ from diffusers.utils import logging
16
+
17
+
18
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
19
+
20
+
21
+ class SeedResizeStableDiffusionPipeline(DiffusionPipeline):
22
+ r"""
23
+ Pipeline for text-to-image generation using Stable Diffusion.
24
+
25
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
26
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
27
+
28
+ Args:
29
+ vae ([`AutoencoderKL`]):
30
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
31
+ text_encoder ([`CLIPTextModel`]):
32
+ Frozen text-encoder. Stable Diffusion uses the text portion of
33
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
34
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
35
+ tokenizer (`CLIPTokenizer`):
36
+ Tokenizer of class
37
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
38
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
39
+ scheduler ([`SchedulerMixin`]):
40
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
41
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
42
+ safety_checker ([`StableDiffusionSafetyChecker`]):
43
+ Classification module that estimates whether generated images could be considered offensive or harmful.
44
+ Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.
45
+ feature_extractor ([`CLIPImageProcessor`]):
46
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
47
+ """
48
+
49
+ def __init__(
50
+ self,
51
+ vae: AutoencoderKL,
52
+ text_encoder: CLIPTextModel,
53
+ tokenizer: CLIPTokenizer,
54
+ unet: UNet2DConditionModel,
55
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
56
+ safety_checker: StableDiffusionSafetyChecker,
57
+ feature_extractor: CLIPImageProcessor,
58
+ ):
59
+ super().__init__()
60
+ self.register_modules(
61
+ vae=vae,
62
+ text_encoder=text_encoder,
63
+ tokenizer=tokenizer,
64
+ unet=unet,
65
+ scheduler=scheduler,
66
+ safety_checker=safety_checker,
67
+ feature_extractor=feature_extractor,
68
+ )
69
+
70
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
71
+ r"""
72
+ Enable sliced attention computation.
73
+
74
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
75
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
76
+
77
+ Args:
78
+ slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
79
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
80
+ a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
81
+ `attention_head_dim` must be a multiple of `slice_size`.
82
+ """
83
+ if slice_size == "auto":
84
+ # half the attention head size is usually a good trade-off between
85
+ # speed and memory
86
+ slice_size = self.unet.config.attention_head_dim // 2
87
+ self.unet.set_attention_slice(slice_size)
88
+
89
+ def disable_attention_slicing(self):
90
+ r"""
91
+ Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
92
+ back to computing attention in one step.
93
+ """
94
+ # set slice_size = `None` to disable `attention slicing`
95
+ self.enable_attention_slicing(None)
96
+
97
+ @torch.no_grad()
98
+ def __call__(
99
+ self,
100
+ prompt: Union[str, List[str]],
101
+ height: int = 512,
102
+ width: int = 512,
103
+ num_inference_steps: int = 50,
104
+ guidance_scale: float = 7.5,
105
+ negative_prompt: Optional[Union[str, List[str]]] = None,
106
+ num_images_per_prompt: Optional[int] = 1,
107
+ eta: float = 0.0,
108
+ generator: Optional[torch.Generator] = None,
109
+ latents: Optional[torch.FloatTensor] = None,
110
+ output_type: Optional[str] = "pil",
111
+ return_dict: bool = True,
112
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
113
+ callback_steps: int = 1,
114
+ text_embeddings: Optional[torch.FloatTensor] = None,
115
+ **kwargs,
116
+ ):
117
+ r"""
118
+ Function invoked when calling the pipeline for generation.
119
+
120
+ Args:
121
+ prompt (`str` or `List[str]`):
122
+ The prompt or prompts to guide the image generation.
123
+ height (`int`, *optional*, defaults to 512):
124
+ The height in pixels of the generated image.
125
+ width (`int`, *optional*, defaults to 512):
126
+ The width in pixels of the generated image.
127
+ num_inference_steps (`int`, *optional*, defaults to 50):
128
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
129
+ expense of slower inference.
130
+ guidance_scale (`float`, *optional*, defaults to 7.5):
131
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
132
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
133
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
134
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
135
+ usually at the expense of lower image quality.
136
+ negative_prompt (`str` or `List[str]`, *optional*):
137
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
138
+ if `guidance_scale` is less than `1`).
139
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
140
+ The number of images to generate per prompt.
141
+ eta (`float`, *optional*, defaults to 0.0):
142
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
143
+ [`schedulers.DDIMScheduler`], will be ignored for others.
144
+ generator (`torch.Generator`, *optional*):
145
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
146
+ deterministic.
147
+ latents (`torch.FloatTensor`, *optional*):
148
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
149
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
150
+ tensor will ge generated by sampling using the supplied random `generator`.
151
+ output_type (`str`, *optional*, defaults to `"pil"`):
152
+ The output format of the generate image. Choose between
153
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
154
+ return_dict (`bool`, *optional*, defaults to `True`):
155
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
156
+ plain tuple.
157
+ callback (`Callable`, *optional*):
158
+ A function that will be called every `callback_steps` steps during inference. The function will be
159
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
160
+ callback_steps (`int`, *optional*, defaults to 1):
161
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
162
+ called at every step.
163
+
164
+ Returns:
165
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
166
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
167
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
168
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
169
+ (nsfw) content, according to the `safety_checker`.
170
+ """
171
+
172
+ if isinstance(prompt, str):
173
+ batch_size = 1
174
+ elif isinstance(prompt, list):
175
+ batch_size = len(prompt)
176
+ else:
177
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
178
+
179
+ if height % 8 != 0 or width % 8 != 0:
180
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
181
+
182
+ if (callback_steps is None) or (
183
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
184
+ ):
185
+ raise ValueError(
186
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
187
+ f" {type(callback_steps)}."
188
+ )
189
+
190
+ # get prompt text embeddings
191
+ text_inputs = self.tokenizer(
192
+ prompt,
193
+ padding="max_length",
194
+ max_length=self.tokenizer.model_max_length,
195
+ return_tensors="pt",
196
+ )
197
+ text_input_ids = text_inputs.input_ids
198
+
199
+ if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
200
+ removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :])
201
+ logger.warning(
202
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
203
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
204
+ )
205
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
206
+
207
+ if text_embeddings is None:
208
+ text_embeddings = self.text_encoder(text_input_ids.to(self.device))[0]
209
+
210
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
211
+ bs_embed, seq_len, _ = text_embeddings.shape
212
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
213
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
214
+
215
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
216
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
217
+ # corresponds to doing no classifier free guidance.
218
+ do_classifier_free_guidance = guidance_scale > 1.0
219
+ # get unconditional embeddings for classifier free guidance
220
+ if do_classifier_free_guidance:
221
+ uncond_tokens: List[str]
222
+ if negative_prompt is None:
223
+ uncond_tokens = [""]
224
+ elif type(prompt) is not type(negative_prompt):
225
+ raise TypeError(
226
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
227
+ f" {type(prompt)}."
228
+ )
229
+ elif isinstance(negative_prompt, str):
230
+ uncond_tokens = [negative_prompt]
231
+ elif batch_size != len(negative_prompt):
232
+ raise ValueError(
233
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
234
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
235
+ " the batch size of `prompt`."
236
+ )
237
+ else:
238
+ uncond_tokens = negative_prompt
239
+
240
+ max_length = text_input_ids.shape[-1]
241
+ uncond_input = self.tokenizer(
242
+ uncond_tokens,
243
+ padding="max_length",
244
+ max_length=max_length,
245
+ truncation=True,
246
+ return_tensors="pt",
247
+ )
248
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
249
+
250
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
251
+ seq_len = uncond_embeddings.shape[1]
252
+ uncond_embeddings = uncond_embeddings.repeat(batch_size, num_images_per_prompt, 1)
253
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
254
+
255
+ # For classifier free guidance, we need to do two forward passes.
256
+ # Here we concatenate the unconditional and text embeddings into a single batch
257
+ # to avoid doing two forward passes
258
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
259
+
260
+ # get the initial random noise unless the user supplied it
261
+
262
+ # Unlike in other pipelines, latents need to be generated in the target device
263
+ # for 1-to-1 results reproducibility with the CompVis implementation.
264
+ # However this currently doesn't work in `mps`.
265
+ latents_shape = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
266
+ latents_shape_reference = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64)
267
+ latents_dtype = text_embeddings.dtype
268
+ if latents is None:
269
+ if self.device.type == "mps":
270
+ # randn does not exist on mps
271
+ latents_reference = torch.randn(
272
+ latents_shape_reference, generator=generator, device="cpu", dtype=latents_dtype
273
+ ).to(self.device)
274
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
275
+ self.device
276
+ )
277
+ else:
278
+ latents_reference = torch.randn(
279
+ latents_shape_reference, generator=generator, device=self.device, dtype=latents_dtype
280
+ )
281
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
282
+ else:
283
+ if latents_reference.shape != latents_shape:
284
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
285
+ latents_reference = latents_reference.to(self.device)
286
+ latents = latents.to(self.device)
287
+
288
+ # This is the key part of the pipeline where we
289
+ # try to ensure that the generated images w/ the same seed
290
+ # but different sizes actually result in similar images
291
+ dx = (latents_shape[3] - latents_shape_reference[3]) // 2
292
+ dy = (latents_shape[2] - latents_shape_reference[2]) // 2
293
+ w = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx
294
+ h = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy
295
+ tx = 0 if dx < 0 else dx
296
+ ty = 0 if dy < 0 else dy
297
+ dx = max(-dx, 0)
298
+ dy = max(-dy, 0)
299
+ # import pdb
300
+ # pdb.set_trace()
301
+ latents[:, :, ty : ty + h, tx : tx + w] = latents_reference[:, :, dy : dy + h, dx : dx + w]
302
+
303
+ # set timesteps
304
+ self.scheduler.set_timesteps(num_inference_steps)
305
+
306
+ # Some schedulers like PNDM have timesteps as arrays
307
+ # It's more optimized to move all timesteps to correct device beforehand
308
+ timesteps_tensor = self.scheduler.timesteps.to(self.device)
309
+
310
+ # scale the initial noise by the standard deviation required by the scheduler
311
+ latents = latents * self.scheduler.init_noise_sigma
312
+
313
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
314
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
315
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
316
+ # and should be between [0, 1]
317
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
318
+ extra_step_kwargs = {}
319
+ if accepts_eta:
320
+ extra_step_kwargs["eta"] = eta
321
+
322
+ for i, t in enumerate(self.progress_bar(timesteps_tensor)):
323
+ # expand the latents if we are doing classifier free guidance
324
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
325
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
326
+
327
+ # predict the noise residual
328
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
329
+
330
+ # perform guidance
331
+ if do_classifier_free_guidance:
332
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
333
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
334
+
335
+ # compute the previous noisy sample x_t -> x_t-1
336
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
337
+
338
+ # call the callback, if provided
339
+ if callback is not None and i % callback_steps == 0:
340
+ step_idx = i // getattr(self.scheduler, "order", 1)
341
+ callback(step_idx, t, latents)
342
+
343
+ latents = 1 / 0.18215 * latents
344
+ image = self.vae.decode(latents).sample
345
+
346
+ image = (image / 2 + 0.5).clamp(0, 1)
347
+
348
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
349
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
350
+
351
+ if self.safety_checker is not None:
352
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(
353
+ self.device
354
+ )
355
+ image, has_nsfw_concept = self.safety_checker(
356
+ images=image, clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype)
357
+ )
358
+ else:
359
+ has_nsfw_concept = None
360
+
361
+ if output_type == "pil":
362
+ image = self.numpy_to_pil(image)
363
+
364
+ if not return_dict:
365
+ return (image, has_nsfw_concept)
366
+
367
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.22.0/speech_to_image_diffusion.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import Callable, List, Optional, Union
3
+
4
+ import torch
5
+ from transformers import (
6
+ CLIPImageProcessor,
7
+ CLIPTextModel,
8
+ CLIPTokenizer,
9
+ WhisperForConditionalGeneration,
10
+ WhisperProcessor,
11
+ )
12
+
13
+ from diffusers import (
14
+ AutoencoderKL,
15
+ DDIMScheduler,
16
+ DiffusionPipeline,
17
+ LMSDiscreteScheduler,
18
+ PNDMScheduler,
19
+ UNet2DConditionModel,
20
+ )
21
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
22
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
23
+ from diffusers.utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
27
+
28
+
29
+ class SpeechToImagePipeline(DiffusionPipeline):
30
+ def __init__(
31
+ self,
32
+ speech_model: WhisperForConditionalGeneration,
33
+ speech_processor: WhisperProcessor,
34
+ vae: AutoencoderKL,
35
+ text_encoder: CLIPTextModel,
36
+ tokenizer: CLIPTokenizer,
37
+ unet: UNet2DConditionModel,
38
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
39
+ safety_checker: StableDiffusionSafetyChecker,
40
+ feature_extractor: CLIPImageProcessor,
41
+ ):
42
+ super().__init__()
43
+
44
+ if safety_checker is None:
45
+ logger.warning(
46
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
47
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
48
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
49
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
50
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
51
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
52
+ )
53
+
54
+ self.register_modules(
55
+ speech_model=speech_model,
56
+ speech_processor=speech_processor,
57
+ vae=vae,
58
+ text_encoder=text_encoder,
59
+ tokenizer=tokenizer,
60
+ unet=unet,
61
+ scheduler=scheduler,
62
+ feature_extractor=feature_extractor,
63
+ )
64
+
65
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
66
+ if slice_size == "auto":
67
+ slice_size = self.unet.config.attention_head_dim // 2
68
+ self.unet.set_attention_slice(slice_size)
69
+
70
+ def disable_attention_slicing(self):
71
+ self.enable_attention_slicing(None)
72
+
73
+ @torch.no_grad()
74
+ def __call__(
75
+ self,
76
+ audio,
77
+ sampling_rate=16_000,
78
+ height: int = 512,
79
+ width: int = 512,
80
+ num_inference_steps: int = 50,
81
+ guidance_scale: float = 7.5,
82
+ negative_prompt: Optional[Union[str, List[str]]] = None,
83
+ num_images_per_prompt: Optional[int] = 1,
84
+ eta: float = 0.0,
85
+ generator: Optional[torch.Generator] = None,
86
+ latents: Optional[torch.FloatTensor] = None,
87
+ output_type: Optional[str] = "pil",
88
+ return_dict: bool = True,
89
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
90
+ callback_steps: int = 1,
91
+ **kwargs,
92
+ ):
93
+ inputs = self.speech_processor.feature_extractor(
94
+ audio, return_tensors="pt", sampling_rate=sampling_rate
95
+ ).input_features.to(self.device)
96
+ predicted_ids = self.speech_model.generate(inputs, max_length=480_000)
97
+
98
+ prompt = self.speech_processor.tokenizer.batch_decode(predicted_ids, skip_special_tokens=True, normalize=True)[
99
+ 0
100
+ ]
101
+
102
+ if isinstance(prompt, str):
103
+ batch_size = 1
104
+ elif isinstance(prompt, list):
105
+ batch_size = len(prompt)
106
+ else:
107
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
108
+
109
+ if height % 8 != 0 or width % 8 != 0:
110
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
111
+
112
+ if (callback_steps is None) or (
113
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
114
+ ):
115
+ raise ValueError(
116
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
117
+ f" {type(callback_steps)}."
118
+ )
119
+
120
+ # get prompt text embeddings
121
+ text_inputs = self.tokenizer(
122
+ prompt,
123
+ padding="max_length",
124
+ max_length=self.tokenizer.model_max_length,
125
+ return_tensors="pt",
126
+ )
127
+ text_input_ids = text_inputs.input_ids
128
+
129
+ if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
130
+ removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :])
131
+ logger.warning(
132
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
133
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
134
+ )
135
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
136
+ text_embeddings = self.text_encoder(text_input_ids.to(self.device))[0]
137
+
138
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
139
+ bs_embed, seq_len, _ = text_embeddings.shape
140
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
141
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
142
+
143
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
144
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
145
+ # corresponds to doing no classifier free guidance.
146
+ do_classifier_free_guidance = guidance_scale > 1.0
147
+ # get unconditional embeddings for classifier free guidance
148
+ if do_classifier_free_guidance:
149
+ uncond_tokens: List[str]
150
+ if negative_prompt is None:
151
+ uncond_tokens = [""] * batch_size
152
+ elif type(prompt) is not type(negative_prompt):
153
+ raise TypeError(
154
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
155
+ f" {type(prompt)}."
156
+ )
157
+ elif isinstance(negative_prompt, str):
158
+ uncond_tokens = [negative_prompt]
159
+ elif batch_size != len(negative_prompt):
160
+ raise ValueError(
161
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
162
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
163
+ " the batch size of `prompt`."
164
+ )
165
+ else:
166
+ uncond_tokens = negative_prompt
167
+
168
+ max_length = text_input_ids.shape[-1]
169
+ uncond_input = self.tokenizer(
170
+ uncond_tokens,
171
+ padding="max_length",
172
+ max_length=max_length,
173
+ truncation=True,
174
+ return_tensors="pt",
175
+ )
176
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
177
+
178
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
179
+ seq_len = uncond_embeddings.shape[1]
180
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
181
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
182
+
183
+ # For classifier free guidance, we need to do two forward passes.
184
+ # Here we concatenate the unconditional and text embeddings into a single batch
185
+ # to avoid doing two forward passes
186
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
187
+
188
+ # get the initial random noise unless the user supplied it
189
+
190
+ # Unlike in other pipelines, latents need to be generated in the target device
191
+ # for 1-to-1 results reproducibility with the CompVis implementation.
192
+ # However this currently doesn't work in `mps`.
193
+ latents_shape = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
194
+ latents_dtype = text_embeddings.dtype
195
+ if latents is None:
196
+ if self.device.type == "mps":
197
+ # randn does not exist on mps
198
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
199
+ self.device
200
+ )
201
+ else:
202
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
203
+ else:
204
+ if latents.shape != latents_shape:
205
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
206
+ latents = latents.to(self.device)
207
+
208
+ # set timesteps
209
+ self.scheduler.set_timesteps(num_inference_steps)
210
+
211
+ # Some schedulers like PNDM have timesteps as arrays
212
+ # It's more optimized to move all timesteps to correct device beforehand
213
+ timesteps_tensor = self.scheduler.timesteps.to(self.device)
214
+
215
+ # scale the initial noise by the standard deviation required by the scheduler
216
+ latents = latents * self.scheduler.init_noise_sigma
217
+
218
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
219
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
220
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
221
+ # and should be between [0, 1]
222
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
223
+ extra_step_kwargs = {}
224
+ if accepts_eta:
225
+ extra_step_kwargs["eta"] = eta
226
+
227
+ for i, t in enumerate(self.progress_bar(timesteps_tensor)):
228
+ # expand the latents if we are doing classifier free guidance
229
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
230
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
231
+
232
+ # predict the noise residual
233
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
234
+
235
+ # perform guidance
236
+ if do_classifier_free_guidance:
237
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
238
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
239
+
240
+ # compute the previous noisy sample x_t -> x_t-1
241
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
242
+
243
+ # call the callback, if provided
244
+ if callback is not None and i % callback_steps == 0:
245
+ step_idx = i // getattr(self.scheduler, "order", 1)
246
+ callback(step_idx, t, latents)
247
+
248
+ latents = 1 / 0.18215 * latents
249
+ image = self.vae.decode(latents).sample
250
+
251
+ image = (image / 2 + 0.5).clamp(0, 1)
252
+
253
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
254
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
255
+
256
+ if output_type == "pil":
257
+ image = self.numpy_to_pil(image)
258
+
259
+ if not return_dict:
260
+ return image
261
+
262
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=None)
v0.22.0/stable_diffusion_comparison.py ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, Dict, List, Optional, Union
2
+
3
+ import torch
4
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
5
+
6
+ from diffusers import (
7
+ AutoencoderKL,
8
+ DDIMScheduler,
9
+ DiffusionPipeline,
10
+ LMSDiscreteScheduler,
11
+ PNDMScheduler,
12
+ StableDiffusionPipeline,
13
+ UNet2DConditionModel,
14
+ )
15
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
16
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
17
+
18
+
19
+ pipe1_model_id = "CompVis/stable-diffusion-v1-1"
20
+ pipe2_model_id = "CompVis/stable-diffusion-v1-2"
21
+ pipe3_model_id = "CompVis/stable-diffusion-v1-3"
22
+ pipe4_model_id = "CompVis/stable-diffusion-v1-4"
23
+
24
+
25
+ class StableDiffusionComparisonPipeline(DiffusionPipeline):
26
+ r"""
27
+ Pipeline for parallel comparison of Stable Diffusion v1-v4
28
+ This pipeline inherits from DiffusionPipeline and depends on the use of an Auth Token for
29
+ downloading pre-trained checkpoints from Hugging Face Hub.
30
+ If using Hugging Face Hub, pass the Model ID for Stable Diffusion v1.4 as the previous 3 checkpoints will be loaded
31
+ automatically.
32
+ Args:
33
+ vae ([`AutoencoderKL`]):
34
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
35
+ text_encoder ([`CLIPTextModel`]):
36
+ Frozen text-encoder. Stable Diffusion uses the text portion of
37
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
38
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
39
+ tokenizer (`CLIPTokenizer`):
40
+ Tokenizer of class
41
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
42
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
43
+ scheduler ([`SchedulerMixin`]):
44
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
45
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
46
+ safety_checker ([`StableDiffusionMegaSafetyChecker`]):
47
+ Classification module that estimates whether generated images could be considered offensive or harmful.
48
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
49
+ feature_extractor ([`CLIPImageProcessor`]):
50
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ vae: AutoencoderKL,
56
+ text_encoder: CLIPTextModel,
57
+ tokenizer: CLIPTokenizer,
58
+ unet: UNet2DConditionModel,
59
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
60
+ safety_checker: StableDiffusionSafetyChecker,
61
+ feature_extractor: CLIPImageProcessor,
62
+ requires_safety_checker: bool = True,
63
+ ):
64
+ super()._init_()
65
+
66
+ self.pipe1 = StableDiffusionPipeline.from_pretrained(pipe1_model_id)
67
+ self.pipe2 = StableDiffusionPipeline.from_pretrained(pipe2_model_id)
68
+ self.pipe3 = StableDiffusionPipeline.from_pretrained(pipe3_model_id)
69
+ self.pipe4 = StableDiffusionPipeline(
70
+ vae=vae,
71
+ text_encoder=text_encoder,
72
+ tokenizer=tokenizer,
73
+ unet=unet,
74
+ scheduler=scheduler,
75
+ safety_checker=safety_checker,
76
+ feature_extractor=feature_extractor,
77
+ requires_safety_checker=requires_safety_checker,
78
+ )
79
+
80
+ self.register_modules(pipeline1=self.pipe1, pipeline2=self.pipe2, pipeline3=self.pipe3, pipeline4=self.pipe4)
81
+
82
+ @property
83
+ def layers(self) -> Dict[str, Any]:
84
+ return {k: getattr(self, k) for k in self.config.keys() if not k.startswith("_")}
85
+
86
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
87
+ r"""
88
+ Enable sliced attention computation.
89
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
90
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
91
+ Args:
92
+ slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
93
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
94
+ a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
95
+ `attention_head_dim` must be a multiple of `slice_size`.
96
+ """
97
+ if slice_size == "auto":
98
+ # half the attention head size is usually a good trade-off between
99
+ # speed and memory
100
+ slice_size = self.unet.config.attention_head_dim // 2
101
+ self.unet.set_attention_slice(slice_size)
102
+
103
+ def disable_attention_slicing(self):
104
+ r"""
105
+ Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
106
+ back to computing attention in one step.
107
+ """
108
+ # set slice_size = `None` to disable `attention slicing`
109
+ self.enable_attention_slicing(None)
110
+
111
+ @torch.no_grad()
112
+ def text2img_sd1_1(
113
+ self,
114
+ prompt: Union[str, List[str]],
115
+ height: int = 512,
116
+ width: int = 512,
117
+ num_inference_steps: int = 50,
118
+ guidance_scale: float = 7.5,
119
+ negative_prompt: Optional[Union[str, List[str]]] = None,
120
+ num_images_per_prompt: Optional[int] = 1,
121
+ eta: float = 0.0,
122
+ generator: Optional[torch.Generator] = None,
123
+ latents: Optional[torch.FloatTensor] = None,
124
+ output_type: Optional[str] = "pil",
125
+ return_dict: bool = True,
126
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
127
+ callback_steps: int = 1,
128
+ **kwargs,
129
+ ):
130
+ return self.pipe1(
131
+ prompt=prompt,
132
+ height=height,
133
+ width=width,
134
+ num_inference_steps=num_inference_steps,
135
+ guidance_scale=guidance_scale,
136
+ negative_prompt=negative_prompt,
137
+ num_images_per_prompt=num_images_per_prompt,
138
+ eta=eta,
139
+ generator=generator,
140
+ latents=latents,
141
+ output_type=output_type,
142
+ return_dict=return_dict,
143
+ callback=callback,
144
+ callback_steps=callback_steps,
145
+ **kwargs,
146
+ )
147
+
148
+ @torch.no_grad()
149
+ def text2img_sd1_2(
150
+ self,
151
+ prompt: Union[str, List[str]],
152
+ height: int = 512,
153
+ width: int = 512,
154
+ num_inference_steps: int = 50,
155
+ guidance_scale: float = 7.5,
156
+ negative_prompt: Optional[Union[str, List[str]]] = None,
157
+ num_images_per_prompt: Optional[int] = 1,
158
+ eta: float = 0.0,
159
+ generator: Optional[torch.Generator] = None,
160
+ latents: Optional[torch.FloatTensor] = None,
161
+ output_type: Optional[str] = "pil",
162
+ return_dict: bool = True,
163
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
164
+ callback_steps: int = 1,
165
+ **kwargs,
166
+ ):
167
+ return self.pipe2(
168
+ prompt=prompt,
169
+ height=height,
170
+ width=width,
171
+ num_inference_steps=num_inference_steps,
172
+ guidance_scale=guidance_scale,
173
+ negative_prompt=negative_prompt,
174
+ num_images_per_prompt=num_images_per_prompt,
175
+ eta=eta,
176
+ generator=generator,
177
+ latents=latents,
178
+ output_type=output_type,
179
+ return_dict=return_dict,
180
+ callback=callback,
181
+ callback_steps=callback_steps,
182
+ **kwargs,
183
+ )
184
+
185
+ @torch.no_grad()
186
+ def text2img_sd1_3(
187
+ self,
188
+ prompt: Union[str, List[str]],
189
+ height: int = 512,
190
+ width: int = 512,
191
+ num_inference_steps: int = 50,
192
+ guidance_scale: float = 7.5,
193
+ negative_prompt: Optional[Union[str, List[str]]] = None,
194
+ num_images_per_prompt: Optional[int] = 1,
195
+ eta: float = 0.0,
196
+ generator: Optional[torch.Generator] = None,
197
+ latents: Optional[torch.FloatTensor] = None,
198
+ output_type: Optional[str] = "pil",
199
+ return_dict: bool = True,
200
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
201
+ callback_steps: int = 1,
202
+ **kwargs,
203
+ ):
204
+ return self.pipe3(
205
+ prompt=prompt,
206
+ height=height,
207
+ width=width,
208
+ num_inference_steps=num_inference_steps,
209
+ guidance_scale=guidance_scale,
210
+ negative_prompt=negative_prompt,
211
+ num_images_per_prompt=num_images_per_prompt,
212
+ eta=eta,
213
+ generator=generator,
214
+ latents=latents,
215
+ output_type=output_type,
216
+ return_dict=return_dict,
217
+ callback=callback,
218
+ callback_steps=callback_steps,
219
+ **kwargs,
220
+ )
221
+
222
+ @torch.no_grad()
223
+ def text2img_sd1_4(
224
+ self,
225
+ prompt: Union[str, List[str]],
226
+ height: int = 512,
227
+ width: int = 512,
228
+ num_inference_steps: int = 50,
229
+ guidance_scale: float = 7.5,
230
+ negative_prompt: Optional[Union[str, List[str]]] = None,
231
+ num_images_per_prompt: Optional[int] = 1,
232
+ eta: float = 0.0,
233
+ generator: Optional[torch.Generator] = None,
234
+ latents: Optional[torch.FloatTensor] = None,
235
+ output_type: Optional[str] = "pil",
236
+ return_dict: bool = True,
237
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
238
+ callback_steps: int = 1,
239
+ **kwargs,
240
+ ):
241
+ return self.pipe4(
242
+ prompt=prompt,
243
+ height=height,
244
+ width=width,
245
+ num_inference_steps=num_inference_steps,
246
+ guidance_scale=guidance_scale,
247
+ negative_prompt=negative_prompt,
248
+ num_images_per_prompt=num_images_per_prompt,
249
+ eta=eta,
250
+ generator=generator,
251
+ latents=latents,
252
+ output_type=output_type,
253
+ return_dict=return_dict,
254
+ callback=callback,
255
+ callback_steps=callback_steps,
256
+ **kwargs,
257
+ )
258
+
259
+ @torch.no_grad()
260
+ def _call_(
261
+ self,
262
+ prompt: Union[str, List[str]],
263
+ height: int = 512,
264
+ width: int = 512,
265
+ num_inference_steps: int = 50,
266
+ guidance_scale: float = 7.5,
267
+ negative_prompt: Optional[Union[str, List[str]]] = None,
268
+ num_images_per_prompt: Optional[int] = 1,
269
+ eta: float = 0.0,
270
+ generator: Optional[torch.Generator] = None,
271
+ latents: Optional[torch.FloatTensor] = None,
272
+ output_type: Optional[str] = "pil",
273
+ return_dict: bool = True,
274
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
275
+ callback_steps: int = 1,
276
+ **kwargs,
277
+ ):
278
+ r"""
279
+ Function invoked when calling the pipeline for generation. This function will generate 4 results as part
280
+ of running all the 4 pipelines for SD1.1-1.4 together in a serial-processing, parallel-invocation fashion.
281
+ Args:
282
+ prompt (`str` or `List[str]`):
283
+ The prompt or prompts to guide the image generation.
284
+ height (`int`, optional, defaults to 512):
285
+ The height in pixels of the generated image.
286
+ width (`int`, optional, defaults to 512):
287
+ The width in pixels of the generated image.
288
+ num_inference_steps (`int`, optional, defaults to 50):
289
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
290
+ expense of slower inference.
291
+ guidance_scale (`float`, optional, defaults to 7.5):
292
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
293
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
294
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
295
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
296
+ usually at the expense of lower image quality.
297
+ eta (`float`, optional, defaults to 0.0):
298
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
299
+ [`schedulers.DDIMScheduler`], will be ignored for others.
300
+ generator (`torch.Generator`, optional):
301
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
302
+ deterministic.
303
+ latents (`torch.FloatTensor`, optional):
304
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
305
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
306
+ tensor will ge generated by sampling using the supplied random `generator`.
307
+ output_type (`str`, optional, defaults to `"pil"`):
308
+ The output format of the generate image. Choose between
309
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
310
+ return_dict (`bool`, optional, defaults to `True`):
311
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
312
+ plain tuple.
313
+ Returns:
314
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
315
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
316
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
317
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
318
+ (nsfw) content, according to the `safety_checker`.
319
+ """
320
+
321
+ device = "cuda" if torch.cuda.is_available() else "cpu"
322
+ self.to(device)
323
+
324
+ # Checks if the height and width are divisible by 8 or not
325
+ if height % 8 != 0 or width % 8 != 0:
326
+ raise ValueError(f"`height` and `width` must be divisible by 8 but are {height} and {width}.")
327
+
328
+ # Get first result from Stable Diffusion Checkpoint v1.1
329
+ res1 = self.text2img_sd1_1(
330
+ prompt=prompt,
331
+ height=height,
332
+ width=width,
333
+ num_inference_steps=num_inference_steps,
334
+ guidance_scale=guidance_scale,
335
+ negative_prompt=negative_prompt,
336
+ num_images_per_prompt=num_images_per_prompt,
337
+ eta=eta,
338
+ generator=generator,
339
+ latents=latents,
340
+ output_type=output_type,
341
+ return_dict=return_dict,
342
+ callback=callback,
343
+ callback_steps=callback_steps,
344
+ **kwargs,
345
+ )
346
+
347
+ # Get first result from Stable Diffusion Checkpoint v1.2
348
+ res2 = self.text2img_sd1_2(
349
+ prompt=prompt,
350
+ height=height,
351
+ width=width,
352
+ num_inference_steps=num_inference_steps,
353
+ guidance_scale=guidance_scale,
354
+ negative_prompt=negative_prompt,
355
+ num_images_per_prompt=num_images_per_prompt,
356
+ eta=eta,
357
+ generator=generator,
358
+ latents=latents,
359
+ output_type=output_type,
360
+ return_dict=return_dict,
361
+ callback=callback,
362
+ callback_steps=callback_steps,
363
+ **kwargs,
364
+ )
365
+
366
+ # Get first result from Stable Diffusion Checkpoint v1.3
367
+ res3 = self.text2img_sd1_3(
368
+ prompt=prompt,
369
+ height=height,
370
+ width=width,
371
+ num_inference_steps=num_inference_steps,
372
+ guidance_scale=guidance_scale,
373
+ negative_prompt=negative_prompt,
374
+ num_images_per_prompt=num_images_per_prompt,
375
+ eta=eta,
376
+ generator=generator,
377
+ latents=latents,
378
+ output_type=output_type,
379
+ return_dict=return_dict,
380
+ callback=callback,
381
+ callback_steps=callback_steps,
382
+ **kwargs,
383
+ )
384
+
385
+ # Get first result from Stable Diffusion Checkpoint v1.4
386
+ res4 = self.text2img_sd1_4(
387
+ prompt=prompt,
388
+ height=height,
389
+ width=width,
390
+ num_inference_steps=num_inference_steps,
391
+ guidance_scale=guidance_scale,
392
+ negative_prompt=negative_prompt,
393
+ num_images_per_prompt=num_images_per_prompt,
394
+ eta=eta,
395
+ generator=generator,
396
+ latents=latents,
397
+ output_type=output_type,
398
+ return_dict=return_dict,
399
+ callback=callback,
400
+ callback_steps=callback_steps,
401
+ **kwargs,
402
+ )
403
+
404
+ # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result
405
+ return StableDiffusionPipelineOutput([res1[0], res2[0], res3[0], res4[0]])
v0.22.0/stable_diffusion_controlnet_img2img.py ADDED
@@ -0,0 +1,990 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inspired by: https://github.com/haofanwang/ControlNet-for-Diffusers/
2
+
3
+ import inspect
4
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
5
+
6
+ import numpy as np
7
+ import PIL.Image
8
+ import torch
9
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
10
+
11
+ from diffusers import AutoencoderKL, ControlNetModel, DiffusionPipeline, UNet2DConditionModel, logging
12
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput, StableDiffusionSafetyChecker
13
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel
14
+ from diffusers.schedulers import KarrasDiffusionSchedulers
15
+ from diffusers.utils import (
16
+ PIL_INTERPOLATION,
17
+ is_accelerate_available,
18
+ is_accelerate_version,
19
+ replace_example_docstring,
20
+ )
21
+ from diffusers.utils.torch_utils import randn_tensor
22
+
23
+
24
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
25
+
26
+ EXAMPLE_DOC_STRING = """
27
+ Examples:
28
+ ```py
29
+ >>> import numpy as np
30
+ >>> import torch
31
+ >>> from PIL import Image
32
+ >>> from diffusers import ControlNetModel, UniPCMultistepScheduler
33
+ >>> from diffusers.utils import load_image
34
+
35
+ >>> input_image = load_image("https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png")
36
+
37
+ >>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
38
+
39
+ >>> pipe_controlnet = StableDiffusionControlNetImg2ImgPipeline.from_pretrained(
40
+ "runwayml/stable-diffusion-v1-5",
41
+ controlnet=controlnet,
42
+ safety_checker=None,
43
+ torch_dtype=torch.float16
44
+ )
45
+
46
+ >>> pipe_controlnet.scheduler = UniPCMultistepScheduler.from_config(pipe_controlnet.scheduler.config)
47
+ >>> pipe_controlnet.enable_xformers_memory_efficient_attention()
48
+ >>> pipe_controlnet.enable_model_cpu_offload()
49
+
50
+ # using image with edges for our canny controlnet
51
+ >>> control_image = load_image(
52
+ "https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/vermeer_canny_edged.png")
53
+
54
+
55
+ >>> result_img = pipe_controlnet(controlnet_conditioning_image=control_image,
56
+ image=input_image,
57
+ prompt="an android robot, cyberpank, digitl art masterpiece",
58
+ num_inference_steps=20).images[0]
59
+
60
+ >>> result_img.show()
61
+ ```
62
+ """
63
+
64
+
65
+ def prepare_image(image):
66
+ if isinstance(image, torch.Tensor):
67
+ # Batch single image
68
+ if image.ndim == 3:
69
+ image = image.unsqueeze(0)
70
+
71
+ image = image.to(dtype=torch.float32)
72
+ else:
73
+ # preprocess image
74
+ if isinstance(image, (PIL.Image.Image, np.ndarray)):
75
+ image = [image]
76
+
77
+ if isinstance(image, list) and isinstance(image[0], PIL.Image.Image):
78
+ image = [np.array(i.convert("RGB"))[None, :] for i in image]
79
+ image = np.concatenate(image, axis=0)
80
+ elif isinstance(image, list) and isinstance(image[0], np.ndarray):
81
+ image = np.concatenate([i[None, :] for i in image], axis=0)
82
+
83
+ image = image.transpose(0, 3, 1, 2)
84
+ image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
85
+
86
+ return image
87
+
88
+
89
+ def prepare_controlnet_conditioning_image(
90
+ controlnet_conditioning_image,
91
+ width,
92
+ height,
93
+ batch_size,
94
+ num_images_per_prompt,
95
+ device,
96
+ dtype,
97
+ do_classifier_free_guidance,
98
+ ):
99
+ if not isinstance(controlnet_conditioning_image, torch.Tensor):
100
+ if isinstance(controlnet_conditioning_image, PIL.Image.Image):
101
+ controlnet_conditioning_image = [controlnet_conditioning_image]
102
+
103
+ if isinstance(controlnet_conditioning_image[0], PIL.Image.Image):
104
+ controlnet_conditioning_image = [
105
+ np.array(i.resize((width, height), resample=PIL_INTERPOLATION["lanczos"]))[None, :]
106
+ for i in controlnet_conditioning_image
107
+ ]
108
+ controlnet_conditioning_image = np.concatenate(controlnet_conditioning_image, axis=0)
109
+ controlnet_conditioning_image = np.array(controlnet_conditioning_image).astype(np.float32) / 255.0
110
+ controlnet_conditioning_image = controlnet_conditioning_image.transpose(0, 3, 1, 2)
111
+ controlnet_conditioning_image = torch.from_numpy(controlnet_conditioning_image)
112
+ elif isinstance(controlnet_conditioning_image[0], torch.Tensor):
113
+ controlnet_conditioning_image = torch.cat(controlnet_conditioning_image, dim=0)
114
+
115
+ image_batch_size = controlnet_conditioning_image.shape[0]
116
+
117
+ if image_batch_size == 1:
118
+ repeat_by = batch_size
119
+ else:
120
+ # image batch size is the same as prompt batch size
121
+ repeat_by = num_images_per_prompt
122
+
123
+ controlnet_conditioning_image = controlnet_conditioning_image.repeat_interleave(repeat_by, dim=0)
124
+
125
+ controlnet_conditioning_image = controlnet_conditioning_image.to(device=device, dtype=dtype)
126
+
127
+ if do_classifier_free_guidance:
128
+ controlnet_conditioning_image = torch.cat([controlnet_conditioning_image] * 2)
129
+
130
+ return controlnet_conditioning_image
131
+
132
+
133
+ class StableDiffusionControlNetImg2ImgPipeline(DiffusionPipeline):
134
+ """
135
+ Inspired by: https://github.com/haofanwang/ControlNet-for-Diffusers/
136
+ """
137
+
138
+ _optional_components = ["safety_checker", "feature_extractor"]
139
+
140
+ def __init__(
141
+ self,
142
+ vae: AutoencoderKL,
143
+ text_encoder: CLIPTextModel,
144
+ tokenizer: CLIPTokenizer,
145
+ unet: UNet2DConditionModel,
146
+ controlnet: Union[ControlNetModel, List[ControlNetModel], Tuple[ControlNetModel], MultiControlNetModel],
147
+ scheduler: KarrasDiffusionSchedulers,
148
+ safety_checker: StableDiffusionSafetyChecker,
149
+ feature_extractor: CLIPImageProcessor,
150
+ requires_safety_checker: bool = True,
151
+ ):
152
+ super().__init__()
153
+
154
+ if safety_checker is None and requires_safety_checker:
155
+ logger.warning(
156
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
157
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
158
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
159
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
160
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
161
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
162
+ )
163
+
164
+ if safety_checker is not None and feature_extractor is None:
165
+ raise ValueError(
166
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
167
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
168
+ )
169
+
170
+ if isinstance(controlnet, (list, tuple)):
171
+ controlnet = MultiControlNetModel(controlnet)
172
+
173
+ self.register_modules(
174
+ vae=vae,
175
+ text_encoder=text_encoder,
176
+ tokenizer=tokenizer,
177
+ unet=unet,
178
+ controlnet=controlnet,
179
+ scheduler=scheduler,
180
+ safety_checker=safety_checker,
181
+ feature_extractor=feature_extractor,
182
+ )
183
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
184
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
185
+
186
+ def enable_vae_slicing(self):
187
+ r"""
188
+ Enable sliced VAE decoding.
189
+
190
+ When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
191
+ steps. This is useful to save some memory and allow larger batch sizes.
192
+ """
193
+ self.vae.enable_slicing()
194
+
195
+ def disable_vae_slicing(self):
196
+ r"""
197
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to
198
+ computing decoding in one step.
199
+ """
200
+ self.vae.disable_slicing()
201
+
202
+ def enable_sequential_cpu_offload(self, gpu_id=0):
203
+ r"""
204
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
205
+ text_encoder, vae, controlnet, and safety checker have their state dicts saved to CPU and then are moved to a
206
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
207
+ Note that offloading happens on a submodule basis. Memory savings are higher than with
208
+ `enable_model_cpu_offload`, but performance is lower.
209
+ """
210
+ if is_accelerate_available():
211
+ from accelerate import cpu_offload
212
+ else:
213
+ raise ImportError("Please install accelerate via `pip install accelerate`")
214
+
215
+ device = torch.device(f"cuda:{gpu_id}")
216
+
217
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.controlnet]:
218
+ cpu_offload(cpu_offloaded_model, device)
219
+
220
+ if self.safety_checker is not None:
221
+ cpu_offload(self.safety_checker, execution_device=device, offload_buffers=True)
222
+
223
+ def enable_model_cpu_offload(self, gpu_id=0):
224
+ r"""
225
+ Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
226
+ to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
227
+ method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
228
+ `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
229
+ """
230
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
231
+ from accelerate import cpu_offload_with_hook
232
+ else:
233
+ raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")
234
+
235
+ device = torch.device(f"cuda:{gpu_id}")
236
+
237
+ hook = None
238
+ for cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]:
239
+ _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
240
+
241
+ if self.safety_checker is not None:
242
+ # the safety checker can offload the vae again
243
+ _, hook = cpu_offload_with_hook(self.safety_checker, device, prev_module_hook=hook)
244
+
245
+ # control net hook has be manually offloaded as it alternates with unet
246
+ cpu_offload_with_hook(self.controlnet, device)
247
+
248
+ # We'll offload the last model manually.
249
+ self.final_offload_hook = hook
250
+
251
+ @property
252
+ def _execution_device(self):
253
+ r"""
254
+ Returns the device on which the pipeline's models will be executed. After calling
255
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
256
+ hooks.
257
+ """
258
+ if not hasattr(self.unet, "_hf_hook"):
259
+ return self.device
260
+ for module in self.unet.modules():
261
+ if (
262
+ hasattr(module, "_hf_hook")
263
+ and hasattr(module._hf_hook, "execution_device")
264
+ and module._hf_hook.execution_device is not None
265
+ ):
266
+ return torch.device(module._hf_hook.execution_device)
267
+ return self.device
268
+
269
+ def _encode_prompt(
270
+ self,
271
+ prompt,
272
+ device,
273
+ num_images_per_prompt,
274
+ do_classifier_free_guidance,
275
+ negative_prompt=None,
276
+ prompt_embeds: Optional[torch.FloatTensor] = None,
277
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
278
+ ):
279
+ r"""
280
+ Encodes the prompt into text encoder hidden states.
281
+
282
+ Args:
283
+ prompt (`str` or `List[str]`, *optional*):
284
+ prompt to be encoded
285
+ device: (`torch.device`):
286
+ torch device
287
+ num_images_per_prompt (`int`):
288
+ number of images that should be generated per prompt
289
+ do_classifier_free_guidance (`bool`):
290
+ whether to use classifier free guidance or not
291
+ negative_prompt (`str` or `List[str]`, *optional*):
292
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
293
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
294
+ prompt_embeds (`torch.FloatTensor`, *optional*):
295
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
296
+ provided, text embeddings will be generated from `prompt` input argument.
297
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
298
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
299
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
300
+ argument.
301
+ """
302
+ if prompt is not None and isinstance(prompt, str):
303
+ batch_size = 1
304
+ elif prompt is not None and isinstance(prompt, list):
305
+ batch_size = len(prompt)
306
+ else:
307
+ batch_size = prompt_embeds.shape[0]
308
+
309
+ if prompt_embeds is None:
310
+ text_inputs = self.tokenizer(
311
+ prompt,
312
+ padding="max_length",
313
+ max_length=self.tokenizer.model_max_length,
314
+ truncation=True,
315
+ return_tensors="pt",
316
+ )
317
+ text_input_ids = text_inputs.input_ids
318
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
319
+
320
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
321
+ text_input_ids, untruncated_ids
322
+ ):
323
+ removed_text = self.tokenizer.batch_decode(
324
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
325
+ )
326
+ logger.warning(
327
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
328
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
329
+ )
330
+
331
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
332
+ attention_mask = text_inputs.attention_mask.to(device)
333
+ else:
334
+ attention_mask = None
335
+
336
+ prompt_embeds = self.text_encoder(
337
+ text_input_ids.to(device),
338
+ attention_mask=attention_mask,
339
+ )
340
+ prompt_embeds = prompt_embeds[0]
341
+
342
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
343
+
344
+ bs_embed, seq_len, _ = prompt_embeds.shape
345
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
346
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
347
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
348
+
349
+ # get unconditional embeddings for classifier free guidance
350
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
351
+ uncond_tokens: List[str]
352
+ if negative_prompt is None:
353
+ uncond_tokens = [""] * batch_size
354
+ elif type(prompt) is not type(negative_prompt):
355
+ raise TypeError(
356
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
357
+ f" {type(prompt)}."
358
+ )
359
+ elif isinstance(negative_prompt, str):
360
+ uncond_tokens = [negative_prompt]
361
+ elif batch_size != len(negative_prompt):
362
+ raise ValueError(
363
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
364
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
365
+ " the batch size of `prompt`."
366
+ )
367
+ else:
368
+ uncond_tokens = negative_prompt
369
+
370
+ max_length = prompt_embeds.shape[1]
371
+ uncond_input = self.tokenizer(
372
+ uncond_tokens,
373
+ padding="max_length",
374
+ max_length=max_length,
375
+ truncation=True,
376
+ return_tensors="pt",
377
+ )
378
+
379
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
380
+ attention_mask = uncond_input.attention_mask.to(device)
381
+ else:
382
+ attention_mask = None
383
+
384
+ negative_prompt_embeds = self.text_encoder(
385
+ uncond_input.input_ids.to(device),
386
+ attention_mask=attention_mask,
387
+ )
388
+ negative_prompt_embeds = negative_prompt_embeds[0]
389
+
390
+ if do_classifier_free_guidance:
391
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
392
+ seq_len = negative_prompt_embeds.shape[1]
393
+
394
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
395
+
396
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
397
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
398
+
399
+ # For classifier free guidance, we need to do two forward passes.
400
+ # Here we concatenate the unconditional and text embeddings into a single batch
401
+ # to avoid doing two forward passes
402
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
403
+
404
+ return prompt_embeds
405
+
406
+ def run_safety_checker(self, image, device, dtype):
407
+ if self.safety_checker is not None:
408
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
409
+ image, has_nsfw_concept = self.safety_checker(
410
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
411
+ )
412
+ else:
413
+ has_nsfw_concept = None
414
+ return image, has_nsfw_concept
415
+
416
+ def decode_latents(self, latents):
417
+ latents = 1 / self.vae.config.scaling_factor * latents
418
+ image = self.vae.decode(latents).sample
419
+ image = (image / 2 + 0.5).clamp(0, 1)
420
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
421
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
422
+ return image
423
+
424
+ def prepare_extra_step_kwargs(self, generator, eta):
425
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
426
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
427
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
428
+ # and should be between [0, 1]
429
+
430
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
431
+ extra_step_kwargs = {}
432
+ if accepts_eta:
433
+ extra_step_kwargs["eta"] = eta
434
+
435
+ # check if the scheduler accepts generator
436
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
437
+ if accepts_generator:
438
+ extra_step_kwargs["generator"] = generator
439
+ return extra_step_kwargs
440
+
441
+ def check_controlnet_conditioning_image(self, image, prompt, prompt_embeds):
442
+ image_is_pil = isinstance(image, PIL.Image.Image)
443
+ image_is_tensor = isinstance(image, torch.Tensor)
444
+ image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
445
+ image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
446
+
447
+ if not image_is_pil and not image_is_tensor and not image_is_pil_list and not image_is_tensor_list:
448
+ raise TypeError(
449
+ "image must be passed and be one of PIL image, torch tensor, list of PIL images, or list of torch tensors"
450
+ )
451
+
452
+ if image_is_pil:
453
+ image_batch_size = 1
454
+ elif image_is_tensor:
455
+ image_batch_size = image.shape[0]
456
+ elif image_is_pil_list:
457
+ image_batch_size = len(image)
458
+ elif image_is_tensor_list:
459
+ image_batch_size = len(image)
460
+ else:
461
+ raise ValueError("controlnet condition image is not valid")
462
+
463
+ if prompt is not None and isinstance(prompt, str):
464
+ prompt_batch_size = 1
465
+ elif prompt is not None and isinstance(prompt, list):
466
+ prompt_batch_size = len(prompt)
467
+ elif prompt_embeds is not None:
468
+ prompt_batch_size = prompt_embeds.shape[0]
469
+ else:
470
+ raise ValueError("prompt or prompt_embeds are not valid")
471
+
472
+ if image_batch_size != 1 and image_batch_size != prompt_batch_size:
473
+ raise ValueError(
474
+ f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
475
+ )
476
+
477
+ def check_inputs(
478
+ self,
479
+ prompt,
480
+ image,
481
+ controlnet_conditioning_image,
482
+ height,
483
+ width,
484
+ callback_steps,
485
+ negative_prompt=None,
486
+ prompt_embeds=None,
487
+ negative_prompt_embeds=None,
488
+ strength=None,
489
+ controlnet_guidance_start=None,
490
+ controlnet_guidance_end=None,
491
+ controlnet_conditioning_scale=None,
492
+ ):
493
+ if height % 8 != 0 or width % 8 != 0:
494
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
495
+
496
+ if (callback_steps is None) or (
497
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
498
+ ):
499
+ raise ValueError(
500
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
501
+ f" {type(callback_steps)}."
502
+ )
503
+
504
+ if prompt is not None and prompt_embeds is not None:
505
+ raise ValueError(
506
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
507
+ " only forward one of the two."
508
+ )
509
+ elif prompt is None and prompt_embeds is None:
510
+ raise ValueError(
511
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
512
+ )
513
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
514
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
515
+
516
+ if negative_prompt is not None and negative_prompt_embeds is not None:
517
+ raise ValueError(
518
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
519
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
520
+ )
521
+
522
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
523
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
524
+ raise ValueError(
525
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
526
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
527
+ f" {negative_prompt_embeds.shape}."
528
+ )
529
+
530
+ # check controlnet condition image
531
+
532
+ if isinstance(self.controlnet, ControlNetModel):
533
+ self.check_controlnet_conditioning_image(controlnet_conditioning_image, prompt, prompt_embeds)
534
+ elif isinstance(self.controlnet, MultiControlNetModel):
535
+ if not isinstance(controlnet_conditioning_image, list):
536
+ raise TypeError("For multiple controlnets: `image` must be type `list`")
537
+
538
+ if len(controlnet_conditioning_image) != len(self.controlnet.nets):
539
+ raise ValueError(
540
+ "For multiple controlnets: `image` must have the same length as the number of controlnets."
541
+ )
542
+
543
+ for image_ in controlnet_conditioning_image:
544
+ self.check_controlnet_conditioning_image(image_, prompt, prompt_embeds)
545
+ else:
546
+ assert False
547
+
548
+ # Check `controlnet_conditioning_scale`
549
+
550
+ if isinstance(self.controlnet, ControlNetModel):
551
+ if not isinstance(controlnet_conditioning_scale, float):
552
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
553
+ elif isinstance(self.controlnet, MultiControlNetModel):
554
+ if isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(
555
+ self.controlnet.nets
556
+ ):
557
+ raise ValueError(
558
+ "For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
559
+ " the same length as the number of controlnets"
560
+ )
561
+ else:
562
+ assert False
563
+
564
+ if isinstance(image, torch.Tensor):
565
+ if image.ndim != 3 and image.ndim != 4:
566
+ raise ValueError("`image` must have 3 or 4 dimensions")
567
+
568
+ if image.ndim == 3:
569
+ image_batch_size = 1
570
+ image_channels, image_height, image_width = image.shape
571
+ elif image.ndim == 4:
572
+ image_batch_size, image_channels, image_height, image_width = image.shape
573
+ else:
574
+ assert False
575
+
576
+ if image_channels != 3:
577
+ raise ValueError("`image` must have 3 channels")
578
+
579
+ if image.min() < -1 or image.max() > 1:
580
+ raise ValueError("`image` should be in range [-1, 1]")
581
+
582
+ if self.vae.config.latent_channels != self.unet.config.in_channels:
583
+ raise ValueError(
584
+ f"The config of `pipeline.unet` expects {self.unet.config.in_channels} but received"
585
+ f" latent channels: {self.vae.config.latent_channels},"
586
+ f" Please verify the config of `pipeline.unet` and the `pipeline.vae`"
587
+ )
588
+
589
+ if strength < 0 or strength > 1:
590
+ raise ValueError(f"The value of `strength` should in [0.0, 1.0] but is {strength}")
591
+
592
+ if controlnet_guidance_start < 0 or controlnet_guidance_start > 1:
593
+ raise ValueError(
594
+ f"The value of `controlnet_guidance_start` should in [0.0, 1.0] but is {controlnet_guidance_start}"
595
+ )
596
+
597
+ if controlnet_guidance_end < 0 or controlnet_guidance_end > 1:
598
+ raise ValueError(
599
+ f"The value of `controlnet_guidance_end` should in [0.0, 1.0] but is {controlnet_guidance_end}"
600
+ )
601
+
602
+ if controlnet_guidance_start > controlnet_guidance_end:
603
+ raise ValueError(
604
+ "The value of `controlnet_guidance_start` should be less than `controlnet_guidance_end`, but got"
605
+ f" `controlnet_guidance_start` {controlnet_guidance_start} >= `controlnet_guidance_end` {controlnet_guidance_end}"
606
+ )
607
+
608
+ def get_timesteps(self, num_inference_steps, strength, device):
609
+ # get the original timestep using init_timestep
610
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
611
+
612
+ t_start = max(num_inference_steps - init_timestep, 0)
613
+ timesteps = self.scheduler.timesteps[t_start:]
614
+
615
+ return timesteps, num_inference_steps - t_start
616
+
617
+ def prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None):
618
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
619
+ raise ValueError(
620
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
621
+ )
622
+
623
+ image = image.to(device=device, dtype=dtype)
624
+
625
+ batch_size = batch_size * num_images_per_prompt
626
+ if isinstance(generator, list) and len(generator) != batch_size:
627
+ raise ValueError(
628
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
629
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
630
+ )
631
+
632
+ if isinstance(generator, list):
633
+ init_latents = [
634
+ self.vae.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(batch_size)
635
+ ]
636
+ init_latents = torch.cat(init_latents, dim=0)
637
+ else:
638
+ init_latents = self.vae.encode(image).latent_dist.sample(generator)
639
+
640
+ init_latents = self.vae.config.scaling_factor * init_latents
641
+
642
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
643
+ raise ValueError(
644
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
645
+ )
646
+ else:
647
+ init_latents = torch.cat([init_latents], dim=0)
648
+
649
+ shape = init_latents.shape
650
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
651
+
652
+ # get latents
653
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
654
+ latents = init_latents
655
+
656
+ return latents
657
+
658
+ def _default_height_width(self, height, width, image):
659
+ if isinstance(image, list):
660
+ image = image[0]
661
+
662
+ if height is None:
663
+ if isinstance(image, PIL.Image.Image):
664
+ height = image.height
665
+ elif isinstance(image, torch.Tensor):
666
+ height = image.shape[3]
667
+
668
+ height = (height // 8) * 8 # round down to nearest multiple of 8
669
+
670
+ if width is None:
671
+ if isinstance(image, PIL.Image.Image):
672
+ width = image.width
673
+ elif isinstance(image, torch.Tensor):
674
+ width = image.shape[2]
675
+
676
+ width = (width // 8) * 8 # round down to nearest multiple of 8
677
+
678
+ return height, width
679
+
680
+ @torch.no_grad()
681
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
682
+ def __call__(
683
+ self,
684
+ prompt: Union[str, List[str]] = None,
685
+ image: Union[torch.Tensor, PIL.Image.Image] = None,
686
+ controlnet_conditioning_image: Union[
687
+ torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]
688
+ ] = None,
689
+ strength: float = 0.8,
690
+ height: Optional[int] = None,
691
+ width: Optional[int] = None,
692
+ num_inference_steps: int = 50,
693
+ guidance_scale: float = 7.5,
694
+ negative_prompt: Optional[Union[str, List[str]]] = None,
695
+ num_images_per_prompt: Optional[int] = 1,
696
+ eta: float = 0.0,
697
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
698
+ latents: Optional[torch.FloatTensor] = None,
699
+ prompt_embeds: Optional[torch.FloatTensor] = None,
700
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
701
+ output_type: Optional[str] = "pil",
702
+ return_dict: bool = True,
703
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
704
+ callback_steps: int = 1,
705
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
706
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
707
+ controlnet_guidance_start: float = 0.0,
708
+ controlnet_guidance_end: float = 1.0,
709
+ ):
710
+ r"""
711
+ Function invoked when calling the pipeline for generation.
712
+
713
+ Args:
714
+ prompt (`str` or `List[str]`, *optional*):
715
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
716
+ instead.
717
+ image (`torch.Tensor` or `PIL.Image.Image`):
718
+ `Image`, or tensor representing an image batch which will be inpainted, *i.e.* parts of the image will
719
+ be masked out with `mask_image` and repainted according to `prompt`.
720
+ controlnet_conditioning_image (`torch.FloatTensor`, `PIL.Image.Image`, `List[torch.FloatTensor]` or `List[PIL.Image.Image]`):
721
+ The ControlNet input condition. ControlNet uses this input condition to generate guidance to Unet. If
722
+ the type is specified as `Torch.FloatTensor`, it is passed to ControlNet as is. PIL.Image.Image` can
723
+ also be accepted as an image. The control image is automatically resized to fit the output image.
724
+ strength (`float`, *optional*):
725
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
726
+ will be used as a starting point, adding more noise to it the larger the `strength`. The number of
727
+ denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
728
+ be maximum and the denoising process will run for the full number of iterations specified in
729
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
730
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
731
+ The height in pixels of the generated image.
732
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
733
+ The width in pixels of the generated image.
734
+ num_inference_steps (`int`, *optional*, defaults to 50):
735
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
736
+ expense of slower inference.
737
+ guidance_scale (`float`, *optional*, defaults to 7.5):
738
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
739
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
740
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
741
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
742
+ usually at the expense of lower image quality.
743
+ negative_prompt (`str` or `List[str]`, *optional*):
744
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
745
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
746
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
747
+ The number of images to generate per prompt.
748
+ eta (`float`, *optional*, defaults to 0.0):
749
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
750
+ [`schedulers.DDIMScheduler`], will be ignored for others.
751
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
752
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
753
+ to make generation deterministic.
754
+ latents (`torch.FloatTensor`, *optional*):
755
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
756
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
757
+ tensor will ge generated by sampling using the supplied random `generator`.
758
+ prompt_embeds (`torch.FloatTensor`, *optional*):
759
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
760
+ provided, text embeddings will be generated from `prompt` input argument.
761
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
762
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
763
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
764
+ argument.
765
+ output_type (`str`, *optional*, defaults to `"pil"`):
766
+ The output format of the generate image. Choose between
767
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
768
+ return_dict (`bool`, *optional*, defaults to `True`):
769
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
770
+ plain tuple.
771
+ callback (`Callable`, *optional*):
772
+ A function that will be called every `callback_steps` steps during inference. The function will be
773
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
774
+ callback_steps (`int`, *optional*, defaults to 1):
775
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
776
+ called at every step.
777
+ cross_attention_kwargs (`dict`, *optional*):
778
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
779
+ `self.processor` in
780
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
781
+ controlnet_conditioning_scale (`float`, *optional*, defaults to 1.0):
782
+ The outputs of the controlnet are multiplied by `controlnet_conditioning_scale` before they are added
783
+ to the residual in the original unet.
784
+ controlnet_guidance_start ('float', *optional*, defaults to 0.0):
785
+ The percentage of total steps the controlnet starts applying. Must be between 0 and 1.
786
+ controlnet_guidance_end ('float', *optional*, defaults to 1.0):
787
+ The percentage of total steps the controlnet ends applying. Must be between 0 and 1. Must be greater
788
+ than `controlnet_guidance_start`.
789
+
790
+ Examples:
791
+
792
+ Returns:
793
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
794
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
795
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
796
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
797
+ (nsfw) content, according to the `safety_checker`.
798
+ """
799
+ # 0. Default height and width to unet
800
+ height, width = self._default_height_width(height, width, controlnet_conditioning_image)
801
+
802
+ # 1. Check inputs. Raise error if not correct
803
+ self.check_inputs(
804
+ prompt,
805
+ image,
806
+ controlnet_conditioning_image,
807
+ height,
808
+ width,
809
+ callback_steps,
810
+ negative_prompt,
811
+ prompt_embeds,
812
+ negative_prompt_embeds,
813
+ strength,
814
+ controlnet_guidance_start,
815
+ controlnet_guidance_end,
816
+ controlnet_conditioning_scale,
817
+ )
818
+
819
+ # 2. Define call parameters
820
+ if prompt is not None and isinstance(prompt, str):
821
+ batch_size = 1
822
+ elif prompt is not None and isinstance(prompt, list):
823
+ batch_size = len(prompt)
824
+ else:
825
+ batch_size = prompt_embeds.shape[0]
826
+
827
+ device = self._execution_device
828
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
829
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
830
+ # corresponds to doing no classifier free guidance.
831
+ do_classifier_free_guidance = guidance_scale > 1.0
832
+
833
+ if isinstance(self.controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
834
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(self.controlnet.nets)
835
+
836
+ # 3. Encode input prompt
837
+ prompt_embeds = self._encode_prompt(
838
+ prompt,
839
+ device,
840
+ num_images_per_prompt,
841
+ do_classifier_free_guidance,
842
+ negative_prompt,
843
+ prompt_embeds=prompt_embeds,
844
+ negative_prompt_embeds=negative_prompt_embeds,
845
+ )
846
+
847
+ # 4. Prepare image, and controlnet_conditioning_image
848
+ image = prepare_image(image)
849
+
850
+ # condition image(s)
851
+ if isinstance(self.controlnet, ControlNetModel):
852
+ controlnet_conditioning_image = prepare_controlnet_conditioning_image(
853
+ controlnet_conditioning_image=controlnet_conditioning_image,
854
+ width=width,
855
+ height=height,
856
+ batch_size=batch_size * num_images_per_prompt,
857
+ num_images_per_prompt=num_images_per_prompt,
858
+ device=device,
859
+ dtype=self.controlnet.dtype,
860
+ do_classifier_free_guidance=do_classifier_free_guidance,
861
+ )
862
+ elif isinstance(self.controlnet, MultiControlNetModel):
863
+ controlnet_conditioning_images = []
864
+
865
+ for image_ in controlnet_conditioning_image:
866
+ image_ = prepare_controlnet_conditioning_image(
867
+ controlnet_conditioning_image=image_,
868
+ width=width,
869
+ height=height,
870
+ batch_size=batch_size * num_images_per_prompt,
871
+ num_images_per_prompt=num_images_per_prompt,
872
+ device=device,
873
+ dtype=self.controlnet.dtype,
874
+ do_classifier_free_guidance=do_classifier_free_guidance,
875
+ )
876
+
877
+ controlnet_conditioning_images.append(image_)
878
+
879
+ controlnet_conditioning_image = controlnet_conditioning_images
880
+ else:
881
+ assert False
882
+
883
+ # 5. Prepare timesteps
884
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
885
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
886
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
887
+
888
+ # 6. Prepare latent variables
889
+ latents = self.prepare_latents(
890
+ image,
891
+ latent_timestep,
892
+ batch_size,
893
+ num_images_per_prompt,
894
+ prompt_embeds.dtype,
895
+ device,
896
+ generator,
897
+ )
898
+
899
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
900
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
901
+
902
+ # 8. Denoising loop
903
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
904
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
905
+ for i, t in enumerate(timesteps):
906
+ # expand the latents if we are doing classifier free guidance
907
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
908
+
909
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
910
+
911
+ # compute the percentage of total steps we are at
912
+ current_sampling_percent = i / len(timesteps)
913
+
914
+ if (
915
+ current_sampling_percent < controlnet_guidance_start
916
+ or current_sampling_percent > controlnet_guidance_end
917
+ ):
918
+ # do not apply the controlnet
919
+ down_block_res_samples = None
920
+ mid_block_res_sample = None
921
+ else:
922
+ # apply the controlnet
923
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
924
+ latent_model_input,
925
+ t,
926
+ encoder_hidden_states=prompt_embeds,
927
+ controlnet_cond=controlnet_conditioning_image,
928
+ conditioning_scale=controlnet_conditioning_scale,
929
+ return_dict=False,
930
+ )
931
+
932
+ # predict the noise residual
933
+ noise_pred = self.unet(
934
+ latent_model_input,
935
+ t,
936
+ encoder_hidden_states=prompt_embeds,
937
+ cross_attention_kwargs=cross_attention_kwargs,
938
+ down_block_additional_residuals=down_block_res_samples,
939
+ mid_block_additional_residual=mid_block_res_sample,
940
+ ).sample
941
+
942
+ # perform guidance
943
+ if do_classifier_free_guidance:
944
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
945
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
946
+
947
+ # compute the previous noisy sample x_t -> x_t-1
948
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
949
+
950
+ # call the callback, if provided
951
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
952
+ progress_bar.update()
953
+ if callback is not None and i % callback_steps == 0:
954
+ step_idx = i // getattr(self.scheduler, "order", 1)
955
+ callback(step_idx, t, latents)
956
+
957
+ # If we do sequential model offloading, let's offload unet and controlnet
958
+ # manually for max memory savings
959
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
960
+ self.unet.to("cpu")
961
+ self.controlnet.to("cpu")
962
+ torch.cuda.empty_cache()
963
+
964
+ if output_type == "latent":
965
+ image = latents
966
+ has_nsfw_concept = None
967
+ elif output_type == "pil":
968
+ # 8. Post-processing
969
+ image = self.decode_latents(latents)
970
+
971
+ # 9. Run safety checker
972
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
973
+
974
+ # 10. Convert to PIL
975
+ image = self.numpy_to_pil(image)
976
+ else:
977
+ # 8. Post-processing
978
+ image = self.decode_latents(latents)
979
+
980
+ # 9. Run safety checker
981
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
982
+
983
+ # Offload last model to CPU
984
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
985
+ self.final_offload_hook.offload()
986
+
987
+ if not return_dict:
988
+ return (image, has_nsfw_concept)
989
+
990
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.22.0/stable_diffusion_controlnet_inpaint.py ADDED
@@ -0,0 +1,1139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inspired by: https://github.com/haofanwang/ControlNet-for-Diffusers/
2
+
3
+ import inspect
4
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
5
+
6
+ import numpy as np
7
+ import PIL.Image
8
+ import torch
9
+ import torch.nn.functional as F
10
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
11
+
12
+ from diffusers import AutoencoderKL, ControlNetModel, DiffusionPipeline, UNet2DConditionModel, logging
13
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput, StableDiffusionSafetyChecker
14
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel
15
+ from diffusers.schedulers import KarrasDiffusionSchedulers
16
+ from diffusers.utils import (
17
+ PIL_INTERPOLATION,
18
+ is_accelerate_available,
19
+ is_accelerate_version,
20
+ replace_example_docstring,
21
+ )
22
+ from diffusers.utils.torch_utils import randn_tensor
23
+
24
+
25
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
26
+
27
+ EXAMPLE_DOC_STRING = """
28
+ Examples:
29
+ ```py
30
+ >>> import numpy as np
31
+ >>> import torch
32
+ >>> from PIL import Image
33
+ >>> from stable_diffusion_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline
34
+
35
+ >>> from transformers import AutoImageProcessor, UperNetForSemanticSegmentation
36
+ >>> from diffusers import ControlNetModel, UniPCMultistepScheduler
37
+ >>> from diffusers.utils import load_image
38
+
39
+ >>> def ade_palette():
40
+ return [[120, 120, 120], [180, 120, 120], [6, 230, 230], [80, 50, 50],
41
+ [4, 200, 3], [120, 120, 80], [140, 140, 140], [204, 5, 255],
42
+ [230, 230, 230], [4, 250, 7], [224, 5, 255], [235, 255, 7],
43
+ [150, 5, 61], [120, 120, 70], [8, 255, 51], [255, 6, 82],
44
+ [143, 255, 140], [204, 255, 4], [255, 51, 7], [204, 70, 3],
45
+ [0, 102, 200], [61, 230, 250], [255, 6, 51], [11, 102, 255],
46
+ [255, 7, 71], [255, 9, 224], [9, 7, 230], [220, 220, 220],
47
+ [255, 9, 92], [112, 9, 255], [8, 255, 214], [7, 255, 224],
48
+ [255, 184, 6], [10, 255, 71], [255, 41, 10], [7, 255, 255],
49
+ [224, 255, 8], [102, 8, 255], [255, 61, 6], [255, 194, 7],
50
+ [255, 122, 8], [0, 255, 20], [255, 8, 41], [255, 5, 153],
51
+ [6, 51, 255], [235, 12, 255], [160, 150, 20], [0, 163, 255],
52
+ [140, 140, 140], [250, 10, 15], [20, 255, 0], [31, 255, 0],
53
+ [255, 31, 0], [255, 224, 0], [153, 255, 0], [0, 0, 255],
54
+ [255, 71, 0], [0, 235, 255], [0, 173, 255], [31, 0, 255],
55
+ [11, 200, 200], [255, 82, 0], [0, 255, 245], [0, 61, 255],
56
+ [0, 255, 112], [0, 255, 133], [255, 0, 0], [255, 163, 0],
57
+ [255, 102, 0], [194, 255, 0], [0, 143, 255], [51, 255, 0],
58
+ [0, 82, 255], [0, 255, 41], [0, 255, 173], [10, 0, 255],
59
+ [173, 255, 0], [0, 255, 153], [255, 92, 0], [255, 0, 255],
60
+ [255, 0, 245], [255, 0, 102], [255, 173, 0], [255, 0, 20],
61
+ [255, 184, 184], [0, 31, 255], [0, 255, 61], [0, 71, 255],
62
+ [255, 0, 204], [0, 255, 194], [0, 255, 82], [0, 10, 255],
63
+ [0, 112, 255], [51, 0, 255], [0, 194, 255], [0, 122, 255],
64
+ [0, 255, 163], [255, 153, 0], [0, 255, 10], [255, 112, 0],
65
+ [143, 255, 0], [82, 0, 255], [163, 255, 0], [255, 235, 0],
66
+ [8, 184, 170], [133, 0, 255], [0, 255, 92], [184, 0, 255],
67
+ [255, 0, 31], [0, 184, 255], [0, 214, 255], [255, 0, 112],
68
+ [92, 255, 0], [0, 224, 255], [112, 224, 255], [70, 184, 160],
69
+ [163, 0, 255], [153, 0, 255], [71, 255, 0], [255, 0, 163],
70
+ [255, 204, 0], [255, 0, 143], [0, 255, 235], [133, 255, 0],
71
+ [255, 0, 235], [245, 0, 255], [255, 0, 122], [255, 245, 0],
72
+ [10, 190, 212], [214, 255, 0], [0, 204, 255], [20, 0, 255],
73
+ [255, 255, 0], [0, 153, 255], [0, 41, 255], [0, 255, 204],
74
+ [41, 0, 255], [41, 255, 0], [173, 0, 255], [0, 245, 255],
75
+ [71, 0, 255], [122, 0, 255], [0, 255, 184], [0, 92, 255],
76
+ [184, 255, 0], [0, 133, 255], [255, 214, 0], [25, 194, 194],
77
+ [102, 255, 0], [92, 0, 255]]
78
+
79
+ >>> image_processor = AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-small")
80
+ >>> image_segmentor = UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-small")
81
+
82
+ >>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-seg", torch_dtype=torch.float16)
83
+
84
+ >>> pipe = StableDiffusionControlNetInpaintPipeline.from_pretrained(
85
+ "runwayml/stable-diffusion-inpainting", controlnet=controlnet, safety_checker=None, torch_dtype=torch.float16
86
+ )
87
+
88
+ >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
89
+ >>> pipe.enable_xformers_memory_efficient_attention()
90
+ >>> pipe.enable_model_cpu_offload()
91
+
92
+ >>> def image_to_seg(image):
93
+ pixel_values = image_processor(image, return_tensors="pt").pixel_values
94
+ with torch.no_grad():
95
+ outputs = image_segmentor(pixel_values)
96
+ seg = image_processor.post_process_semantic_segmentation(outputs, target_sizes=[image.size[::-1]])[0]
97
+ color_seg = np.zeros((seg.shape[0], seg.shape[1], 3), dtype=np.uint8) # height, width, 3
98
+ palette = np.array(ade_palette())
99
+ for label, color in enumerate(palette):
100
+ color_seg[seg == label, :] = color
101
+ color_seg = color_seg.astype(np.uint8)
102
+ seg_image = Image.fromarray(color_seg)
103
+ return seg_image
104
+
105
+ >>> image = load_image(
106
+ "https://github.com/CompVis/latent-diffusion/raw/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
107
+ )
108
+
109
+ >>> mask_image = load_image(
110
+ "https://github.com/CompVis/latent-diffusion/raw/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
111
+ )
112
+
113
+ >>> controlnet_conditioning_image = image_to_seg(image)
114
+
115
+ >>> image = pipe(
116
+ "Face of a yellow cat, high resolution, sitting on a park bench",
117
+ image,
118
+ mask_image,
119
+ controlnet_conditioning_image,
120
+ num_inference_steps=20,
121
+ ).images[0]
122
+
123
+ >>> image.save("out.png")
124
+ ```
125
+ """
126
+
127
+
128
+ def prepare_image(image):
129
+ if isinstance(image, torch.Tensor):
130
+ # Batch single image
131
+ if image.ndim == 3:
132
+ image = image.unsqueeze(0)
133
+
134
+ image = image.to(dtype=torch.float32)
135
+ else:
136
+ # preprocess image
137
+ if isinstance(image, (PIL.Image.Image, np.ndarray)):
138
+ image = [image]
139
+
140
+ if isinstance(image, list) and isinstance(image[0], PIL.Image.Image):
141
+ image = [np.array(i.convert("RGB"))[None, :] for i in image]
142
+ image = np.concatenate(image, axis=0)
143
+ elif isinstance(image, list) and isinstance(image[0], np.ndarray):
144
+ image = np.concatenate([i[None, :] for i in image], axis=0)
145
+
146
+ image = image.transpose(0, 3, 1, 2)
147
+ image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
148
+
149
+ return image
150
+
151
+
152
+ def prepare_mask_image(mask_image):
153
+ if isinstance(mask_image, torch.Tensor):
154
+ if mask_image.ndim == 2:
155
+ # Batch and add channel dim for single mask
156
+ mask_image = mask_image.unsqueeze(0).unsqueeze(0)
157
+ elif mask_image.ndim == 3 and mask_image.shape[0] == 1:
158
+ # Single mask, the 0'th dimension is considered to be
159
+ # the existing batch size of 1
160
+ mask_image = mask_image.unsqueeze(0)
161
+ elif mask_image.ndim == 3 and mask_image.shape[0] != 1:
162
+ # Batch of mask, the 0'th dimension is considered to be
163
+ # the batching dimension
164
+ mask_image = mask_image.unsqueeze(1)
165
+
166
+ # Binarize mask
167
+ mask_image[mask_image < 0.5] = 0
168
+ mask_image[mask_image >= 0.5] = 1
169
+ else:
170
+ # preprocess mask
171
+ if isinstance(mask_image, (PIL.Image.Image, np.ndarray)):
172
+ mask_image = [mask_image]
173
+
174
+ if isinstance(mask_image, list) and isinstance(mask_image[0], PIL.Image.Image):
175
+ mask_image = np.concatenate([np.array(m.convert("L"))[None, None, :] for m in mask_image], axis=0)
176
+ mask_image = mask_image.astype(np.float32) / 255.0
177
+ elif isinstance(mask_image, list) and isinstance(mask_image[0], np.ndarray):
178
+ mask_image = np.concatenate([m[None, None, :] for m in mask_image], axis=0)
179
+
180
+ mask_image[mask_image < 0.5] = 0
181
+ mask_image[mask_image >= 0.5] = 1
182
+ mask_image = torch.from_numpy(mask_image)
183
+
184
+ return mask_image
185
+
186
+
187
+ def prepare_controlnet_conditioning_image(
188
+ controlnet_conditioning_image,
189
+ width,
190
+ height,
191
+ batch_size,
192
+ num_images_per_prompt,
193
+ device,
194
+ dtype,
195
+ do_classifier_free_guidance,
196
+ ):
197
+ if not isinstance(controlnet_conditioning_image, torch.Tensor):
198
+ if isinstance(controlnet_conditioning_image, PIL.Image.Image):
199
+ controlnet_conditioning_image = [controlnet_conditioning_image]
200
+
201
+ if isinstance(controlnet_conditioning_image[0], PIL.Image.Image):
202
+ controlnet_conditioning_image = [
203
+ np.array(i.resize((width, height), resample=PIL_INTERPOLATION["lanczos"]))[None, :]
204
+ for i in controlnet_conditioning_image
205
+ ]
206
+ controlnet_conditioning_image = np.concatenate(controlnet_conditioning_image, axis=0)
207
+ controlnet_conditioning_image = np.array(controlnet_conditioning_image).astype(np.float32) / 255.0
208
+ controlnet_conditioning_image = controlnet_conditioning_image.transpose(0, 3, 1, 2)
209
+ controlnet_conditioning_image = torch.from_numpy(controlnet_conditioning_image)
210
+ elif isinstance(controlnet_conditioning_image[0], torch.Tensor):
211
+ controlnet_conditioning_image = torch.cat(controlnet_conditioning_image, dim=0)
212
+
213
+ image_batch_size = controlnet_conditioning_image.shape[0]
214
+
215
+ if image_batch_size == 1:
216
+ repeat_by = batch_size
217
+ else:
218
+ # image batch size is the same as prompt batch size
219
+ repeat_by = num_images_per_prompt
220
+
221
+ controlnet_conditioning_image = controlnet_conditioning_image.repeat_interleave(repeat_by, dim=0)
222
+
223
+ controlnet_conditioning_image = controlnet_conditioning_image.to(device=device, dtype=dtype)
224
+
225
+ if do_classifier_free_guidance:
226
+ controlnet_conditioning_image = torch.cat([controlnet_conditioning_image] * 2)
227
+
228
+ return controlnet_conditioning_image
229
+
230
+
231
+ class StableDiffusionControlNetInpaintPipeline(DiffusionPipeline):
232
+ """
233
+ Inspired by: https://github.com/haofanwang/ControlNet-for-Diffusers/
234
+ """
235
+
236
+ _optional_components = ["safety_checker", "feature_extractor"]
237
+
238
+ def __init__(
239
+ self,
240
+ vae: AutoencoderKL,
241
+ text_encoder: CLIPTextModel,
242
+ tokenizer: CLIPTokenizer,
243
+ unet: UNet2DConditionModel,
244
+ controlnet: Union[ControlNetModel, List[ControlNetModel], Tuple[ControlNetModel], MultiControlNetModel],
245
+ scheduler: KarrasDiffusionSchedulers,
246
+ safety_checker: StableDiffusionSafetyChecker,
247
+ feature_extractor: CLIPImageProcessor,
248
+ requires_safety_checker: bool = True,
249
+ ):
250
+ super().__init__()
251
+
252
+ if safety_checker is None and requires_safety_checker:
253
+ logger.warning(
254
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
255
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
256
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
257
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
258
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
259
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
260
+ )
261
+
262
+ if safety_checker is not None and feature_extractor is None:
263
+ raise ValueError(
264
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
265
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
266
+ )
267
+
268
+ if isinstance(controlnet, (list, tuple)):
269
+ controlnet = MultiControlNetModel(controlnet)
270
+
271
+ self.register_modules(
272
+ vae=vae,
273
+ text_encoder=text_encoder,
274
+ tokenizer=tokenizer,
275
+ unet=unet,
276
+ controlnet=controlnet,
277
+ scheduler=scheduler,
278
+ safety_checker=safety_checker,
279
+ feature_extractor=feature_extractor,
280
+ )
281
+
282
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
283
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
284
+
285
+ def enable_vae_slicing(self):
286
+ r"""
287
+ Enable sliced VAE decoding.
288
+
289
+ When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
290
+ steps. This is useful to save some memory and allow larger batch sizes.
291
+ """
292
+ self.vae.enable_slicing()
293
+
294
+ def disable_vae_slicing(self):
295
+ r"""
296
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to
297
+ computing decoding in one step.
298
+ """
299
+ self.vae.disable_slicing()
300
+
301
+ def enable_sequential_cpu_offload(self, gpu_id=0):
302
+ r"""
303
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
304
+ text_encoder, vae, controlnet, and safety checker have their state dicts saved to CPU and then are moved to a
305
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
306
+ Note that offloading happens on a submodule basis. Memory savings are higher than with
307
+ `enable_model_cpu_offload`, but performance is lower.
308
+ """
309
+ if is_accelerate_available():
310
+ from accelerate import cpu_offload
311
+ else:
312
+ raise ImportError("Please install accelerate via `pip install accelerate`")
313
+
314
+ device = torch.device(f"cuda:{gpu_id}")
315
+
316
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.controlnet]:
317
+ cpu_offload(cpu_offloaded_model, device)
318
+
319
+ if self.safety_checker is not None:
320
+ cpu_offload(self.safety_checker, execution_device=device, offload_buffers=True)
321
+
322
+ def enable_model_cpu_offload(self, gpu_id=0):
323
+ r"""
324
+ Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
325
+ to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
326
+ method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
327
+ `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
328
+ """
329
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
330
+ from accelerate import cpu_offload_with_hook
331
+ else:
332
+ raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")
333
+
334
+ device = torch.device(f"cuda:{gpu_id}")
335
+
336
+ hook = None
337
+ for cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]:
338
+ _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
339
+
340
+ if self.safety_checker is not None:
341
+ # the safety checker can offload the vae again
342
+ _, hook = cpu_offload_with_hook(self.safety_checker, device, prev_module_hook=hook)
343
+
344
+ # control net hook has be manually offloaded as it alternates with unet
345
+ cpu_offload_with_hook(self.controlnet, device)
346
+
347
+ # We'll offload the last model manually.
348
+ self.final_offload_hook = hook
349
+
350
+ @property
351
+ def _execution_device(self):
352
+ r"""
353
+ Returns the device on which the pipeline's models will be executed. After calling
354
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
355
+ hooks.
356
+ """
357
+ if not hasattr(self.unet, "_hf_hook"):
358
+ return self.device
359
+ for module in self.unet.modules():
360
+ if (
361
+ hasattr(module, "_hf_hook")
362
+ and hasattr(module._hf_hook, "execution_device")
363
+ and module._hf_hook.execution_device is not None
364
+ ):
365
+ return torch.device(module._hf_hook.execution_device)
366
+ return self.device
367
+
368
+ def _encode_prompt(
369
+ self,
370
+ prompt,
371
+ device,
372
+ num_images_per_prompt,
373
+ do_classifier_free_guidance,
374
+ negative_prompt=None,
375
+ prompt_embeds: Optional[torch.FloatTensor] = None,
376
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
377
+ ):
378
+ r"""
379
+ Encodes the prompt into text encoder hidden states.
380
+
381
+ Args:
382
+ prompt (`str` or `List[str]`, *optional*):
383
+ prompt to be encoded
384
+ device: (`torch.device`):
385
+ torch device
386
+ num_images_per_prompt (`int`):
387
+ number of images that should be generated per prompt
388
+ do_classifier_free_guidance (`bool`):
389
+ whether to use classifier free guidance or not
390
+ negative_prompt (`str` or `List[str]`, *optional*):
391
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds` instead.
392
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
393
+ prompt_embeds (`torch.FloatTensor`, *optional*):
394
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
395
+ provided, text embeddings will be generated from `prompt` input argument.
396
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
397
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
398
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
399
+ argument.
400
+ """
401
+ if prompt is not None and isinstance(prompt, str):
402
+ batch_size = 1
403
+ elif prompt is not None and isinstance(prompt, list):
404
+ batch_size = len(prompt)
405
+ else:
406
+ batch_size = prompt_embeds.shape[0]
407
+
408
+ if prompt_embeds is None:
409
+ text_inputs = self.tokenizer(
410
+ prompt,
411
+ padding="max_length",
412
+ max_length=self.tokenizer.model_max_length,
413
+ truncation=True,
414
+ return_tensors="pt",
415
+ )
416
+ text_input_ids = text_inputs.input_ids
417
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
418
+
419
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
420
+ text_input_ids, untruncated_ids
421
+ ):
422
+ removed_text = self.tokenizer.batch_decode(
423
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
424
+ )
425
+ logger.warning(
426
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
427
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
428
+ )
429
+
430
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
431
+ attention_mask = text_inputs.attention_mask.to(device)
432
+ else:
433
+ attention_mask = None
434
+
435
+ prompt_embeds = self.text_encoder(
436
+ text_input_ids.to(device),
437
+ attention_mask=attention_mask,
438
+ )
439
+ prompt_embeds = prompt_embeds[0]
440
+
441
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
442
+
443
+ bs_embed, seq_len, _ = prompt_embeds.shape
444
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
445
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
446
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
447
+
448
+ # get unconditional embeddings for classifier free guidance
449
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
450
+ uncond_tokens: List[str]
451
+ if negative_prompt is None:
452
+ uncond_tokens = [""] * batch_size
453
+ elif type(prompt) is not type(negative_prompt):
454
+ raise TypeError(
455
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
456
+ f" {type(prompt)}."
457
+ )
458
+ elif isinstance(negative_prompt, str):
459
+ uncond_tokens = [negative_prompt]
460
+ elif batch_size != len(negative_prompt):
461
+ raise ValueError(
462
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
463
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
464
+ " the batch size of `prompt`."
465
+ )
466
+ else:
467
+ uncond_tokens = negative_prompt
468
+
469
+ max_length = prompt_embeds.shape[1]
470
+ uncond_input = self.tokenizer(
471
+ uncond_tokens,
472
+ padding="max_length",
473
+ max_length=max_length,
474
+ truncation=True,
475
+ return_tensors="pt",
476
+ )
477
+
478
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
479
+ attention_mask = uncond_input.attention_mask.to(device)
480
+ else:
481
+ attention_mask = None
482
+
483
+ negative_prompt_embeds = self.text_encoder(
484
+ uncond_input.input_ids.to(device),
485
+ attention_mask=attention_mask,
486
+ )
487
+ negative_prompt_embeds = negative_prompt_embeds[0]
488
+
489
+ if do_classifier_free_guidance:
490
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
491
+ seq_len = negative_prompt_embeds.shape[1]
492
+
493
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
494
+
495
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
496
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
497
+
498
+ # For classifier free guidance, we need to do two forward passes.
499
+ # Here we concatenate the unconditional and text embeddings into a single batch
500
+ # to avoid doing two forward passes
501
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
502
+
503
+ return prompt_embeds
504
+
505
+ def run_safety_checker(self, image, device, dtype):
506
+ if self.safety_checker is not None:
507
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
508
+ image, has_nsfw_concept = self.safety_checker(
509
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
510
+ )
511
+ else:
512
+ has_nsfw_concept = None
513
+ return image, has_nsfw_concept
514
+
515
+ def decode_latents(self, latents):
516
+ latents = 1 / self.vae.config.scaling_factor * latents
517
+ image = self.vae.decode(latents).sample
518
+ image = (image / 2 + 0.5).clamp(0, 1)
519
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
520
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
521
+ return image
522
+
523
+ def prepare_extra_step_kwargs(self, generator, eta):
524
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
525
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
526
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
527
+ # and should be between [0, 1]
528
+
529
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
530
+ extra_step_kwargs = {}
531
+ if accepts_eta:
532
+ extra_step_kwargs["eta"] = eta
533
+
534
+ # check if the scheduler accepts generator
535
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
536
+ if accepts_generator:
537
+ extra_step_kwargs["generator"] = generator
538
+ return extra_step_kwargs
539
+
540
+ def check_controlnet_conditioning_image(self, image, prompt, prompt_embeds):
541
+ image_is_pil = isinstance(image, PIL.Image.Image)
542
+ image_is_tensor = isinstance(image, torch.Tensor)
543
+ image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
544
+ image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
545
+
546
+ if not image_is_pil and not image_is_tensor and not image_is_pil_list and not image_is_tensor_list:
547
+ raise TypeError(
548
+ "image must be passed and be one of PIL image, torch tensor, list of PIL images, or list of torch tensors"
549
+ )
550
+
551
+ if image_is_pil:
552
+ image_batch_size = 1
553
+ elif image_is_tensor:
554
+ image_batch_size = image.shape[0]
555
+ elif image_is_pil_list:
556
+ image_batch_size = len(image)
557
+ elif image_is_tensor_list:
558
+ image_batch_size = len(image)
559
+ else:
560
+ raise ValueError("controlnet condition image is not valid")
561
+
562
+ if prompt is not None and isinstance(prompt, str):
563
+ prompt_batch_size = 1
564
+ elif prompt is not None and isinstance(prompt, list):
565
+ prompt_batch_size = len(prompt)
566
+ elif prompt_embeds is not None:
567
+ prompt_batch_size = prompt_embeds.shape[0]
568
+ else:
569
+ raise ValueError("prompt or prompt_embeds are not valid")
570
+
571
+ if image_batch_size != 1 and image_batch_size != prompt_batch_size:
572
+ raise ValueError(
573
+ f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
574
+ )
575
+
576
+ def check_inputs(
577
+ self,
578
+ prompt,
579
+ image,
580
+ mask_image,
581
+ controlnet_conditioning_image,
582
+ height,
583
+ width,
584
+ callback_steps,
585
+ negative_prompt=None,
586
+ prompt_embeds=None,
587
+ negative_prompt_embeds=None,
588
+ controlnet_conditioning_scale=None,
589
+ ):
590
+ if height % 8 != 0 or width % 8 != 0:
591
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
592
+
593
+ if (callback_steps is None) or (
594
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
595
+ ):
596
+ raise ValueError(
597
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
598
+ f" {type(callback_steps)}."
599
+ )
600
+
601
+ if prompt is not None and prompt_embeds is not None:
602
+ raise ValueError(
603
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
604
+ " only forward one of the two."
605
+ )
606
+ elif prompt is None and prompt_embeds is None:
607
+ raise ValueError(
608
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
609
+ )
610
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
611
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
612
+
613
+ if negative_prompt is not None and negative_prompt_embeds is not None:
614
+ raise ValueError(
615
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
616
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
617
+ )
618
+
619
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
620
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
621
+ raise ValueError(
622
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
623
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
624
+ f" {negative_prompt_embeds.shape}."
625
+ )
626
+
627
+ # check controlnet condition image
628
+ if isinstance(self.controlnet, ControlNetModel):
629
+ self.check_controlnet_conditioning_image(controlnet_conditioning_image, prompt, prompt_embeds)
630
+ elif isinstance(self.controlnet, MultiControlNetModel):
631
+ if not isinstance(controlnet_conditioning_image, list):
632
+ raise TypeError("For multiple controlnets: `image` must be type `list`")
633
+ if len(controlnet_conditioning_image) != len(self.controlnet.nets):
634
+ raise ValueError(
635
+ "For multiple controlnets: `image` must have the same length as the number of controlnets."
636
+ )
637
+ for image_ in controlnet_conditioning_image:
638
+ self.check_controlnet_conditioning_image(image_, prompt, prompt_embeds)
639
+ else:
640
+ assert False
641
+
642
+ # Check `controlnet_conditioning_scale`
643
+ if isinstance(self.controlnet, ControlNetModel):
644
+ if not isinstance(controlnet_conditioning_scale, float):
645
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
646
+ elif isinstance(self.controlnet, MultiControlNetModel):
647
+ if isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(
648
+ self.controlnet.nets
649
+ ):
650
+ raise ValueError(
651
+ "For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
652
+ " the same length as the number of controlnets"
653
+ )
654
+ else:
655
+ assert False
656
+
657
+ if isinstance(image, torch.Tensor) and not isinstance(mask_image, torch.Tensor):
658
+ raise TypeError("if `image` is a tensor, `mask_image` must also be a tensor")
659
+
660
+ if isinstance(image, PIL.Image.Image) and not isinstance(mask_image, PIL.Image.Image):
661
+ raise TypeError("if `image` is a PIL image, `mask_image` must also be a PIL image")
662
+
663
+ if isinstance(image, torch.Tensor):
664
+ if image.ndim != 3 and image.ndim != 4:
665
+ raise ValueError("`image` must have 3 or 4 dimensions")
666
+
667
+ if mask_image.ndim != 2 and mask_image.ndim != 3 and mask_image.ndim != 4:
668
+ raise ValueError("`mask_image` must have 2, 3, or 4 dimensions")
669
+
670
+ if image.ndim == 3:
671
+ image_batch_size = 1
672
+ image_channels, image_height, image_width = image.shape
673
+ elif image.ndim == 4:
674
+ image_batch_size, image_channels, image_height, image_width = image.shape
675
+ else:
676
+ assert False
677
+
678
+ if mask_image.ndim == 2:
679
+ mask_image_batch_size = 1
680
+ mask_image_channels = 1
681
+ mask_image_height, mask_image_width = mask_image.shape
682
+ elif mask_image.ndim == 3:
683
+ mask_image_channels = 1
684
+ mask_image_batch_size, mask_image_height, mask_image_width = mask_image.shape
685
+ elif mask_image.ndim == 4:
686
+ mask_image_batch_size, mask_image_channels, mask_image_height, mask_image_width = mask_image.shape
687
+
688
+ if image_channels != 3:
689
+ raise ValueError("`image` must have 3 channels")
690
+
691
+ if mask_image_channels != 1:
692
+ raise ValueError("`mask_image` must have 1 channel")
693
+
694
+ if image_batch_size != mask_image_batch_size:
695
+ raise ValueError("`image` and `mask_image` mush have the same batch sizes")
696
+
697
+ if image_height != mask_image_height or image_width != mask_image_width:
698
+ raise ValueError("`image` and `mask_image` must have the same height and width dimensions")
699
+
700
+ if image.min() < -1 or image.max() > 1:
701
+ raise ValueError("`image` should be in range [-1, 1]")
702
+
703
+ if mask_image.min() < 0 or mask_image.max() > 1:
704
+ raise ValueError("`mask_image` should be in range [0, 1]")
705
+ else:
706
+ mask_image_channels = 1
707
+ image_channels = 3
708
+
709
+ single_image_latent_channels = self.vae.config.latent_channels
710
+
711
+ total_latent_channels = single_image_latent_channels * 2 + mask_image_channels
712
+
713
+ if total_latent_channels != self.unet.config.in_channels:
714
+ raise ValueError(
715
+ f"The config of `pipeline.unet` expects {self.unet.config.in_channels} but received"
716
+ f" non inpainting latent channels: {single_image_latent_channels},"
717
+ f" mask channels: {mask_image_channels}, and masked image channels: {single_image_latent_channels}."
718
+ f" Please verify the config of `pipeline.unet` and the `mask_image` and `image` inputs."
719
+ )
720
+
721
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
722
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
723
+ if isinstance(generator, list) and len(generator) != batch_size:
724
+ raise ValueError(
725
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
726
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
727
+ )
728
+
729
+ if latents is None:
730
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
731
+ else:
732
+ latents = latents.to(device)
733
+
734
+ # scale the initial noise by the standard deviation required by the scheduler
735
+ latents = latents * self.scheduler.init_noise_sigma
736
+
737
+ return latents
738
+
739
+ def prepare_mask_latents(self, mask_image, batch_size, height, width, dtype, device, do_classifier_free_guidance):
740
+ # resize the mask to latents shape as we concatenate the mask to the latents
741
+ # we do that before converting to dtype to avoid breaking in case we're using cpu_offload
742
+ # and half precision
743
+ mask_image = F.interpolate(mask_image, size=(height // self.vae_scale_factor, width // self.vae_scale_factor))
744
+ mask_image = mask_image.to(device=device, dtype=dtype)
745
+
746
+ # duplicate mask for each generation per prompt, using mps friendly method
747
+ if mask_image.shape[0] < batch_size:
748
+ if not batch_size % mask_image.shape[0] == 0:
749
+ raise ValueError(
750
+ "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to"
751
+ f" a total batch size of {batch_size}, but {mask_image.shape[0]} masks were passed. Make sure the number"
752
+ " of masks that you pass is divisible by the total requested batch size."
753
+ )
754
+ mask_image = mask_image.repeat(batch_size // mask_image.shape[0], 1, 1, 1)
755
+
756
+ mask_image = torch.cat([mask_image] * 2) if do_classifier_free_guidance else mask_image
757
+
758
+ mask_image_latents = mask_image
759
+
760
+ return mask_image_latents
761
+
762
+ def prepare_masked_image_latents(
763
+ self, masked_image, batch_size, height, width, dtype, device, generator, do_classifier_free_guidance
764
+ ):
765
+ masked_image = masked_image.to(device=device, dtype=dtype)
766
+
767
+ # encode the mask image into latents space so we can concatenate it to the latents
768
+ if isinstance(generator, list):
769
+ masked_image_latents = [
770
+ self.vae.encode(masked_image[i : i + 1]).latent_dist.sample(generator=generator[i])
771
+ for i in range(batch_size)
772
+ ]
773
+ masked_image_latents = torch.cat(masked_image_latents, dim=0)
774
+ else:
775
+ masked_image_latents = self.vae.encode(masked_image).latent_dist.sample(generator=generator)
776
+ masked_image_latents = self.vae.config.scaling_factor * masked_image_latents
777
+
778
+ # duplicate masked_image_latents for each generation per prompt, using mps friendly method
779
+ if masked_image_latents.shape[0] < batch_size:
780
+ if not batch_size % masked_image_latents.shape[0] == 0:
781
+ raise ValueError(
782
+ "The passed images and the required batch size don't match. Images are supposed to be duplicated"
783
+ f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed."
784
+ " Make sure the number of images that you pass is divisible by the total requested batch size."
785
+ )
786
+ masked_image_latents = masked_image_latents.repeat(batch_size // masked_image_latents.shape[0], 1, 1, 1)
787
+
788
+ masked_image_latents = (
789
+ torch.cat([masked_image_latents] * 2) if do_classifier_free_guidance else masked_image_latents
790
+ )
791
+
792
+ # aligning device to prevent device errors when concating it with the latent model input
793
+ masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
794
+ return masked_image_latents
795
+
796
+ def _default_height_width(self, height, width, image):
797
+ if isinstance(image, list):
798
+ image = image[0]
799
+
800
+ if height is None:
801
+ if isinstance(image, PIL.Image.Image):
802
+ height = image.height
803
+ elif isinstance(image, torch.Tensor):
804
+ height = image.shape[3]
805
+
806
+ height = (height // 8) * 8 # round down to nearest multiple of 8
807
+
808
+ if width is None:
809
+ if isinstance(image, PIL.Image.Image):
810
+ width = image.width
811
+ elif isinstance(image, torch.Tensor):
812
+ width = image.shape[2]
813
+
814
+ width = (width // 8) * 8 # round down to nearest multiple of 8
815
+
816
+ return height, width
817
+
818
+ @torch.no_grad()
819
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
820
+ def __call__(
821
+ self,
822
+ prompt: Union[str, List[str]] = None,
823
+ image: Union[torch.Tensor, PIL.Image.Image] = None,
824
+ mask_image: Union[torch.Tensor, PIL.Image.Image] = None,
825
+ controlnet_conditioning_image: Union[
826
+ torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]
827
+ ] = None,
828
+ height: Optional[int] = None,
829
+ width: Optional[int] = None,
830
+ num_inference_steps: int = 50,
831
+ guidance_scale: float = 7.5,
832
+ negative_prompt: Optional[Union[str, List[str]]] = None,
833
+ num_images_per_prompt: Optional[int] = 1,
834
+ eta: float = 0.0,
835
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
836
+ latents: Optional[torch.FloatTensor] = None,
837
+ prompt_embeds: Optional[torch.FloatTensor] = None,
838
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
839
+ output_type: Optional[str] = "pil",
840
+ return_dict: bool = True,
841
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
842
+ callback_steps: int = 1,
843
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
844
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
845
+ ):
846
+ r"""
847
+ Function invoked when calling the pipeline for generation.
848
+
849
+ Args:
850
+ prompt (`str` or `List[str]`, *optional*):
851
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
852
+ instead.
853
+ image (`torch.Tensor` or `PIL.Image.Image`):
854
+ `Image`, or tensor representing an image batch which will be inpainted, *i.e.* parts of the image will
855
+ be masked out with `mask_image` and repainted according to `prompt`.
856
+ mask_image (`torch.Tensor` or `PIL.Image.Image`):
857
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
858
+ repainted, while black pixels will be preserved. If `mask_image` is a PIL image, it will be converted
859
+ to a single channel (luminance) before use. If it's a tensor, it should contain one color channel (L)
860
+ instead of 3, so the expected shape would be `(B, H, W, 1)`.
861
+ controlnet_conditioning_image (`torch.FloatTensor`, `PIL.Image.Image`, `List[torch.FloatTensor]` or `List[PIL.Image.Image]`):
862
+ The ControlNet input condition. ControlNet uses this input condition to generate guidance to Unet. If
863
+ the type is specified as `Torch.FloatTensor`, it is passed to ControlNet as is. PIL.Image.Image` can
864
+ also be accepted as an image. The control image is automatically resized to fit the output image.
865
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
866
+ The height in pixels of the generated image.
867
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
868
+ The width in pixels of the generated image.
869
+ num_inference_steps (`int`, *optional*, defaults to 50):
870
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
871
+ expense of slower inference.
872
+ guidance_scale (`float`, *optional*, defaults to 7.5):
873
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
874
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
875
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
876
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
877
+ usually at the expense of lower image quality.
878
+ negative_prompt (`str` or `List[str]`, *optional*):
879
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds` instead.
880
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
881
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
882
+ The number of images to generate per prompt.
883
+ eta (`float`, *optional*, defaults to 0.0):
884
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
885
+ [`schedulers.DDIMScheduler`], will be ignored for others.
886
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
887
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
888
+ to make generation deterministic.
889
+ latents (`torch.FloatTensor`, *optional*):
890
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
891
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
892
+ tensor will ge generated by sampling using the supplied random `generator`.
893
+ prompt_embeds (`torch.FloatTensor`, *optional*):
894
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
895
+ provided, text embeddings will be generated from `prompt` input argument.
896
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
897
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
898
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
899
+ argument.
900
+ output_type (`str`, *optional*, defaults to `"pil"`):
901
+ The output format of the generate image. Choose between
902
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
903
+ return_dict (`bool`, *optional*, defaults to `True`):
904
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
905
+ plain tuple.
906
+ callback (`Callable`, *optional*):
907
+ A function that will be called every `callback_steps` steps during inference. The function will be
908
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
909
+ callback_steps (`int`, *optional*, defaults to 1):
910
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
911
+ called at every step.
912
+ cross_attention_kwargs (`dict`, *optional*):
913
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
914
+ `self.processor` in
915
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
916
+ controlnet_conditioning_scale (`float`, *optional*, defaults to 1.0):
917
+ The outputs of the controlnet are multiplied by `controlnet_conditioning_scale` before they are added
918
+ to the residual in the original unet.
919
+
920
+ Examples:
921
+
922
+ Returns:
923
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
924
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
925
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
926
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
927
+ (nsfw) content, according to the `safety_checker`.
928
+ """
929
+ # 0. Default height and width to unet
930
+ height, width = self._default_height_width(height, width, controlnet_conditioning_image)
931
+
932
+ # 1. Check inputs. Raise error if not correct
933
+ self.check_inputs(
934
+ prompt,
935
+ image,
936
+ mask_image,
937
+ controlnet_conditioning_image,
938
+ height,
939
+ width,
940
+ callback_steps,
941
+ negative_prompt,
942
+ prompt_embeds,
943
+ negative_prompt_embeds,
944
+ controlnet_conditioning_scale,
945
+ )
946
+
947
+ # 2. Define call parameters
948
+ if prompt is not None and isinstance(prompt, str):
949
+ batch_size = 1
950
+ elif prompt is not None and isinstance(prompt, list):
951
+ batch_size = len(prompt)
952
+ else:
953
+ batch_size = prompt_embeds.shape[0]
954
+
955
+ device = self._execution_device
956
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
957
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
958
+ # corresponds to doing no classifier free guidance.
959
+ do_classifier_free_guidance = guidance_scale > 1.0
960
+
961
+ if isinstance(self.controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
962
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(self.controlnet.nets)
963
+
964
+ # 3. Encode input prompt
965
+ prompt_embeds = self._encode_prompt(
966
+ prompt,
967
+ device,
968
+ num_images_per_prompt,
969
+ do_classifier_free_guidance,
970
+ negative_prompt,
971
+ prompt_embeds=prompt_embeds,
972
+ negative_prompt_embeds=negative_prompt_embeds,
973
+ )
974
+
975
+ # 4. Prepare mask, image, and controlnet_conditioning_image
976
+ image = prepare_image(image)
977
+
978
+ mask_image = prepare_mask_image(mask_image)
979
+
980
+ # condition image(s)
981
+ if isinstance(self.controlnet, ControlNetModel):
982
+ controlnet_conditioning_image = prepare_controlnet_conditioning_image(
983
+ controlnet_conditioning_image=controlnet_conditioning_image,
984
+ width=width,
985
+ height=height,
986
+ batch_size=batch_size * num_images_per_prompt,
987
+ num_images_per_prompt=num_images_per_prompt,
988
+ device=device,
989
+ dtype=self.controlnet.dtype,
990
+ do_classifier_free_guidance=do_classifier_free_guidance,
991
+ )
992
+ elif isinstance(self.controlnet, MultiControlNetModel):
993
+ controlnet_conditioning_images = []
994
+
995
+ for image_ in controlnet_conditioning_image:
996
+ image_ = prepare_controlnet_conditioning_image(
997
+ controlnet_conditioning_image=image_,
998
+ width=width,
999
+ height=height,
1000
+ batch_size=batch_size * num_images_per_prompt,
1001
+ num_images_per_prompt=num_images_per_prompt,
1002
+ device=device,
1003
+ dtype=self.controlnet.dtype,
1004
+ do_classifier_free_guidance=do_classifier_free_guidance,
1005
+ )
1006
+ controlnet_conditioning_images.append(image_)
1007
+
1008
+ controlnet_conditioning_image = controlnet_conditioning_images
1009
+ else:
1010
+ assert False
1011
+
1012
+ masked_image = image * (mask_image < 0.5)
1013
+
1014
+ # 5. Prepare timesteps
1015
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
1016
+ timesteps = self.scheduler.timesteps
1017
+
1018
+ # 6. Prepare latent variables
1019
+ num_channels_latents = self.vae.config.latent_channels
1020
+ latents = self.prepare_latents(
1021
+ batch_size * num_images_per_prompt,
1022
+ num_channels_latents,
1023
+ height,
1024
+ width,
1025
+ prompt_embeds.dtype,
1026
+ device,
1027
+ generator,
1028
+ latents,
1029
+ )
1030
+
1031
+ mask_image_latents = self.prepare_mask_latents(
1032
+ mask_image,
1033
+ batch_size * num_images_per_prompt,
1034
+ height,
1035
+ width,
1036
+ prompt_embeds.dtype,
1037
+ device,
1038
+ do_classifier_free_guidance,
1039
+ )
1040
+
1041
+ masked_image_latents = self.prepare_masked_image_latents(
1042
+ masked_image,
1043
+ batch_size * num_images_per_prompt,
1044
+ height,
1045
+ width,
1046
+ prompt_embeds.dtype,
1047
+ device,
1048
+ generator,
1049
+ do_classifier_free_guidance,
1050
+ )
1051
+
1052
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1053
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1054
+
1055
+ # 8. Denoising loop
1056
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1057
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1058
+ for i, t in enumerate(timesteps):
1059
+ # expand the latents if we are doing classifier free guidance
1060
+ non_inpainting_latent_model_input = (
1061
+ torch.cat([latents] * 2) if do_classifier_free_guidance else latents
1062
+ )
1063
+
1064
+ non_inpainting_latent_model_input = self.scheduler.scale_model_input(
1065
+ non_inpainting_latent_model_input, t
1066
+ )
1067
+
1068
+ inpainting_latent_model_input = torch.cat(
1069
+ [non_inpainting_latent_model_input, mask_image_latents, masked_image_latents], dim=1
1070
+ )
1071
+
1072
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
1073
+ non_inpainting_latent_model_input,
1074
+ t,
1075
+ encoder_hidden_states=prompt_embeds,
1076
+ controlnet_cond=controlnet_conditioning_image,
1077
+ conditioning_scale=controlnet_conditioning_scale,
1078
+ return_dict=False,
1079
+ )
1080
+
1081
+ # predict the noise residual
1082
+ noise_pred = self.unet(
1083
+ inpainting_latent_model_input,
1084
+ t,
1085
+ encoder_hidden_states=prompt_embeds,
1086
+ cross_attention_kwargs=cross_attention_kwargs,
1087
+ down_block_additional_residuals=down_block_res_samples,
1088
+ mid_block_additional_residual=mid_block_res_sample,
1089
+ ).sample
1090
+
1091
+ # perform guidance
1092
+ if do_classifier_free_guidance:
1093
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1094
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1095
+
1096
+ # compute the previous noisy sample x_t -> x_t-1
1097
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
1098
+
1099
+ # call the callback, if provided
1100
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1101
+ progress_bar.update()
1102
+ if callback is not None and i % callback_steps == 0:
1103
+ step_idx = i // getattr(self.scheduler, "order", 1)
1104
+ callback(step_idx, t, latents)
1105
+
1106
+ # If we do sequential model offloading, let's offload unet and controlnet
1107
+ # manually for max memory savings
1108
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
1109
+ self.unet.to("cpu")
1110
+ self.controlnet.to("cpu")
1111
+ torch.cuda.empty_cache()
1112
+
1113
+ if output_type == "latent":
1114
+ image = latents
1115
+ has_nsfw_concept = None
1116
+ elif output_type == "pil":
1117
+ # 8. Post-processing
1118
+ image = self.decode_latents(latents)
1119
+
1120
+ # 9. Run safety checker
1121
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1122
+
1123
+ # 10. Convert to PIL
1124
+ image = self.numpy_to_pil(image)
1125
+ else:
1126
+ # 8. Post-processing
1127
+ image = self.decode_latents(latents)
1128
+
1129
+ # 9. Run safety checker
1130
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1131
+
1132
+ # Offload last model to CPU
1133
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
1134
+ self.final_offload_hook.offload()
1135
+
1136
+ if not return_dict:
1137
+ return (image, has_nsfw_concept)
1138
+
1139
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.22.0/stable_diffusion_controlnet_inpaint_img2img.py ADDED
@@ -0,0 +1,1120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inspired by: https://github.com/haofanwang/ControlNet-for-Diffusers/
2
+
3
+ import inspect
4
+ from typing import Any, Callable, Dict, List, Optional, Union
5
+
6
+ import numpy as np
7
+ import PIL.Image
8
+ import torch
9
+ import torch.nn.functional as F
10
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
11
+
12
+ from diffusers import AutoencoderKL, ControlNetModel, DiffusionPipeline, UNet2DConditionModel, logging
13
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput, StableDiffusionSafetyChecker
14
+ from diffusers.schedulers import KarrasDiffusionSchedulers
15
+ from diffusers.utils import (
16
+ PIL_INTERPOLATION,
17
+ is_accelerate_available,
18
+ is_accelerate_version,
19
+ replace_example_docstring,
20
+ )
21
+ from diffusers.utils.torch_utils import randn_tensor
22
+
23
+
24
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
25
+
26
+ EXAMPLE_DOC_STRING = """
27
+ Examples:
28
+ ```py
29
+ >>> import numpy as np
30
+ >>> import torch
31
+ >>> from PIL import Image
32
+ >>> from stable_diffusion_controlnet_inpaint_img2img import StableDiffusionControlNetInpaintImg2ImgPipeline
33
+
34
+ >>> from transformers import AutoImageProcessor, UperNetForSemanticSegmentation
35
+ >>> from diffusers import ControlNetModel, UniPCMultistepScheduler
36
+ >>> from diffusers.utils import load_image
37
+
38
+ >>> def ade_palette():
39
+ return [[120, 120, 120], [180, 120, 120], [6, 230, 230], [80, 50, 50],
40
+ [4, 200, 3], [120, 120, 80], [140, 140, 140], [204, 5, 255],
41
+ [230, 230, 230], [4, 250, 7], [224, 5, 255], [235, 255, 7],
42
+ [150, 5, 61], [120, 120, 70], [8, 255, 51], [255, 6, 82],
43
+ [143, 255, 140], [204, 255, 4], [255, 51, 7], [204, 70, 3],
44
+ [0, 102, 200], [61, 230, 250], [255, 6, 51], [11, 102, 255],
45
+ [255, 7, 71], [255, 9, 224], [9, 7, 230], [220, 220, 220],
46
+ [255, 9, 92], [112, 9, 255], [8, 255, 214], [7, 255, 224],
47
+ [255, 184, 6], [10, 255, 71], [255, 41, 10], [7, 255, 255],
48
+ [224, 255, 8], [102, 8, 255], [255, 61, 6], [255, 194, 7],
49
+ [255, 122, 8], [0, 255, 20], [255, 8, 41], [255, 5, 153],
50
+ [6, 51, 255], [235, 12, 255], [160, 150, 20], [0, 163, 255],
51
+ [140, 140, 140], [250, 10, 15], [20, 255, 0], [31, 255, 0],
52
+ [255, 31, 0], [255, 224, 0], [153, 255, 0], [0, 0, 255],
53
+ [255, 71, 0], [0, 235, 255], [0, 173, 255], [31, 0, 255],
54
+ [11, 200, 200], [255, 82, 0], [0, 255, 245], [0, 61, 255],
55
+ [0, 255, 112], [0, 255, 133], [255, 0, 0], [255, 163, 0],
56
+ [255, 102, 0], [194, 255, 0], [0, 143, 255], [51, 255, 0],
57
+ [0, 82, 255], [0, 255, 41], [0, 255, 173], [10, 0, 255],
58
+ [173, 255, 0], [0, 255, 153], [255, 92, 0], [255, 0, 255],
59
+ [255, 0, 245], [255, 0, 102], [255, 173, 0], [255, 0, 20],
60
+ [255, 184, 184], [0, 31, 255], [0, 255, 61], [0, 71, 255],
61
+ [255, 0, 204], [0, 255, 194], [0, 255, 82], [0, 10, 255],
62
+ [0, 112, 255], [51, 0, 255], [0, 194, 255], [0, 122, 255],
63
+ [0, 255, 163], [255, 153, 0], [0, 255, 10], [255, 112, 0],
64
+ [143, 255, 0], [82, 0, 255], [163, 255, 0], [255, 235, 0],
65
+ [8, 184, 170], [133, 0, 255], [0, 255, 92], [184, 0, 255],
66
+ [255, 0, 31], [0, 184, 255], [0, 214, 255], [255, 0, 112],
67
+ [92, 255, 0], [0, 224, 255], [112, 224, 255], [70, 184, 160],
68
+ [163, 0, 255], [153, 0, 255], [71, 255, 0], [255, 0, 163],
69
+ [255, 204, 0], [255, 0, 143], [0, 255, 235], [133, 255, 0],
70
+ [255, 0, 235], [245, 0, 255], [255, 0, 122], [255, 245, 0],
71
+ [10, 190, 212], [214, 255, 0], [0, 204, 255], [20, 0, 255],
72
+ [255, 255, 0], [0, 153, 255], [0, 41, 255], [0, 255, 204],
73
+ [41, 0, 255], [41, 255, 0], [173, 0, 255], [0, 245, 255],
74
+ [71, 0, 255], [122, 0, 255], [0, 255, 184], [0, 92, 255],
75
+ [184, 255, 0], [0, 133, 255], [255, 214, 0], [25, 194, 194],
76
+ [102, 255, 0], [92, 0, 255]]
77
+
78
+ >>> image_processor = AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-small")
79
+ >>> image_segmentor = UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-small")
80
+
81
+ >>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-seg", torch_dtype=torch.float16)
82
+
83
+ >>> pipe = StableDiffusionControlNetInpaintImg2ImgPipeline.from_pretrained(
84
+ "runwayml/stable-diffusion-inpainting", controlnet=controlnet, safety_checker=None, torch_dtype=torch.float16
85
+ )
86
+
87
+ >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
88
+ >>> pipe.enable_xformers_memory_efficient_attention()
89
+ >>> pipe.enable_model_cpu_offload()
90
+
91
+ >>> def image_to_seg(image):
92
+ pixel_values = image_processor(image, return_tensors="pt").pixel_values
93
+ with torch.no_grad():
94
+ outputs = image_segmentor(pixel_values)
95
+ seg = image_processor.post_process_semantic_segmentation(outputs, target_sizes=[image.size[::-1]])[0]
96
+ color_seg = np.zeros((seg.shape[0], seg.shape[1], 3), dtype=np.uint8) # height, width, 3
97
+ palette = np.array(ade_palette())
98
+ for label, color in enumerate(palette):
99
+ color_seg[seg == label, :] = color
100
+ color_seg = color_seg.astype(np.uint8)
101
+ seg_image = Image.fromarray(color_seg)
102
+ return seg_image
103
+
104
+ >>> image = load_image(
105
+ "https://github.com/CompVis/latent-diffusion/raw/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
106
+ )
107
+
108
+ >>> mask_image = load_image(
109
+ "https://github.com/CompVis/latent-diffusion/raw/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
110
+ )
111
+
112
+ >>> controlnet_conditioning_image = image_to_seg(image)
113
+
114
+ >>> image = pipe(
115
+ "Face of a yellow cat, high resolution, sitting on a park bench",
116
+ image,
117
+ mask_image,
118
+ controlnet_conditioning_image,
119
+ num_inference_steps=20,
120
+ ).images[0]
121
+
122
+ >>> image.save("out.png")
123
+ ```
124
+ """
125
+
126
+
127
+ def prepare_image(image):
128
+ if isinstance(image, torch.Tensor):
129
+ # Batch single image
130
+ if image.ndim == 3:
131
+ image = image.unsqueeze(0)
132
+
133
+ image = image.to(dtype=torch.float32)
134
+ else:
135
+ # preprocess image
136
+ if isinstance(image, (PIL.Image.Image, np.ndarray)):
137
+ image = [image]
138
+
139
+ if isinstance(image, list) and isinstance(image[0], PIL.Image.Image):
140
+ image = [np.array(i.convert("RGB"))[None, :] for i in image]
141
+ image = np.concatenate(image, axis=0)
142
+ elif isinstance(image, list) and isinstance(image[0], np.ndarray):
143
+ image = np.concatenate([i[None, :] for i in image], axis=0)
144
+
145
+ image = image.transpose(0, 3, 1, 2)
146
+ image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
147
+
148
+ return image
149
+
150
+
151
+ def prepare_mask_image(mask_image):
152
+ if isinstance(mask_image, torch.Tensor):
153
+ if mask_image.ndim == 2:
154
+ # Batch and add channel dim for single mask
155
+ mask_image = mask_image.unsqueeze(0).unsqueeze(0)
156
+ elif mask_image.ndim == 3 and mask_image.shape[0] == 1:
157
+ # Single mask, the 0'th dimension is considered to be
158
+ # the existing batch size of 1
159
+ mask_image = mask_image.unsqueeze(0)
160
+ elif mask_image.ndim == 3 and mask_image.shape[0] != 1:
161
+ # Batch of mask, the 0'th dimension is considered to be
162
+ # the batching dimension
163
+ mask_image = mask_image.unsqueeze(1)
164
+
165
+ # Binarize mask
166
+ mask_image[mask_image < 0.5] = 0
167
+ mask_image[mask_image >= 0.5] = 1
168
+ else:
169
+ # preprocess mask
170
+ if isinstance(mask_image, (PIL.Image.Image, np.ndarray)):
171
+ mask_image = [mask_image]
172
+
173
+ if isinstance(mask_image, list) and isinstance(mask_image[0], PIL.Image.Image):
174
+ mask_image = np.concatenate([np.array(m.convert("L"))[None, None, :] for m in mask_image], axis=0)
175
+ mask_image = mask_image.astype(np.float32) / 255.0
176
+ elif isinstance(mask_image, list) and isinstance(mask_image[0], np.ndarray):
177
+ mask_image = np.concatenate([m[None, None, :] for m in mask_image], axis=0)
178
+
179
+ mask_image[mask_image < 0.5] = 0
180
+ mask_image[mask_image >= 0.5] = 1
181
+ mask_image = torch.from_numpy(mask_image)
182
+
183
+ return mask_image
184
+
185
+
186
+ def prepare_controlnet_conditioning_image(
187
+ controlnet_conditioning_image, width, height, batch_size, num_images_per_prompt, device, dtype
188
+ ):
189
+ if not isinstance(controlnet_conditioning_image, torch.Tensor):
190
+ if isinstance(controlnet_conditioning_image, PIL.Image.Image):
191
+ controlnet_conditioning_image = [controlnet_conditioning_image]
192
+
193
+ if isinstance(controlnet_conditioning_image[0], PIL.Image.Image):
194
+ controlnet_conditioning_image = [
195
+ np.array(i.resize((width, height), resample=PIL_INTERPOLATION["lanczos"]))[None, :]
196
+ for i in controlnet_conditioning_image
197
+ ]
198
+ controlnet_conditioning_image = np.concatenate(controlnet_conditioning_image, axis=0)
199
+ controlnet_conditioning_image = np.array(controlnet_conditioning_image).astype(np.float32) / 255.0
200
+ controlnet_conditioning_image = controlnet_conditioning_image.transpose(0, 3, 1, 2)
201
+ controlnet_conditioning_image = torch.from_numpy(controlnet_conditioning_image)
202
+ elif isinstance(controlnet_conditioning_image[0], torch.Tensor):
203
+ controlnet_conditioning_image = torch.cat(controlnet_conditioning_image, dim=0)
204
+
205
+ image_batch_size = controlnet_conditioning_image.shape[0]
206
+
207
+ if image_batch_size == 1:
208
+ repeat_by = batch_size
209
+ else:
210
+ # image batch size is the same as prompt batch size
211
+ repeat_by = num_images_per_prompt
212
+
213
+ controlnet_conditioning_image = controlnet_conditioning_image.repeat_interleave(repeat_by, dim=0)
214
+
215
+ controlnet_conditioning_image = controlnet_conditioning_image.to(device=device, dtype=dtype)
216
+
217
+ return controlnet_conditioning_image
218
+
219
+
220
+ class StableDiffusionControlNetInpaintImg2ImgPipeline(DiffusionPipeline):
221
+ """
222
+ Inspired by: https://github.com/haofanwang/ControlNet-for-Diffusers/
223
+ """
224
+
225
+ _optional_components = ["safety_checker", "feature_extractor"]
226
+
227
+ def __init__(
228
+ self,
229
+ vae: AutoencoderKL,
230
+ text_encoder: CLIPTextModel,
231
+ tokenizer: CLIPTokenizer,
232
+ unet: UNet2DConditionModel,
233
+ controlnet: ControlNetModel,
234
+ scheduler: KarrasDiffusionSchedulers,
235
+ safety_checker: StableDiffusionSafetyChecker,
236
+ feature_extractor: CLIPImageProcessor,
237
+ requires_safety_checker: bool = True,
238
+ ):
239
+ super().__init__()
240
+
241
+ if safety_checker is None and requires_safety_checker:
242
+ logger.warning(
243
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
244
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
245
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
246
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
247
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
248
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
249
+ )
250
+
251
+ if safety_checker is not None and feature_extractor is None:
252
+ raise ValueError(
253
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
254
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
255
+ )
256
+
257
+ self.register_modules(
258
+ vae=vae,
259
+ text_encoder=text_encoder,
260
+ tokenizer=tokenizer,
261
+ unet=unet,
262
+ controlnet=controlnet,
263
+ scheduler=scheduler,
264
+ safety_checker=safety_checker,
265
+ feature_extractor=feature_extractor,
266
+ )
267
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
268
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
269
+
270
+ def enable_vae_slicing(self):
271
+ r"""
272
+ Enable sliced VAE decoding.
273
+
274
+ When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
275
+ steps. This is useful to save some memory and allow larger batch sizes.
276
+ """
277
+ self.vae.enable_slicing()
278
+
279
+ def disable_vae_slicing(self):
280
+ r"""
281
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to
282
+ computing decoding in one step.
283
+ """
284
+ self.vae.disable_slicing()
285
+
286
+ def enable_sequential_cpu_offload(self, gpu_id=0):
287
+ r"""
288
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
289
+ text_encoder, vae, controlnet, and safety checker have their state dicts saved to CPU and then are moved to a
290
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
291
+ Note that offloading happens on a submodule basis. Memory savings are higher than with
292
+ `enable_model_cpu_offload`, but performance is lower.
293
+ """
294
+ if is_accelerate_available():
295
+ from accelerate import cpu_offload
296
+ else:
297
+ raise ImportError("Please install accelerate via `pip install accelerate`")
298
+
299
+ device = torch.device(f"cuda:{gpu_id}")
300
+
301
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.controlnet]:
302
+ cpu_offload(cpu_offloaded_model, device)
303
+
304
+ if self.safety_checker is not None:
305
+ cpu_offload(self.safety_checker, execution_device=device, offload_buffers=True)
306
+
307
+ def enable_model_cpu_offload(self, gpu_id=0):
308
+ r"""
309
+ Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
310
+ to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
311
+ method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
312
+ `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
313
+ """
314
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
315
+ from accelerate import cpu_offload_with_hook
316
+ else:
317
+ raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")
318
+
319
+ device = torch.device(f"cuda:{gpu_id}")
320
+
321
+ hook = None
322
+ for cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]:
323
+ _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
324
+
325
+ if self.safety_checker is not None:
326
+ # the safety checker can offload the vae again
327
+ _, hook = cpu_offload_with_hook(self.safety_checker, device, prev_module_hook=hook)
328
+
329
+ # control net hook has be manually offloaded as it alternates with unet
330
+ cpu_offload_with_hook(self.controlnet, device)
331
+
332
+ # We'll offload the last model manually.
333
+ self.final_offload_hook = hook
334
+
335
+ @property
336
+ def _execution_device(self):
337
+ r"""
338
+ Returns the device on which the pipeline's models will be executed. After calling
339
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
340
+ hooks.
341
+ """
342
+ if not hasattr(self.unet, "_hf_hook"):
343
+ return self.device
344
+ for module in self.unet.modules():
345
+ if (
346
+ hasattr(module, "_hf_hook")
347
+ and hasattr(module._hf_hook, "execution_device")
348
+ and module._hf_hook.execution_device is not None
349
+ ):
350
+ return torch.device(module._hf_hook.execution_device)
351
+ return self.device
352
+
353
+ def _encode_prompt(
354
+ self,
355
+ prompt,
356
+ device,
357
+ num_images_per_prompt,
358
+ do_classifier_free_guidance,
359
+ negative_prompt=None,
360
+ prompt_embeds: Optional[torch.FloatTensor] = None,
361
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
362
+ ):
363
+ r"""
364
+ Encodes the prompt into text encoder hidden states.
365
+
366
+ Args:
367
+ prompt (`str` or `List[str]`, *optional*):
368
+ prompt to be encoded
369
+ device: (`torch.device`):
370
+ torch device
371
+ num_images_per_prompt (`int`):
372
+ number of images that should be generated per prompt
373
+ do_classifier_free_guidance (`bool`):
374
+ whether to use classifier free guidance or not
375
+ negative_prompt (`str` or `List[str]`, *optional*):
376
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds` instead.
377
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
378
+ prompt_embeds (`torch.FloatTensor`, *optional*):
379
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
380
+ provided, text embeddings will be generated from `prompt` input argument.
381
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
382
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
383
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
384
+ argument.
385
+ """
386
+ if prompt is not None and isinstance(prompt, str):
387
+ batch_size = 1
388
+ elif prompt is not None and isinstance(prompt, list):
389
+ batch_size = len(prompt)
390
+ else:
391
+ batch_size = prompt_embeds.shape[0]
392
+
393
+ if prompt_embeds is None:
394
+ text_inputs = self.tokenizer(
395
+ prompt,
396
+ padding="max_length",
397
+ max_length=self.tokenizer.model_max_length,
398
+ truncation=True,
399
+ return_tensors="pt",
400
+ )
401
+ text_input_ids = text_inputs.input_ids
402
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
403
+
404
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
405
+ text_input_ids, untruncated_ids
406
+ ):
407
+ removed_text = self.tokenizer.batch_decode(
408
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
409
+ )
410
+ logger.warning(
411
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
412
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
413
+ )
414
+
415
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
416
+ attention_mask = text_inputs.attention_mask.to(device)
417
+ else:
418
+ attention_mask = None
419
+
420
+ prompt_embeds = self.text_encoder(
421
+ text_input_ids.to(device),
422
+ attention_mask=attention_mask,
423
+ )
424
+ prompt_embeds = prompt_embeds[0]
425
+
426
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
427
+
428
+ bs_embed, seq_len, _ = prompt_embeds.shape
429
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
430
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
431
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
432
+
433
+ # get unconditional embeddings for classifier free guidance
434
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
435
+ uncond_tokens: List[str]
436
+ if negative_prompt is None:
437
+ uncond_tokens = [""] * batch_size
438
+ elif type(prompt) is not type(negative_prompt):
439
+ raise TypeError(
440
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
441
+ f" {type(prompt)}."
442
+ )
443
+ elif isinstance(negative_prompt, str):
444
+ uncond_tokens = [negative_prompt]
445
+ elif batch_size != len(negative_prompt):
446
+ raise ValueError(
447
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
448
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
449
+ " the batch size of `prompt`."
450
+ )
451
+ else:
452
+ uncond_tokens = negative_prompt
453
+
454
+ max_length = prompt_embeds.shape[1]
455
+ uncond_input = self.tokenizer(
456
+ uncond_tokens,
457
+ padding="max_length",
458
+ max_length=max_length,
459
+ truncation=True,
460
+ return_tensors="pt",
461
+ )
462
+
463
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
464
+ attention_mask = uncond_input.attention_mask.to(device)
465
+ else:
466
+ attention_mask = None
467
+
468
+ negative_prompt_embeds = self.text_encoder(
469
+ uncond_input.input_ids.to(device),
470
+ attention_mask=attention_mask,
471
+ )
472
+ negative_prompt_embeds = negative_prompt_embeds[0]
473
+
474
+ if do_classifier_free_guidance:
475
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
476
+ seq_len = negative_prompt_embeds.shape[1]
477
+
478
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
479
+
480
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
481
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
482
+
483
+ # For classifier free guidance, we need to do two forward passes.
484
+ # Here we concatenate the unconditional and text embeddings into a single batch
485
+ # to avoid doing two forward passes
486
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
487
+
488
+ return prompt_embeds
489
+
490
+ def run_safety_checker(self, image, device, dtype):
491
+ if self.safety_checker is not None:
492
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
493
+ image, has_nsfw_concept = self.safety_checker(
494
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
495
+ )
496
+ else:
497
+ has_nsfw_concept = None
498
+ return image, has_nsfw_concept
499
+
500
+ def decode_latents(self, latents):
501
+ latents = 1 / self.vae.config.scaling_factor * latents
502
+ image = self.vae.decode(latents).sample
503
+ image = (image / 2 + 0.5).clamp(0, 1)
504
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
505
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
506
+ return image
507
+
508
+ def prepare_extra_step_kwargs(self, generator, eta):
509
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
510
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
511
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
512
+ # and should be between [0, 1]
513
+
514
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
515
+ extra_step_kwargs = {}
516
+ if accepts_eta:
517
+ extra_step_kwargs["eta"] = eta
518
+
519
+ # check if the scheduler accepts generator
520
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
521
+ if accepts_generator:
522
+ extra_step_kwargs["generator"] = generator
523
+ return extra_step_kwargs
524
+
525
+ def check_inputs(
526
+ self,
527
+ prompt,
528
+ image,
529
+ mask_image,
530
+ controlnet_conditioning_image,
531
+ height,
532
+ width,
533
+ callback_steps,
534
+ negative_prompt=None,
535
+ prompt_embeds=None,
536
+ negative_prompt_embeds=None,
537
+ strength=None,
538
+ ):
539
+ if height % 8 != 0 or width % 8 != 0:
540
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
541
+
542
+ if (callback_steps is None) or (
543
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
544
+ ):
545
+ raise ValueError(
546
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
547
+ f" {type(callback_steps)}."
548
+ )
549
+
550
+ if prompt is not None and prompt_embeds is not None:
551
+ raise ValueError(
552
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
553
+ " only forward one of the two."
554
+ )
555
+ elif prompt is None and prompt_embeds is None:
556
+ raise ValueError(
557
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
558
+ )
559
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
560
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
561
+
562
+ if negative_prompt is not None and negative_prompt_embeds is not None:
563
+ raise ValueError(
564
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
565
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
566
+ )
567
+
568
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
569
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
570
+ raise ValueError(
571
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
572
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
573
+ f" {negative_prompt_embeds.shape}."
574
+ )
575
+
576
+ controlnet_cond_image_is_pil = isinstance(controlnet_conditioning_image, PIL.Image.Image)
577
+ controlnet_cond_image_is_tensor = isinstance(controlnet_conditioning_image, torch.Tensor)
578
+ controlnet_cond_image_is_pil_list = isinstance(controlnet_conditioning_image, list) and isinstance(
579
+ controlnet_conditioning_image[0], PIL.Image.Image
580
+ )
581
+ controlnet_cond_image_is_tensor_list = isinstance(controlnet_conditioning_image, list) and isinstance(
582
+ controlnet_conditioning_image[0], torch.Tensor
583
+ )
584
+
585
+ if (
586
+ not controlnet_cond_image_is_pil
587
+ and not controlnet_cond_image_is_tensor
588
+ and not controlnet_cond_image_is_pil_list
589
+ and not controlnet_cond_image_is_tensor_list
590
+ ):
591
+ raise TypeError(
592
+ "image must be passed and be one of PIL image, torch tensor, list of PIL images, or list of torch tensors"
593
+ )
594
+
595
+ if controlnet_cond_image_is_pil:
596
+ controlnet_cond_image_batch_size = 1
597
+ elif controlnet_cond_image_is_tensor:
598
+ controlnet_cond_image_batch_size = controlnet_conditioning_image.shape[0]
599
+ elif controlnet_cond_image_is_pil_list:
600
+ controlnet_cond_image_batch_size = len(controlnet_conditioning_image)
601
+ elif controlnet_cond_image_is_tensor_list:
602
+ controlnet_cond_image_batch_size = len(controlnet_conditioning_image)
603
+
604
+ if prompt is not None and isinstance(prompt, str):
605
+ prompt_batch_size = 1
606
+ elif prompt is not None and isinstance(prompt, list):
607
+ prompt_batch_size = len(prompt)
608
+ elif prompt_embeds is not None:
609
+ prompt_batch_size = prompt_embeds.shape[0]
610
+
611
+ if controlnet_cond_image_batch_size != 1 and controlnet_cond_image_batch_size != prompt_batch_size:
612
+ raise ValueError(
613
+ f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {controlnet_cond_image_batch_size}, prompt batch size: {prompt_batch_size}"
614
+ )
615
+
616
+ if isinstance(image, torch.Tensor) and not isinstance(mask_image, torch.Tensor):
617
+ raise TypeError("if `image` is a tensor, `mask_image` must also be a tensor")
618
+
619
+ if isinstance(image, PIL.Image.Image) and not isinstance(mask_image, PIL.Image.Image):
620
+ raise TypeError("if `image` is a PIL image, `mask_image` must also be a PIL image")
621
+
622
+ if isinstance(image, torch.Tensor):
623
+ if image.ndim != 3 and image.ndim != 4:
624
+ raise ValueError("`image` must have 3 or 4 dimensions")
625
+
626
+ if mask_image.ndim != 2 and mask_image.ndim != 3 and mask_image.ndim != 4:
627
+ raise ValueError("`mask_image` must have 2, 3, or 4 dimensions")
628
+
629
+ if image.ndim == 3:
630
+ image_batch_size = 1
631
+ image_channels, image_height, image_width = image.shape
632
+ elif image.ndim == 4:
633
+ image_batch_size, image_channels, image_height, image_width = image.shape
634
+
635
+ if mask_image.ndim == 2:
636
+ mask_image_batch_size = 1
637
+ mask_image_channels = 1
638
+ mask_image_height, mask_image_width = mask_image.shape
639
+ elif mask_image.ndim == 3:
640
+ mask_image_channels = 1
641
+ mask_image_batch_size, mask_image_height, mask_image_width = mask_image.shape
642
+ elif mask_image.ndim == 4:
643
+ mask_image_batch_size, mask_image_channels, mask_image_height, mask_image_width = mask_image.shape
644
+
645
+ if image_channels != 3:
646
+ raise ValueError("`image` must have 3 channels")
647
+
648
+ if mask_image_channels != 1:
649
+ raise ValueError("`mask_image` must have 1 channel")
650
+
651
+ if image_batch_size != mask_image_batch_size:
652
+ raise ValueError("`image` and `mask_image` mush have the same batch sizes")
653
+
654
+ if image_height != mask_image_height or image_width != mask_image_width:
655
+ raise ValueError("`image` and `mask_image` must have the same height and width dimensions")
656
+
657
+ if image.min() < -1 or image.max() > 1:
658
+ raise ValueError("`image` should be in range [-1, 1]")
659
+
660
+ if mask_image.min() < 0 or mask_image.max() > 1:
661
+ raise ValueError("`mask_image` should be in range [0, 1]")
662
+ else:
663
+ mask_image_channels = 1
664
+ image_channels = 3
665
+
666
+ single_image_latent_channels = self.vae.config.latent_channels
667
+
668
+ total_latent_channels = single_image_latent_channels * 2 + mask_image_channels
669
+
670
+ if total_latent_channels != self.unet.config.in_channels:
671
+ raise ValueError(
672
+ f"The config of `pipeline.unet` expects {self.unet.config.in_channels} but received"
673
+ f" non inpainting latent channels: {single_image_latent_channels},"
674
+ f" mask channels: {mask_image_channels}, and masked image channels: {single_image_latent_channels}."
675
+ f" Please verify the config of `pipeline.unet` and the `mask_image` and `image` inputs."
676
+ )
677
+
678
+ if strength < 0 or strength > 1:
679
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
680
+
681
+ def get_timesteps(self, num_inference_steps, strength, device):
682
+ # get the original timestep using init_timestep
683
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
684
+
685
+ t_start = max(num_inference_steps - init_timestep, 0)
686
+ timesteps = self.scheduler.timesteps[t_start:]
687
+
688
+ return timesteps, num_inference_steps - t_start
689
+
690
+ def prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None):
691
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
692
+ raise ValueError(
693
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
694
+ )
695
+
696
+ image = image.to(device=device, dtype=dtype)
697
+
698
+ batch_size = batch_size * num_images_per_prompt
699
+ if isinstance(generator, list) and len(generator) != batch_size:
700
+ raise ValueError(
701
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
702
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
703
+ )
704
+
705
+ if isinstance(generator, list):
706
+ init_latents = [
707
+ self.vae.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(batch_size)
708
+ ]
709
+ init_latents = torch.cat(init_latents, dim=0)
710
+ else:
711
+ init_latents = self.vae.encode(image).latent_dist.sample(generator)
712
+
713
+ init_latents = self.vae.config.scaling_factor * init_latents
714
+
715
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
716
+ raise ValueError(
717
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
718
+ )
719
+ else:
720
+ init_latents = torch.cat([init_latents], dim=0)
721
+
722
+ shape = init_latents.shape
723
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
724
+
725
+ # get latents
726
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
727
+ latents = init_latents
728
+
729
+ return latents
730
+
731
+ def prepare_mask_latents(self, mask_image, batch_size, height, width, dtype, device, do_classifier_free_guidance):
732
+ # resize the mask to latents shape as we concatenate the mask to the latents
733
+ # we do that before converting to dtype to avoid breaking in case we're using cpu_offload
734
+ # and half precision
735
+ mask_image = F.interpolate(mask_image, size=(height // self.vae_scale_factor, width // self.vae_scale_factor))
736
+ mask_image = mask_image.to(device=device, dtype=dtype)
737
+
738
+ # duplicate mask for each generation per prompt, using mps friendly method
739
+ if mask_image.shape[0] < batch_size:
740
+ if not batch_size % mask_image.shape[0] == 0:
741
+ raise ValueError(
742
+ "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to"
743
+ f" a total batch size of {batch_size}, but {mask_image.shape[0]} masks were passed. Make sure the number"
744
+ " of masks that you pass is divisible by the total requested batch size."
745
+ )
746
+ mask_image = mask_image.repeat(batch_size // mask_image.shape[0], 1, 1, 1)
747
+
748
+ mask_image = torch.cat([mask_image] * 2) if do_classifier_free_guidance else mask_image
749
+
750
+ mask_image_latents = mask_image
751
+
752
+ return mask_image_latents
753
+
754
+ def prepare_masked_image_latents(
755
+ self, masked_image, batch_size, height, width, dtype, device, generator, do_classifier_free_guidance
756
+ ):
757
+ masked_image = masked_image.to(device=device, dtype=dtype)
758
+
759
+ # encode the mask image into latents space so we can concatenate it to the latents
760
+ if isinstance(generator, list):
761
+ masked_image_latents = [
762
+ self.vae.encode(masked_image[i : i + 1]).latent_dist.sample(generator=generator[i])
763
+ for i in range(batch_size)
764
+ ]
765
+ masked_image_latents = torch.cat(masked_image_latents, dim=0)
766
+ else:
767
+ masked_image_latents = self.vae.encode(masked_image).latent_dist.sample(generator=generator)
768
+ masked_image_latents = self.vae.config.scaling_factor * masked_image_latents
769
+
770
+ # duplicate masked_image_latents for each generation per prompt, using mps friendly method
771
+ if masked_image_latents.shape[0] < batch_size:
772
+ if not batch_size % masked_image_latents.shape[0] == 0:
773
+ raise ValueError(
774
+ "The passed images and the required batch size don't match. Images are supposed to be duplicated"
775
+ f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed."
776
+ " Make sure the number of images that you pass is divisible by the total requested batch size."
777
+ )
778
+ masked_image_latents = masked_image_latents.repeat(batch_size // masked_image_latents.shape[0], 1, 1, 1)
779
+
780
+ masked_image_latents = (
781
+ torch.cat([masked_image_latents] * 2) if do_classifier_free_guidance else masked_image_latents
782
+ )
783
+
784
+ # aligning device to prevent device errors when concating it with the latent model input
785
+ masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
786
+ return masked_image_latents
787
+
788
+ def _default_height_width(self, height, width, image):
789
+ if isinstance(image, list):
790
+ image = image[0]
791
+
792
+ if height is None:
793
+ if isinstance(image, PIL.Image.Image):
794
+ height = image.height
795
+ elif isinstance(image, torch.Tensor):
796
+ height = image.shape[3]
797
+
798
+ height = (height // 8) * 8 # round down to nearest multiple of 8
799
+
800
+ if width is None:
801
+ if isinstance(image, PIL.Image.Image):
802
+ width = image.width
803
+ elif isinstance(image, torch.Tensor):
804
+ width = image.shape[2]
805
+
806
+ width = (width // 8) * 8 # round down to nearest multiple of 8
807
+
808
+ return height, width
809
+
810
+ @torch.no_grad()
811
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
812
+ def __call__(
813
+ self,
814
+ prompt: Union[str, List[str]] = None,
815
+ image: Union[torch.Tensor, PIL.Image.Image] = None,
816
+ mask_image: Union[torch.Tensor, PIL.Image.Image] = None,
817
+ controlnet_conditioning_image: Union[
818
+ torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]
819
+ ] = None,
820
+ strength: float = 0.8,
821
+ height: Optional[int] = None,
822
+ width: Optional[int] = None,
823
+ num_inference_steps: int = 50,
824
+ guidance_scale: float = 7.5,
825
+ negative_prompt: Optional[Union[str, List[str]]] = None,
826
+ num_images_per_prompt: Optional[int] = 1,
827
+ eta: float = 0.0,
828
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
829
+ latents: Optional[torch.FloatTensor] = None,
830
+ prompt_embeds: Optional[torch.FloatTensor] = None,
831
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
832
+ output_type: Optional[str] = "pil",
833
+ return_dict: bool = True,
834
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
835
+ callback_steps: int = 1,
836
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
837
+ controlnet_conditioning_scale: float = 1.0,
838
+ ):
839
+ r"""
840
+ Function invoked when calling the pipeline for generation.
841
+
842
+ Args:
843
+ prompt (`str` or `List[str]`, *optional*):
844
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
845
+ instead.
846
+ image (`torch.Tensor` or `PIL.Image.Image`):
847
+ `Image`, or tensor representing an image batch which will be inpainted, *i.e.* parts of the image will
848
+ be masked out with `mask_image` and repainted according to `prompt`.
849
+ mask_image (`torch.Tensor` or `PIL.Image.Image`):
850
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
851
+ repainted, while black pixels will be preserved. If `mask_image` is a PIL image, it will be converted
852
+ to a single channel (luminance) before use. If it's a tensor, it should contain one color channel (L)
853
+ instead of 3, so the expected shape would be `(B, H, W, 1)`.
854
+ controlnet_conditioning_image (`torch.FloatTensor`, `PIL.Image.Image`, `List[torch.FloatTensor]` or `List[PIL.Image.Image]`):
855
+ The ControlNet input condition. ControlNet uses this input condition to generate guidance to Unet. If
856
+ the type is specified as `Torch.FloatTensor`, it is passed to ControlNet as is. PIL.Image.Image` can
857
+ also be accepted as an image. The control image is automatically resized to fit the output image.
858
+ strength (`float`, *optional*):
859
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
860
+ will be used as a starting point, adding more noise to it the larger the `strength`. The number of
861
+ denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
862
+ be maximum and the denoising process will run for the full number of iterations specified in
863
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
864
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
865
+ The height in pixels of the generated image.
866
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
867
+ The width in pixels of the generated image.
868
+ num_inference_steps (`int`, *optional*, defaults to 50):
869
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
870
+ expense of slower inference.
871
+ guidance_scale (`float`, *optional*, defaults to 7.5):
872
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
873
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
874
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
875
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
876
+ usually at the expense of lower image quality.
877
+ negative_prompt (`str` or `List[str]`, *optional*):
878
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds` instead.
879
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
880
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
881
+ The number of images to generate per prompt.
882
+ eta (`float`, *optional*, defaults to 0.0):
883
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
884
+ [`schedulers.DDIMScheduler`], will be ignored for others.
885
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
886
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
887
+ to make generation deterministic.
888
+ latents (`torch.FloatTensor`, *optional*):
889
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
890
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
891
+ tensor will ge generated by sampling using the supplied random `generator`.
892
+ prompt_embeds (`torch.FloatTensor`, *optional*):
893
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
894
+ provided, text embeddings will be generated from `prompt` input argument.
895
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
896
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
897
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
898
+ argument.
899
+ output_type (`str`, *optional*, defaults to `"pil"`):
900
+ The output format of the generate image. Choose between
901
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
902
+ return_dict (`bool`, *optional*, defaults to `True`):
903
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
904
+ plain tuple.
905
+ callback (`Callable`, *optional*):
906
+ A function that will be called every `callback_steps` steps during inference. The function will be
907
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
908
+ callback_steps (`int`, *optional*, defaults to 1):
909
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
910
+ called at every step.
911
+ cross_attention_kwargs (`dict`, *optional*):
912
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
913
+ `self.processor` in
914
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
915
+ controlnet_conditioning_scale (`float`, *optional*, defaults to 1.0):
916
+ The outputs of the controlnet are multiplied by `controlnet_conditioning_scale` before they are added
917
+ to the residual in the original unet.
918
+
919
+ Examples:
920
+
921
+ Returns:
922
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
923
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
924
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
925
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
926
+ (nsfw) content, according to the `safety_checker`.
927
+ """
928
+ # 0. Default height and width to unet
929
+ height, width = self._default_height_width(height, width, controlnet_conditioning_image)
930
+
931
+ # 1. Check inputs. Raise error if not correct
932
+ self.check_inputs(
933
+ prompt,
934
+ image,
935
+ mask_image,
936
+ controlnet_conditioning_image,
937
+ height,
938
+ width,
939
+ callback_steps,
940
+ negative_prompt,
941
+ prompt_embeds,
942
+ negative_prompt_embeds,
943
+ strength,
944
+ )
945
+
946
+ # 2. Define call parameters
947
+ if prompt is not None and isinstance(prompt, str):
948
+ batch_size = 1
949
+ elif prompt is not None and isinstance(prompt, list):
950
+ batch_size = len(prompt)
951
+ else:
952
+ batch_size = prompt_embeds.shape[0]
953
+
954
+ device = self._execution_device
955
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
956
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
957
+ # corresponds to doing no classifier free guidance.
958
+ do_classifier_free_guidance = guidance_scale > 1.0
959
+
960
+ # 3. Encode input prompt
961
+ prompt_embeds = self._encode_prompt(
962
+ prompt,
963
+ device,
964
+ num_images_per_prompt,
965
+ do_classifier_free_guidance,
966
+ negative_prompt,
967
+ prompt_embeds=prompt_embeds,
968
+ negative_prompt_embeds=negative_prompt_embeds,
969
+ )
970
+
971
+ # 4. Prepare mask, image, and controlnet_conditioning_image
972
+ image = prepare_image(image)
973
+
974
+ mask_image = prepare_mask_image(mask_image)
975
+
976
+ controlnet_conditioning_image = prepare_controlnet_conditioning_image(
977
+ controlnet_conditioning_image,
978
+ width,
979
+ height,
980
+ batch_size * num_images_per_prompt,
981
+ num_images_per_prompt,
982
+ device,
983
+ self.controlnet.dtype,
984
+ )
985
+
986
+ masked_image = image * (mask_image < 0.5)
987
+
988
+ # 5. Prepare timesteps
989
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
990
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
991
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
992
+
993
+ # 6. Prepare latent variables
994
+ latents = self.prepare_latents(
995
+ image,
996
+ latent_timestep,
997
+ batch_size,
998
+ num_images_per_prompt,
999
+ prompt_embeds.dtype,
1000
+ device,
1001
+ generator,
1002
+ )
1003
+
1004
+ mask_image_latents = self.prepare_mask_latents(
1005
+ mask_image,
1006
+ batch_size * num_images_per_prompt,
1007
+ height,
1008
+ width,
1009
+ prompt_embeds.dtype,
1010
+ device,
1011
+ do_classifier_free_guidance,
1012
+ )
1013
+
1014
+ masked_image_latents = self.prepare_masked_image_latents(
1015
+ masked_image,
1016
+ batch_size * num_images_per_prompt,
1017
+ height,
1018
+ width,
1019
+ prompt_embeds.dtype,
1020
+ device,
1021
+ generator,
1022
+ do_classifier_free_guidance,
1023
+ )
1024
+
1025
+ if do_classifier_free_guidance:
1026
+ controlnet_conditioning_image = torch.cat([controlnet_conditioning_image] * 2)
1027
+
1028
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1029
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1030
+
1031
+ # 8. Denoising loop
1032
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1033
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1034
+ for i, t in enumerate(timesteps):
1035
+ # expand the latents if we are doing classifier free guidance
1036
+ non_inpainting_latent_model_input = (
1037
+ torch.cat([latents] * 2) if do_classifier_free_guidance else latents
1038
+ )
1039
+
1040
+ non_inpainting_latent_model_input = self.scheduler.scale_model_input(
1041
+ non_inpainting_latent_model_input, t
1042
+ )
1043
+
1044
+ inpainting_latent_model_input = torch.cat(
1045
+ [non_inpainting_latent_model_input, mask_image_latents, masked_image_latents], dim=1
1046
+ )
1047
+
1048
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
1049
+ non_inpainting_latent_model_input,
1050
+ t,
1051
+ encoder_hidden_states=prompt_embeds,
1052
+ controlnet_cond=controlnet_conditioning_image,
1053
+ return_dict=False,
1054
+ )
1055
+
1056
+ down_block_res_samples = [
1057
+ down_block_res_sample * controlnet_conditioning_scale
1058
+ for down_block_res_sample in down_block_res_samples
1059
+ ]
1060
+ mid_block_res_sample *= controlnet_conditioning_scale
1061
+
1062
+ # predict the noise residual
1063
+ noise_pred = self.unet(
1064
+ inpainting_latent_model_input,
1065
+ t,
1066
+ encoder_hidden_states=prompt_embeds,
1067
+ cross_attention_kwargs=cross_attention_kwargs,
1068
+ down_block_additional_residuals=down_block_res_samples,
1069
+ mid_block_additional_residual=mid_block_res_sample,
1070
+ ).sample
1071
+
1072
+ # perform guidance
1073
+ if do_classifier_free_guidance:
1074
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1075
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1076
+
1077
+ # compute the previous noisy sample x_t -> x_t-1
1078
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
1079
+
1080
+ # call the callback, if provided
1081
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1082
+ progress_bar.update()
1083
+ if callback is not None and i % callback_steps == 0:
1084
+ step_idx = i // getattr(self.scheduler, "order", 1)
1085
+ callback(step_idx, t, latents)
1086
+
1087
+ # If we do sequential model offloading, let's offload unet and controlnet
1088
+ # manually for max memory savings
1089
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
1090
+ self.unet.to("cpu")
1091
+ self.controlnet.to("cpu")
1092
+ torch.cuda.empty_cache()
1093
+
1094
+ if output_type == "latent":
1095
+ image = latents
1096
+ has_nsfw_concept = None
1097
+ elif output_type == "pil":
1098
+ # 8. Post-processing
1099
+ image = self.decode_latents(latents)
1100
+
1101
+ # 9. Run safety checker
1102
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1103
+
1104
+ # 10. Convert to PIL
1105
+ image = self.numpy_to_pil(image)
1106
+ else:
1107
+ # 8. Post-processing
1108
+ image = self.decode_latents(latents)
1109
+
1110
+ # 9. Run safety checker
1111
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1112
+
1113
+ # Offload last model to CPU
1114
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
1115
+ self.final_offload_hook.offload()
1116
+
1117
+ if not return_dict:
1118
+ return (image, has_nsfw_concept)
1119
+
1120
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.22.0/stable_diffusion_controlnet_reference.py ADDED
@@ -0,0 +1,836 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inspired by: https://github.com/Mikubill/sd-webui-controlnet/discussions/1236 and https://github.com/Mikubill/sd-webui-controlnet/discussions/1280
2
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
3
+
4
+ import numpy as np
5
+ import PIL.Image
6
+ import torch
7
+
8
+ from diffusers import StableDiffusionControlNetPipeline
9
+ from diffusers.models import ControlNetModel
10
+ from diffusers.models.attention import BasicTransformerBlock
11
+ from diffusers.models.unet_2d_blocks import CrossAttnDownBlock2D, CrossAttnUpBlock2D, DownBlock2D, UpBlock2D
12
+ from diffusers.pipelines.controlnet.multicontrolnet import MultiControlNetModel
13
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
14
+ from diffusers.utils import logging
15
+ from diffusers.utils.torch_utils import is_compiled_module, randn_tensor
16
+
17
+
18
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
19
+
20
+ EXAMPLE_DOC_STRING = """
21
+ Examples:
22
+ ```py
23
+ >>> import cv2
24
+ >>> import torch
25
+ >>> import numpy as np
26
+ >>> from PIL import Image
27
+ >>> from diffusers import UniPCMultistepScheduler
28
+ >>> from diffusers.utils import load_image
29
+
30
+ >>> input_image = load_image("https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png")
31
+
32
+ >>> # get canny image
33
+ >>> image = cv2.Canny(np.array(input_image), 100, 200)
34
+ >>> image = image[:, :, None]
35
+ >>> image = np.concatenate([image, image, image], axis=2)
36
+ >>> canny_image = Image.fromarray(image)
37
+
38
+ >>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
39
+ >>> pipe = StableDiffusionControlNetReferencePipeline.from_pretrained(
40
+ "runwayml/stable-diffusion-v1-5",
41
+ controlnet=controlnet,
42
+ safety_checker=None,
43
+ torch_dtype=torch.float16
44
+ ).to('cuda:0')
45
+
46
+ >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe_controlnet.scheduler.config)
47
+
48
+ >>> result_img = pipe(ref_image=input_image,
49
+ prompt="1girl",
50
+ image=canny_image,
51
+ num_inference_steps=20,
52
+ reference_attn=True,
53
+ reference_adain=True).images[0]
54
+
55
+ >>> result_img.show()
56
+ ```
57
+ """
58
+
59
+
60
+ def torch_dfs(model: torch.nn.Module):
61
+ result = [model]
62
+ for child in model.children():
63
+ result += torch_dfs(child)
64
+ return result
65
+
66
+
67
+ class StableDiffusionControlNetReferencePipeline(StableDiffusionControlNetPipeline):
68
+ def prepare_ref_latents(self, refimage, batch_size, dtype, device, generator, do_classifier_free_guidance):
69
+ refimage = refimage.to(device=device, dtype=dtype)
70
+
71
+ # encode the mask image into latents space so we can concatenate it to the latents
72
+ if isinstance(generator, list):
73
+ ref_image_latents = [
74
+ self.vae.encode(refimage[i : i + 1]).latent_dist.sample(generator=generator[i])
75
+ for i in range(batch_size)
76
+ ]
77
+ ref_image_latents = torch.cat(ref_image_latents, dim=0)
78
+ else:
79
+ ref_image_latents = self.vae.encode(refimage).latent_dist.sample(generator=generator)
80
+ ref_image_latents = self.vae.config.scaling_factor * ref_image_latents
81
+
82
+ # duplicate mask and ref_image_latents for each generation per prompt, using mps friendly method
83
+ if ref_image_latents.shape[0] < batch_size:
84
+ if not batch_size % ref_image_latents.shape[0] == 0:
85
+ raise ValueError(
86
+ "The passed images and the required batch size don't match. Images are supposed to be duplicated"
87
+ f" to a total batch size of {batch_size}, but {ref_image_latents.shape[0]} images were passed."
88
+ " Make sure the number of images that you pass is divisible by the total requested batch size."
89
+ )
90
+ ref_image_latents = ref_image_latents.repeat(batch_size // ref_image_latents.shape[0], 1, 1, 1)
91
+
92
+ ref_image_latents = torch.cat([ref_image_latents] * 2) if do_classifier_free_guidance else ref_image_latents
93
+
94
+ # aligning device to prevent device errors when concating it with the latent model input
95
+ ref_image_latents = ref_image_latents.to(device=device, dtype=dtype)
96
+ return ref_image_latents
97
+
98
+ @torch.no_grad()
99
+ def __call__(
100
+ self,
101
+ prompt: Union[str, List[str]] = None,
102
+ image: Union[
103
+ torch.FloatTensor,
104
+ PIL.Image.Image,
105
+ np.ndarray,
106
+ List[torch.FloatTensor],
107
+ List[PIL.Image.Image],
108
+ List[np.ndarray],
109
+ ] = None,
110
+ ref_image: Union[torch.FloatTensor, PIL.Image.Image] = None,
111
+ height: Optional[int] = None,
112
+ width: Optional[int] = None,
113
+ num_inference_steps: int = 50,
114
+ guidance_scale: float = 7.5,
115
+ negative_prompt: Optional[Union[str, List[str]]] = None,
116
+ num_images_per_prompt: Optional[int] = 1,
117
+ eta: float = 0.0,
118
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
119
+ latents: Optional[torch.FloatTensor] = None,
120
+ prompt_embeds: Optional[torch.FloatTensor] = None,
121
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
122
+ output_type: Optional[str] = "pil",
123
+ return_dict: bool = True,
124
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
125
+ callback_steps: int = 1,
126
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
127
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
128
+ guess_mode: bool = False,
129
+ attention_auto_machine_weight: float = 1.0,
130
+ gn_auto_machine_weight: float = 1.0,
131
+ style_fidelity: float = 0.5,
132
+ reference_attn: bool = True,
133
+ reference_adain: bool = True,
134
+ ):
135
+ r"""
136
+ Function invoked when calling the pipeline for generation.
137
+
138
+ Args:
139
+ prompt (`str` or `List[str]`, *optional*):
140
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
141
+ instead.
142
+ image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
143
+ `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
144
+ The ControlNet input condition. ControlNet uses this input condition to generate guidance to Unet. If
145
+ the type is specified as `Torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can
146
+ also be accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If
147
+ height and/or width are passed, `image` is resized according to them. If multiple ControlNets are
148
+ specified in init, images must be passed as a list such that each element of the list can be correctly
149
+ batched for input to a single controlnet.
150
+ ref_image (`torch.FloatTensor`, `PIL.Image.Image`):
151
+ The Reference Control input condition. Reference Control uses this input condition to generate guidance to Unet. If
152
+ the type is specified as `Torch.FloatTensor`, it is passed to Reference Control as is. `PIL.Image.Image` can
153
+ also be accepted as an image.
154
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
155
+ The height in pixels of the generated image.
156
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
157
+ The width in pixels of the generated image.
158
+ num_inference_steps (`int`, *optional*, defaults to 50):
159
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
160
+ expense of slower inference.
161
+ guidance_scale (`float`, *optional*, defaults to 7.5):
162
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
163
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
164
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
165
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
166
+ usually at the expense of lower image quality.
167
+ negative_prompt (`str` or `List[str]`, *optional*):
168
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
169
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
170
+ less than `1`).
171
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
172
+ The number of images to generate per prompt.
173
+ eta (`float`, *optional*, defaults to 0.0):
174
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
175
+ [`schedulers.DDIMScheduler`], will be ignored for others.
176
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
177
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
178
+ to make generation deterministic.
179
+ latents (`torch.FloatTensor`, *optional*):
180
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
181
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
182
+ tensor will ge generated by sampling using the supplied random `generator`.
183
+ prompt_embeds (`torch.FloatTensor`, *optional*):
184
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
185
+ provided, text embeddings will be generated from `prompt` input argument.
186
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
187
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
188
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
189
+ argument.
190
+ output_type (`str`, *optional*, defaults to `"pil"`):
191
+ The output format of the generate image. Choose between
192
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
193
+ return_dict (`bool`, *optional*, defaults to `True`):
194
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
195
+ plain tuple.
196
+ callback (`Callable`, *optional*):
197
+ A function that will be called every `callback_steps` steps during inference. The function will be
198
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
199
+ callback_steps (`int`, *optional*, defaults to 1):
200
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
201
+ called at every step.
202
+ cross_attention_kwargs (`dict`, *optional*):
203
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
204
+ `self.processor` in
205
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
206
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
207
+ The outputs of the controlnet are multiplied by `controlnet_conditioning_scale` before they are added
208
+ to the residual in the original unet. If multiple ControlNets are specified in init, you can set the
209
+ corresponding scale as a list.
210
+ guess_mode (`bool`, *optional*, defaults to `False`):
211
+ In this mode, the ControlNet encoder will try best to recognize the content of the input image even if
212
+ you remove all prompts. The `guidance_scale` between 3.0 and 5.0 is recommended.
213
+ attention_auto_machine_weight (`float`):
214
+ Weight of using reference query for self attention's context.
215
+ If attention_auto_machine_weight=1.0, use reference query for all self attention's context.
216
+ gn_auto_machine_weight (`float`):
217
+ Weight of using reference adain. If gn_auto_machine_weight=2.0, use all reference adain plugins.
218
+ style_fidelity (`float`):
219
+ style fidelity of ref_uncond_xt. If style_fidelity=1.0, control more important,
220
+ elif style_fidelity=0.0, prompt more important, else balanced.
221
+ reference_attn (`bool`):
222
+ Whether to use reference query for self attention's context.
223
+ reference_adain (`bool`):
224
+ Whether to use reference adain.
225
+
226
+ Examples:
227
+
228
+ Returns:
229
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
230
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
231
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
232
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
233
+ (nsfw) content, according to the `safety_checker`.
234
+ """
235
+ assert reference_attn or reference_adain, "`reference_attn` or `reference_adain` must be True."
236
+
237
+ # 1. Check inputs. Raise error if not correct
238
+ self.check_inputs(
239
+ prompt,
240
+ image,
241
+ callback_steps,
242
+ negative_prompt,
243
+ prompt_embeds,
244
+ negative_prompt_embeds,
245
+ controlnet_conditioning_scale,
246
+ )
247
+
248
+ # 2. Define call parameters
249
+ if prompt is not None and isinstance(prompt, str):
250
+ batch_size = 1
251
+ elif prompt is not None and isinstance(prompt, list):
252
+ batch_size = len(prompt)
253
+ else:
254
+ batch_size = prompt_embeds.shape[0]
255
+
256
+ device = self._execution_device
257
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
258
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
259
+ # corresponds to doing no classifier free guidance.
260
+ do_classifier_free_guidance = guidance_scale > 1.0
261
+
262
+ controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
263
+
264
+ if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
265
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
266
+
267
+ global_pool_conditions = (
268
+ controlnet.config.global_pool_conditions
269
+ if isinstance(controlnet, ControlNetModel)
270
+ else controlnet.nets[0].config.global_pool_conditions
271
+ )
272
+ guess_mode = guess_mode or global_pool_conditions
273
+
274
+ # 3. Encode input prompt
275
+ text_encoder_lora_scale = (
276
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
277
+ )
278
+ prompt_embeds = self._encode_prompt(
279
+ prompt,
280
+ device,
281
+ num_images_per_prompt,
282
+ do_classifier_free_guidance,
283
+ negative_prompt,
284
+ prompt_embeds=prompt_embeds,
285
+ negative_prompt_embeds=negative_prompt_embeds,
286
+ lora_scale=text_encoder_lora_scale,
287
+ )
288
+
289
+ # 4. Prepare image
290
+ if isinstance(controlnet, ControlNetModel):
291
+ image = self.prepare_image(
292
+ image=image,
293
+ width=width,
294
+ height=height,
295
+ batch_size=batch_size * num_images_per_prompt,
296
+ num_images_per_prompt=num_images_per_prompt,
297
+ device=device,
298
+ dtype=controlnet.dtype,
299
+ do_classifier_free_guidance=do_classifier_free_guidance,
300
+ guess_mode=guess_mode,
301
+ )
302
+ height, width = image.shape[-2:]
303
+ elif isinstance(controlnet, MultiControlNetModel):
304
+ images = []
305
+
306
+ for image_ in image:
307
+ image_ = self.prepare_image(
308
+ image=image_,
309
+ width=width,
310
+ height=height,
311
+ batch_size=batch_size * num_images_per_prompt,
312
+ num_images_per_prompt=num_images_per_prompt,
313
+ device=device,
314
+ dtype=controlnet.dtype,
315
+ do_classifier_free_guidance=do_classifier_free_guidance,
316
+ guess_mode=guess_mode,
317
+ )
318
+
319
+ images.append(image_)
320
+
321
+ image = images
322
+ height, width = image[0].shape[-2:]
323
+ else:
324
+ assert False
325
+
326
+ # 5. Preprocess reference image
327
+ ref_image = self.prepare_image(
328
+ image=ref_image,
329
+ width=width,
330
+ height=height,
331
+ batch_size=batch_size * num_images_per_prompt,
332
+ num_images_per_prompt=num_images_per_prompt,
333
+ device=device,
334
+ dtype=prompt_embeds.dtype,
335
+ )
336
+
337
+ # 6. Prepare timesteps
338
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
339
+ timesteps = self.scheduler.timesteps
340
+
341
+ # 7. Prepare latent variables
342
+ num_channels_latents = self.unet.config.in_channels
343
+ latents = self.prepare_latents(
344
+ batch_size * num_images_per_prompt,
345
+ num_channels_latents,
346
+ height,
347
+ width,
348
+ prompt_embeds.dtype,
349
+ device,
350
+ generator,
351
+ latents,
352
+ )
353
+
354
+ # 8. Prepare reference latent variables
355
+ ref_image_latents = self.prepare_ref_latents(
356
+ ref_image,
357
+ batch_size * num_images_per_prompt,
358
+ prompt_embeds.dtype,
359
+ device,
360
+ generator,
361
+ do_classifier_free_guidance,
362
+ )
363
+
364
+ # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
365
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
366
+
367
+ # 9. Modify self attention and group norm
368
+ MODE = "write"
369
+ uc_mask = (
370
+ torch.Tensor([1] * batch_size * num_images_per_prompt + [0] * batch_size * num_images_per_prompt)
371
+ .type_as(ref_image_latents)
372
+ .bool()
373
+ )
374
+
375
+ def hacked_basic_transformer_inner_forward(
376
+ self,
377
+ hidden_states: torch.FloatTensor,
378
+ attention_mask: Optional[torch.FloatTensor] = None,
379
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
380
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
381
+ timestep: Optional[torch.LongTensor] = None,
382
+ cross_attention_kwargs: Dict[str, Any] = None,
383
+ class_labels: Optional[torch.LongTensor] = None,
384
+ ):
385
+ if self.use_ada_layer_norm:
386
+ norm_hidden_states = self.norm1(hidden_states, timestep)
387
+ elif self.use_ada_layer_norm_zero:
388
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
389
+ hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
390
+ )
391
+ else:
392
+ norm_hidden_states = self.norm1(hidden_states)
393
+
394
+ # 1. Self-Attention
395
+ cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}
396
+ if self.only_cross_attention:
397
+ attn_output = self.attn1(
398
+ norm_hidden_states,
399
+ encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
400
+ attention_mask=attention_mask,
401
+ **cross_attention_kwargs,
402
+ )
403
+ else:
404
+ if MODE == "write":
405
+ self.bank.append(norm_hidden_states.detach().clone())
406
+ attn_output = self.attn1(
407
+ norm_hidden_states,
408
+ encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
409
+ attention_mask=attention_mask,
410
+ **cross_attention_kwargs,
411
+ )
412
+ if MODE == "read":
413
+ if attention_auto_machine_weight > self.attn_weight:
414
+ attn_output_uc = self.attn1(
415
+ norm_hidden_states,
416
+ encoder_hidden_states=torch.cat([norm_hidden_states] + self.bank, dim=1),
417
+ # attention_mask=attention_mask,
418
+ **cross_attention_kwargs,
419
+ )
420
+ attn_output_c = attn_output_uc.clone()
421
+ if do_classifier_free_guidance and style_fidelity > 0:
422
+ attn_output_c[uc_mask] = self.attn1(
423
+ norm_hidden_states[uc_mask],
424
+ encoder_hidden_states=norm_hidden_states[uc_mask],
425
+ **cross_attention_kwargs,
426
+ )
427
+ attn_output = style_fidelity * attn_output_c + (1.0 - style_fidelity) * attn_output_uc
428
+ self.bank.clear()
429
+ else:
430
+ attn_output = self.attn1(
431
+ norm_hidden_states,
432
+ encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
433
+ attention_mask=attention_mask,
434
+ **cross_attention_kwargs,
435
+ )
436
+ if self.use_ada_layer_norm_zero:
437
+ attn_output = gate_msa.unsqueeze(1) * attn_output
438
+ hidden_states = attn_output + hidden_states
439
+
440
+ if self.attn2 is not None:
441
+ norm_hidden_states = (
442
+ self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)
443
+ )
444
+
445
+ # 2. Cross-Attention
446
+ attn_output = self.attn2(
447
+ norm_hidden_states,
448
+ encoder_hidden_states=encoder_hidden_states,
449
+ attention_mask=encoder_attention_mask,
450
+ **cross_attention_kwargs,
451
+ )
452
+ hidden_states = attn_output + hidden_states
453
+
454
+ # 3. Feed-forward
455
+ norm_hidden_states = self.norm3(hidden_states)
456
+
457
+ if self.use_ada_layer_norm_zero:
458
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
459
+
460
+ ff_output = self.ff(norm_hidden_states)
461
+
462
+ if self.use_ada_layer_norm_zero:
463
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
464
+
465
+ hidden_states = ff_output + hidden_states
466
+
467
+ return hidden_states
468
+
469
+ def hacked_mid_forward(self, *args, **kwargs):
470
+ eps = 1e-6
471
+ x = self.original_forward(*args, **kwargs)
472
+ if MODE == "write":
473
+ if gn_auto_machine_weight >= self.gn_weight:
474
+ var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)
475
+ self.mean_bank.append(mean)
476
+ self.var_bank.append(var)
477
+ if MODE == "read":
478
+ if len(self.mean_bank) > 0 and len(self.var_bank) > 0:
479
+ var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)
480
+ std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5
481
+ mean_acc = sum(self.mean_bank) / float(len(self.mean_bank))
482
+ var_acc = sum(self.var_bank) / float(len(self.var_bank))
483
+ std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5
484
+ x_uc = (((x - mean) / std) * std_acc) + mean_acc
485
+ x_c = x_uc.clone()
486
+ if do_classifier_free_guidance and style_fidelity > 0:
487
+ x_c[uc_mask] = x[uc_mask]
488
+ x = style_fidelity * x_c + (1.0 - style_fidelity) * x_uc
489
+ self.mean_bank = []
490
+ self.var_bank = []
491
+ return x
492
+
493
+ def hack_CrossAttnDownBlock2D_forward(
494
+ self,
495
+ hidden_states: torch.FloatTensor,
496
+ temb: Optional[torch.FloatTensor] = None,
497
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
498
+ attention_mask: Optional[torch.FloatTensor] = None,
499
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
500
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
501
+ ):
502
+ eps = 1e-6
503
+
504
+ # TODO(Patrick, William) - attention mask is not used
505
+ output_states = ()
506
+
507
+ for i, (resnet, attn) in enumerate(zip(self.resnets, self.attentions)):
508
+ hidden_states = resnet(hidden_states, temb)
509
+ hidden_states = attn(
510
+ hidden_states,
511
+ encoder_hidden_states=encoder_hidden_states,
512
+ cross_attention_kwargs=cross_attention_kwargs,
513
+ attention_mask=attention_mask,
514
+ encoder_attention_mask=encoder_attention_mask,
515
+ return_dict=False,
516
+ )[0]
517
+ if MODE == "write":
518
+ if gn_auto_machine_weight >= self.gn_weight:
519
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
520
+ self.mean_bank.append([mean])
521
+ self.var_bank.append([var])
522
+ if MODE == "read":
523
+ if len(self.mean_bank) > 0 and len(self.var_bank) > 0:
524
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
525
+ std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5
526
+ mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))
527
+ var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))
528
+ std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5
529
+ hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc
530
+ hidden_states_c = hidden_states_uc.clone()
531
+ if do_classifier_free_guidance and style_fidelity > 0:
532
+ hidden_states_c[uc_mask] = hidden_states[uc_mask]
533
+ hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc
534
+
535
+ output_states = output_states + (hidden_states,)
536
+
537
+ if MODE == "read":
538
+ self.mean_bank = []
539
+ self.var_bank = []
540
+
541
+ if self.downsamplers is not None:
542
+ for downsampler in self.downsamplers:
543
+ hidden_states = downsampler(hidden_states)
544
+
545
+ output_states = output_states + (hidden_states,)
546
+
547
+ return hidden_states, output_states
548
+
549
+ def hacked_DownBlock2D_forward(self, hidden_states, temb=None):
550
+ eps = 1e-6
551
+
552
+ output_states = ()
553
+
554
+ for i, resnet in enumerate(self.resnets):
555
+ hidden_states = resnet(hidden_states, temb)
556
+
557
+ if MODE == "write":
558
+ if gn_auto_machine_weight >= self.gn_weight:
559
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
560
+ self.mean_bank.append([mean])
561
+ self.var_bank.append([var])
562
+ if MODE == "read":
563
+ if len(self.mean_bank) > 0 and len(self.var_bank) > 0:
564
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
565
+ std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5
566
+ mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))
567
+ var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))
568
+ std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5
569
+ hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc
570
+ hidden_states_c = hidden_states_uc.clone()
571
+ if do_classifier_free_guidance and style_fidelity > 0:
572
+ hidden_states_c[uc_mask] = hidden_states[uc_mask]
573
+ hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc
574
+
575
+ output_states = output_states + (hidden_states,)
576
+
577
+ if MODE == "read":
578
+ self.mean_bank = []
579
+ self.var_bank = []
580
+
581
+ if self.downsamplers is not None:
582
+ for downsampler in self.downsamplers:
583
+ hidden_states = downsampler(hidden_states)
584
+
585
+ output_states = output_states + (hidden_states,)
586
+
587
+ return hidden_states, output_states
588
+
589
+ def hacked_CrossAttnUpBlock2D_forward(
590
+ self,
591
+ hidden_states: torch.FloatTensor,
592
+ res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],
593
+ temb: Optional[torch.FloatTensor] = None,
594
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
595
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
596
+ upsample_size: Optional[int] = None,
597
+ attention_mask: Optional[torch.FloatTensor] = None,
598
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
599
+ ):
600
+ eps = 1e-6
601
+ # TODO(Patrick, William) - attention mask is not used
602
+ for i, (resnet, attn) in enumerate(zip(self.resnets, self.attentions)):
603
+ # pop res hidden states
604
+ res_hidden_states = res_hidden_states_tuple[-1]
605
+ res_hidden_states_tuple = res_hidden_states_tuple[:-1]
606
+ hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
607
+ hidden_states = resnet(hidden_states, temb)
608
+ hidden_states = attn(
609
+ hidden_states,
610
+ encoder_hidden_states=encoder_hidden_states,
611
+ cross_attention_kwargs=cross_attention_kwargs,
612
+ attention_mask=attention_mask,
613
+ encoder_attention_mask=encoder_attention_mask,
614
+ return_dict=False,
615
+ )[0]
616
+
617
+ if MODE == "write":
618
+ if gn_auto_machine_weight >= self.gn_weight:
619
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
620
+ self.mean_bank.append([mean])
621
+ self.var_bank.append([var])
622
+ if MODE == "read":
623
+ if len(self.mean_bank) > 0 and len(self.var_bank) > 0:
624
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
625
+ std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5
626
+ mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))
627
+ var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))
628
+ std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5
629
+ hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc
630
+ hidden_states_c = hidden_states_uc.clone()
631
+ if do_classifier_free_guidance and style_fidelity > 0:
632
+ hidden_states_c[uc_mask] = hidden_states[uc_mask]
633
+ hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc
634
+
635
+ if MODE == "read":
636
+ self.mean_bank = []
637
+ self.var_bank = []
638
+
639
+ if self.upsamplers is not None:
640
+ for upsampler in self.upsamplers:
641
+ hidden_states = upsampler(hidden_states, upsample_size)
642
+
643
+ return hidden_states
644
+
645
+ def hacked_UpBlock2D_forward(self, hidden_states, res_hidden_states_tuple, temb=None, upsample_size=None):
646
+ eps = 1e-6
647
+ for i, resnet in enumerate(self.resnets):
648
+ # pop res hidden states
649
+ res_hidden_states = res_hidden_states_tuple[-1]
650
+ res_hidden_states_tuple = res_hidden_states_tuple[:-1]
651
+ hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
652
+ hidden_states = resnet(hidden_states, temb)
653
+
654
+ if MODE == "write":
655
+ if gn_auto_machine_weight >= self.gn_weight:
656
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
657
+ self.mean_bank.append([mean])
658
+ self.var_bank.append([var])
659
+ if MODE == "read":
660
+ if len(self.mean_bank) > 0 and len(self.var_bank) > 0:
661
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
662
+ std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5
663
+ mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))
664
+ var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))
665
+ std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5
666
+ hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc
667
+ hidden_states_c = hidden_states_uc.clone()
668
+ if do_classifier_free_guidance and style_fidelity > 0:
669
+ hidden_states_c[uc_mask] = hidden_states[uc_mask]
670
+ hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc
671
+
672
+ if MODE == "read":
673
+ self.mean_bank = []
674
+ self.var_bank = []
675
+
676
+ if self.upsamplers is not None:
677
+ for upsampler in self.upsamplers:
678
+ hidden_states = upsampler(hidden_states, upsample_size)
679
+
680
+ return hidden_states
681
+
682
+ if reference_attn:
683
+ attn_modules = [module for module in torch_dfs(self.unet) if isinstance(module, BasicTransformerBlock)]
684
+ attn_modules = sorted(attn_modules, key=lambda x: -x.norm1.normalized_shape[0])
685
+
686
+ for i, module in enumerate(attn_modules):
687
+ module._original_inner_forward = module.forward
688
+ module.forward = hacked_basic_transformer_inner_forward.__get__(module, BasicTransformerBlock)
689
+ module.bank = []
690
+ module.attn_weight = float(i) / float(len(attn_modules))
691
+
692
+ if reference_adain:
693
+ gn_modules = [self.unet.mid_block]
694
+ self.unet.mid_block.gn_weight = 0
695
+
696
+ down_blocks = self.unet.down_blocks
697
+ for w, module in enumerate(down_blocks):
698
+ module.gn_weight = 1.0 - float(w) / float(len(down_blocks))
699
+ gn_modules.append(module)
700
+
701
+ up_blocks = self.unet.up_blocks
702
+ for w, module in enumerate(up_blocks):
703
+ module.gn_weight = float(w) / float(len(up_blocks))
704
+ gn_modules.append(module)
705
+
706
+ for i, module in enumerate(gn_modules):
707
+ if getattr(module, "original_forward", None) is None:
708
+ module.original_forward = module.forward
709
+ if i == 0:
710
+ # mid_block
711
+ module.forward = hacked_mid_forward.__get__(module, torch.nn.Module)
712
+ elif isinstance(module, CrossAttnDownBlock2D):
713
+ module.forward = hack_CrossAttnDownBlock2D_forward.__get__(module, CrossAttnDownBlock2D)
714
+ elif isinstance(module, DownBlock2D):
715
+ module.forward = hacked_DownBlock2D_forward.__get__(module, DownBlock2D)
716
+ elif isinstance(module, CrossAttnUpBlock2D):
717
+ module.forward = hacked_CrossAttnUpBlock2D_forward.__get__(module, CrossAttnUpBlock2D)
718
+ elif isinstance(module, UpBlock2D):
719
+ module.forward = hacked_UpBlock2D_forward.__get__(module, UpBlock2D)
720
+ module.mean_bank = []
721
+ module.var_bank = []
722
+ module.gn_weight *= 2
723
+
724
+ # 11. Denoising loop
725
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
726
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
727
+ for i, t in enumerate(timesteps):
728
+ # expand the latents if we are doing classifier free guidance
729
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
730
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
731
+
732
+ # controlnet(s) inference
733
+ if guess_mode and do_classifier_free_guidance:
734
+ # Infer ControlNet only for the conditional batch.
735
+ control_model_input = latents
736
+ control_model_input = self.scheduler.scale_model_input(control_model_input, t)
737
+ controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
738
+ else:
739
+ control_model_input = latent_model_input
740
+ controlnet_prompt_embeds = prompt_embeds
741
+
742
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
743
+ control_model_input,
744
+ t,
745
+ encoder_hidden_states=controlnet_prompt_embeds,
746
+ controlnet_cond=image,
747
+ conditioning_scale=controlnet_conditioning_scale,
748
+ guess_mode=guess_mode,
749
+ return_dict=False,
750
+ )
751
+
752
+ if guess_mode and do_classifier_free_guidance:
753
+ # Infered ControlNet only for the conditional batch.
754
+ # To apply the output of ControlNet to both the unconditional and conditional batches,
755
+ # add 0 to the unconditional batch to keep it unchanged.
756
+ down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
757
+ mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
758
+
759
+ # ref only part
760
+ noise = randn_tensor(
761
+ ref_image_latents.shape, generator=generator, device=device, dtype=ref_image_latents.dtype
762
+ )
763
+ ref_xt = self.scheduler.add_noise(
764
+ ref_image_latents,
765
+ noise,
766
+ t.reshape(
767
+ 1,
768
+ ),
769
+ )
770
+ ref_xt = self.scheduler.scale_model_input(ref_xt, t)
771
+
772
+ MODE = "write"
773
+ self.unet(
774
+ ref_xt,
775
+ t,
776
+ encoder_hidden_states=prompt_embeds,
777
+ cross_attention_kwargs=cross_attention_kwargs,
778
+ return_dict=False,
779
+ )
780
+
781
+ # predict the noise residual
782
+ MODE = "read"
783
+ noise_pred = self.unet(
784
+ latent_model_input,
785
+ t,
786
+ encoder_hidden_states=prompt_embeds,
787
+ cross_attention_kwargs=cross_attention_kwargs,
788
+ down_block_additional_residuals=down_block_res_samples,
789
+ mid_block_additional_residual=mid_block_res_sample,
790
+ return_dict=False,
791
+ )[0]
792
+
793
+ # perform guidance
794
+ if do_classifier_free_guidance:
795
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
796
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
797
+
798
+ # compute the previous noisy sample x_t -> x_t-1
799
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
800
+
801
+ # call the callback, if provided
802
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
803
+ progress_bar.update()
804
+ if callback is not None and i % callback_steps == 0:
805
+ step_idx = i // getattr(self.scheduler, "order", 1)
806
+ callback(step_idx, t, latents)
807
+
808
+ # If we do sequential model offloading, let's offload unet and controlnet
809
+ # manually for max memory savings
810
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
811
+ self.unet.to("cpu")
812
+ self.controlnet.to("cpu")
813
+ torch.cuda.empty_cache()
814
+
815
+ if not output_type == "latent":
816
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
817
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
818
+ else:
819
+ image = latents
820
+ has_nsfw_concept = None
821
+
822
+ if has_nsfw_concept is None:
823
+ do_denormalize = [True] * image.shape[0]
824
+ else:
825
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
826
+
827
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
828
+
829
+ # Offload last model to CPU
830
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
831
+ self.final_offload_hook.offload()
832
+
833
+ if not return_dict:
834
+ return (image, has_nsfw_concept)
835
+
836
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.22.0/stable_diffusion_ipex.py ADDED
@@ -0,0 +1,858 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Union
17
+
18
+ import intel_extension_for_pytorch as ipex
19
+ import torch
20
+ from packaging import version
21
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
22
+
23
+ from diffusers.configuration_utils import FrozenDict
24
+ from diffusers.loaders import TextualInversionLoaderMixin
25
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
26
+ from diffusers.pipeline_utils import DiffusionPipeline
27
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
28
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
29
+ from diffusers.schedulers import KarrasDiffusionSchedulers
30
+ from diffusers.utils import (
31
+ deprecate,
32
+ is_accelerate_available,
33
+ is_accelerate_version,
34
+ logging,
35
+ replace_example_docstring,
36
+ )
37
+ from diffusers.utils.torch_utils import randn_tensor
38
+
39
+
40
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
41
+
42
+ EXAMPLE_DOC_STRING = """
43
+ Examples:
44
+ ```py
45
+ >>> import torch
46
+ >>> from diffusers import StableDiffusionPipeline
47
+
48
+ >>> pipe = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", custom_pipeline="stable_diffusion_ipex")
49
+
50
+ >>> # For Float32
51
+ >>> pipe.prepare_for_ipex(prompt, dtype=torch.float32, height=512, width=512) #value of image height/width should be consistent with the pipeline inference
52
+ >>> # For BFloat16
53
+ >>> pipe.prepare_for_ipex(prompt, dtype=torch.bfloat16, height=512, width=512) #value of image height/width should be consistent with the pipeline inference
54
+
55
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
56
+ >>> # For Float32
57
+ >>> image = pipe(prompt, num_inference_steps=num_inference_steps, height=512, width=512).images[0] #value of image height/width should be consistent with 'prepare_for_ipex()'
58
+ >>> # For BFloat16
59
+ >>> with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloat16):
60
+ >>> image = pipe(prompt, num_inference_steps=num_inference_steps, height=512, width=512).images[0] #value of image height/width should be consistent with 'prepare_for_ipex()'
61
+ ```
62
+ """
63
+
64
+
65
+ class StableDiffusionIPEXPipeline(DiffusionPipeline, TextualInversionLoaderMixin):
66
+ r"""
67
+ Pipeline for text-to-image generation using Stable Diffusion on IPEX.
68
+
69
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
70
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
71
+
72
+ Args:
73
+ vae ([`AutoencoderKL`]):
74
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
75
+ text_encoder ([`CLIPTextModel`]):
76
+ Frozen text-encoder. Stable Diffusion uses the text portion of
77
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
78
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
79
+ tokenizer (`CLIPTokenizer`):
80
+ Tokenizer of class
81
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
82
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
83
+ scheduler ([`SchedulerMixin`]):
84
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
85
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
86
+ safety_checker ([`StableDiffusionSafetyChecker`]):
87
+ Classification module that estimates whether generated images could be considered offensive or harmful.
88
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
89
+ feature_extractor ([`CLIPFeatureExtractor`]):
90
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
91
+ """
92
+ _optional_components = ["safety_checker", "feature_extractor"]
93
+
94
+ def __init__(
95
+ self,
96
+ vae: AutoencoderKL,
97
+ text_encoder: CLIPTextModel,
98
+ tokenizer: CLIPTokenizer,
99
+ unet: UNet2DConditionModel,
100
+ scheduler: KarrasDiffusionSchedulers,
101
+ safety_checker: StableDiffusionSafetyChecker,
102
+ feature_extractor: CLIPFeatureExtractor,
103
+ requires_safety_checker: bool = True,
104
+ ):
105
+ super().__init__()
106
+
107
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
108
+ deprecation_message = (
109
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
110
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
111
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
112
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
113
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
114
+ " file"
115
+ )
116
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
117
+ new_config = dict(scheduler.config)
118
+ new_config["steps_offset"] = 1
119
+ scheduler._internal_dict = FrozenDict(new_config)
120
+
121
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
122
+ deprecation_message = (
123
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
124
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
125
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
126
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
127
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
128
+ )
129
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
130
+ new_config = dict(scheduler.config)
131
+ new_config["clip_sample"] = False
132
+ scheduler._internal_dict = FrozenDict(new_config)
133
+
134
+ if safety_checker is None and requires_safety_checker:
135
+ logger.warning(
136
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
137
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
138
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
139
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
140
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
141
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
142
+ )
143
+
144
+ if safety_checker is not None and feature_extractor is None:
145
+ raise ValueError(
146
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
147
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
148
+ )
149
+
150
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
151
+ version.parse(unet.config._diffusers_version).base_version
152
+ ) < version.parse("0.9.0.dev0")
153
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
154
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
155
+ deprecation_message = (
156
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
157
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
158
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
159
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
160
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
161
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
162
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
163
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
164
+ " the `unet/config.json` file"
165
+ )
166
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
167
+ new_config = dict(unet.config)
168
+ new_config["sample_size"] = 64
169
+ unet._internal_dict = FrozenDict(new_config)
170
+
171
+ self.register_modules(
172
+ vae=vae,
173
+ text_encoder=text_encoder,
174
+ tokenizer=tokenizer,
175
+ unet=unet,
176
+ scheduler=scheduler,
177
+ safety_checker=safety_checker,
178
+ feature_extractor=feature_extractor,
179
+ )
180
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
181
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
182
+
183
+ def get_input_example(self, prompt, height=None, width=None, guidance_scale=7.5, num_images_per_prompt=1):
184
+ prompt_embeds = None
185
+ negative_prompt_embeds = None
186
+ negative_prompt = None
187
+ callback_steps = 1
188
+ generator = None
189
+ latents = None
190
+
191
+ # 0. Default height and width to unet
192
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
193
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
194
+
195
+ # 1. Check inputs. Raise error if not correct
196
+ self.check_inputs(
197
+ prompt, height, width, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds
198
+ )
199
+
200
+ # 2. Define call parameters
201
+ if prompt is not None and isinstance(prompt, str):
202
+ batch_size = 1
203
+ elif prompt is not None and isinstance(prompt, list):
204
+ batch_size = len(prompt)
205
+
206
+ device = "cpu"
207
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
208
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
209
+ # corresponds to doing no classifier free guidance.
210
+ do_classifier_free_guidance = guidance_scale > 1.0
211
+
212
+ # 3. Encode input prompt
213
+ prompt_embeds = self._encode_prompt(
214
+ prompt,
215
+ device,
216
+ num_images_per_prompt,
217
+ do_classifier_free_guidance,
218
+ negative_prompt,
219
+ prompt_embeds=prompt_embeds,
220
+ negative_prompt_embeds=negative_prompt_embeds,
221
+ )
222
+
223
+ # 5. Prepare latent variables
224
+ latents = self.prepare_latents(
225
+ batch_size * num_images_per_prompt,
226
+ self.unet.in_channels,
227
+ height,
228
+ width,
229
+ prompt_embeds.dtype,
230
+ device,
231
+ generator,
232
+ latents,
233
+ )
234
+ dummy = torch.ones(1, dtype=torch.int32)
235
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
236
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, dummy)
237
+
238
+ unet_input_example = (latent_model_input, dummy, prompt_embeds)
239
+ vae_decoder_input_example = latents
240
+
241
+ return unet_input_example, vae_decoder_input_example
242
+
243
+ def prepare_for_ipex(self, promt, dtype=torch.float32, height=None, width=None, guidance_scale=7.5):
244
+ self.unet = self.unet.to(memory_format=torch.channels_last)
245
+ self.vae.decoder = self.vae.decoder.to(memory_format=torch.channels_last)
246
+ self.text_encoder = self.text_encoder.to(memory_format=torch.channels_last)
247
+ if self.safety_checker is not None:
248
+ self.safety_checker = self.safety_checker.to(memory_format=torch.channels_last)
249
+
250
+ unet_input_example, vae_decoder_input_example = self.get_input_example(promt, height, width, guidance_scale)
251
+
252
+ # optimize with ipex
253
+ if dtype == torch.bfloat16:
254
+ self.unet = ipex.optimize(
255
+ self.unet.eval(), dtype=torch.bfloat16, inplace=True, sample_input=unet_input_example
256
+ )
257
+ self.vae.decoder = ipex.optimize(self.vae.decoder.eval(), dtype=torch.bfloat16, inplace=True)
258
+ self.text_encoder = ipex.optimize(self.text_encoder.eval(), dtype=torch.bfloat16, inplace=True)
259
+ if self.safety_checker is not None:
260
+ self.safety_checker = ipex.optimize(self.safety_checker.eval(), dtype=torch.bfloat16, inplace=True)
261
+ elif dtype == torch.float32:
262
+ self.unet = ipex.optimize(
263
+ self.unet.eval(),
264
+ dtype=torch.float32,
265
+ inplace=True,
266
+ sample_input=unet_input_example,
267
+ level="O1",
268
+ weights_prepack=True,
269
+ auto_kernel_selection=False,
270
+ )
271
+ self.vae.decoder = ipex.optimize(
272
+ self.vae.decoder.eval(),
273
+ dtype=torch.float32,
274
+ inplace=True,
275
+ level="O1",
276
+ weights_prepack=True,
277
+ auto_kernel_selection=False,
278
+ )
279
+ self.text_encoder = ipex.optimize(
280
+ self.text_encoder.eval(),
281
+ dtype=torch.float32,
282
+ inplace=True,
283
+ level="O1",
284
+ weights_prepack=True,
285
+ auto_kernel_selection=False,
286
+ )
287
+ if self.safety_checker is not None:
288
+ self.safety_checker = ipex.optimize(
289
+ self.safety_checker.eval(),
290
+ dtype=torch.float32,
291
+ inplace=True,
292
+ level="O1",
293
+ weights_prepack=True,
294
+ auto_kernel_selection=False,
295
+ )
296
+ else:
297
+ raise ValueError(" The value of 'dtype' should be 'torch.bfloat16' or 'torch.float32' !")
298
+
299
+ # trace unet model to get better performance on IPEX
300
+ with torch.cpu.amp.autocast(enabled=dtype == torch.bfloat16), torch.no_grad():
301
+ unet_trace_model = torch.jit.trace(self.unet, unet_input_example, check_trace=False, strict=False)
302
+ unet_trace_model = torch.jit.freeze(unet_trace_model)
303
+ self.unet.forward = unet_trace_model.forward
304
+
305
+ # trace vae.decoder model to get better performance on IPEX
306
+ with torch.cpu.amp.autocast(enabled=dtype == torch.bfloat16), torch.no_grad():
307
+ ave_decoder_trace_model = torch.jit.trace(
308
+ self.vae.decoder, vae_decoder_input_example, check_trace=False, strict=False
309
+ )
310
+ ave_decoder_trace_model = torch.jit.freeze(ave_decoder_trace_model)
311
+ self.vae.decoder.forward = ave_decoder_trace_model.forward
312
+
313
+ def enable_vae_slicing(self):
314
+ r"""
315
+ Enable sliced VAE decoding.
316
+
317
+ When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
318
+ steps. This is useful to save some memory and allow larger batch sizes.
319
+ """
320
+ self.vae.enable_slicing()
321
+
322
+ def disable_vae_slicing(self):
323
+ r"""
324
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to
325
+ computing decoding in one step.
326
+ """
327
+ self.vae.disable_slicing()
328
+
329
+ def enable_vae_tiling(self):
330
+ r"""
331
+ Enable tiled VAE decoding.
332
+
333
+ When this option is enabled, the VAE will split the input tensor into tiles to compute decoding and encoding in
334
+ several steps. This is useful to save a large amount of memory and to allow the processing of larger images.
335
+ """
336
+ self.vae.enable_tiling()
337
+
338
+ def disable_vae_tiling(self):
339
+ r"""
340
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously invoked, this method will go back to
341
+ computing decoding in one step.
342
+ """
343
+ self.vae.disable_tiling()
344
+
345
+ def enable_sequential_cpu_offload(self, gpu_id=0):
346
+ r"""
347
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
348
+ text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
349
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
350
+ Note that offloading happens on a submodule basis. Memory savings are higher than with
351
+ `enable_model_cpu_offload`, but performance is lower.
352
+ """
353
+ if is_accelerate_available() and is_accelerate_version(">=", "0.14.0"):
354
+ from accelerate import cpu_offload
355
+ else:
356
+ raise ImportError("`enable_sequential_cpu_offload` requires `accelerate v0.14.0` or higher")
357
+
358
+ device = torch.device(f"cuda:{gpu_id}")
359
+
360
+ if self.device.type != "cpu":
361
+ self.to("cpu", silence_dtype_warnings=True)
362
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
363
+
364
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]:
365
+ cpu_offload(cpu_offloaded_model, device)
366
+
367
+ if self.safety_checker is not None:
368
+ cpu_offload(self.safety_checker, execution_device=device, offload_buffers=True)
369
+
370
+ def enable_model_cpu_offload(self, gpu_id=0):
371
+ r"""
372
+ Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
373
+ to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
374
+ method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
375
+ `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
376
+ """
377
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
378
+ from accelerate import cpu_offload_with_hook
379
+ else:
380
+ raise ImportError("`enable_model_offload` requires `accelerate v0.17.0` or higher.")
381
+
382
+ device = torch.device(f"cuda:{gpu_id}")
383
+
384
+ if self.device.type != "cpu":
385
+ self.to("cpu", silence_dtype_warnings=True)
386
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
387
+
388
+ hook = None
389
+ for cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]:
390
+ _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
391
+
392
+ if self.safety_checker is not None:
393
+ _, hook = cpu_offload_with_hook(self.safety_checker, device, prev_module_hook=hook)
394
+
395
+ # We'll offload the last model manually.
396
+ self.final_offload_hook = hook
397
+
398
+ @property
399
+ def _execution_device(self):
400
+ r"""
401
+ Returns the device on which the pipeline's models will be executed. After calling
402
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
403
+ hooks.
404
+ """
405
+ if not hasattr(self.unet, "_hf_hook"):
406
+ return self.device
407
+ for module in self.unet.modules():
408
+ if (
409
+ hasattr(module, "_hf_hook")
410
+ and hasattr(module._hf_hook, "execution_device")
411
+ and module._hf_hook.execution_device is not None
412
+ ):
413
+ return torch.device(module._hf_hook.execution_device)
414
+ return self.device
415
+
416
+ def _encode_prompt(
417
+ self,
418
+ prompt,
419
+ device,
420
+ num_images_per_prompt,
421
+ do_classifier_free_guidance,
422
+ negative_prompt=None,
423
+ prompt_embeds: Optional[torch.FloatTensor] = None,
424
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
425
+ ):
426
+ r"""
427
+ Encodes the prompt into text encoder hidden states.
428
+
429
+ Args:
430
+ prompt (`str` or `List[str]`, *optional*):
431
+ prompt to be encoded
432
+ device: (`torch.device`):
433
+ torch device
434
+ num_images_per_prompt (`int`):
435
+ number of images that should be generated per prompt
436
+ do_classifier_free_guidance (`bool`):
437
+ whether to use classifier free guidance or not
438
+ negative_prompt (`str` or `List[str]`, *optional*):
439
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
440
+ `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
441
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
442
+ prompt_embeds (`torch.FloatTensor`, *optional*):
443
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
444
+ provided, text embeddings will be generated from `prompt` input argument.
445
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
446
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
447
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
448
+ argument.
449
+ """
450
+ if prompt is not None and isinstance(prompt, str):
451
+ batch_size = 1
452
+ elif prompt is not None and isinstance(prompt, list):
453
+ batch_size = len(prompt)
454
+ else:
455
+ batch_size = prompt_embeds.shape[0]
456
+
457
+ if prompt_embeds is None:
458
+ # textual inversion: procecss multi-vector tokens if necessary
459
+ if isinstance(self, TextualInversionLoaderMixin):
460
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
461
+
462
+ text_inputs = self.tokenizer(
463
+ prompt,
464
+ padding="max_length",
465
+ max_length=self.tokenizer.model_max_length,
466
+ truncation=True,
467
+ return_tensors="pt",
468
+ )
469
+ text_input_ids = text_inputs.input_ids
470
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
471
+
472
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
473
+ text_input_ids, untruncated_ids
474
+ ):
475
+ removed_text = self.tokenizer.batch_decode(
476
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
477
+ )
478
+ logger.warning(
479
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
480
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
481
+ )
482
+
483
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
484
+ attention_mask = text_inputs.attention_mask.to(device)
485
+ else:
486
+ attention_mask = None
487
+
488
+ prompt_embeds = self.text_encoder(
489
+ text_input_ids.to(device),
490
+ attention_mask=attention_mask,
491
+ )
492
+ prompt_embeds = prompt_embeds[0]
493
+
494
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
495
+
496
+ bs_embed, seq_len, _ = prompt_embeds.shape
497
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
498
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
499
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
500
+
501
+ # get unconditional embeddings for classifier free guidance
502
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
503
+ uncond_tokens: List[str]
504
+ if negative_prompt is None:
505
+ uncond_tokens = [""] * batch_size
506
+ elif type(prompt) is not type(negative_prompt):
507
+ raise TypeError(
508
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
509
+ f" {type(prompt)}."
510
+ )
511
+ elif isinstance(negative_prompt, str):
512
+ uncond_tokens = [negative_prompt]
513
+ elif batch_size != len(negative_prompt):
514
+ raise ValueError(
515
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
516
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
517
+ " the batch size of `prompt`."
518
+ )
519
+ else:
520
+ uncond_tokens = negative_prompt
521
+
522
+ # textual inversion: procecss multi-vector tokens if necessary
523
+ if isinstance(self, TextualInversionLoaderMixin):
524
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
525
+
526
+ max_length = prompt_embeds.shape[1]
527
+ uncond_input = self.tokenizer(
528
+ uncond_tokens,
529
+ padding="max_length",
530
+ max_length=max_length,
531
+ truncation=True,
532
+ return_tensors="pt",
533
+ )
534
+
535
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
536
+ attention_mask = uncond_input.attention_mask.to(device)
537
+ else:
538
+ attention_mask = None
539
+
540
+ negative_prompt_embeds = self.text_encoder(
541
+ uncond_input.input_ids.to(device),
542
+ attention_mask=attention_mask,
543
+ )
544
+ negative_prompt_embeds = negative_prompt_embeds[0]
545
+
546
+ if do_classifier_free_guidance:
547
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
548
+ seq_len = negative_prompt_embeds.shape[1]
549
+
550
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
551
+
552
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
553
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
554
+
555
+ # For classifier free guidance, we need to do two forward passes.
556
+ # Here we concatenate the unconditional and text embeddings into a single batch
557
+ # to avoid doing two forward passes
558
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
559
+
560
+ return prompt_embeds
561
+
562
+ def run_safety_checker(self, image, device, dtype):
563
+ if self.safety_checker is not None:
564
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
565
+ image, has_nsfw_concept = self.safety_checker(
566
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
567
+ )
568
+ else:
569
+ has_nsfw_concept = None
570
+ return image, has_nsfw_concept
571
+
572
+ def decode_latents(self, latents):
573
+ latents = 1 / self.vae.config.scaling_factor * latents
574
+ image = self.vae.decode(latents).sample
575
+ image = (image / 2 + 0.5).clamp(0, 1)
576
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
577
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
578
+ return image
579
+
580
+ def prepare_extra_step_kwargs(self, generator, eta):
581
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
582
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
583
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
584
+ # and should be between [0, 1]
585
+
586
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
587
+ extra_step_kwargs = {}
588
+ if accepts_eta:
589
+ extra_step_kwargs["eta"] = eta
590
+
591
+ # check if the scheduler accepts generator
592
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
593
+ if accepts_generator:
594
+ extra_step_kwargs["generator"] = generator
595
+ return extra_step_kwargs
596
+
597
+ def check_inputs(
598
+ self,
599
+ prompt,
600
+ height,
601
+ width,
602
+ callback_steps,
603
+ negative_prompt=None,
604
+ prompt_embeds=None,
605
+ negative_prompt_embeds=None,
606
+ ):
607
+ if height % 8 != 0 or width % 8 != 0:
608
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
609
+
610
+ if (callback_steps is None) or (
611
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
612
+ ):
613
+ raise ValueError(
614
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
615
+ f" {type(callback_steps)}."
616
+ )
617
+
618
+ if prompt is not None and prompt_embeds is not None:
619
+ raise ValueError(
620
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
621
+ " only forward one of the two."
622
+ )
623
+ elif prompt is None and prompt_embeds is None:
624
+ raise ValueError(
625
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
626
+ )
627
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
628
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
629
+
630
+ if negative_prompt is not None and negative_prompt_embeds is not None:
631
+ raise ValueError(
632
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
633
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
634
+ )
635
+
636
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
637
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
638
+ raise ValueError(
639
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
640
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
641
+ f" {negative_prompt_embeds.shape}."
642
+ )
643
+
644
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
645
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
646
+ if isinstance(generator, list) and len(generator) != batch_size:
647
+ raise ValueError(
648
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
649
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
650
+ )
651
+
652
+ if latents is None:
653
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
654
+ else:
655
+ latents = latents.to(device)
656
+
657
+ # scale the initial noise by the standard deviation required by the scheduler
658
+ latents = latents * self.scheduler.init_noise_sigma
659
+ return latents
660
+
661
+ @torch.no_grad()
662
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
663
+ def __call__(
664
+ self,
665
+ prompt: Union[str, List[str]] = None,
666
+ height: Optional[int] = None,
667
+ width: Optional[int] = None,
668
+ num_inference_steps: int = 50,
669
+ guidance_scale: float = 7.5,
670
+ negative_prompt: Optional[Union[str, List[str]]] = None,
671
+ num_images_per_prompt: Optional[int] = 1,
672
+ eta: float = 0.0,
673
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
674
+ latents: Optional[torch.FloatTensor] = None,
675
+ prompt_embeds: Optional[torch.FloatTensor] = None,
676
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
677
+ output_type: Optional[str] = "pil",
678
+ return_dict: bool = True,
679
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
680
+ callback_steps: int = 1,
681
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
682
+ ):
683
+ r"""
684
+ Function invoked when calling the pipeline for generation.
685
+
686
+ Args:
687
+ prompt (`str` or `List[str]`, *optional*):
688
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
689
+ instead.
690
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
691
+ The height in pixels of the generated image.
692
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
693
+ The width in pixels of the generated image.
694
+ num_inference_steps (`int`, *optional*, defaults to 50):
695
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
696
+ expense of slower inference.
697
+ guidance_scale (`float`, *optional*, defaults to 7.5):
698
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
699
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
700
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
701
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
702
+ usually at the expense of lower image quality.
703
+ negative_prompt (`str` or `List[str]`, *optional*):
704
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
705
+ `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
706
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
707
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
708
+ The number of images to generate per prompt.
709
+ eta (`float`, *optional*, defaults to 0.0):
710
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
711
+ [`schedulers.DDIMScheduler`], will be ignored for others.
712
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
713
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
714
+ to make generation deterministic.
715
+ latents (`torch.FloatTensor`, *optional*):
716
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
717
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
718
+ tensor will ge generated by sampling using the supplied random `generator`.
719
+ prompt_embeds (`torch.FloatTensor`, *optional*):
720
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
721
+ provided, text embeddings will be generated from `prompt` input argument.
722
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
723
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
724
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
725
+ argument.
726
+ output_type (`str`, *optional*, defaults to `"pil"`):
727
+ The output format of the generate image. Choose between
728
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
729
+ return_dict (`bool`, *optional*, defaults to `True`):
730
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
731
+ plain tuple.
732
+ callback (`Callable`, *optional*):
733
+ A function that will be called every `callback_steps` steps during inference. The function will be
734
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
735
+ callback_steps (`int`, *optional*, defaults to 1):
736
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
737
+ called at every step.
738
+ cross_attention_kwargs (`dict`, *optional*):
739
+ A kwargs dictionary that if specified is passed along to the `AttnProcessor` as defined under
740
+ `self.processor` in
741
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
742
+
743
+ Examples:
744
+
745
+ Returns:
746
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
747
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
748
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
749
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
750
+ (nsfw) content, according to the `safety_checker`.
751
+ """
752
+ # 0. Default height and width to unet
753
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
754
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
755
+
756
+ # 1. Check inputs. Raise error if not correct
757
+ self.check_inputs(
758
+ prompt, height, width, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds
759
+ )
760
+
761
+ # 2. Define call parameters
762
+ if prompt is not None and isinstance(prompt, str):
763
+ batch_size = 1
764
+ elif prompt is not None and isinstance(prompt, list):
765
+ batch_size = len(prompt)
766
+ else:
767
+ batch_size = prompt_embeds.shape[0]
768
+
769
+ device = self._execution_device
770
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
771
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
772
+ # corresponds to doing no classifier free guidance.
773
+ do_classifier_free_guidance = guidance_scale > 1.0
774
+
775
+ # 3. Encode input prompt
776
+ prompt_embeds = self._encode_prompt(
777
+ prompt,
778
+ device,
779
+ num_images_per_prompt,
780
+ do_classifier_free_guidance,
781
+ negative_prompt,
782
+ prompt_embeds=prompt_embeds,
783
+ negative_prompt_embeds=negative_prompt_embeds,
784
+ )
785
+
786
+ # 4. Prepare timesteps
787
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
788
+ timesteps = self.scheduler.timesteps
789
+
790
+ # 5. Prepare latent variables
791
+ num_channels_latents = self.unet.in_channels
792
+ latents = self.prepare_latents(
793
+ batch_size * num_images_per_prompt,
794
+ num_channels_latents,
795
+ height,
796
+ width,
797
+ prompt_embeds.dtype,
798
+ device,
799
+ generator,
800
+ latents,
801
+ )
802
+
803
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
804
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
805
+
806
+ # 7. Denoising loop
807
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
808
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
809
+ for i, t in enumerate(timesteps):
810
+ # expand the latents if we are doing classifier free guidance
811
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
812
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
813
+
814
+ # predict the noise residual
815
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=prompt_embeds)["sample"]
816
+
817
+ # perform guidance
818
+ if do_classifier_free_guidance:
819
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
820
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
821
+
822
+ # compute the previous noisy sample x_t -> x_t-1
823
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
824
+
825
+ # call the callback, if provided
826
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
827
+ progress_bar.update()
828
+ if callback is not None and i % callback_steps == 0:
829
+ step_idx = i // getattr(self.scheduler, "order", 1)
830
+ callback(step_idx, t, latents)
831
+
832
+ if output_type == "latent":
833
+ image = latents
834
+ has_nsfw_concept = None
835
+ elif output_type == "pil":
836
+ # 8. Post-processing
837
+ image = self.decode_latents(latents)
838
+
839
+ # 9. Run safety checker
840
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
841
+
842
+ # 10. Convert to PIL
843
+ image = self.numpy_to_pil(image)
844
+ else:
845
+ # 8. Post-processing
846
+ image = self.decode_latents(latents)
847
+
848
+ # 9. Run safety checker
849
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
850
+
851
+ # Offload last model to CPU
852
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
853
+ self.final_offload_hook.offload()
854
+
855
+ if not return_dict:
856
+ return (image, has_nsfw_concept)
857
+
858
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.22.0/stable_diffusion_mega.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, Dict, List, Optional, Union
2
+
3
+ import PIL.Image
4
+ import torch
5
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
6
+
7
+ from diffusers import (
8
+ AutoencoderKL,
9
+ DDIMScheduler,
10
+ DiffusionPipeline,
11
+ LMSDiscreteScheduler,
12
+ PNDMScheduler,
13
+ StableDiffusionImg2ImgPipeline,
14
+ StableDiffusionInpaintPipelineLegacy,
15
+ StableDiffusionPipeline,
16
+ UNet2DConditionModel,
17
+ )
18
+ from diffusers.configuration_utils import FrozenDict
19
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
20
+ from diffusers.utils import deprecate, logging
21
+
22
+
23
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
24
+
25
+
26
+ class StableDiffusionMegaPipeline(DiffusionPipeline):
27
+ r"""
28
+ Pipeline for text-to-image generation using Stable Diffusion.
29
+
30
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
31
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
32
+
33
+ Args:
34
+ vae ([`AutoencoderKL`]):
35
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
36
+ text_encoder ([`CLIPTextModel`]):
37
+ Frozen text-encoder. Stable Diffusion uses the text portion of
38
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
39
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
40
+ tokenizer (`CLIPTokenizer`):
41
+ Tokenizer of class
42
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
43
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
44
+ scheduler ([`SchedulerMixin`]):
45
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
46
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
47
+ safety_checker ([`StableDiffusionMegaSafetyChecker`]):
48
+ Classification module that estimates whether generated images could be considered offensive or harmful.
49
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
50
+ feature_extractor ([`CLIPImageProcessor`]):
51
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
52
+ """
53
+ _optional_components = ["safety_checker", "feature_extractor"]
54
+
55
+ def __init__(
56
+ self,
57
+ vae: AutoencoderKL,
58
+ text_encoder: CLIPTextModel,
59
+ tokenizer: CLIPTokenizer,
60
+ unet: UNet2DConditionModel,
61
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
62
+ safety_checker: StableDiffusionSafetyChecker,
63
+ feature_extractor: CLIPImageProcessor,
64
+ requires_safety_checker: bool = True,
65
+ ):
66
+ super().__init__()
67
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
68
+ deprecation_message = (
69
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
70
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
71
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
72
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
73
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
74
+ " file"
75
+ )
76
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
77
+ new_config = dict(scheduler.config)
78
+ new_config["steps_offset"] = 1
79
+ scheduler._internal_dict = FrozenDict(new_config)
80
+
81
+ self.register_modules(
82
+ vae=vae,
83
+ text_encoder=text_encoder,
84
+ tokenizer=tokenizer,
85
+ unet=unet,
86
+ scheduler=scheduler,
87
+ safety_checker=safety_checker,
88
+ feature_extractor=feature_extractor,
89
+ )
90
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
91
+
92
+ @property
93
+ def components(self) -> Dict[str, Any]:
94
+ return {k: getattr(self, k) for k in self.config.keys() if not k.startswith("_")}
95
+
96
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
97
+ r"""
98
+ Enable sliced attention computation.
99
+
100
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
101
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
102
+
103
+ Args:
104
+ slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
105
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
106
+ a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
107
+ `attention_head_dim` must be a multiple of `slice_size`.
108
+ """
109
+ if slice_size == "auto":
110
+ # half the attention head size is usually a good trade-off between
111
+ # speed and memory
112
+ slice_size = self.unet.config.attention_head_dim // 2
113
+ self.unet.set_attention_slice(slice_size)
114
+
115
+ def disable_attention_slicing(self):
116
+ r"""
117
+ Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
118
+ back to computing attention in one step.
119
+ """
120
+ # set slice_size = `None` to disable `attention slicing`
121
+ self.enable_attention_slicing(None)
122
+
123
+ @torch.no_grad()
124
+ def inpaint(
125
+ self,
126
+ prompt: Union[str, List[str]],
127
+ image: Union[torch.FloatTensor, PIL.Image.Image],
128
+ mask_image: Union[torch.FloatTensor, PIL.Image.Image],
129
+ strength: float = 0.8,
130
+ num_inference_steps: Optional[int] = 50,
131
+ guidance_scale: Optional[float] = 7.5,
132
+ negative_prompt: Optional[Union[str, List[str]]] = None,
133
+ num_images_per_prompt: Optional[int] = 1,
134
+ eta: Optional[float] = 0.0,
135
+ generator: Optional[torch.Generator] = None,
136
+ output_type: Optional[str] = "pil",
137
+ return_dict: bool = True,
138
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
139
+ callback_steps: int = 1,
140
+ ):
141
+ # For more information on how this function works, please see: https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionImg2ImgPipeline
142
+ return StableDiffusionInpaintPipelineLegacy(**self.components)(
143
+ prompt=prompt,
144
+ image=image,
145
+ mask_image=mask_image,
146
+ strength=strength,
147
+ num_inference_steps=num_inference_steps,
148
+ guidance_scale=guidance_scale,
149
+ negative_prompt=negative_prompt,
150
+ num_images_per_prompt=num_images_per_prompt,
151
+ eta=eta,
152
+ generator=generator,
153
+ output_type=output_type,
154
+ return_dict=return_dict,
155
+ callback=callback,
156
+ )
157
+
158
+ @torch.no_grad()
159
+ def img2img(
160
+ self,
161
+ prompt: Union[str, List[str]],
162
+ image: Union[torch.FloatTensor, PIL.Image.Image],
163
+ strength: float = 0.8,
164
+ num_inference_steps: Optional[int] = 50,
165
+ guidance_scale: Optional[float] = 7.5,
166
+ negative_prompt: Optional[Union[str, List[str]]] = None,
167
+ num_images_per_prompt: Optional[int] = 1,
168
+ eta: Optional[float] = 0.0,
169
+ generator: Optional[torch.Generator] = None,
170
+ output_type: Optional[str] = "pil",
171
+ return_dict: bool = True,
172
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
173
+ callback_steps: int = 1,
174
+ **kwargs,
175
+ ):
176
+ # For more information on how this function works, please see: https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionImg2ImgPipeline
177
+ return StableDiffusionImg2ImgPipeline(**self.components)(
178
+ prompt=prompt,
179
+ image=image,
180
+ strength=strength,
181
+ num_inference_steps=num_inference_steps,
182
+ guidance_scale=guidance_scale,
183
+ negative_prompt=negative_prompt,
184
+ num_images_per_prompt=num_images_per_prompt,
185
+ eta=eta,
186
+ generator=generator,
187
+ output_type=output_type,
188
+ return_dict=return_dict,
189
+ callback=callback,
190
+ callback_steps=callback_steps,
191
+ )
192
+
193
+ @torch.no_grad()
194
+ def text2img(
195
+ self,
196
+ prompt: Union[str, List[str]],
197
+ height: int = 512,
198
+ width: int = 512,
199
+ num_inference_steps: int = 50,
200
+ guidance_scale: float = 7.5,
201
+ negative_prompt: Optional[Union[str, List[str]]] = None,
202
+ num_images_per_prompt: Optional[int] = 1,
203
+ eta: float = 0.0,
204
+ generator: Optional[torch.Generator] = None,
205
+ latents: Optional[torch.FloatTensor] = None,
206
+ output_type: Optional[str] = "pil",
207
+ return_dict: bool = True,
208
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
209
+ callback_steps: int = 1,
210
+ ):
211
+ # For more information on how this function https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionPipeline
212
+ return StableDiffusionPipeline(**self.components)(
213
+ prompt=prompt,
214
+ height=height,
215
+ width=width,
216
+ num_inference_steps=num_inference_steps,
217
+ guidance_scale=guidance_scale,
218
+ negative_prompt=negative_prompt,
219
+ num_images_per_prompt=num_images_per_prompt,
220
+ eta=eta,
221
+ generator=generator,
222
+ latents=latents,
223
+ output_type=output_type,
224
+ return_dict=return_dict,
225
+ callback=callback,
226
+ callback_steps=callback_steps,
227
+ )
v0.22.0/stable_diffusion_reference.py ADDED
@@ -0,0 +1,797 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inspired by: https://github.com/Mikubill/sd-webui-controlnet/discussions/1236 and https://github.com/Mikubill/sd-webui-controlnet/discussions/1280
2
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
3
+
4
+ import numpy as np
5
+ import PIL.Image
6
+ import torch
7
+
8
+ from diffusers import StableDiffusionPipeline
9
+ from diffusers.models.attention import BasicTransformerBlock
10
+ from diffusers.models.unet_2d_blocks import CrossAttnDownBlock2D, CrossAttnUpBlock2D, DownBlock2D, UpBlock2D
11
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
12
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import rescale_noise_cfg
13
+ from diffusers.utils import PIL_INTERPOLATION, logging
14
+ from diffusers.utils.torch_utils import randn_tensor
15
+
16
+
17
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
18
+
19
+ EXAMPLE_DOC_STRING = """
20
+ Examples:
21
+ ```py
22
+ >>> import torch
23
+ >>> from diffusers import UniPCMultistepScheduler
24
+ >>> from diffusers.utils import load_image
25
+
26
+ >>> input_image = load_image("https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png")
27
+
28
+ >>> pipe = StableDiffusionReferencePipeline.from_pretrained(
29
+ "runwayml/stable-diffusion-v1-5",
30
+ safety_checker=None,
31
+ torch_dtype=torch.float16
32
+ ).to('cuda:0')
33
+
34
+ >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe_controlnet.scheduler.config)
35
+
36
+ >>> result_img = pipe(ref_image=input_image,
37
+ prompt="1girl",
38
+ num_inference_steps=20,
39
+ reference_attn=True,
40
+ reference_adain=True).images[0]
41
+
42
+ >>> result_img.show()
43
+ ```
44
+ """
45
+
46
+
47
+ def torch_dfs(model: torch.nn.Module):
48
+ result = [model]
49
+ for child in model.children():
50
+ result += torch_dfs(child)
51
+ return result
52
+
53
+
54
+ class StableDiffusionReferencePipeline(StableDiffusionPipeline):
55
+ def _default_height_width(self, height, width, image):
56
+ # NOTE: It is possible that a list of images have different
57
+ # dimensions for each image, so just checking the first image
58
+ # is not _exactly_ correct, but it is simple.
59
+ while isinstance(image, list):
60
+ image = image[0]
61
+
62
+ if height is None:
63
+ if isinstance(image, PIL.Image.Image):
64
+ height = image.height
65
+ elif isinstance(image, torch.Tensor):
66
+ height = image.shape[2]
67
+
68
+ height = (height // 8) * 8 # round down to nearest multiple of 8
69
+
70
+ if width is None:
71
+ if isinstance(image, PIL.Image.Image):
72
+ width = image.width
73
+ elif isinstance(image, torch.Tensor):
74
+ width = image.shape[3]
75
+
76
+ width = (width // 8) * 8 # round down to nearest multiple of 8
77
+
78
+ return height, width
79
+
80
+ def prepare_image(
81
+ self,
82
+ image,
83
+ width,
84
+ height,
85
+ batch_size,
86
+ num_images_per_prompt,
87
+ device,
88
+ dtype,
89
+ do_classifier_free_guidance=False,
90
+ guess_mode=False,
91
+ ):
92
+ if not isinstance(image, torch.Tensor):
93
+ if isinstance(image, PIL.Image.Image):
94
+ image = [image]
95
+
96
+ if isinstance(image[0], PIL.Image.Image):
97
+ images = []
98
+
99
+ for image_ in image:
100
+ image_ = image_.convert("RGB")
101
+ image_ = image_.resize((width, height), resample=PIL_INTERPOLATION["lanczos"])
102
+ image_ = np.array(image_)
103
+ image_ = image_[None, :]
104
+ images.append(image_)
105
+
106
+ image = images
107
+
108
+ image = np.concatenate(image, axis=0)
109
+ image = np.array(image).astype(np.float32) / 255.0
110
+ image = (image - 0.5) / 0.5
111
+ image = image.transpose(0, 3, 1, 2)
112
+ image = torch.from_numpy(image)
113
+ elif isinstance(image[0], torch.Tensor):
114
+ image = torch.cat(image, dim=0)
115
+
116
+ image_batch_size = image.shape[0]
117
+
118
+ if image_batch_size == 1:
119
+ repeat_by = batch_size
120
+ else:
121
+ # image batch size is the same as prompt batch size
122
+ repeat_by = num_images_per_prompt
123
+
124
+ image = image.repeat_interleave(repeat_by, dim=0)
125
+
126
+ image = image.to(device=device, dtype=dtype)
127
+
128
+ if do_classifier_free_guidance and not guess_mode:
129
+ image = torch.cat([image] * 2)
130
+
131
+ return image
132
+
133
+ def prepare_ref_latents(self, refimage, batch_size, dtype, device, generator, do_classifier_free_guidance):
134
+ refimage = refimage.to(device=device, dtype=dtype)
135
+
136
+ # encode the mask image into latents space so we can concatenate it to the latents
137
+ if isinstance(generator, list):
138
+ ref_image_latents = [
139
+ self.vae.encode(refimage[i : i + 1]).latent_dist.sample(generator=generator[i])
140
+ for i in range(batch_size)
141
+ ]
142
+ ref_image_latents = torch.cat(ref_image_latents, dim=0)
143
+ else:
144
+ ref_image_latents = self.vae.encode(refimage).latent_dist.sample(generator=generator)
145
+ ref_image_latents = self.vae.config.scaling_factor * ref_image_latents
146
+
147
+ # duplicate mask and ref_image_latents for each generation per prompt, using mps friendly method
148
+ if ref_image_latents.shape[0] < batch_size:
149
+ if not batch_size % ref_image_latents.shape[0] == 0:
150
+ raise ValueError(
151
+ "The passed images and the required batch size don't match. Images are supposed to be duplicated"
152
+ f" to a total batch size of {batch_size}, but {ref_image_latents.shape[0]} images were passed."
153
+ " Make sure the number of images that you pass is divisible by the total requested batch size."
154
+ )
155
+ ref_image_latents = ref_image_latents.repeat(batch_size // ref_image_latents.shape[0], 1, 1, 1)
156
+
157
+ # aligning device to prevent device errors when concating it with the latent model input
158
+ ref_image_latents = ref_image_latents.to(device=device, dtype=dtype)
159
+ return ref_image_latents
160
+
161
+ @torch.no_grad()
162
+ def __call__(
163
+ self,
164
+ prompt: Union[str, List[str]] = None,
165
+ ref_image: Union[torch.FloatTensor, PIL.Image.Image] = None,
166
+ height: Optional[int] = None,
167
+ width: Optional[int] = None,
168
+ num_inference_steps: int = 50,
169
+ guidance_scale: float = 7.5,
170
+ negative_prompt: Optional[Union[str, List[str]]] = None,
171
+ num_images_per_prompt: Optional[int] = 1,
172
+ eta: float = 0.0,
173
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
174
+ latents: Optional[torch.FloatTensor] = None,
175
+ prompt_embeds: Optional[torch.FloatTensor] = None,
176
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
177
+ output_type: Optional[str] = "pil",
178
+ return_dict: bool = True,
179
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
180
+ callback_steps: int = 1,
181
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
182
+ guidance_rescale: float = 0.0,
183
+ attention_auto_machine_weight: float = 1.0,
184
+ gn_auto_machine_weight: float = 1.0,
185
+ style_fidelity: float = 0.5,
186
+ reference_attn: bool = True,
187
+ reference_adain: bool = True,
188
+ ):
189
+ r"""
190
+ Function invoked when calling the pipeline for generation.
191
+
192
+ Args:
193
+ prompt (`str` or `List[str]`, *optional*):
194
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
195
+ instead.
196
+ ref_image (`torch.FloatTensor`, `PIL.Image.Image`):
197
+ The Reference Control input condition. Reference Control uses this input condition to generate guidance to Unet. If
198
+ the type is specified as `Torch.FloatTensor`, it is passed to Reference Control as is. `PIL.Image.Image` can
199
+ also be accepted as an image.
200
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
201
+ The height in pixels of the generated image.
202
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
203
+ The width in pixels of the generated image.
204
+ num_inference_steps (`int`, *optional*, defaults to 50):
205
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
206
+ expense of slower inference.
207
+ guidance_scale (`float`, *optional*, defaults to 7.5):
208
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
209
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
210
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
211
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
212
+ usually at the expense of lower image quality.
213
+ negative_prompt (`str` or `List[str]`, *optional*):
214
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
215
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
216
+ less than `1`).
217
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
218
+ The number of images to generate per prompt.
219
+ eta (`float`, *optional*, defaults to 0.0):
220
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
221
+ [`schedulers.DDIMScheduler`], will be ignored for others.
222
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
223
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
224
+ to make generation deterministic.
225
+ latents (`torch.FloatTensor`, *optional*):
226
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
227
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
228
+ tensor will ge generated by sampling using the supplied random `generator`.
229
+ prompt_embeds (`torch.FloatTensor`, *optional*):
230
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
231
+ provided, text embeddings will be generated from `prompt` input argument.
232
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
233
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
234
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
235
+ argument.
236
+ output_type (`str`, *optional*, defaults to `"pil"`):
237
+ The output format of the generate image. Choose between
238
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
239
+ return_dict (`bool`, *optional*, defaults to `True`):
240
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
241
+ plain tuple.
242
+ callback (`Callable`, *optional*):
243
+ A function that will be called every `callback_steps` steps during inference. The function will be
244
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
245
+ callback_steps (`int`, *optional*, defaults to 1):
246
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
247
+ called at every step.
248
+ cross_attention_kwargs (`dict`, *optional*):
249
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
250
+ `self.processor` in
251
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
252
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
253
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
254
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
255
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
256
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
257
+ attention_auto_machine_weight (`float`):
258
+ Weight of using reference query for self attention's context.
259
+ If attention_auto_machine_weight=1.0, use reference query for all self attention's context.
260
+ gn_auto_machine_weight (`float`):
261
+ Weight of using reference adain. If gn_auto_machine_weight=2.0, use all reference adain plugins.
262
+ style_fidelity (`float`):
263
+ style fidelity of ref_uncond_xt. If style_fidelity=1.0, control more important,
264
+ elif style_fidelity=0.0, prompt more important, else balanced.
265
+ reference_attn (`bool`):
266
+ Whether to use reference query for self attention's context.
267
+ reference_adain (`bool`):
268
+ Whether to use reference adain.
269
+
270
+ Examples:
271
+
272
+ Returns:
273
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
274
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
275
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
276
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
277
+ (nsfw) content, according to the `safety_checker`.
278
+ """
279
+ assert reference_attn or reference_adain, "`reference_attn` or `reference_adain` must be True."
280
+
281
+ # 0. Default height and width to unet
282
+ height, width = self._default_height_width(height, width, ref_image)
283
+
284
+ # 1. Check inputs. Raise error if not correct
285
+ self.check_inputs(
286
+ prompt, height, width, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds
287
+ )
288
+
289
+ # 2. Define call parameters
290
+ if prompt is not None and isinstance(prompt, str):
291
+ batch_size = 1
292
+ elif prompt is not None and isinstance(prompt, list):
293
+ batch_size = len(prompt)
294
+ else:
295
+ batch_size = prompt_embeds.shape[0]
296
+
297
+ device = self._execution_device
298
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
299
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
300
+ # corresponds to doing no classifier free guidance.
301
+ do_classifier_free_guidance = guidance_scale > 1.0
302
+
303
+ # 3. Encode input prompt
304
+ text_encoder_lora_scale = (
305
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
306
+ )
307
+ prompt_embeds = self._encode_prompt(
308
+ prompt,
309
+ device,
310
+ num_images_per_prompt,
311
+ do_classifier_free_guidance,
312
+ negative_prompt,
313
+ prompt_embeds=prompt_embeds,
314
+ negative_prompt_embeds=negative_prompt_embeds,
315
+ lora_scale=text_encoder_lora_scale,
316
+ )
317
+
318
+ # 4. Preprocess reference image
319
+ ref_image = self.prepare_image(
320
+ image=ref_image,
321
+ width=width,
322
+ height=height,
323
+ batch_size=batch_size * num_images_per_prompt,
324
+ num_images_per_prompt=num_images_per_prompt,
325
+ device=device,
326
+ dtype=prompt_embeds.dtype,
327
+ )
328
+
329
+ # 5. Prepare timesteps
330
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
331
+ timesteps = self.scheduler.timesteps
332
+
333
+ # 6. Prepare latent variables
334
+ num_channels_latents = self.unet.config.in_channels
335
+ latents = self.prepare_latents(
336
+ batch_size * num_images_per_prompt,
337
+ num_channels_latents,
338
+ height,
339
+ width,
340
+ prompt_embeds.dtype,
341
+ device,
342
+ generator,
343
+ latents,
344
+ )
345
+
346
+ # 7. Prepare reference latent variables
347
+ ref_image_latents = self.prepare_ref_latents(
348
+ ref_image,
349
+ batch_size * num_images_per_prompt,
350
+ prompt_embeds.dtype,
351
+ device,
352
+ generator,
353
+ do_classifier_free_guidance,
354
+ )
355
+
356
+ # 8. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
357
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
358
+
359
+ # 9. Modify self attention and group norm
360
+ MODE = "write"
361
+ uc_mask = (
362
+ torch.Tensor([1] * batch_size * num_images_per_prompt + [0] * batch_size * num_images_per_prompt)
363
+ .type_as(ref_image_latents)
364
+ .bool()
365
+ )
366
+
367
+ def hacked_basic_transformer_inner_forward(
368
+ self,
369
+ hidden_states: torch.FloatTensor,
370
+ attention_mask: Optional[torch.FloatTensor] = None,
371
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
372
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
373
+ timestep: Optional[torch.LongTensor] = None,
374
+ cross_attention_kwargs: Dict[str, Any] = None,
375
+ class_labels: Optional[torch.LongTensor] = None,
376
+ ):
377
+ if self.use_ada_layer_norm:
378
+ norm_hidden_states = self.norm1(hidden_states, timestep)
379
+ elif self.use_ada_layer_norm_zero:
380
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
381
+ hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
382
+ )
383
+ else:
384
+ norm_hidden_states = self.norm1(hidden_states)
385
+
386
+ # 1. Self-Attention
387
+ cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}
388
+ if self.only_cross_attention:
389
+ attn_output = self.attn1(
390
+ norm_hidden_states,
391
+ encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
392
+ attention_mask=attention_mask,
393
+ **cross_attention_kwargs,
394
+ )
395
+ else:
396
+ if MODE == "write":
397
+ self.bank.append(norm_hidden_states.detach().clone())
398
+ attn_output = self.attn1(
399
+ norm_hidden_states,
400
+ encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
401
+ attention_mask=attention_mask,
402
+ **cross_attention_kwargs,
403
+ )
404
+ if MODE == "read":
405
+ if attention_auto_machine_weight > self.attn_weight:
406
+ attn_output_uc = self.attn1(
407
+ norm_hidden_states,
408
+ encoder_hidden_states=torch.cat([norm_hidden_states] + self.bank, dim=1),
409
+ # attention_mask=attention_mask,
410
+ **cross_attention_kwargs,
411
+ )
412
+ attn_output_c = attn_output_uc.clone()
413
+ if do_classifier_free_guidance and style_fidelity > 0:
414
+ attn_output_c[uc_mask] = self.attn1(
415
+ norm_hidden_states[uc_mask],
416
+ encoder_hidden_states=norm_hidden_states[uc_mask],
417
+ **cross_attention_kwargs,
418
+ )
419
+ attn_output = style_fidelity * attn_output_c + (1.0 - style_fidelity) * attn_output_uc
420
+ self.bank.clear()
421
+ else:
422
+ attn_output = self.attn1(
423
+ norm_hidden_states,
424
+ encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
425
+ attention_mask=attention_mask,
426
+ **cross_attention_kwargs,
427
+ )
428
+ if self.use_ada_layer_norm_zero:
429
+ attn_output = gate_msa.unsqueeze(1) * attn_output
430
+ hidden_states = attn_output + hidden_states
431
+
432
+ if self.attn2 is not None:
433
+ norm_hidden_states = (
434
+ self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)
435
+ )
436
+
437
+ # 2. Cross-Attention
438
+ attn_output = self.attn2(
439
+ norm_hidden_states,
440
+ encoder_hidden_states=encoder_hidden_states,
441
+ attention_mask=encoder_attention_mask,
442
+ **cross_attention_kwargs,
443
+ )
444
+ hidden_states = attn_output + hidden_states
445
+
446
+ # 3. Feed-forward
447
+ norm_hidden_states = self.norm3(hidden_states)
448
+
449
+ if self.use_ada_layer_norm_zero:
450
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
451
+
452
+ ff_output = self.ff(norm_hidden_states)
453
+
454
+ if self.use_ada_layer_norm_zero:
455
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
456
+
457
+ hidden_states = ff_output + hidden_states
458
+
459
+ return hidden_states
460
+
461
+ def hacked_mid_forward(self, *args, **kwargs):
462
+ eps = 1e-6
463
+ x = self.original_forward(*args, **kwargs)
464
+ if MODE == "write":
465
+ if gn_auto_machine_weight >= self.gn_weight:
466
+ var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)
467
+ self.mean_bank.append(mean)
468
+ self.var_bank.append(var)
469
+ if MODE == "read":
470
+ if len(self.mean_bank) > 0 and len(self.var_bank) > 0:
471
+ var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)
472
+ std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5
473
+ mean_acc = sum(self.mean_bank) / float(len(self.mean_bank))
474
+ var_acc = sum(self.var_bank) / float(len(self.var_bank))
475
+ std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5
476
+ x_uc = (((x - mean) / std) * std_acc) + mean_acc
477
+ x_c = x_uc.clone()
478
+ if do_classifier_free_guidance and style_fidelity > 0:
479
+ x_c[uc_mask] = x[uc_mask]
480
+ x = style_fidelity * x_c + (1.0 - style_fidelity) * x_uc
481
+ self.mean_bank = []
482
+ self.var_bank = []
483
+ return x
484
+
485
+ def hack_CrossAttnDownBlock2D_forward(
486
+ self,
487
+ hidden_states: torch.FloatTensor,
488
+ temb: Optional[torch.FloatTensor] = None,
489
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
490
+ attention_mask: Optional[torch.FloatTensor] = None,
491
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
492
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
493
+ ):
494
+ eps = 1e-6
495
+
496
+ # TODO(Patrick, William) - attention mask is not used
497
+ output_states = ()
498
+
499
+ for i, (resnet, attn) in enumerate(zip(self.resnets, self.attentions)):
500
+ hidden_states = resnet(hidden_states, temb)
501
+ hidden_states = attn(
502
+ hidden_states,
503
+ encoder_hidden_states=encoder_hidden_states,
504
+ cross_attention_kwargs=cross_attention_kwargs,
505
+ attention_mask=attention_mask,
506
+ encoder_attention_mask=encoder_attention_mask,
507
+ return_dict=False,
508
+ )[0]
509
+ if MODE == "write":
510
+ if gn_auto_machine_weight >= self.gn_weight:
511
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
512
+ self.mean_bank.append([mean])
513
+ self.var_bank.append([var])
514
+ if MODE == "read":
515
+ if len(self.mean_bank) > 0 and len(self.var_bank) > 0:
516
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
517
+ std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5
518
+ mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))
519
+ var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))
520
+ std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5
521
+ hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc
522
+ hidden_states_c = hidden_states_uc.clone()
523
+ if do_classifier_free_guidance and style_fidelity > 0:
524
+ hidden_states_c[uc_mask] = hidden_states[uc_mask]
525
+ hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc
526
+
527
+ output_states = output_states + (hidden_states,)
528
+
529
+ if MODE == "read":
530
+ self.mean_bank = []
531
+ self.var_bank = []
532
+
533
+ if self.downsamplers is not None:
534
+ for downsampler in self.downsamplers:
535
+ hidden_states = downsampler(hidden_states)
536
+
537
+ output_states = output_states + (hidden_states,)
538
+
539
+ return hidden_states, output_states
540
+
541
+ def hacked_DownBlock2D_forward(self, hidden_states, temb=None):
542
+ eps = 1e-6
543
+
544
+ output_states = ()
545
+
546
+ for i, resnet in enumerate(self.resnets):
547
+ hidden_states = resnet(hidden_states, temb)
548
+
549
+ if MODE == "write":
550
+ if gn_auto_machine_weight >= self.gn_weight:
551
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
552
+ self.mean_bank.append([mean])
553
+ self.var_bank.append([var])
554
+ if MODE == "read":
555
+ if len(self.mean_bank) > 0 and len(self.var_bank) > 0:
556
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
557
+ std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5
558
+ mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))
559
+ var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))
560
+ std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5
561
+ hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc
562
+ hidden_states_c = hidden_states_uc.clone()
563
+ if do_classifier_free_guidance and style_fidelity > 0:
564
+ hidden_states_c[uc_mask] = hidden_states[uc_mask]
565
+ hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc
566
+
567
+ output_states = output_states + (hidden_states,)
568
+
569
+ if MODE == "read":
570
+ self.mean_bank = []
571
+ self.var_bank = []
572
+
573
+ if self.downsamplers is not None:
574
+ for downsampler in self.downsamplers:
575
+ hidden_states = downsampler(hidden_states)
576
+
577
+ output_states = output_states + (hidden_states,)
578
+
579
+ return hidden_states, output_states
580
+
581
+ def hacked_CrossAttnUpBlock2D_forward(
582
+ self,
583
+ hidden_states: torch.FloatTensor,
584
+ res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],
585
+ temb: Optional[torch.FloatTensor] = None,
586
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
587
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
588
+ upsample_size: Optional[int] = None,
589
+ attention_mask: Optional[torch.FloatTensor] = None,
590
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
591
+ ):
592
+ eps = 1e-6
593
+ # TODO(Patrick, William) - attention mask is not used
594
+ for i, (resnet, attn) in enumerate(zip(self.resnets, self.attentions)):
595
+ # pop res hidden states
596
+ res_hidden_states = res_hidden_states_tuple[-1]
597
+ res_hidden_states_tuple = res_hidden_states_tuple[:-1]
598
+ hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
599
+ hidden_states = resnet(hidden_states, temb)
600
+ hidden_states = attn(
601
+ hidden_states,
602
+ encoder_hidden_states=encoder_hidden_states,
603
+ cross_attention_kwargs=cross_attention_kwargs,
604
+ attention_mask=attention_mask,
605
+ encoder_attention_mask=encoder_attention_mask,
606
+ return_dict=False,
607
+ )[0]
608
+
609
+ if MODE == "write":
610
+ if gn_auto_machine_weight >= self.gn_weight:
611
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
612
+ self.mean_bank.append([mean])
613
+ self.var_bank.append([var])
614
+ if MODE == "read":
615
+ if len(self.mean_bank) > 0 and len(self.var_bank) > 0:
616
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
617
+ std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5
618
+ mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))
619
+ var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))
620
+ std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5
621
+ hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc
622
+ hidden_states_c = hidden_states_uc.clone()
623
+ if do_classifier_free_guidance and style_fidelity > 0:
624
+ hidden_states_c[uc_mask] = hidden_states[uc_mask]
625
+ hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc
626
+
627
+ if MODE == "read":
628
+ self.mean_bank = []
629
+ self.var_bank = []
630
+
631
+ if self.upsamplers is not None:
632
+ for upsampler in self.upsamplers:
633
+ hidden_states = upsampler(hidden_states, upsample_size)
634
+
635
+ return hidden_states
636
+
637
+ def hacked_UpBlock2D_forward(self, hidden_states, res_hidden_states_tuple, temb=None, upsample_size=None):
638
+ eps = 1e-6
639
+ for i, resnet in enumerate(self.resnets):
640
+ # pop res hidden states
641
+ res_hidden_states = res_hidden_states_tuple[-1]
642
+ res_hidden_states_tuple = res_hidden_states_tuple[:-1]
643
+ hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
644
+ hidden_states = resnet(hidden_states, temb)
645
+
646
+ if MODE == "write":
647
+ if gn_auto_machine_weight >= self.gn_weight:
648
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
649
+ self.mean_bank.append([mean])
650
+ self.var_bank.append([var])
651
+ if MODE == "read":
652
+ if len(self.mean_bank) > 0 and len(self.var_bank) > 0:
653
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
654
+ std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5
655
+ mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))
656
+ var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))
657
+ std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5
658
+ hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc
659
+ hidden_states_c = hidden_states_uc.clone()
660
+ if do_classifier_free_guidance and style_fidelity > 0:
661
+ hidden_states_c[uc_mask] = hidden_states[uc_mask]
662
+ hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc
663
+
664
+ if MODE == "read":
665
+ self.mean_bank = []
666
+ self.var_bank = []
667
+
668
+ if self.upsamplers is not None:
669
+ for upsampler in self.upsamplers:
670
+ hidden_states = upsampler(hidden_states, upsample_size)
671
+
672
+ return hidden_states
673
+
674
+ if reference_attn:
675
+ attn_modules = [module for module in torch_dfs(self.unet) if isinstance(module, BasicTransformerBlock)]
676
+ attn_modules = sorted(attn_modules, key=lambda x: -x.norm1.normalized_shape[0])
677
+
678
+ for i, module in enumerate(attn_modules):
679
+ module._original_inner_forward = module.forward
680
+ module.forward = hacked_basic_transformer_inner_forward.__get__(module, BasicTransformerBlock)
681
+ module.bank = []
682
+ module.attn_weight = float(i) / float(len(attn_modules))
683
+
684
+ if reference_adain:
685
+ gn_modules = [self.unet.mid_block]
686
+ self.unet.mid_block.gn_weight = 0
687
+
688
+ down_blocks = self.unet.down_blocks
689
+ for w, module in enumerate(down_blocks):
690
+ module.gn_weight = 1.0 - float(w) / float(len(down_blocks))
691
+ gn_modules.append(module)
692
+
693
+ up_blocks = self.unet.up_blocks
694
+ for w, module in enumerate(up_blocks):
695
+ module.gn_weight = float(w) / float(len(up_blocks))
696
+ gn_modules.append(module)
697
+
698
+ for i, module in enumerate(gn_modules):
699
+ if getattr(module, "original_forward", None) is None:
700
+ module.original_forward = module.forward
701
+ if i == 0:
702
+ # mid_block
703
+ module.forward = hacked_mid_forward.__get__(module, torch.nn.Module)
704
+ elif isinstance(module, CrossAttnDownBlock2D):
705
+ module.forward = hack_CrossAttnDownBlock2D_forward.__get__(module, CrossAttnDownBlock2D)
706
+ elif isinstance(module, DownBlock2D):
707
+ module.forward = hacked_DownBlock2D_forward.__get__(module, DownBlock2D)
708
+ elif isinstance(module, CrossAttnUpBlock2D):
709
+ module.forward = hacked_CrossAttnUpBlock2D_forward.__get__(module, CrossAttnUpBlock2D)
710
+ elif isinstance(module, UpBlock2D):
711
+ module.forward = hacked_UpBlock2D_forward.__get__(module, UpBlock2D)
712
+ module.mean_bank = []
713
+ module.var_bank = []
714
+ module.gn_weight *= 2
715
+
716
+ # 10. Denoising loop
717
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
718
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
719
+ for i, t in enumerate(timesteps):
720
+ # expand the latents if we are doing classifier free guidance
721
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
722
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
723
+
724
+ # ref only part
725
+ noise = randn_tensor(
726
+ ref_image_latents.shape, generator=generator, device=device, dtype=ref_image_latents.dtype
727
+ )
728
+ ref_xt = self.scheduler.add_noise(
729
+ ref_image_latents,
730
+ noise,
731
+ t.reshape(
732
+ 1,
733
+ ),
734
+ )
735
+ ref_xt = torch.cat([ref_xt] * 2) if do_classifier_free_guidance else ref_xt
736
+ ref_xt = self.scheduler.scale_model_input(ref_xt, t)
737
+
738
+ MODE = "write"
739
+ self.unet(
740
+ ref_xt,
741
+ t,
742
+ encoder_hidden_states=prompt_embeds,
743
+ cross_attention_kwargs=cross_attention_kwargs,
744
+ return_dict=False,
745
+ )
746
+
747
+ # predict the noise residual
748
+ MODE = "read"
749
+ noise_pred = self.unet(
750
+ latent_model_input,
751
+ t,
752
+ encoder_hidden_states=prompt_embeds,
753
+ cross_attention_kwargs=cross_attention_kwargs,
754
+ return_dict=False,
755
+ )[0]
756
+
757
+ # perform guidance
758
+ if do_classifier_free_guidance:
759
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
760
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
761
+
762
+ if do_classifier_free_guidance and guidance_rescale > 0.0:
763
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
764
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
765
+
766
+ # compute the previous noisy sample x_t -> x_t-1
767
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
768
+
769
+ # call the callback, if provided
770
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
771
+ progress_bar.update()
772
+ if callback is not None and i % callback_steps == 0:
773
+ step_idx = i // getattr(self.scheduler, "order", 1)
774
+ callback(step_idx, t, latents)
775
+
776
+ if not output_type == "latent":
777
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
778
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
779
+ else:
780
+ image = latents
781
+ has_nsfw_concept = None
782
+
783
+ if has_nsfw_concept is None:
784
+ do_denormalize = [True] * image.shape[0]
785
+ else:
786
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
787
+
788
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
789
+
790
+ # Offload last model to CPU
791
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
792
+ self.final_offload_hook.offload()
793
+
794
+ if not return_dict:
795
+ return (image, has_nsfw_concept)
796
+
797
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.22.0/stable_diffusion_repaint.py ADDED
@@ -0,0 +1,957 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 inspect
16
+ from typing import Callable, List, Optional, Union
17
+
18
+ import numpy as np
19
+ import PIL.Image
20
+ import torch
21
+ from packaging import version
22
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
23
+
24
+ from diffusers import AutoencoderKL, DiffusionPipeline, UNet2DConditionModel
25
+ from diffusers.configuration_utils import FrozenDict, deprecate
26
+ from diffusers.loaders import LoraLoaderMixin, TextualInversionLoaderMixin
27
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
28
+ from diffusers.pipelines.stable_diffusion.safety_checker import (
29
+ StableDiffusionSafetyChecker,
30
+ )
31
+ from diffusers.schedulers import KarrasDiffusionSchedulers
32
+ from diffusers.utils import (
33
+ is_accelerate_available,
34
+ is_accelerate_version,
35
+ logging,
36
+ )
37
+ from diffusers.utils.torch_utils import randn_tensor
38
+
39
+
40
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
41
+
42
+
43
+ def prepare_mask_and_masked_image(image, mask):
44
+ """
45
+ Prepares a pair (image, mask) to be consumed by the Stable Diffusion pipeline. This means that those inputs will be
46
+ converted to ``torch.Tensor`` with shapes ``batch x channels x height x width`` where ``channels`` is ``3`` for the
47
+ ``image`` and ``1`` for the ``mask``.
48
+ The ``image`` will be converted to ``torch.float32`` and normalized to be in ``[-1, 1]``. The ``mask`` will be
49
+ binarized (``mask > 0.5``) and cast to ``torch.float32`` too.
50
+ Args:
51
+ image (Union[np.array, PIL.Image, torch.Tensor]): The image to inpaint.
52
+ It can be a ``PIL.Image``, or a ``height x width x 3`` ``np.array`` or a ``channels x height x width``
53
+ ``torch.Tensor`` or a ``batch x channels x height x width`` ``torch.Tensor``.
54
+ mask (_type_): The mask to apply to the image, i.e. regions to inpaint.
55
+ It can be a ``PIL.Image``, or a ``height x width`` ``np.array`` or a ``1 x height x width``
56
+ ``torch.Tensor`` or a ``batch x 1 x height x width`` ``torch.Tensor``.
57
+ Raises:
58
+ ValueError: ``torch.Tensor`` images should be in the ``[-1, 1]`` range. ValueError: ``torch.Tensor`` mask
59
+ should be in the ``[0, 1]`` range. ValueError: ``mask`` and ``image`` should have the same spatial dimensions.
60
+ TypeError: ``mask`` is a ``torch.Tensor`` but ``image`` is not
61
+ (ot the other way around).
62
+ Returns:
63
+ tuple[torch.Tensor]: The pair (mask, masked_image) as ``torch.Tensor`` with 4
64
+ dimensions: ``batch x channels x height x width``.
65
+ """
66
+ if isinstance(image, torch.Tensor):
67
+ if not isinstance(mask, torch.Tensor):
68
+ raise TypeError(f"`image` is a torch.Tensor but `mask` (type: {type(mask)} is not")
69
+
70
+ # Batch single image
71
+ if image.ndim == 3:
72
+ assert image.shape[0] == 3, "Image outside a batch should be of shape (3, H, W)"
73
+ image = image.unsqueeze(0)
74
+
75
+ # Batch and add channel dim for single mask
76
+ if mask.ndim == 2:
77
+ mask = mask.unsqueeze(0).unsqueeze(0)
78
+
79
+ # Batch single mask or add channel dim
80
+ if mask.ndim == 3:
81
+ # Single batched mask, no channel dim or single mask not batched but channel dim
82
+ if mask.shape[0] == 1:
83
+ mask = mask.unsqueeze(0)
84
+
85
+ # Batched masks no channel dim
86
+ else:
87
+ mask = mask.unsqueeze(1)
88
+
89
+ assert image.ndim == 4 and mask.ndim == 4, "Image and Mask must have 4 dimensions"
90
+ assert image.shape[-2:] == mask.shape[-2:], "Image and Mask must have the same spatial dimensions"
91
+ assert image.shape[0] == mask.shape[0], "Image and Mask must have the same batch size"
92
+
93
+ # Check image is in [-1, 1]
94
+ if image.min() < -1 or image.max() > 1:
95
+ raise ValueError("Image should be in [-1, 1] range")
96
+
97
+ # Check mask is in [0, 1]
98
+ if mask.min() < 0 or mask.max() > 1:
99
+ raise ValueError("Mask should be in [0, 1] range")
100
+
101
+ # Binarize mask
102
+ mask[mask < 0.5] = 0
103
+ mask[mask >= 0.5] = 1
104
+
105
+ # Image as float32
106
+ image = image.to(dtype=torch.float32)
107
+ elif isinstance(mask, torch.Tensor):
108
+ raise TypeError(f"`mask` is a torch.Tensor but `image` (type: {type(image)} is not")
109
+ else:
110
+ # preprocess image
111
+ if isinstance(image, (PIL.Image.Image, np.ndarray)):
112
+ image = [image]
113
+
114
+ if isinstance(image, list) and isinstance(image[0], PIL.Image.Image):
115
+ image = [np.array(i.convert("RGB"))[None, :] for i in image]
116
+ image = np.concatenate(image, axis=0)
117
+ elif isinstance(image, list) and isinstance(image[0], np.ndarray):
118
+ image = np.concatenate([i[None, :] for i in image], axis=0)
119
+
120
+ image = image.transpose(0, 3, 1, 2)
121
+ image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
122
+
123
+ # preprocess mask
124
+ if isinstance(mask, (PIL.Image.Image, np.ndarray)):
125
+ mask = [mask]
126
+
127
+ if isinstance(mask, list) and isinstance(mask[0], PIL.Image.Image):
128
+ mask = np.concatenate([np.array(m.convert("L"))[None, None, :] for m in mask], axis=0)
129
+ mask = mask.astype(np.float32) / 255.0
130
+ elif isinstance(mask, list) and isinstance(mask[0], np.ndarray):
131
+ mask = np.concatenate([m[None, None, :] for m in mask], axis=0)
132
+
133
+ mask[mask < 0.5] = 0
134
+ mask[mask >= 0.5] = 1
135
+ mask = torch.from_numpy(mask)
136
+
137
+ # masked_image = image * (mask >= 0.5)
138
+ masked_image = image
139
+
140
+ return mask, masked_image
141
+
142
+
143
+ class StableDiffusionRepaintPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin):
144
+ r"""
145
+ Pipeline for text-guided image inpainting using Stable Diffusion. *This is an experimental feature*.
146
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
147
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
148
+ In addition the pipeline inherits the following loading methods:
149
+ - *Textual-Inversion*: [`loaders.TextualInversionLoaderMixin.load_textual_inversion`]
150
+ - *LoRA*: [`loaders.LoraLoaderMixin.load_lora_weights`]
151
+ as well as the following saving methods:
152
+ - *LoRA*: [`loaders.LoraLoaderMixin.save_lora_weights`]
153
+ Args:
154
+ vae ([`AutoencoderKL`]):
155
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
156
+ text_encoder ([`CLIPTextModel`]):
157
+ Frozen text-encoder. Stable Diffusion uses the text portion of
158
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
159
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
160
+ tokenizer (`CLIPTokenizer`):
161
+ Tokenizer of class
162
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
163
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
164
+ scheduler ([`SchedulerMixin`]):
165
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
166
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
167
+ safety_checker ([`StableDiffusionSafetyChecker`]):
168
+ Classification module that estimates whether generated images could be considered offensive or harmful.
169
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
170
+ feature_extractor ([`CLIPImageProcessor`]):
171
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
172
+ """
173
+ _optional_components = ["safety_checker", "feature_extractor"]
174
+
175
+ def __init__(
176
+ self,
177
+ vae: AutoencoderKL,
178
+ text_encoder: CLIPTextModel,
179
+ tokenizer: CLIPTokenizer,
180
+ unet: UNet2DConditionModel,
181
+ scheduler: KarrasDiffusionSchedulers,
182
+ safety_checker: StableDiffusionSafetyChecker,
183
+ feature_extractor: CLIPImageProcessor,
184
+ requires_safety_checker: bool = True,
185
+ ):
186
+ super().__init__()
187
+
188
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
189
+ deprecation_message = (
190
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
191
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
192
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
193
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
194
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
195
+ " file"
196
+ )
197
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
198
+ new_config = dict(scheduler.config)
199
+ new_config["steps_offset"] = 1
200
+ scheduler._internal_dict = FrozenDict(new_config)
201
+
202
+ if hasattr(scheduler.config, "skip_prk_steps") and scheduler.config.skip_prk_steps is False:
203
+ deprecation_message = (
204
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration"
205
+ " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make"
206
+ " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to"
207
+ " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face"
208
+ " Hub, it would be very nice if you could open a Pull request for the"
209
+ " `scheduler/scheduler_config.json` file"
210
+ )
211
+ deprecate(
212
+ "skip_prk_steps not set",
213
+ "1.0.0",
214
+ deprecation_message,
215
+ standard_warn=False,
216
+ )
217
+ new_config = dict(scheduler.config)
218
+ new_config["skip_prk_steps"] = True
219
+ scheduler._internal_dict = FrozenDict(new_config)
220
+
221
+ if safety_checker is None and requires_safety_checker:
222
+ logger.warning(
223
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
224
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
225
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
226
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
227
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
228
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
229
+ )
230
+
231
+ if safety_checker is not None and feature_extractor is None:
232
+ raise ValueError(
233
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
234
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
235
+ )
236
+
237
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
238
+ version.parse(unet.config._diffusers_version).base_version
239
+ ) < version.parse("0.9.0.dev0")
240
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
241
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
242
+ deprecation_message = (
243
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
244
+ " 64 which seems highly unlikely .If you're checkpoint is a fine-tuned version of any of the"
245
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
246
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
247
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
248
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
249
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
250
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
251
+ " the `unet/config.json` file"
252
+ )
253
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
254
+ new_config = dict(unet.config)
255
+ new_config["sample_size"] = 64
256
+ unet._internal_dict = FrozenDict(new_config)
257
+ # Check shapes, assume num_channels_latents == 4, num_channels_mask == 1, num_channels_masked == 4
258
+ if unet.config.in_channels != 4:
259
+ logger.warning(
260
+ f"You have loaded a UNet with {unet.config.in_channels} input channels, whereas by default,"
261
+ f" {self.__class__} assumes that `pipeline.unet` has 4 input channels: 4 for `num_channels_latents`,"
262
+ ". If you did not intend to modify"
263
+ " this behavior, please check whether you have loaded the right checkpoint."
264
+ )
265
+
266
+ self.register_modules(
267
+ vae=vae,
268
+ text_encoder=text_encoder,
269
+ tokenizer=tokenizer,
270
+ unet=unet,
271
+ scheduler=scheduler,
272
+ safety_checker=safety_checker,
273
+ feature_extractor=feature_extractor,
274
+ )
275
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
276
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
277
+
278
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_sequential_cpu_offload
279
+ def enable_sequential_cpu_offload(self, gpu_id=0):
280
+ r"""
281
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
282
+ text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
283
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
284
+ Note that offloading happens on a submodule basis. Memory savings are higher than with
285
+ `enable_model_cpu_offload`, but performance is lower.
286
+ """
287
+ if is_accelerate_available() and is_accelerate_version(">=", "0.14.0"):
288
+ from accelerate import cpu_offload
289
+ else:
290
+ raise ImportError("`enable_sequential_cpu_offload` requires `accelerate v0.14.0` or higher")
291
+
292
+ device = torch.device(f"cuda:{gpu_id}")
293
+
294
+ if self.device.type != "cpu":
295
+ self.to("cpu", silence_dtype_warnings=True)
296
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
297
+
298
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]:
299
+ cpu_offload(cpu_offloaded_model, device)
300
+
301
+ if self.safety_checker is not None:
302
+ cpu_offload(self.safety_checker, execution_device=device, offload_buffers=True)
303
+
304
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_model_cpu_offload
305
+ def enable_model_cpu_offload(self, gpu_id=0):
306
+ r"""
307
+ Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
308
+ to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
309
+ method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
310
+ `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
311
+ """
312
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
313
+ from accelerate import cpu_offload_with_hook
314
+ else:
315
+ raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")
316
+
317
+ device = torch.device(f"cuda:{gpu_id}")
318
+
319
+ if self.device.type != "cpu":
320
+ self.to("cpu", silence_dtype_warnings=True)
321
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
322
+
323
+ hook = None
324
+ for cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]:
325
+ _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
326
+
327
+ if self.safety_checker is not None:
328
+ _, hook = cpu_offload_with_hook(self.safety_checker, device, prev_module_hook=hook)
329
+
330
+ # We'll offload the last model manually.
331
+ self.final_offload_hook = hook
332
+
333
+ @property
334
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
335
+ def _execution_device(self):
336
+ r"""
337
+ Returns the device on which the pipeline's models will be executed. After calling
338
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
339
+ hooks.
340
+ """
341
+ if not hasattr(self.unet, "_hf_hook"):
342
+ return self.device
343
+ for module in self.unet.modules():
344
+ if (
345
+ hasattr(module, "_hf_hook")
346
+ and hasattr(module._hf_hook, "execution_device")
347
+ and module._hf_hook.execution_device is not None
348
+ ):
349
+ return torch.device(module._hf_hook.execution_device)
350
+ return self.device
351
+
352
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt
353
+ def _encode_prompt(
354
+ self,
355
+ prompt,
356
+ device,
357
+ num_images_per_prompt,
358
+ do_classifier_free_guidance,
359
+ negative_prompt=None,
360
+ prompt_embeds: Optional[torch.FloatTensor] = None,
361
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
362
+ ):
363
+ r"""
364
+ Encodes the prompt into text encoder hidden states.
365
+ Args:
366
+ prompt (`str` or `List[str]`, *optional*):
367
+ prompt to be encoded
368
+ device: (`torch.device`):
369
+ torch device
370
+ num_images_per_prompt (`int`):
371
+ number of images that should be generated per prompt
372
+ do_classifier_free_guidance (`bool`):
373
+ whether to use classifier free guidance or not
374
+ negative_prompt (`str` or `List[str]`, *optional*):
375
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
376
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
377
+ less than `1`).
378
+ prompt_embeds (`torch.FloatTensor`, *optional*):
379
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
380
+ provided, text embeddings will be generated from `prompt` input argument.
381
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
382
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
383
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
384
+ argument.
385
+ """
386
+ if prompt is not None and isinstance(prompt, str):
387
+ batch_size = 1
388
+ elif prompt is not None and isinstance(prompt, list):
389
+ batch_size = len(prompt)
390
+ else:
391
+ batch_size = prompt_embeds.shape[0]
392
+
393
+ if prompt_embeds is None:
394
+ # textual inversion: procecss multi-vector tokens if necessary
395
+ if isinstance(self, TextualInversionLoaderMixin):
396
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
397
+
398
+ text_inputs = self.tokenizer(
399
+ prompt,
400
+ padding="max_length",
401
+ max_length=self.tokenizer.model_max_length,
402
+ truncation=True,
403
+ return_tensors="pt",
404
+ )
405
+ text_input_ids = text_inputs.input_ids
406
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
407
+
408
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
409
+ text_input_ids, untruncated_ids
410
+ ):
411
+ removed_text = self.tokenizer.batch_decode(
412
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
413
+ )
414
+ logger.warning(
415
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
416
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
417
+ )
418
+
419
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
420
+ attention_mask = text_inputs.attention_mask.to(device)
421
+ else:
422
+ attention_mask = None
423
+
424
+ prompt_embeds = self.text_encoder(
425
+ text_input_ids.to(device),
426
+ attention_mask=attention_mask,
427
+ )
428
+ prompt_embeds = prompt_embeds[0]
429
+
430
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
431
+
432
+ bs_embed, seq_len, _ = prompt_embeds.shape
433
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
434
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
435
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
436
+
437
+ # get unconditional embeddings for classifier free guidance
438
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
439
+ uncond_tokens: List[str]
440
+ if negative_prompt is None:
441
+ uncond_tokens = [""] * batch_size
442
+ elif type(prompt) is not type(negative_prompt):
443
+ raise TypeError(
444
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
445
+ f" {type(prompt)}."
446
+ )
447
+ elif isinstance(negative_prompt, str):
448
+ uncond_tokens = [negative_prompt]
449
+ elif batch_size != len(negative_prompt):
450
+ raise ValueError(
451
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
452
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
453
+ " the batch size of `prompt`."
454
+ )
455
+ else:
456
+ uncond_tokens = negative_prompt
457
+
458
+ # textual inversion: procecss multi-vector tokens if necessary
459
+ if isinstance(self, TextualInversionLoaderMixin):
460
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
461
+
462
+ max_length = prompt_embeds.shape[1]
463
+ uncond_input = self.tokenizer(
464
+ uncond_tokens,
465
+ padding="max_length",
466
+ max_length=max_length,
467
+ truncation=True,
468
+ return_tensors="pt",
469
+ )
470
+
471
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
472
+ attention_mask = uncond_input.attention_mask.to(device)
473
+ else:
474
+ attention_mask = None
475
+
476
+ negative_prompt_embeds = self.text_encoder(
477
+ uncond_input.input_ids.to(device),
478
+ attention_mask=attention_mask,
479
+ )
480
+ negative_prompt_embeds = negative_prompt_embeds[0]
481
+
482
+ if do_classifier_free_guidance:
483
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
484
+ seq_len = negative_prompt_embeds.shape[1]
485
+
486
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
487
+
488
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
489
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
490
+
491
+ # For classifier free guidance, we need to do two forward passes.
492
+ # Here we concatenate the unconditional and text embeddings into a single batch
493
+ # to avoid doing two forward passes
494
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
495
+
496
+ return prompt_embeds
497
+
498
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
499
+ def run_safety_checker(self, image, device, dtype):
500
+ if self.safety_checker is not None:
501
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
502
+ image, has_nsfw_concept = self.safety_checker(
503
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
504
+ )
505
+ else:
506
+ has_nsfw_concept = None
507
+ return image, has_nsfw_concept
508
+
509
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
510
+ def prepare_extra_step_kwargs(self, generator, eta):
511
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
512
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
513
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
514
+ # and should be between [0, 1]
515
+
516
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
517
+ extra_step_kwargs = {}
518
+ if accepts_eta:
519
+ extra_step_kwargs["eta"] = eta
520
+
521
+ # check if the scheduler accepts generator
522
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
523
+ if accepts_generator:
524
+ extra_step_kwargs["generator"] = generator
525
+ return extra_step_kwargs
526
+
527
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents
528
+ def decode_latents(self, latents):
529
+ latents = 1 / self.vae.config.scaling_factor * latents
530
+ image = self.vae.decode(latents).sample
531
+ image = (image / 2 + 0.5).clamp(0, 1)
532
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
533
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
534
+ return image
535
+
536
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.check_inputs
537
+ def check_inputs(
538
+ self,
539
+ prompt,
540
+ height,
541
+ width,
542
+ callback_steps,
543
+ negative_prompt=None,
544
+ prompt_embeds=None,
545
+ negative_prompt_embeds=None,
546
+ ):
547
+ if height % 8 != 0 or width % 8 != 0:
548
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
549
+
550
+ if (callback_steps is None) or (
551
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
552
+ ):
553
+ raise ValueError(
554
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
555
+ f" {type(callback_steps)}."
556
+ )
557
+
558
+ if prompt is not None and prompt_embeds is not None:
559
+ raise ValueError(
560
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
561
+ " only forward one of the two."
562
+ )
563
+ elif prompt is None and prompt_embeds is None:
564
+ raise ValueError(
565
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
566
+ )
567
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
568
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
569
+
570
+ if negative_prompt is not None and negative_prompt_embeds is not None:
571
+ raise ValueError(
572
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
573
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
574
+ )
575
+
576
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
577
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
578
+ raise ValueError(
579
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
580
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
581
+ f" {negative_prompt_embeds.shape}."
582
+ )
583
+
584
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
585
+ def prepare_latents(
586
+ self,
587
+ batch_size,
588
+ num_channels_latents,
589
+ height,
590
+ width,
591
+ dtype,
592
+ device,
593
+ generator,
594
+ latents=None,
595
+ ):
596
+ shape = (
597
+ batch_size,
598
+ num_channels_latents,
599
+ height // self.vae_scale_factor,
600
+ width // self.vae_scale_factor,
601
+ )
602
+ if isinstance(generator, list) and len(generator) != batch_size:
603
+ raise ValueError(
604
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
605
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
606
+ )
607
+
608
+ if latents is None:
609
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
610
+ else:
611
+ latents = latents.to(device)
612
+
613
+ # scale the initial noise by the standard deviation required by the scheduler
614
+ latents = latents * self.scheduler.init_noise_sigma
615
+ return latents
616
+
617
+ def prepare_mask_latents(
618
+ self,
619
+ mask,
620
+ masked_image,
621
+ batch_size,
622
+ height,
623
+ width,
624
+ dtype,
625
+ device,
626
+ generator,
627
+ do_classifier_free_guidance,
628
+ ):
629
+ # resize the mask to latents shape as we concatenate the mask to the latents
630
+ # we do that before converting to dtype to avoid breaking in case we're using cpu_offload
631
+ # and half precision
632
+ mask = torch.nn.functional.interpolate(
633
+ mask, size=(height // self.vae_scale_factor, width // self.vae_scale_factor)
634
+ )
635
+ mask = mask.to(device=device, dtype=dtype)
636
+
637
+ masked_image = masked_image.to(device=device, dtype=dtype)
638
+
639
+ # encode the mask image into latents space so we can concatenate it to the latents
640
+ if isinstance(generator, list):
641
+ masked_image_latents = [
642
+ self.vae.encode(masked_image[i : i + 1]).latent_dist.sample(generator=generator[i])
643
+ for i in range(batch_size)
644
+ ]
645
+ masked_image_latents = torch.cat(masked_image_latents, dim=0)
646
+ else:
647
+ masked_image_latents = self.vae.encode(masked_image).latent_dist.sample(generator=generator)
648
+ masked_image_latents = self.vae.config.scaling_factor * masked_image_latents
649
+
650
+ # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method
651
+ if mask.shape[0] < batch_size:
652
+ if not batch_size % mask.shape[0] == 0:
653
+ raise ValueError(
654
+ "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to"
655
+ f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number"
656
+ " of masks that you pass is divisible by the total requested batch size."
657
+ )
658
+ mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1)
659
+ if masked_image_latents.shape[0] < batch_size:
660
+ if not batch_size % masked_image_latents.shape[0] == 0:
661
+ raise ValueError(
662
+ "The passed images and the required batch size don't match. Images are supposed to be duplicated"
663
+ f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed."
664
+ " Make sure the number of images that you pass is divisible by the total requested batch size."
665
+ )
666
+ masked_image_latents = masked_image_latents.repeat(batch_size // masked_image_latents.shape[0], 1, 1, 1)
667
+
668
+ mask = torch.cat([mask] * 2) if do_classifier_free_guidance else mask
669
+ masked_image_latents = (
670
+ torch.cat([masked_image_latents] * 2) if do_classifier_free_guidance else masked_image_latents
671
+ )
672
+
673
+ # aligning device to prevent device errors when concating it with the latent model input
674
+ masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
675
+ return mask, masked_image_latents
676
+
677
+ @torch.no_grad()
678
+ def __call__(
679
+ self,
680
+ prompt: Union[str, List[str]] = None,
681
+ image: Union[torch.FloatTensor, PIL.Image.Image] = None,
682
+ mask_image: Union[torch.FloatTensor, PIL.Image.Image] = None,
683
+ height: Optional[int] = None,
684
+ width: Optional[int] = None,
685
+ num_inference_steps: int = 50,
686
+ jump_length: Optional[int] = 10,
687
+ jump_n_sample: Optional[int] = 10,
688
+ guidance_scale: float = 7.5,
689
+ negative_prompt: Optional[Union[str, List[str]]] = None,
690
+ num_images_per_prompt: Optional[int] = 1,
691
+ eta: float = 0.0,
692
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
693
+ latents: Optional[torch.FloatTensor] = None,
694
+ prompt_embeds: Optional[torch.FloatTensor] = None,
695
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
696
+ output_type: Optional[str] = "pil",
697
+ return_dict: bool = True,
698
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
699
+ callback_steps: int = 1,
700
+ ):
701
+ r"""
702
+ Function invoked when calling the pipeline for generation.
703
+ Args:
704
+ prompt (`str` or `List[str]`, *optional*):
705
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
706
+ instead.
707
+ image (`PIL.Image.Image`):
708
+ `Image`, or tensor representing an image batch which will be inpainted, *i.e.* parts of the image will
709
+ be masked out with `mask_image` and repainted according to `prompt`.
710
+ mask_image (`PIL.Image.Image`):
711
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
712
+ repainted, while black pixels will be preserved. If `mask_image` is a PIL image, it will be converted
713
+ to a single channel (luminance) before use. If it's a tensor, it should contain one color channel (L)
714
+ instead of 3, so the expected shape would be `(B, H, W, 1)`.
715
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
716
+ The height in pixels of the generated image.
717
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
718
+ The width in pixels of the generated image.
719
+ num_inference_steps (`int`, *optional*, defaults to 50):
720
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
721
+ expense of slower inference.
722
+ jump_length (`int`, *optional*, defaults to 10):
723
+ The number of steps taken forward in time before going backward in time for a single jump ("j" in
724
+ RePaint paper). Take a look at Figure 9 and 10 in https://arxiv.org/pdf/2201.09865.pdf.
725
+ jump_n_sample (`int`, *optional*, defaults to 10):
726
+ The number of times we will make forward time jump for a given chosen time sample. Take a look at
727
+ Figure 9 and 10 in https://arxiv.org/pdf/2201.09865.pdf.
728
+ guidance_scale (`float`, *optional*, defaults to 7.5):
729
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
730
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
731
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
732
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
733
+ usually at the expense of lower image quality.
734
+ negative_prompt (`str` or `List[str]`, *optional*):
735
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
736
+ `negative_prompt_embeds`. instead. Ignored when not using guidance (i.e., ignored if `guidance_scale`
737
+ is less than `1`).
738
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
739
+ The number of images to generate per prompt.
740
+ eta (`float`, *optional*, defaults to 0.0):
741
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
742
+ [`schedulers.DDIMScheduler`], will be ignored for others.
743
+ generator (`torch.Generator`, *optional*):
744
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
745
+ to make generation deterministic.
746
+ latents (`torch.FloatTensor`, *optional*):
747
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
748
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
749
+ tensor will ge generated by sampling using the supplied random `generator`.
750
+ prompt_embeds (`torch.FloatTensor`, *optional*):
751
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
752
+ provided, text embeddings will be generated from `prompt` input argument.
753
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
754
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
755
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
756
+ argument.
757
+ output_type (`str`, *optional*, defaults to `"pil"`):
758
+ The output format of the generate image. Choose between
759
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
760
+ return_dict (`bool`, *optional*, defaults to `True`):
761
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
762
+ plain tuple.
763
+ callback (`Callable`, *optional*):
764
+ A function that will be called every `callback_steps` steps during inference. The function will be
765
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
766
+ callback_steps (`int`, *optional*, defaults to 1):
767
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
768
+ called at every step.
769
+ Examples:
770
+ ```py
771
+ >>> import PIL
772
+ >>> import requests
773
+ >>> import torch
774
+ >>> from io import BytesIO
775
+ >>> from diffusers import StableDiffusionPipeline, RePaintScheduler
776
+ >>> def download_image(url):
777
+ ... response = requests.get(url)
778
+ ... return PIL.Image.open(BytesIO(response.content)).convert("RGB")
779
+ >>> base_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/"
780
+ >>> img_url = base_url + "overture-creations-5sI6fQgYIuo.png"
781
+ >>> mask_url = base_url + "overture-creations-5sI6fQgYIuo_mask.png "
782
+ >>> init_image = download_image(img_url).resize((512, 512))
783
+ >>> mask_image = download_image(mask_url).resize((512, 512))
784
+ >>> pipe = DiffusionPipeline.from_pretrained(
785
+ ... "CompVis/stable-diffusion-v1-4", torch_dtype=torch.float16, custom_pipeline="stable_diffusion_repaint",
786
+ ... )
787
+ >>> pipe.scheduler = RePaintScheduler.from_config(pipe.scheduler.config)
788
+ >>> pipe = pipe.to("cuda")
789
+ >>> prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
790
+ >>> image = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images[0]
791
+ ```
792
+ Returns:
793
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
794
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
795
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
796
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
797
+ (nsfw) content, according to the `safety_checker`.
798
+ """
799
+ # 0. Default height and width to unet
800
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
801
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
802
+
803
+ # 1. Check inputs
804
+ self.check_inputs(
805
+ prompt,
806
+ height,
807
+ width,
808
+ callback_steps,
809
+ negative_prompt,
810
+ prompt_embeds,
811
+ negative_prompt_embeds,
812
+ )
813
+
814
+ if image is None:
815
+ raise ValueError("`image` input cannot be undefined.")
816
+
817
+ if mask_image is None:
818
+ raise ValueError("`mask_image` input cannot be undefined.")
819
+
820
+ # 2. Define call parameters
821
+ if prompt is not None and isinstance(prompt, str):
822
+ batch_size = 1
823
+ elif prompt is not None and isinstance(prompt, list):
824
+ batch_size = len(prompt)
825
+ else:
826
+ batch_size = prompt_embeds.shape[0]
827
+
828
+ device = self._execution_device
829
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
830
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
831
+ # corresponds to doing no classifier free guidance.
832
+ do_classifier_free_guidance = guidance_scale > 1.0
833
+
834
+ # 3. Encode input prompt
835
+ prompt_embeds = self._encode_prompt(
836
+ prompt,
837
+ device,
838
+ num_images_per_prompt,
839
+ do_classifier_free_guidance,
840
+ negative_prompt,
841
+ prompt_embeds=prompt_embeds,
842
+ negative_prompt_embeds=negative_prompt_embeds,
843
+ )
844
+
845
+ # 4. Preprocess mask and image
846
+ mask, masked_image = prepare_mask_and_masked_image(image, mask_image)
847
+
848
+ # 5. set timesteps
849
+ self.scheduler.set_timesteps(num_inference_steps, jump_length, jump_n_sample, device)
850
+ self.scheduler.eta = eta
851
+
852
+ timesteps = self.scheduler.timesteps
853
+ # latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
854
+
855
+ # 6. Prepare latent variables
856
+ num_channels_latents = self.vae.config.latent_channels
857
+ latents = self.prepare_latents(
858
+ batch_size * num_images_per_prompt,
859
+ num_channels_latents,
860
+ height,
861
+ width,
862
+ prompt_embeds.dtype,
863
+ device,
864
+ generator,
865
+ latents,
866
+ )
867
+
868
+ # 7. Prepare mask latent variables
869
+ mask, masked_image_latents = self.prepare_mask_latents(
870
+ mask,
871
+ masked_image,
872
+ batch_size * num_images_per_prompt,
873
+ height,
874
+ width,
875
+ prompt_embeds.dtype,
876
+ device,
877
+ generator,
878
+ do_classifier_free_guidance=False, # We do not need duplicate mask and image
879
+ )
880
+
881
+ # 8. Check that sizes of mask, masked image and latents match
882
+ # num_channels_mask = mask.shape[1]
883
+ # num_channels_masked_image = masked_image_latents.shape[1]
884
+ if num_channels_latents != self.unet.config.in_channels:
885
+ raise ValueError(
886
+ f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects"
887
+ f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} "
888
+ f" = Please verify the config of"
889
+ " `pipeline.unet` or your `mask_image` or `image` input."
890
+ )
891
+
892
+ # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
893
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
894
+
895
+ t_last = timesteps[0] + 1
896
+
897
+ # 10. Denoising loop
898
+ with self.progress_bar(total=len(timesteps)) as progress_bar:
899
+ for i, t in enumerate(timesteps):
900
+ if t >= t_last:
901
+ # compute the reverse: x_t-1 -> x_t
902
+ latents = self.scheduler.undo_step(latents, t_last, generator)
903
+ progress_bar.update()
904
+ t_last = t
905
+ continue
906
+
907
+ # expand the latents if we are doing classifier free guidance
908
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
909
+
910
+ # concat latents, mask, masked_image_latents in the channel dimension
911
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
912
+ # latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1)
913
+
914
+ # predict the noise residual
915
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=prompt_embeds).sample
916
+
917
+ # perform guidance
918
+ if do_classifier_free_guidance:
919
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
920
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
921
+
922
+ # compute the previous noisy sample x_t -> x_t-1
923
+ latents = self.scheduler.step(
924
+ noise_pred,
925
+ t,
926
+ latents,
927
+ masked_image_latents,
928
+ mask,
929
+ **extra_step_kwargs,
930
+ ).prev_sample
931
+
932
+ # call the callback, if provided
933
+ progress_bar.update()
934
+ if callback is not None and i % callback_steps == 0:
935
+ step_idx = i // getattr(self.scheduler, "order", 1)
936
+ callback(step_idx, t, latents)
937
+
938
+ t_last = t
939
+
940
+ # 11. Post-processing
941
+ image = self.decode_latents(latents)
942
+
943
+ # 12. Run safety checker
944
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
945
+
946
+ # 13. Convert to PIL
947
+ if output_type == "pil":
948
+ image = self.numpy_to_pil(image)
949
+
950
+ # Offload last model to CPU
951
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
952
+ self.final_offload_hook.offload()
953
+
954
+ if not return_dict:
955
+ return (image, has_nsfw_concept)
956
+
957
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.22.0/stable_diffusion_tensorrt_img2img.py ADDED
@@ -0,0 +1,1055 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright 2023 The HuggingFace Inc. team.
3
+ # SPDX-FileCopyrightText: Copyright (c) 1993-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
4
+ # SPDX-License-Identifier: Apache-2.0
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ import gc
19
+ import os
20
+ from collections import OrderedDict
21
+ from copy import copy
22
+ from typing import List, Optional, Union
23
+
24
+ import numpy as np
25
+ import onnx
26
+ import onnx_graphsurgeon as gs
27
+ import PIL.Image
28
+ import tensorrt as trt
29
+ import torch
30
+ from huggingface_hub import snapshot_download
31
+ from onnx import shape_inference
32
+ from polygraphy import cuda
33
+ from polygraphy.backend.common import bytes_from_path
34
+ from polygraphy.backend.onnx.loader import fold_constants
35
+ from polygraphy.backend.trt import (
36
+ CreateConfig,
37
+ Profile,
38
+ engine_from_bytes,
39
+ engine_from_network,
40
+ network_from_onnx_path,
41
+ save_engine,
42
+ )
43
+ from polygraphy.backend.trt import util as trt_util
44
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
45
+
46
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
47
+ from diffusers.pipelines.stable_diffusion import (
48
+ StableDiffusionImg2ImgPipeline,
49
+ StableDiffusionPipelineOutput,
50
+ StableDiffusionSafetyChecker,
51
+ )
52
+ from diffusers.schedulers import DDIMScheduler
53
+ from diffusers.utils import DIFFUSERS_CACHE, logging
54
+
55
+
56
+ """
57
+ Installation instructions
58
+ python3 -m pip install --upgrade transformers diffusers>=0.16.0
59
+ python3 -m pip install --upgrade tensorrt>=8.6.1
60
+ python3 -m pip install --upgrade polygraphy>=0.47.0 onnx-graphsurgeon --extra-index-url https://pypi.ngc.nvidia.com
61
+ python3 -m pip install onnxruntime
62
+ """
63
+
64
+ TRT_LOGGER = trt.Logger(trt.Logger.ERROR)
65
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
66
+
67
+ # Map of numpy dtype -> torch dtype
68
+ numpy_to_torch_dtype_dict = {
69
+ np.uint8: torch.uint8,
70
+ np.int8: torch.int8,
71
+ np.int16: torch.int16,
72
+ np.int32: torch.int32,
73
+ np.int64: torch.int64,
74
+ np.float16: torch.float16,
75
+ np.float32: torch.float32,
76
+ np.float64: torch.float64,
77
+ np.complex64: torch.complex64,
78
+ np.complex128: torch.complex128,
79
+ }
80
+ if np.version.full_version >= "1.24.0":
81
+ numpy_to_torch_dtype_dict[np.bool_] = torch.bool
82
+ else:
83
+ numpy_to_torch_dtype_dict[np.bool] = torch.bool
84
+
85
+ # Map of torch dtype -> numpy dtype
86
+ torch_to_numpy_dtype_dict = {value: key for (key, value) in numpy_to_torch_dtype_dict.items()}
87
+
88
+
89
+ def device_view(t):
90
+ return cuda.DeviceView(ptr=t.data_ptr(), shape=t.shape, dtype=torch_to_numpy_dtype_dict[t.dtype])
91
+
92
+
93
+ def preprocess_image(image):
94
+ """
95
+ image: torch.Tensor
96
+ """
97
+ w, h = image.size
98
+ w, h = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32
99
+ image = image.resize((w, h))
100
+ image = np.array(image).astype(np.float32) / 255.0
101
+ image = image[None].transpose(0, 3, 1, 2)
102
+ image = torch.from_numpy(image).contiguous()
103
+ return 2.0 * image - 1.0
104
+
105
+
106
+ class Engine:
107
+ def __init__(self, engine_path):
108
+ self.engine_path = engine_path
109
+ self.engine = None
110
+ self.context = None
111
+ self.buffers = OrderedDict()
112
+ self.tensors = OrderedDict()
113
+
114
+ def __del__(self):
115
+ [buf.free() for buf in self.buffers.values() if isinstance(buf, cuda.DeviceArray)]
116
+ del self.engine
117
+ del self.context
118
+ del self.buffers
119
+ del self.tensors
120
+
121
+ def build(
122
+ self,
123
+ onnx_path,
124
+ fp16,
125
+ input_profile=None,
126
+ enable_preview=False,
127
+ enable_all_tactics=False,
128
+ timing_cache=None,
129
+ workspace_size=0,
130
+ ):
131
+ logger.warning(f"Building TensorRT engine for {onnx_path}: {self.engine_path}")
132
+ p = Profile()
133
+ if input_profile:
134
+ for name, dims in input_profile.items():
135
+ assert len(dims) == 3
136
+ p.add(name, min=dims[0], opt=dims[1], max=dims[2])
137
+
138
+ config_kwargs = {}
139
+
140
+ config_kwargs["preview_features"] = [trt.PreviewFeature.DISABLE_EXTERNAL_TACTIC_SOURCES_FOR_CORE_0805]
141
+ if enable_preview:
142
+ # Faster dynamic shapes made optional since it increases engine build time.
143
+ config_kwargs["preview_features"].append(trt.PreviewFeature.FASTER_DYNAMIC_SHAPES_0805)
144
+ if workspace_size > 0:
145
+ config_kwargs["memory_pool_limits"] = {trt.MemoryPoolType.WORKSPACE: workspace_size}
146
+ if not enable_all_tactics:
147
+ config_kwargs["tactic_sources"] = []
148
+
149
+ engine = engine_from_network(
150
+ network_from_onnx_path(onnx_path, flags=[trt.OnnxParserFlag.NATIVE_INSTANCENORM]),
151
+ config=CreateConfig(fp16=fp16, profiles=[p], load_timing_cache=timing_cache, **config_kwargs),
152
+ save_timing_cache=timing_cache,
153
+ )
154
+ save_engine(engine, path=self.engine_path)
155
+
156
+ def load(self):
157
+ logger.warning(f"Loading TensorRT engine: {self.engine_path}")
158
+ self.engine = engine_from_bytes(bytes_from_path(self.engine_path))
159
+
160
+ def activate(self):
161
+ self.context = self.engine.create_execution_context()
162
+
163
+ def allocate_buffers(self, shape_dict=None, device="cuda"):
164
+ for idx in range(trt_util.get_bindings_per_profile(self.engine)):
165
+ binding = self.engine[idx]
166
+ if shape_dict and binding in shape_dict:
167
+ shape = shape_dict[binding]
168
+ else:
169
+ shape = self.engine.get_binding_shape(binding)
170
+ dtype = trt.nptype(self.engine.get_binding_dtype(binding))
171
+ if self.engine.binding_is_input(binding):
172
+ self.context.set_binding_shape(idx, shape)
173
+ tensor = torch.empty(tuple(shape), dtype=numpy_to_torch_dtype_dict[dtype]).to(device=device)
174
+ self.tensors[binding] = tensor
175
+ self.buffers[binding] = cuda.DeviceView(ptr=tensor.data_ptr(), shape=shape, dtype=dtype)
176
+
177
+ def infer(self, feed_dict, stream):
178
+ start_binding, end_binding = trt_util.get_active_profile_bindings(self.context)
179
+ # shallow copy of ordered dict
180
+ device_buffers = copy(self.buffers)
181
+ for name, buf in feed_dict.items():
182
+ assert isinstance(buf, cuda.DeviceView)
183
+ device_buffers[name] = buf
184
+ bindings = [0] * start_binding + [buf.ptr for buf in device_buffers.values()]
185
+ noerror = self.context.execute_async_v2(bindings=bindings, stream_handle=stream.ptr)
186
+ if not noerror:
187
+ raise ValueError("ERROR: inference failed.")
188
+
189
+ return self.tensors
190
+
191
+
192
+ class Optimizer:
193
+ def __init__(self, onnx_graph):
194
+ self.graph = gs.import_onnx(onnx_graph)
195
+
196
+ def cleanup(self, return_onnx=False):
197
+ self.graph.cleanup().toposort()
198
+ if return_onnx:
199
+ return gs.export_onnx(self.graph)
200
+
201
+ def select_outputs(self, keep, names=None):
202
+ self.graph.outputs = [self.graph.outputs[o] for o in keep]
203
+ if names:
204
+ for i, name in enumerate(names):
205
+ self.graph.outputs[i].name = name
206
+
207
+ def fold_constants(self, return_onnx=False):
208
+ onnx_graph = fold_constants(gs.export_onnx(self.graph), allow_onnxruntime_shape_inference=True)
209
+ self.graph = gs.import_onnx(onnx_graph)
210
+ if return_onnx:
211
+ return onnx_graph
212
+
213
+ def infer_shapes(self, return_onnx=False):
214
+ onnx_graph = gs.export_onnx(self.graph)
215
+ if onnx_graph.ByteSize() > 2147483648:
216
+ raise TypeError("ERROR: model size exceeds supported 2GB limit")
217
+ else:
218
+ onnx_graph = shape_inference.infer_shapes(onnx_graph)
219
+
220
+ self.graph = gs.import_onnx(onnx_graph)
221
+ if return_onnx:
222
+ return onnx_graph
223
+
224
+
225
+ class BaseModel:
226
+ def __init__(self, model, fp16=False, device="cuda", max_batch_size=16, embedding_dim=768, text_maxlen=77):
227
+ self.model = model
228
+ self.name = "SD Model"
229
+ self.fp16 = fp16
230
+ self.device = device
231
+
232
+ self.min_batch = 1
233
+ self.max_batch = max_batch_size
234
+ self.min_image_shape = 256 # min image resolution: 256x256
235
+ self.max_image_shape = 1024 # max image resolution: 1024x1024
236
+ self.min_latent_shape = self.min_image_shape // 8
237
+ self.max_latent_shape = self.max_image_shape // 8
238
+
239
+ self.embedding_dim = embedding_dim
240
+ self.text_maxlen = text_maxlen
241
+
242
+ def get_model(self):
243
+ return self.model
244
+
245
+ def get_input_names(self):
246
+ pass
247
+
248
+ def get_output_names(self):
249
+ pass
250
+
251
+ def get_dynamic_axes(self):
252
+ return None
253
+
254
+ def get_sample_input(self, batch_size, image_height, image_width):
255
+ pass
256
+
257
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
258
+ return None
259
+
260
+ def get_shape_dict(self, batch_size, image_height, image_width):
261
+ return None
262
+
263
+ def optimize(self, onnx_graph):
264
+ opt = Optimizer(onnx_graph)
265
+ opt.cleanup()
266
+ opt.fold_constants()
267
+ opt.infer_shapes()
268
+ onnx_opt_graph = opt.cleanup(return_onnx=True)
269
+ return onnx_opt_graph
270
+
271
+ def check_dims(self, batch_size, image_height, image_width):
272
+ assert batch_size >= self.min_batch and batch_size <= self.max_batch
273
+ assert image_height % 8 == 0 or image_width % 8 == 0
274
+ latent_height = image_height // 8
275
+ latent_width = image_width // 8
276
+ assert latent_height >= self.min_latent_shape and latent_height <= self.max_latent_shape
277
+ assert latent_width >= self.min_latent_shape and latent_width <= self.max_latent_shape
278
+ return (latent_height, latent_width)
279
+
280
+ def get_minmax_dims(self, batch_size, image_height, image_width, static_batch, static_shape):
281
+ min_batch = batch_size if static_batch else self.min_batch
282
+ max_batch = batch_size if static_batch else self.max_batch
283
+ latent_height = image_height // 8
284
+ latent_width = image_width // 8
285
+ min_image_height = image_height if static_shape else self.min_image_shape
286
+ max_image_height = image_height if static_shape else self.max_image_shape
287
+ min_image_width = image_width if static_shape else self.min_image_shape
288
+ max_image_width = image_width if static_shape else self.max_image_shape
289
+ min_latent_height = latent_height if static_shape else self.min_latent_shape
290
+ max_latent_height = latent_height if static_shape else self.max_latent_shape
291
+ min_latent_width = latent_width if static_shape else self.min_latent_shape
292
+ max_latent_width = latent_width if static_shape else self.max_latent_shape
293
+ return (
294
+ min_batch,
295
+ max_batch,
296
+ min_image_height,
297
+ max_image_height,
298
+ min_image_width,
299
+ max_image_width,
300
+ min_latent_height,
301
+ max_latent_height,
302
+ min_latent_width,
303
+ max_latent_width,
304
+ )
305
+
306
+
307
+ def getOnnxPath(model_name, onnx_dir, opt=True):
308
+ return os.path.join(onnx_dir, model_name + (".opt" if opt else "") + ".onnx")
309
+
310
+
311
+ def getEnginePath(model_name, engine_dir):
312
+ return os.path.join(engine_dir, model_name + ".plan")
313
+
314
+
315
+ def build_engines(
316
+ models: dict,
317
+ engine_dir,
318
+ onnx_dir,
319
+ onnx_opset,
320
+ opt_image_height,
321
+ opt_image_width,
322
+ opt_batch_size=1,
323
+ force_engine_rebuild=False,
324
+ static_batch=False,
325
+ static_shape=True,
326
+ enable_preview=False,
327
+ enable_all_tactics=False,
328
+ timing_cache=None,
329
+ max_workspace_size=0,
330
+ ):
331
+ built_engines = {}
332
+ if not os.path.isdir(onnx_dir):
333
+ os.makedirs(onnx_dir)
334
+ if not os.path.isdir(engine_dir):
335
+ os.makedirs(engine_dir)
336
+
337
+ # Export models to ONNX
338
+ for model_name, model_obj in models.items():
339
+ engine_path = getEnginePath(model_name, engine_dir)
340
+ if force_engine_rebuild or not os.path.exists(engine_path):
341
+ logger.warning("Building Engines...")
342
+ logger.warning("Engine build can take a while to complete")
343
+ onnx_path = getOnnxPath(model_name, onnx_dir, opt=False)
344
+ onnx_opt_path = getOnnxPath(model_name, onnx_dir)
345
+ if force_engine_rebuild or not os.path.exists(onnx_opt_path):
346
+ if force_engine_rebuild or not os.path.exists(onnx_path):
347
+ logger.warning(f"Exporting model: {onnx_path}")
348
+ model = model_obj.get_model()
349
+ with torch.inference_mode(), torch.autocast("cuda"):
350
+ inputs = model_obj.get_sample_input(opt_batch_size, opt_image_height, opt_image_width)
351
+ torch.onnx.export(
352
+ model,
353
+ inputs,
354
+ onnx_path,
355
+ export_params=True,
356
+ opset_version=onnx_opset,
357
+ do_constant_folding=True,
358
+ input_names=model_obj.get_input_names(),
359
+ output_names=model_obj.get_output_names(),
360
+ dynamic_axes=model_obj.get_dynamic_axes(),
361
+ )
362
+ del model
363
+ torch.cuda.empty_cache()
364
+ gc.collect()
365
+ else:
366
+ logger.warning(f"Found cached model: {onnx_path}")
367
+
368
+ # Optimize onnx
369
+ if force_engine_rebuild or not os.path.exists(onnx_opt_path):
370
+ logger.warning(f"Generating optimizing model: {onnx_opt_path}")
371
+ onnx_opt_graph = model_obj.optimize(onnx.load(onnx_path))
372
+ onnx.save(onnx_opt_graph, onnx_opt_path)
373
+ else:
374
+ logger.warning(f"Found cached optimized model: {onnx_opt_path} ")
375
+
376
+ # Build TensorRT engines
377
+ for model_name, model_obj in models.items():
378
+ engine_path = getEnginePath(model_name, engine_dir)
379
+ engine = Engine(engine_path)
380
+ onnx_path = getOnnxPath(model_name, onnx_dir, opt=False)
381
+ onnx_opt_path = getOnnxPath(model_name, onnx_dir)
382
+
383
+ if force_engine_rebuild or not os.path.exists(engine.engine_path):
384
+ engine.build(
385
+ onnx_opt_path,
386
+ fp16=True,
387
+ input_profile=model_obj.get_input_profile(
388
+ opt_batch_size,
389
+ opt_image_height,
390
+ opt_image_width,
391
+ static_batch=static_batch,
392
+ static_shape=static_shape,
393
+ ),
394
+ enable_preview=enable_preview,
395
+ timing_cache=timing_cache,
396
+ workspace_size=max_workspace_size,
397
+ )
398
+ built_engines[model_name] = engine
399
+
400
+ # Load and activate TensorRT engines
401
+ for model_name, model_obj in models.items():
402
+ engine = built_engines[model_name]
403
+ engine.load()
404
+ engine.activate()
405
+
406
+ return built_engines
407
+
408
+
409
+ def runEngine(engine, feed_dict, stream):
410
+ return engine.infer(feed_dict, stream)
411
+
412
+
413
+ class CLIP(BaseModel):
414
+ def __init__(self, model, device, max_batch_size, embedding_dim):
415
+ super(CLIP, self).__init__(
416
+ model=model, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim
417
+ )
418
+ self.name = "CLIP"
419
+
420
+ def get_input_names(self):
421
+ return ["input_ids"]
422
+
423
+ def get_output_names(self):
424
+ return ["text_embeddings", "pooler_output"]
425
+
426
+ def get_dynamic_axes(self):
427
+ return {"input_ids": {0: "B"}, "text_embeddings": {0: "B"}}
428
+
429
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
430
+ self.check_dims(batch_size, image_height, image_width)
431
+ min_batch, max_batch, _, _, _, _, _, _, _, _ = self.get_minmax_dims(
432
+ batch_size, image_height, image_width, static_batch, static_shape
433
+ )
434
+ return {
435
+ "input_ids": [(min_batch, self.text_maxlen), (batch_size, self.text_maxlen), (max_batch, self.text_maxlen)]
436
+ }
437
+
438
+ def get_shape_dict(self, batch_size, image_height, image_width):
439
+ self.check_dims(batch_size, image_height, image_width)
440
+ return {
441
+ "input_ids": (batch_size, self.text_maxlen),
442
+ "text_embeddings": (batch_size, self.text_maxlen, self.embedding_dim),
443
+ }
444
+
445
+ def get_sample_input(self, batch_size, image_height, image_width):
446
+ self.check_dims(batch_size, image_height, image_width)
447
+ return torch.zeros(batch_size, self.text_maxlen, dtype=torch.int32, device=self.device)
448
+
449
+ def optimize(self, onnx_graph):
450
+ opt = Optimizer(onnx_graph)
451
+ opt.select_outputs([0]) # delete graph output#1
452
+ opt.cleanup()
453
+ opt.fold_constants()
454
+ opt.infer_shapes()
455
+ opt.select_outputs([0], names=["text_embeddings"]) # rename network output
456
+ opt_onnx_graph = opt.cleanup(return_onnx=True)
457
+ return opt_onnx_graph
458
+
459
+
460
+ def make_CLIP(model, device, max_batch_size, embedding_dim, inpaint=False):
461
+ return CLIP(model, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim)
462
+
463
+
464
+ class UNet(BaseModel):
465
+ def __init__(
466
+ self, model, fp16=False, device="cuda", max_batch_size=16, embedding_dim=768, text_maxlen=77, unet_dim=4
467
+ ):
468
+ super(UNet, self).__init__(
469
+ model=model,
470
+ fp16=fp16,
471
+ device=device,
472
+ max_batch_size=max_batch_size,
473
+ embedding_dim=embedding_dim,
474
+ text_maxlen=text_maxlen,
475
+ )
476
+ self.unet_dim = unet_dim
477
+ self.name = "UNet"
478
+
479
+ def get_input_names(self):
480
+ return ["sample", "timestep", "encoder_hidden_states"]
481
+
482
+ def get_output_names(self):
483
+ return ["latent"]
484
+
485
+ def get_dynamic_axes(self):
486
+ return {
487
+ "sample": {0: "2B", 2: "H", 3: "W"},
488
+ "encoder_hidden_states": {0: "2B"},
489
+ "latent": {0: "2B", 2: "H", 3: "W"},
490
+ }
491
+
492
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
493
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
494
+ (
495
+ min_batch,
496
+ max_batch,
497
+ _,
498
+ _,
499
+ _,
500
+ _,
501
+ min_latent_height,
502
+ max_latent_height,
503
+ min_latent_width,
504
+ max_latent_width,
505
+ ) = self.get_minmax_dims(batch_size, image_height, image_width, static_batch, static_shape)
506
+ return {
507
+ "sample": [
508
+ (2 * min_batch, self.unet_dim, min_latent_height, min_latent_width),
509
+ (2 * batch_size, self.unet_dim, latent_height, latent_width),
510
+ (2 * max_batch, self.unet_dim, max_latent_height, max_latent_width),
511
+ ],
512
+ "encoder_hidden_states": [
513
+ (2 * min_batch, self.text_maxlen, self.embedding_dim),
514
+ (2 * batch_size, self.text_maxlen, self.embedding_dim),
515
+ (2 * max_batch, self.text_maxlen, self.embedding_dim),
516
+ ],
517
+ }
518
+
519
+ def get_shape_dict(self, batch_size, image_height, image_width):
520
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
521
+ return {
522
+ "sample": (2 * batch_size, self.unet_dim, latent_height, latent_width),
523
+ "encoder_hidden_states": (2 * batch_size, self.text_maxlen, self.embedding_dim),
524
+ "latent": (2 * batch_size, 4, latent_height, latent_width),
525
+ }
526
+
527
+ def get_sample_input(self, batch_size, image_height, image_width):
528
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
529
+ dtype = torch.float16 if self.fp16 else torch.float32
530
+ return (
531
+ torch.randn(
532
+ 2 * batch_size, self.unet_dim, latent_height, latent_width, dtype=torch.float32, device=self.device
533
+ ),
534
+ torch.tensor([1.0], dtype=torch.float32, device=self.device),
535
+ torch.randn(2 * batch_size, self.text_maxlen, self.embedding_dim, dtype=dtype, device=self.device),
536
+ )
537
+
538
+
539
+ def make_UNet(model, device, max_batch_size, embedding_dim, inpaint=False):
540
+ return UNet(
541
+ model,
542
+ fp16=True,
543
+ device=device,
544
+ max_batch_size=max_batch_size,
545
+ embedding_dim=embedding_dim,
546
+ unet_dim=(9 if inpaint else 4),
547
+ )
548
+
549
+
550
+ class VAE(BaseModel):
551
+ def __init__(self, model, device, max_batch_size, embedding_dim):
552
+ super(VAE, self).__init__(
553
+ model=model, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim
554
+ )
555
+ self.name = "VAE decoder"
556
+
557
+ def get_input_names(self):
558
+ return ["latent"]
559
+
560
+ def get_output_names(self):
561
+ return ["images"]
562
+
563
+ def get_dynamic_axes(self):
564
+ return {"latent": {0: "B", 2: "H", 3: "W"}, "images": {0: "B", 2: "8H", 3: "8W"}}
565
+
566
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
567
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
568
+ (
569
+ min_batch,
570
+ max_batch,
571
+ _,
572
+ _,
573
+ _,
574
+ _,
575
+ min_latent_height,
576
+ max_latent_height,
577
+ min_latent_width,
578
+ max_latent_width,
579
+ ) = self.get_minmax_dims(batch_size, image_height, image_width, static_batch, static_shape)
580
+ return {
581
+ "latent": [
582
+ (min_batch, 4, min_latent_height, min_latent_width),
583
+ (batch_size, 4, latent_height, latent_width),
584
+ (max_batch, 4, max_latent_height, max_latent_width),
585
+ ]
586
+ }
587
+
588
+ def get_shape_dict(self, batch_size, image_height, image_width):
589
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
590
+ return {
591
+ "latent": (batch_size, 4, latent_height, latent_width),
592
+ "images": (batch_size, 3, image_height, image_width),
593
+ }
594
+
595
+ def get_sample_input(self, batch_size, image_height, image_width):
596
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
597
+ return torch.randn(batch_size, 4, latent_height, latent_width, dtype=torch.float32, device=self.device)
598
+
599
+
600
+ def make_VAE(model, device, max_batch_size, embedding_dim, inpaint=False):
601
+ return VAE(model, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim)
602
+
603
+
604
+ class TorchVAEEncoder(torch.nn.Module):
605
+ def __init__(self, model):
606
+ super().__init__()
607
+ self.vae_encoder = model
608
+
609
+ def forward(self, x):
610
+ return self.vae_encoder.encode(x).latent_dist.sample()
611
+
612
+
613
+ class VAEEncoder(BaseModel):
614
+ def __init__(self, model, device, max_batch_size, embedding_dim):
615
+ super(VAEEncoder, self).__init__(
616
+ model=model, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim
617
+ )
618
+ self.name = "VAE encoder"
619
+
620
+ def get_model(self):
621
+ vae_encoder = TorchVAEEncoder(self.model)
622
+ return vae_encoder
623
+
624
+ def get_input_names(self):
625
+ return ["images"]
626
+
627
+ def get_output_names(self):
628
+ return ["latent"]
629
+
630
+ def get_dynamic_axes(self):
631
+ return {"images": {0: "B", 2: "8H", 3: "8W"}, "latent": {0: "B", 2: "H", 3: "W"}}
632
+
633
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
634
+ assert batch_size >= self.min_batch and batch_size <= self.max_batch
635
+ min_batch = batch_size if static_batch else self.min_batch
636
+ max_batch = batch_size if static_batch else self.max_batch
637
+ self.check_dims(batch_size, image_height, image_width)
638
+ (
639
+ min_batch,
640
+ max_batch,
641
+ min_image_height,
642
+ max_image_height,
643
+ min_image_width,
644
+ max_image_width,
645
+ _,
646
+ _,
647
+ _,
648
+ _,
649
+ ) = self.get_minmax_dims(batch_size, image_height, image_width, static_batch, static_shape)
650
+
651
+ return {
652
+ "images": [
653
+ (min_batch, 3, min_image_height, min_image_width),
654
+ (batch_size, 3, image_height, image_width),
655
+ (max_batch, 3, max_image_height, max_image_width),
656
+ ]
657
+ }
658
+
659
+ def get_shape_dict(self, batch_size, image_height, image_width):
660
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
661
+ return {
662
+ "images": (batch_size, 3, image_height, image_width),
663
+ "latent": (batch_size, 4, latent_height, latent_width),
664
+ }
665
+
666
+ def get_sample_input(self, batch_size, image_height, image_width):
667
+ self.check_dims(batch_size, image_height, image_width)
668
+ return torch.randn(batch_size, 3, image_height, image_width, dtype=torch.float32, device=self.device)
669
+
670
+
671
+ def make_VAEEncoder(model, device, max_batch_size, embedding_dim, inpaint=False):
672
+ return VAEEncoder(model, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim)
673
+
674
+
675
+ class TensorRTStableDiffusionImg2ImgPipeline(StableDiffusionImg2ImgPipeline):
676
+ r"""
677
+ Pipeline for image-to-image generation using TensorRT accelerated Stable Diffusion.
678
+
679
+ This model inherits from [`StableDiffusionImg2ImgPipeline`]. Check the superclass documentation for the generic methods the
680
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
681
+
682
+ Args:
683
+ vae ([`AutoencoderKL`]):
684
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
685
+ text_encoder ([`CLIPTextModel`]):
686
+ Frozen text-encoder. Stable Diffusion uses the text portion of
687
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
688
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
689
+ tokenizer (`CLIPTokenizer`):
690
+ Tokenizer of class
691
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
692
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
693
+ scheduler ([`SchedulerMixin`]):
694
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
695
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
696
+ safety_checker ([`StableDiffusionSafetyChecker`]):
697
+ Classification module that estimates whether generated images could be considered offensive or harmful.
698
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
699
+ feature_extractor ([`CLIPFeatureExtractor`]):
700
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
701
+ """
702
+
703
+ def __init__(
704
+ self,
705
+ vae: AutoencoderKL,
706
+ text_encoder: CLIPTextModel,
707
+ tokenizer: CLIPTokenizer,
708
+ unet: UNet2DConditionModel,
709
+ scheduler: DDIMScheduler,
710
+ safety_checker: StableDiffusionSafetyChecker,
711
+ feature_extractor: CLIPFeatureExtractor,
712
+ requires_safety_checker: bool = True,
713
+ stages=["clip", "unet", "vae", "vae_encoder"],
714
+ image_height: int = 512,
715
+ image_width: int = 512,
716
+ max_batch_size: int = 16,
717
+ # ONNX export parameters
718
+ onnx_opset: int = 17,
719
+ onnx_dir: str = "onnx",
720
+ # TensorRT engine build parameters
721
+ engine_dir: str = "engine",
722
+ build_preview_features: bool = True,
723
+ force_engine_rebuild: bool = False,
724
+ timing_cache: str = "timing_cache",
725
+ ):
726
+ super().__init__(
727
+ vae, text_encoder, tokenizer, unet, scheduler, safety_checker, feature_extractor, requires_safety_checker
728
+ )
729
+
730
+ self.vae.forward = self.vae.decode
731
+
732
+ self.stages = stages
733
+ self.image_height, self.image_width = image_height, image_width
734
+ self.inpaint = False
735
+ self.onnx_opset = onnx_opset
736
+ self.onnx_dir = onnx_dir
737
+ self.engine_dir = engine_dir
738
+ self.force_engine_rebuild = force_engine_rebuild
739
+ self.timing_cache = timing_cache
740
+ self.build_static_batch = False
741
+ self.build_dynamic_shape = False
742
+ self.build_preview_features = build_preview_features
743
+
744
+ self.max_batch_size = max_batch_size
745
+ # TODO: Restrict batch size to 4 for larger image dimensions as a WAR for TensorRT limitation.
746
+ if self.build_dynamic_shape or self.image_height > 512 or self.image_width > 512:
747
+ self.max_batch_size = 4
748
+
749
+ self.stream = None # loaded in loadResources()
750
+ self.models = {} # loaded in __loadModels()
751
+ self.engine = {} # loaded in build_engines()
752
+
753
+ def __loadModels(self):
754
+ # Load pipeline models
755
+ self.embedding_dim = self.text_encoder.config.hidden_size
756
+ models_args = {
757
+ "device": self.torch_device,
758
+ "max_batch_size": self.max_batch_size,
759
+ "embedding_dim": self.embedding_dim,
760
+ "inpaint": self.inpaint,
761
+ }
762
+ if "clip" in self.stages:
763
+ self.models["clip"] = make_CLIP(self.text_encoder, **models_args)
764
+ if "unet" in self.stages:
765
+ self.models["unet"] = make_UNet(self.unet, **models_args)
766
+ if "vae" in self.stages:
767
+ self.models["vae"] = make_VAE(self.vae, **models_args)
768
+ if "vae_encoder" in self.stages:
769
+ self.models["vae_encoder"] = make_VAEEncoder(self.vae, **models_args)
770
+
771
+ @classmethod
772
+ def set_cached_folder(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], **kwargs):
773
+ cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
774
+ resume_download = kwargs.pop("resume_download", False)
775
+ proxies = kwargs.pop("proxies", None)
776
+ local_files_only = kwargs.pop("local_files_only", False)
777
+ use_auth_token = kwargs.pop("use_auth_token", None)
778
+ revision = kwargs.pop("revision", None)
779
+
780
+ cls.cached_folder = (
781
+ pretrained_model_name_or_path
782
+ if os.path.isdir(pretrained_model_name_or_path)
783
+ else snapshot_download(
784
+ pretrained_model_name_or_path,
785
+ cache_dir=cache_dir,
786
+ resume_download=resume_download,
787
+ proxies=proxies,
788
+ local_files_only=local_files_only,
789
+ use_auth_token=use_auth_token,
790
+ revision=revision,
791
+ )
792
+ )
793
+
794
+ def to(self, torch_device: Optional[Union[str, torch.device]] = None, silence_dtype_warnings: bool = False):
795
+ super().to(torch_device, silence_dtype_warnings=silence_dtype_warnings)
796
+
797
+ self.onnx_dir = os.path.join(self.cached_folder, self.onnx_dir)
798
+ self.engine_dir = os.path.join(self.cached_folder, self.engine_dir)
799
+ self.timing_cache = os.path.join(self.cached_folder, self.timing_cache)
800
+
801
+ # set device
802
+ self.torch_device = self._execution_device
803
+ logger.warning(f"Running inference on device: {self.torch_device}")
804
+
805
+ # load models
806
+ self.__loadModels()
807
+
808
+ # build engines
809
+ self.engine = build_engines(
810
+ self.models,
811
+ self.engine_dir,
812
+ self.onnx_dir,
813
+ self.onnx_opset,
814
+ opt_image_height=self.image_height,
815
+ opt_image_width=self.image_width,
816
+ force_engine_rebuild=self.force_engine_rebuild,
817
+ static_batch=self.build_static_batch,
818
+ static_shape=not self.build_dynamic_shape,
819
+ enable_preview=self.build_preview_features,
820
+ timing_cache=self.timing_cache,
821
+ )
822
+
823
+ return self
824
+
825
+ def __initialize_timesteps(self, timesteps, strength):
826
+ self.scheduler.set_timesteps(timesteps)
827
+ offset = self.scheduler.steps_offset if hasattr(self.scheduler, "steps_offset") else 0
828
+ init_timestep = int(timesteps * strength) + offset
829
+ init_timestep = min(init_timestep, timesteps)
830
+ t_start = max(timesteps - init_timestep + offset, 0)
831
+ timesteps = self.scheduler.timesteps[t_start:].to(self.torch_device)
832
+ return timesteps, t_start
833
+
834
+ def __preprocess_images(self, batch_size, images=()):
835
+ init_images = []
836
+ for image in images:
837
+ image = image.to(self.torch_device).float()
838
+ image = image.repeat(batch_size, 1, 1, 1)
839
+ init_images.append(image)
840
+ return tuple(init_images)
841
+
842
+ def __encode_image(self, init_image):
843
+ init_latents = runEngine(self.engine["vae_encoder"], {"images": device_view(init_image)}, self.stream)[
844
+ "latent"
845
+ ]
846
+ init_latents = 0.18215 * init_latents
847
+ return init_latents
848
+
849
+ def __encode_prompt(self, prompt, negative_prompt):
850
+ r"""
851
+ Encodes the prompt into text encoder hidden states.
852
+
853
+ Args:
854
+ prompt (`str` or `List[str]`, *optional*):
855
+ prompt to be encoded
856
+ negative_prompt (`str` or `List[str]`, *optional*):
857
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
858
+ `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
859
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
860
+ """
861
+ # Tokenize prompt
862
+ text_input_ids = (
863
+ self.tokenizer(
864
+ prompt,
865
+ padding="max_length",
866
+ max_length=self.tokenizer.model_max_length,
867
+ truncation=True,
868
+ return_tensors="pt",
869
+ )
870
+ .input_ids.type(torch.int32)
871
+ .to(self.torch_device)
872
+ )
873
+
874
+ text_input_ids_inp = device_view(text_input_ids)
875
+ # NOTE: output tensor for CLIP must be cloned because it will be overwritten when called again for negative prompt
876
+ text_embeddings = runEngine(self.engine["clip"], {"input_ids": text_input_ids_inp}, self.stream)[
877
+ "text_embeddings"
878
+ ].clone()
879
+
880
+ # Tokenize negative prompt
881
+ uncond_input_ids = (
882
+ self.tokenizer(
883
+ negative_prompt,
884
+ padding="max_length",
885
+ max_length=self.tokenizer.model_max_length,
886
+ truncation=True,
887
+ return_tensors="pt",
888
+ )
889
+ .input_ids.type(torch.int32)
890
+ .to(self.torch_device)
891
+ )
892
+ uncond_input_ids_inp = device_view(uncond_input_ids)
893
+ uncond_embeddings = runEngine(self.engine["clip"], {"input_ids": uncond_input_ids_inp}, self.stream)[
894
+ "text_embeddings"
895
+ ]
896
+
897
+ # Concatenate the unconditional and text embeddings into a single batch to avoid doing two forward passes for classifier free guidance
898
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings]).to(dtype=torch.float16)
899
+
900
+ return text_embeddings
901
+
902
+ def __denoise_latent(
903
+ self, latents, text_embeddings, timesteps=None, step_offset=0, mask=None, masked_image_latents=None
904
+ ):
905
+ if not isinstance(timesteps, torch.Tensor):
906
+ timesteps = self.scheduler.timesteps
907
+ for step_index, timestep in enumerate(timesteps):
908
+ # Expand the latents if we are doing classifier free guidance
909
+ latent_model_input = torch.cat([latents] * 2)
910
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, timestep)
911
+ if isinstance(mask, torch.Tensor):
912
+ latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1)
913
+
914
+ # Predict the noise residual
915
+ timestep_float = timestep.float() if timestep.dtype != torch.float32 else timestep
916
+
917
+ sample_inp = device_view(latent_model_input)
918
+ timestep_inp = device_view(timestep_float)
919
+ embeddings_inp = device_view(text_embeddings)
920
+ noise_pred = runEngine(
921
+ self.engine["unet"],
922
+ {"sample": sample_inp, "timestep": timestep_inp, "encoder_hidden_states": embeddings_inp},
923
+ self.stream,
924
+ )["latent"]
925
+
926
+ # Perform guidance
927
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
928
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
929
+
930
+ latents = self.scheduler.step(noise_pred, timestep, latents).prev_sample
931
+
932
+ latents = 1.0 / 0.18215 * latents
933
+ return latents
934
+
935
+ def __decode_latent(self, latents):
936
+ images = runEngine(self.engine["vae"], {"latent": device_view(latents)}, self.stream)["images"]
937
+ images = (images / 2 + 0.5).clamp(0, 1)
938
+ return images.cpu().permute(0, 2, 3, 1).float().numpy()
939
+
940
+ def __loadResources(self, image_height, image_width, batch_size):
941
+ self.stream = cuda.Stream()
942
+
943
+ # Allocate buffers for TensorRT engine bindings
944
+ for model_name, obj in self.models.items():
945
+ self.engine[model_name].allocate_buffers(
946
+ shape_dict=obj.get_shape_dict(batch_size, image_height, image_width), device=self.torch_device
947
+ )
948
+
949
+ @torch.no_grad()
950
+ def __call__(
951
+ self,
952
+ prompt: Union[str, List[str]] = None,
953
+ image: Union[torch.FloatTensor, PIL.Image.Image] = None,
954
+ strength: float = 0.8,
955
+ num_inference_steps: int = 50,
956
+ guidance_scale: float = 7.5,
957
+ negative_prompt: Optional[Union[str, List[str]]] = None,
958
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
959
+ ):
960
+ r"""
961
+ Function invoked when calling the pipeline for generation.
962
+
963
+ Args:
964
+ prompt (`str` or `List[str]`, *optional*):
965
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
966
+ instead.
967
+ image (`PIL.Image.Image`):
968
+ `Image`, or tensor representing an image batch which will be inpainted, *i.e.* parts of the image will
969
+ be masked out with `mask_image` and repainted according to `prompt`.
970
+ strength (`float`, *optional*, defaults to 0.8):
971
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
972
+ will be used as a starting point, adding more noise to it the larger the `strength`. The number of
973
+ denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
974
+ be maximum and the denoising process will run for the full number of iterations specified in
975
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
976
+ num_inference_steps (`int`, *optional*, defaults to 50):
977
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
978
+ expense of slower inference.
979
+ guidance_scale (`float`, *optional*, defaults to 7.5):
980
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
981
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
982
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
983
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
984
+ usually at the expense of lower image quality.
985
+ negative_prompt (`str` or `List[str]`, *optional*):
986
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
987
+ `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
988
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
989
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
990
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
991
+ to make generation deterministic.
992
+
993
+ """
994
+ self.generator = generator
995
+ self.denoising_steps = num_inference_steps
996
+ self.guidance_scale = guidance_scale
997
+
998
+ # Pre-compute latent input scales and linear multistep coefficients
999
+ self.scheduler.set_timesteps(self.denoising_steps, device=self.torch_device)
1000
+
1001
+ # Define call parameters
1002
+ if prompt is not None and isinstance(prompt, str):
1003
+ batch_size = 1
1004
+ prompt = [prompt]
1005
+ elif prompt is not None and isinstance(prompt, list):
1006
+ batch_size = len(prompt)
1007
+ else:
1008
+ raise ValueError(f"Expected prompt to be of type list or str but got {type(prompt)}")
1009
+
1010
+ if negative_prompt is None:
1011
+ negative_prompt = [""] * batch_size
1012
+
1013
+ if negative_prompt is not None and isinstance(negative_prompt, str):
1014
+ negative_prompt = [negative_prompt]
1015
+
1016
+ assert len(prompt) == len(negative_prompt)
1017
+
1018
+ if batch_size > self.max_batch_size:
1019
+ raise ValueError(
1020
+ f"Batch size {len(prompt)} is larger than allowed {self.max_batch_size}. If dynamic shape is used, then maximum batch size is 4"
1021
+ )
1022
+
1023
+ # load resources
1024
+ self.__loadResources(self.image_height, self.image_width, batch_size)
1025
+
1026
+ with torch.inference_mode(), torch.autocast("cuda"), trt.Runtime(TRT_LOGGER):
1027
+ # Initialize timesteps
1028
+ timesteps, t_start = self.__initialize_timesteps(self.denoising_steps, strength)
1029
+ latent_timestep = timesteps[:1].repeat(batch_size)
1030
+
1031
+ # Pre-process input image
1032
+ if isinstance(image, PIL.Image.Image):
1033
+ image = preprocess_image(image)
1034
+ init_image = self.__preprocess_images(batch_size, (image,))[0]
1035
+
1036
+ # VAE encode init image
1037
+ init_latents = self.__encode_image(init_image)
1038
+
1039
+ # Add noise to latents using timesteps
1040
+ noise = torch.randn(
1041
+ init_latents.shape, generator=self.generator, device=self.torch_device, dtype=torch.float32
1042
+ )
1043
+ latents = self.scheduler.add_noise(init_latents, noise, latent_timestep)
1044
+
1045
+ # CLIP text encoder
1046
+ text_embeddings = self.__encode_prompt(prompt, negative_prompt)
1047
+
1048
+ # UNet denoiser
1049
+ latents = self.__denoise_latent(latents, text_embeddings, timesteps=timesteps, step_offset=t_start)
1050
+
1051
+ # VAE decode latent
1052
+ images = self.__decode_latent(latents)
1053
+
1054
+ images = self.numpy_to_pil(images)
1055
+ return StableDiffusionPipelineOutput(images=images, nsfw_content_detected=None)
v0.22.0/stable_diffusion_tensorrt_inpaint.py ADDED
@@ -0,0 +1,1107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright 2023 The HuggingFace Inc. team.
3
+ # SPDX-FileCopyrightText: Copyright (c) 1993-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
4
+ # SPDX-License-Identifier: Apache-2.0
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ import gc
19
+ import os
20
+ from collections import OrderedDict
21
+ from copy import copy
22
+ from typing import List, Optional, Union
23
+
24
+ import numpy as np
25
+ import onnx
26
+ import onnx_graphsurgeon as gs
27
+ import PIL.Image
28
+ import tensorrt as trt
29
+ import torch
30
+ from huggingface_hub import snapshot_download
31
+ from onnx import shape_inference
32
+ from polygraphy import cuda
33
+ from polygraphy.backend.common import bytes_from_path
34
+ from polygraphy.backend.onnx.loader import fold_constants
35
+ from polygraphy.backend.trt import (
36
+ CreateConfig,
37
+ Profile,
38
+ engine_from_bytes,
39
+ engine_from_network,
40
+ network_from_onnx_path,
41
+ save_engine,
42
+ )
43
+ from polygraphy.backend.trt import util as trt_util
44
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
45
+
46
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
47
+ from diffusers.pipelines.stable_diffusion import (
48
+ StableDiffusionInpaintPipeline,
49
+ StableDiffusionPipelineOutput,
50
+ StableDiffusionSafetyChecker,
51
+ )
52
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_inpaint import prepare_mask_and_masked_image
53
+ from diffusers.schedulers import DDIMScheduler
54
+ from diffusers.utils import DIFFUSERS_CACHE, logging
55
+
56
+
57
+ """
58
+ Installation instructions
59
+ python3 -m pip install --upgrade transformers diffusers>=0.16.0
60
+ python3 -m pip install --upgrade tensorrt>=8.6.1
61
+ python3 -m pip install --upgrade polygraphy>=0.47.0 onnx-graphsurgeon --extra-index-url https://pypi.ngc.nvidia.com
62
+ python3 -m pip install onnxruntime
63
+ """
64
+
65
+ TRT_LOGGER = trt.Logger(trt.Logger.ERROR)
66
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
67
+
68
+ # Map of numpy dtype -> torch dtype
69
+ numpy_to_torch_dtype_dict = {
70
+ np.uint8: torch.uint8,
71
+ np.int8: torch.int8,
72
+ np.int16: torch.int16,
73
+ np.int32: torch.int32,
74
+ np.int64: torch.int64,
75
+ np.float16: torch.float16,
76
+ np.float32: torch.float32,
77
+ np.float64: torch.float64,
78
+ np.complex64: torch.complex64,
79
+ np.complex128: torch.complex128,
80
+ }
81
+ if np.version.full_version >= "1.24.0":
82
+ numpy_to_torch_dtype_dict[np.bool_] = torch.bool
83
+ else:
84
+ numpy_to_torch_dtype_dict[np.bool] = torch.bool
85
+
86
+ # Map of torch dtype -> numpy dtype
87
+ torch_to_numpy_dtype_dict = {value: key for (key, value) in numpy_to_torch_dtype_dict.items()}
88
+
89
+
90
+ def device_view(t):
91
+ return cuda.DeviceView(ptr=t.data_ptr(), shape=t.shape, dtype=torch_to_numpy_dtype_dict[t.dtype])
92
+
93
+
94
+ def preprocess_image(image):
95
+ """
96
+ image: torch.Tensor
97
+ """
98
+ w, h = image.size
99
+ w, h = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32
100
+ image = image.resize((w, h))
101
+ image = np.array(image).astype(np.float32) / 255.0
102
+ image = image[None].transpose(0, 3, 1, 2)
103
+ image = torch.from_numpy(image).contiguous()
104
+ return 2.0 * image - 1.0
105
+
106
+
107
+ class Engine:
108
+ def __init__(self, engine_path):
109
+ self.engine_path = engine_path
110
+ self.engine = None
111
+ self.context = None
112
+ self.buffers = OrderedDict()
113
+ self.tensors = OrderedDict()
114
+
115
+ def __del__(self):
116
+ [buf.free() for buf in self.buffers.values() if isinstance(buf, cuda.DeviceArray)]
117
+ del self.engine
118
+ del self.context
119
+ del self.buffers
120
+ del self.tensors
121
+
122
+ def build(
123
+ self,
124
+ onnx_path,
125
+ fp16,
126
+ input_profile=None,
127
+ enable_preview=False,
128
+ enable_all_tactics=False,
129
+ timing_cache=None,
130
+ workspace_size=0,
131
+ ):
132
+ logger.warning(f"Building TensorRT engine for {onnx_path}: {self.engine_path}")
133
+ p = Profile()
134
+ if input_profile:
135
+ for name, dims in input_profile.items():
136
+ assert len(dims) == 3
137
+ p.add(name, min=dims[0], opt=dims[1], max=dims[2])
138
+
139
+ config_kwargs = {}
140
+
141
+ config_kwargs["preview_features"] = [trt.PreviewFeature.DISABLE_EXTERNAL_TACTIC_SOURCES_FOR_CORE_0805]
142
+ if enable_preview:
143
+ # Faster dynamic shapes made optional since it increases engine build time.
144
+ config_kwargs["preview_features"].append(trt.PreviewFeature.FASTER_DYNAMIC_SHAPES_0805)
145
+ if workspace_size > 0:
146
+ config_kwargs["memory_pool_limits"] = {trt.MemoryPoolType.WORKSPACE: workspace_size}
147
+ if not enable_all_tactics:
148
+ config_kwargs["tactic_sources"] = []
149
+
150
+ engine = engine_from_network(
151
+ network_from_onnx_path(onnx_path, flags=[trt.OnnxParserFlag.NATIVE_INSTANCENORM]),
152
+ config=CreateConfig(fp16=fp16, profiles=[p], load_timing_cache=timing_cache, **config_kwargs),
153
+ save_timing_cache=timing_cache,
154
+ )
155
+ save_engine(engine, path=self.engine_path)
156
+
157
+ def load(self):
158
+ logger.warning(f"Loading TensorRT engine: {self.engine_path}")
159
+ self.engine = engine_from_bytes(bytes_from_path(self.engine_path))
160
+
161
+ def activate(self):
162
+ self.context = self.engine.create_execution_context()
163
+
164
+ def allocate_buffers(self, shape_dict=None, device="cuda"):
165
+ for idx in range(trt_util.get_bindings_per_profile(self.engine)):
166
+ binding = self.engine[idx]
167
+ if shape_dict and binding in shape_dict:
168
+ shape = shape_dict[binding]
169
+ else:
170
+ shape = self.engine.get_binding_shape(binding)
171
+ dtype = trt.nptype(self.engine.get_binding_dtype(binding))
172
+ if self.engine.binding_is_input(binding):
173
+ self.context.set_binding_shape(idx, shape)
174
+ tensor = torch.empty(tuple(shape), dtype=numpy_to_torch_dtype_dict[dtype]).to(device=device)
175
+ self.tensors[binding] = tensor
176
+ self.buffers[binding] = cuda.DeviceView(ptr=tensor.data_ptr(), shape=shape, dtype=dtype)
177
+
178
+ def infer(self, feed_dict, stream):
179
+ start_binding, end_binding = trt_util.get_active_profile_bindings(self.context)
180
+ # shallow copy of ordered dict
181
+ device_buffers = copy(self.buffers)
182
+ for name, buf in feed_dict.items():
183
+ assert isinstance(buf, cuda.DeviceView)
184
+ device_buffers[name] = buf
185
+ bindings = [0] * start_binding + [buf.ptr for buf in device_buffers.values()]
186
+ noerror = self.context.execute_async_v2(bindings=bindings, stream_handle=stream.ptr)
187
+ if not noerror:
188
+ raise ValueError("ERROR: inference failed.")
189
+
190
+ return self.tensors
191
+
192
+
193
+ class Optimizer:
194
+ def __init__(self, onnx_graph):
195
+ self.graph = gs.import_onnx(onnx_graph)
196
+
197
+ def cleanup(self, return_onnx=False):
198
+ self.graph.cleanup().toposort()
199
+ if return_onnx:
200
+ return gs.export_onnx(self.graph)
201
+
202
+ def select_outputs(self, keep, names=None):
203
+ self.graph.outputs = [self.graph.outputs[o] for o in keep]
204
+ if names:
205
+ for i, name in enumerate(names):
206
+ self.graph.outputs[i].name = name
207
+
208
+ def fold_constants(self, return_onnx=False):
209
+ onnx_graph = fold_constants(gs.export_onnx(self.graph), allow_onnxruntime_shape_inference=True)
210
+ self.graph = gs.import_onnx(onnx_graph)
211
+ if return_onnx:
212
+ return onnx_graph
213
+
214
+ def infer_shapes(self, return_onnx=False):
215
+ onnx_graph = gs.export_onnx(self.graph)
216
+ if onnx_graph.ByteSize() > 2147483648:
217
+ raise TypeError("ERROR: model size exceeds supported 2GB limit")
218
+ else:
219
+ onnx_graph = shape_inference.infer_shapes(onnx_graph)
220
+
221
+ self.graph = gs.import_onnx(onnx_graph)
222
+ if return_onnx:
223
+ return onnx_graph
224
+
225
+
226
+ class BaseModel:
227
+ def __init__(self, model, fp16=False, device="cuda", max_batch_size=16, embedding_dim=768, text_maxlen=77):
228
+ self.model = model
229
+ self.name = "SD Model"
230
+ self.fp16 = fp16
231
+ self.device = device
232
+
233
+ self.min_batch = 1
234
+ self.max_batch = max_batch_size
235
+ self.min_image_shape = 256 # min image resolution: 256x256
236
+ self.max_image_shape = 1024 # max image resolution: 1024x1024
237
+ self.min_latent_shape = self.min_image_shape // 8
238
+ self.max_latent_shape = self.max_image_shape // 8
239
+
240
+ self.embedding_dim = embedding_dim
241
+ self.text_maxlen = text_maxlen
242
+
243
+ def get_model(self):
244
+ return self.model
245
+
246
+ def get_input_names(self):
247
+ pass
248
+
249
+ def get_output_names(self):
250
+ pass
251
+
252
+ def get_dynamic_axes(self):
253
+ return None
254
+
255
+ def get_sample_input(self, batch_size, image_height, image_width):
256
+ pass
257
+
258
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
259
+ return None
260
+
261
+ def get_shape_dict(self, batch_size, image_height, image_width):
262
+ return None
263
+
264
+ def optimize(self, onnx_graph):
265
+ opt = Optimizer(onnx_graph)
266
+ opt.cleanup()
267
+ opt.fold_constants()
268
+ opt.infer_shapes()
269
+ onnx_opt_graph = opt.cleanup(return_onnx=True)
270
+ return onnx_opt_graph
271
+
272
+ def check_dims(self, batch_size, image_height, image_width):
273
+ assert batch_size >= self.min_batch and batch_size <= self.max_batch
274
+ assert image_height % 8 == 0 or image_width % 8 == 0
275
+ latent_height = image_height // 8
276
+ latent_width = image_width // 8
277
+ assert latent_height >= self.min_latent_shape and latent_height <= self.max_latent_shape
278
+ assert latent_width >= self.min_latent_shape and latent_width <= self.max_latent_shape
279
+ return (latent_height, latent_width)
280
+
281
+ def get_minmax_dims(self, batch_size, image_height, image_width, static_batch, static_shape):
282
+ min_batch = batch_size if static_batch else self.min_batch
283
+ max_batch = batch_size if static_batch else self.max_batch
284
+ latent_height = image_height // 8
285
+ latent_width = image_width // 8
286
+ min_image_height = image_height if static_shape else self.min_image_shape
287
+ max_image_height = image_height if static_shape else self.max_image_shape
288
+ min_image_width = image_width if static_shape else self.min_image_shape
289
+ max_image_width = image_width if static_shape else self.max_image_shape
290
+ min_latent_height = latent_height if static_shape else self.min_latent_shape
291
+ max_latent_height = latent_height if static_shape else self.max_latent_shape
292
+ min_latent_width = latent_width if static_shape else self.min_latent_shape
293
+ max_latent_width = latent_width if static_shape else self.max_latent_shape
294
+ return (
295
+ min_batch,
296
+ max_batch,
297
+ min_image_height,
298
+ max_image_height,
299
+ min_image_width,
300
+ max_image_width,
301
+ min_latent_height,
302
+ max_latent_height,
303
+ min_latent_width,
304
+ max_latent_width,
305
+ )
306
+
307
+
308
+ def getOnnxPath(model_name, onnx_dir, opt=True):
309
+ return os.path.join(onnx_dir, model_name + (".opt" if opt else "") + ".onnx")
310
+
311
+
312
+ def getEnginePath(model_name, engine_dir):
313
+ return os.path.join(engine_dir, model_name + ".plan")
314
+
315
+
316
+ def build_engines(
317
+ models: dict,
318
+ engine_dir,
319
+ onnx_dir,
320
+ onnx_opset,
321
+ opt_image_height,
322
+ opt_image_width,
323
+ opt_batch_size=1,
324
+ force_engine_rebuild=False,
325
+ static_batch=False,
326
+ static_shape=True,
327
+ enable_preview=False,
328
+ enable_all_tactics=False,
329
+ timing_cache=None,
330
+ max_workspace_size=0,
331
+ ):
332
+ built_engines = {}
333
+ if not os.path.isdir(onnx_dir):
334
+ os.makedirs(onnx_dir)
335
+ if not os.path.isdir(engine_dir):
336
+ os.makedirs(engine_dir)
337
+
338
+ # Export models to ONNX
339
+ for model_name, model_obj in models.items():
340
+ engine_path = getEnginePath(model_name, engine_dir)
341
+ if force_engine_rebuild or not os.path.exists(engine_path):
342
+ logger.warning("Building Engines...")
343
+ logger.warning("Engine build can take a while to complete")
344
+ onnx_path = getOnnxPath(model_name, onnx_dir, opt=False)
345
+ onnx_opt_path = getOnnxPath(model_name, onnx_dir)
346
+ if force_engine_rebuild or not os.path.exists(onnx_opt_path):
347
+ if force_engine_rebuild or not os.path.exists(onnx_path):
348
+ logger.warning(f"Exporting model: {onnx_path}")
349
+ model = model_obj.get_model()
350
+ with torch.inference_mode(), torch.autocast("cuda"):
351
+ inputs = model_obj.get_sample_input(opt_batch_size, opt_image_height, opt_image_width)
352
+ torch.onnx.export(
353
+ model,
354
+ inputs,
355
+ onnx_path,
356
+ export_params=True,
357
+ opset_version=onnx_opset,
358
+ do_constant_folding=True,
359
+ input_names=model_obj.get_input_names(),
360
+ output_names=model_obj.get_output_names(),
361
+ dynamic_axes=model_obj.get_dynamic_axes(),
362
+ )
363
+ del model
364
+ torch.cuda.empty_cache()
365
+ gc.collect()
366
+ else:
367
+ logger.warning(f"Found cached model: {onnx_path}")
368
+
369
+ # Optimize onnx
370
+ if force_engine_rebuild or not os.path.exists(onnx_opt_path):
371
+ logger.warning(f"Generating optimizing model: {onnx_opt_path}")
372
+ onnx_opt_graph = model_obj.optimize(onnx.load(onnx_path))
373
+ onnx.save(onnx_opt_graph, onnx_opt_path)
374
+ else:
375
+ logger.warning(f"Found cached optimized model: {onnx_opt_path} ")
376
+
377
+ # Build TensorRT engines
378
+ for model_name, model_obj in models.items():
379
+ engine_path = getEnginePath(model_name, engine_dir)
380
+ engine = Engine(engine_path)
381
+ onnx_path = getOnnxPath(model_name, onnx_dir, opt=False)
382
+ onnx_opt_path = getOnnxPath(model_name, onnx_dir)
383
+
384
+ if force_engine_rebuild or not os.path.exists(engine.engine_path):
385
+ engine.build(
386
+ onnx_opt_path,
387
+ fp16=True,
388
+ input_profile=model_obj.get_input_profile(
389
+ opt_batch_size,
390
+ opt_image_height,
391
+ opt_image_width,
392
+ static_batch=static_batch,
393
+ static_shape=static_shape,
394
+ ),
395
+ enable_preview=enable_preview,
396
+ timing_cache=timing_cache,
397
+ workspace_size=max_workspace_size,
398
+ )
399
+ built_engines[model_name] = engine
400
+
401
+ # Load and activate TensorRT engines
402
+ for model_name, model_obj in models.items():
403
+ engine = built_engines[model_name]
404
+ engine.load()
405
+ engine.activate()
406
+
407
+ return built_engines
408
+
409
+
410
+ def runEngine(engine, feed_dict, stream):
411
+ return engine.infer(feed_dict, stream)
412
+
413
+
414
+ class CLIP(BaseModel):
415
+ def __init__(self, model, device, max_batch_size, embedding_dim):
416
+ super(CLIP, self).__init__(
417
+ model=model, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim
418
+ )
419
+ self.name = "CLIP"
420
+
421
+ def get_input_names(self):
422
+ return ["input_ids"]
423
+
424
+ def get_output_names(self):
425
+ return ["text_embeddings", "pooler_output"]
426
+
427
+ def get_dynamic_axes(self):
428
+ return {"input_ids": {0: "B"}, "text_embeddings": {0: "B"}}
429
+
430
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
431
+ self.check_dims(batch_size, image_height, image_width)
432
+ min_batch, max_batch, _, _, _, _, _, _, _, _ = self.get_minmax_dims(
433
+ batch_size, image_height, image_width, static_batch, static_shape
434
+ )
435
+ return {
436
+ "input_ids": [(min_batch, self.text_maxlen), (batch_size, self.text_maxlen), (max_batch, self.text_maxlen)]
437
+ }
438
+
439
+ def get_shape_dict(self, batch_size, image_height, image_width):
440
+ self.check_dims(batch_size, image_height, image_width)
441
+ return {
442
+ "input_ids": (batch_size, self.text_maxlen),
443
+ "text_embeddings": (batch_size, self.text_maxlen, self.embedding_dim),
444
+ }
445
+
446
+ def get_sample_input(self, batch_size, image_height, image_width):
447
+ self.check_dims(batch_size, image_height, image_width)
448
+ return torch.zeros(batch_size, self.text_maxlen, dtype=torch.int32, device=self.device)
449
+
450
+ def optimize(self, onnx_graph):
451
+ opt = Optimizer(onnx_graph)
452
+ opt.select_outputs([0]) # delete graph output#1
453
+ opt.cleanup()
454
+ opt.fold_constants()
455
+ opt.infer_shapes()
456
+ opt.select_outputs([0], names=["text_embeddings"]) # rename network output
457
+ opt_onnx_graph = opt.cleanup(return_onnx=True)
458
+ return opt_onnx_graph
459
+
460
+
461
+ def make_CLIP(model, device, max_batch_size, embedding_dim, inpaint=False):
462
+ return CLIP(model, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim)
463
+
464
+
465
+ class UNet(BaseModel):
466
+ def __init__(
467
+ self, model, fp16=False, device="cuda", max_batch_size=16, embedding_dim=768, text_maxlen=77, unet_dim=4
468
+ ):
469
+ super(UNet, self).__init__(
470
+ model=model,
471
+ fp16=fp16,
472
+ device=device,
473
+ max_batch_size=max_batch_size,
474
+ embedding_dim=embedding_dim,
475
+ text_maxlen=text_maxlen,
476
+ )
477
+ self.unet_dim = unet_dim
478
+ self.name = "UNet"
479
+
480
+ def get_input_names(self):
481
+ return ["sample", "timestep", "encoder_hidden_states"]
482
+
483
+ def get_output_names(self):
484
+ return ["latent"]
485
+
486
+ def get_dynamic_axes(self):
487
+ return {
488
+ "sample": {0: "2B", 2: "H", 3: "W"},
489
+ "encoder_hidden_states": {0: "2B"},
490
+ "latent": {0: "2B", 2: "H", 3: "W"},
491
+ }
492
+
493
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
494
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
495
+ (
496
+ min_batch,
497
+ max_batch,
498
+ _,
499
+ _,
500
+ _,
501
+ _,
502
+ min_latent_height,
503
+ max_latent_height,
504
+ min_latent_width,
505
+ max_latent_width,
506
+ ) = self.get_minmax_dims(batch_size, image_height, image_width, static_batch, static_shape)
507
+ return {
508
+ "sample": [
509
+ (2 * min_batch, self.unet_dim, min_latent_height, min_latent_width),
510
+ (2 * batch_size, self.unet_dim, latent_height, latent_width),
511
+ (2 * max_batch, self.unet_dim, max_latent_height, max_latent_width),
512
+ ],
513
+ "encoder_hidden_states": [
514
+ (2 * min_batch, self.text_maxlen, self.embedding_dim),
515
+ (2 * batch_size, self.text_maxlen, self.embedding_dim),
516
+ (2 * max_batch, self.text_maxlen, self.embedding_dim),
517
+ ],
518
+ }
519
+
520
+ def get_shape_dict(self, batch_size, image_height, image_width):
521
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
522
+ return {
523
+ "sample": (2 * batch_size, self.unet_dim, latent_height, latent_width),
524
+ "encoder_hidden_states": (2 * batch_size, self.text_maxlen, self.embedding_dim),
525
+ "latent": (2 * batch_size, 4, latent_height, latent_width),
526
+ }
527
+
528
+ def get_sample_input(self, batch_size, image_height, image_width):
529
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
530
+ dtype = torch.float16 if self.fp16 else torch.float32
531
+ return (
532
+ torch.randn(
533
+ 2 * batch_size, self.unet_dim, latent_height, latent_width, dtype=torch.float32, device=self.device
534
+ ),
535
+ torch.tensor([1.0], dtype=torch.float32, device=self.device),
536
+ torch.randn(2 * batch_size, self.text_maxlen, self.embedding_dim, dtype=dtype, device=self.device),
537
+ )
538
+
539
+
540
+ def make_UNet(model, device, max_batch_size, embedding_dim, inpaint=False, unet_dim=4):
541
+ return UNet(
542
+ model,
543
+ fp16=True,
544
+ device=device,
545
+ max_batch_size=max_batch_size,
546
+ embedding_dim=embedding_dim,
547
+ unet_dim=unet_dim,
548
+ )
549
+
550
+
551
+ class VAE(BaseModel):
552
+ def __init__(self, model, device, max_batch_size, embedding_dim):
553
+ super(VAE, self).__init__(
554
+ model=model, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim
555
+ )
556
+ self.name = "VAE decoder"
557
+
558
+ def get_input_names(self):
559
+ return ["latent"]
560
+
561
+ def get_output_names(self):
562
+ return ["images"]
563
+
564
+ def get_dynamic_axes(self):
565
+ return {"latent": {0: "B", 2: "H", 3: "W"}, "images": {0: "B", 2: "8H", 3: "8W"}}
566
+
567
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
568
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
569
+ (
570
+ min_batch,
571
+ max_batch,
572
+ _,
573
+ _,
574
+ _,
575
+ _,
576
+ min_latent_height,
577
+ max_latent_height,
578
+ min_latent_width,
579
+ max_latent_width,
580
+ ) = self.get_minmax_dims(batch_size, image_height, image_width, static_batch, static_shape)
581
+ return {
582
+ "latent": [
583
+ (min_batch, 4, min_latent_height, min_latent_width),
584
+ (batch_size, 4, latent_height, latent_width),
585
+ (max_batch, 4, max_latent_height, max_latent_width),
586
+ ]
587
+ }
588
+
589
+ def get_shape_dict(self, batch_size, image_height, image_width):
590
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
591
+ return {
592
+ "latent": (batch_size, 4, latent_height, latent_width),
593
+ "images": (batch_size, 3, image_height, image_width),
594
+ }
595
+
596
+ def get_sample_input(self, batch_size, image_height, image_width):
597
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
598
+ return torch.randn(batch_size, 4, latent_height, latent_width, dtype=torch.float32, device=self.device)
599
+
600
+
601
+ def make_VAE(model, device, max_batch_size, embedding_dim, inpaint=False):
602
+ return VAE(model, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim)
603
+
604
+
605
+ class TorchVAEEncoder(torch.nn.Module):
606
+ def __init__(self, model):
607
+ super().__init__()
608
+ self.vae_encoder = model
609
+
610
+ def forward(self, x):
611
+ return self.vae_encoder.encode(x).latent_dist.sample()
612
+
613
+
614
+ class VAEEncoder(BaseModel):
615
+ def __init__(self, model, device, max_batch_size, embedding_dim):
616
+ super(VAEEncoder, self).__init__(
617
+ model=model, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim
618
+ )
619
+ self.name = "VAE encoder"
620
+
621
+ def get_model(self):
622
+ vae_encoder = TorchVAEEncoder(self.model)
623
+ return vae_encoder
624
+
625
+ def get_input_names(self):
626
+ return ["images"]
627
+
628
+ def get_output_names(self):
629
+ return ["latent"]
630
+
631
+ def get_dynamic_axes(self):
632
+ return {"images": {0: "B", 2: "8H", 3: "8W"}, "latent": {0: "B", 2: "H", 3: "W"}}
633
+
634
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
635
+ assert batch_size >= self.min_batch and batch_size <= self.max_batch
636
+ min_batch = batch_size if static_batch else self.min_batch
637
+ max_batch = batch_size if static_batch else self.max_batch
638
+ self.check_dims(batch_size, image_height, image_width)
639
+ (
640
+ min_batch,
641
+ max_batch,
642
+ min_image_height,
643
+ max_image_height,
644
+ min_image_width,
645
+ max_image_width,
646
+ _,
647
+ _,
648
+ _,
649
+ _,
650
+ ) = self.get_minmax_dims(batch_size, image_height, image_width, static_batch, static_shape)
651
+
652
+ return {
653
+ "images": [
654
+ (min_batch, 3, min_image_height, min_image_width),
655
+ (batch_size, 3, image_height, image_width),
656
+ (max_batch, 3, max_image_height, max_image_width),
657
+ ]
658
+ }
659
+
660
+ def get_shape_dict(self, batch_size, image_height, image_width):
661
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
662
+ return {
663
+ "images": (batch_size, 3, image_height, image_width),
664
+ "latent": (batch_size, 4, latent_height, latent_width),
665
+ }
666
+
667
+ def get_sample_input(self, batch_size, image_height, image_width):
668
+ self.check_dims(batch_size, image_height, image_width)
669
+ return torch.randn(batch_size, 3, image_height, image_width, dtype=torch.float32, device=self.device)
670
+
671
+
672
+ def make_VAEEncoder(model, device, max_batch_size, embedding_dim, inpaint=False):
673
+ return VAEEncoder(model, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim)
674
+
675
+
676
+ class TensorRTStableDiffusionInpaintPipeline(StableDiffusionInpaintPipeline):
677
+ r"""
678
+ Pipeline for inpainting using TensorRT accelerated Stable Diffusion.
679
+
680
+ This model inherits from [`StableDiffusionInpaintPipeline`]. Check the superclass documentation for the generic methods the
681
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
682
+
683
+ Args:
684
+ vae ([`AutoencoderKL`]):
685
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
686
+ text_encoder ([`CLIPTextModel`]):
687
+ Frozen text-encoder. Stable Diffusion uses the text portion of
688
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
689
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
690
+ tokenizer (`CLIPTokenizer`):
691
+ Tokenizer of class
692
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
693
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
694
+ scheduler ([`SchedulerMixin`]):
695
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
696
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
697
+ safety_checker ([`StableDiffusionSafetyChecker`]):
698
+ Classification module that estimates whether generated images could be considered offensive or harmful.
699
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
700
+ feature_extractor ([`CLIPFeatureExtractor`]):
701
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
702
+ """
703
+
704
+ def __init__(
705
+ self,
706
+ vae: AutoencoderKL,
707
+ text_encoder: CLIPTextModel,
708
+ tokenizer: CLIPTokenizer,
709
+ unet: UNet2DConditionModel,
710
+ scheduler: DDIMScheduler,
711
+ safety_checker: StableDiffusionSafetyChecker,
712
+ feature_extractor: CLIPFeatureExtractor,
713
+ requires_safety_checker: bool = True,
714
+ stages=["clip", "unet", "vae", "vae_encoder"],
715
+ image_height: int = 512,
716
+ image_width: int = 512,
717
+ max_batch_size: int = 16,
718
+ # ONNX export parameters
719
+ onnx_opset: int = 17,
720
+ onnx_dir: str = "onnx",
721
+ # TensorRT engine build parameters
722
+ engine_dir: str = "engine",
723
+ build_preview_features: bool = True,
724
+ force_engine_rebuild: bool = False,
725
+ timing_cache: str = "timing_cache",
726
+ ):
727
+ super().__init__(
728
+ vae, text_encoder, tokenizer, unet, scheduler, safety_checker, feature_extractor, requires_safety_checker
729
+ )
730
+
731
+ self.vae.forward = self.vae.decode
732
+
733
+ self.stages = stages
734
+ self.image_height, self.image_width = image_height, image_width
735
+ self.inpaint = True
736
+ self.onnx_opset = onnx_opset
737
+ self.onnx_dir = onnx_dir
738
+ self.engine_dir = engine_dir
739
+ self.force_engine_rebuild = force_engine_rebuild
740
+ self.timing_cache = timing_cache
741
+ self.build_static_batch = False
742
+ self.build_dynamic_shape = False
743
+ self.build_preview_features = build_preview_features
744
+
745
+ self.max_batch_size = max_batch_size
746
+ # TODO: Restrict batch size to 4 for larger image dimensions as a WAR for TensorRT limitation.
747
+ if self.build_dynamic_shape or self.image_height > 512 or self.image_width > 512:
748
+ self.max_batch_size = 4
749
+
750
+ self.stream = None # loaded in loadResources()
751
+ self.models = {} # loaded in __loadModels()
752
+ self.engine = {} # loaded in build_engines()
753
+
754
+ def __loadModels(self):
755
+ # Load pipeline models
756
+ self.embedding_dim = self.text_encoder.config.hidden_size
757
+ models_args = {
758
+ "device": self.torch_device,
759
+ "max_batch_size": self.max_batch_size,
760
+ "embedding_dim": self.embedding_dim,
761
+ "inpaint": self.inpaint,
762
+ }
763
+ if "clip" in self.stages:
764
+ self.models["clip"] = make_CLIP(self.text_encoder, **models_args)
765
+ if "unet" in self.stages:
766
+ self.models["unet"] = make_UNet(self.unet, **models_args, unet_dim=self.unet.config.in_channels)
767
+ if "vae" in self.stages:
768
+ self.models["vae"] = make_VAE(self.vae, **models_args)
769
+ if "vae_encoder" in self.stages:
770
+ self.models["vae_encoder"] = make_VAEEncoder(self.vae, **models_args)
771
+
772
+ @classmethod
773
+ def set_cached_folder(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], **kwargs):
774
+ cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
775
+ resume_download = kwargs.pop("resume_download", False)
776
+ proxies = kwargs.pop("proxies", None)
777
+ local_files_only = kwargs.pop("local_files_only", False)
778
+ use_auth_token = kwargs.pop("use_auth_token", None)
779
+ revision = kwargs.pop("revision", None)
780
+
781
+ cls.cached_folder = (
782
+ pretrained_model_name_or_path
783
+ if os.path.isdir(pretrained_model_name_or_path)
784
+ else snapshot_download(
785
+ pretrained_model_name_or_path,
786
+ cache_dir=cache_dir,
787
+ resume_download=resume_download,
788
+ proxies=proxies,
789
+ local_files_only=local_files_only,
790
+ use_auth_token=use_auth_token,
791
+ revision=revision,
792
+ )
793
+ )
794
+
795
+ def to(self, torch_device: Optional[Union[str, torch.device]] = None, silence_dtype_warnings: bool = False):
796
+ super().to(torch_device, silence_dtype_warnings=silence_dtype_warnings)
797
+
798
+ self.onnx_dir = os.path.join(self.cached_folder, self.onnx_dir)
799
+ self.engine_dir = os.path.join(self.cached_folder, self.engine_dir)
800
+ self.timing_cache = os.path.join(self.cached_folder, self.timing_cache)
801
+
802
+ # set device
803
+ self.torch_device = self._execution_device
804
+ logger.warning(f"Running inference on device: {self.torch_device}")
805
+
806
+ # load models
807
+ self.__loadModels()
808
+
809
+ # build engines
810
+ self.engine = build_engines(
811
+ self.models,
812
+ self.engine_dir,
813
+ self.onnx_dir,
814
+ self.onnx_opset,
815
+ opt_image_height=self.image_height,
816
+ opt_image_width=self.image_width,
817
+ force_engine_rebuild=self.force_engine_rebuild,
818
+ static_batch=self.build_static_batch,
819
+ static_shape=not self.build_dynamic_shape,
820
+ enable_preview=self.build_preview_features,
821
+ timing_cache=self.timing_cache,
822
+ )
823
+
824
+ return self
825
+
826
+ def __initialize_timesteps(self, num_inference_steps, strength):
827
+ self.scheduler.set_timesteps(num_inference_steps)
828
+ offset = self.scheduler.config.steps_offset if hasattr(self.scheduler, "steps_offset") else 0
829
+ init_timestep = int(num_inference_steps * strength) + offset
830
+ init_timestep = min(init_timestep, num_inference_steps)
831
+ t_start = max(num_inference_steps - init_timestep + offset, 0)
832
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :].to(self.torch_device)
833
+ return timesteps, num_inference_steps - t_start
834
+
835
+ def __preprocess_images(self, batch_size, images=()):
836
+ init_images = []
837
+ for image in images:
838
+ image = image.to(self.torch_device).float()
839
+ image = image.repeat(batch_size, 1, 1, 1)
840
+ init_images.append(image)
841
+ return tuple(init_images)
842
+
843
+ def __encode_image(self, init_image):
844
+ init_latents = runEngine(self.engine["vae_encoder"], {"images": device_view(init_image)}, self.stream)[
845
+ "latent"
846
+ ]
847
+ init_latents = 0.18215 * init_latents
848
+ return init_latents
849
+
850
+ def __encode_prompt(self, prompt, negative_prompt):
851
+ r"""
852
+ Encodes the prompt into text encoder hidden states.
853
+
854
+ Args:
855
+ prompt (`str` or `List[str]`, *optional*):
856
+ prompt to be encoded
857
+ negative_prompt (`str` or `List[str]`, *optional*):
858
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
859
+ `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
860
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
861
+ """
862
+ # Tokenize prompt
863
+ text_input_ids = (
864
+ self.tokenizer(
865
+ prompt,
866
+ padding="max_length",
867
+ max_length=self.tokenizer.model_max_length,
868
+ truncation=True,
869
+ return_tensors="pt",
870
+ )
871
+ .input_ids.type(torch.int32)
872
+ .to(self.torch_device)
873
+ )
874
+
875
+ text_input_ids_inp = device_view(text_input_ids)
876
+ # NOTE: output tensor for CLIP must be cloned because it will be overwritten when called again for negative prompt
877
+ text_embeddings = runEngine(self.engine["clip"], {"input_ids": text_input_ids_inp}, self.stream)[
878
+ "text_embeddings"
879
+ ].clone()
880
+
881
+ # Tokenize negative prompt
882
+ uncond_input_ids = (
883
+ self.tokenizer(
884
+ negative_prompt,
885
+ padding="max_length",
886
+ max_length=self.tokenizer.model_max_length,
887
+ truncation=True,
888
+ return_tensors="pt",
889
+ )
890
+ .input_ids.type(torch.int32)
891
+ .to(self.torch_device)
892
+ )
893
+ uncond_input_ids_inp = device_view(uncond_input_ids)
894
+ uncond_embeddings = runEngine(self.engine["clip"], {"input_ids": uncond_input_ids_inp}, self.stream)[
895
+ "text_embeddings"
896
+ ]
897
+
898
+ # Concatenate the unconditional and text embeddings into a single batch to avoid doing two forward passes for classifier free guidance
899
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings]).to(dtype=torch.float16)
900
+
901
+ return text_embeddings
902
+
903
+ def __denoise_latent(
904
+ self, latents, text_embeddings, timesteps=None, step_offset=0, mask=None, masked_image_latents=None
905
+ ):
906
+ if not isinstance(timesteps, torch.Tensor):
907
+ timesteps = self.scheduler.timesteps
908
+ for step_index, timestep in enumerate(timesteps):
909
+ # Expand the latents if we are doing classifier free guidance
910
+ latent_model_input = torch.cat([latents] * 2)
911
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, timestep)
912
+ if isinstance(mask, torch.Tensor):
913
+ latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1)
914
+
915
+ # Predict the noise residual
916
+ timestep_float = timestep.float() if timestep.dtype != torch.float32 else timestep
917
+
918
+ sample_inp = device_view(latent_model_input)
919
+ timestep_inp = device_view(timestep_float)
920
+ embeddings_inp = device_view(text_embeddings)
921
+ noise_pred = runEngine(
922
+ self.engine["unet"],
923
+ {"sample": sample_inp, "timestep": timestep_inp, "encoder_hidden_states": embeddings_inp},
924
+ self.stream,
925
+ )["latent"]
926
+
927
+ # Perform guidance
928
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
929
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
930
+
931
+ latents = self.scheduler.step(noise_pred, timestep, latents).prev_sample
932
+
933
+ latents = 1.0 / 0.18215 * latents
934
+ return latents
935
+
936
+ def __decode_latent(self, latents):
937
+ images = runEngine(self.engine["vae"], {"latent": device_view(latents)}, self.stream)["images"]
938
+ images = (images / 2 + 0.5).clamp(0, 1)
939
+ return images.cpu().permute(0, 2, 3, 1).float().numpy()
940
+
941
+ def __loadResources(self, image_height, image_width, batch_size):
942
+ self.stream = cuda.Stream()
943
+
944
+ # Allocate buffers for TensorRT engine bindings
945
+ for model_name, obj in self.models.items():
946
+ self.engine[model_name].allocate_buffers(
947
+ shape_dict=obj.get_shape_dict(batch_size, image_height, image_width), device=self.torch_device
948
+ )
949
+
950
+ @torch.no_grad()
951
+ def __call__(
952
+ self,
953
+ prompt: Union[str, List[str]] = None,
954
+ image: Union[torch.FloatTensor, PIL.Image.Image] = None,
955
+ mask_image: Union[torch.FloatTensor, PIL.Image.Image] = None,
956
+ strength: float = 1.0,
957
+ num_inference_steps: int = 50,
958
+ guidance_scale: float = 7.5,
959
+ negative_prompt: Optional[Union[str, List[str]]] = None,
960
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
961
+ ):
962
+ r"""
963
+ Function invoked when calling the pipeline for generation.
964
+
965
+ Args:
966
+ prompt (`str` or `List[str]`, *optional*):
967
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
968
+ instead.
969
+ image (`PIL.Image.Image`):
970
+ `Image`, or tensor representing an image batch which will be inpainted, *i.e.* parts of the image will
971
+ be masked out with `mask_image` and repainted according to `prompt`.
972
+ mask_image (`PIL.Image.Image`):
973
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
974
+ repainted, while black pixels will be preserved. If `mask_image` is a PIL image, it will be converted
975
+ to a single channel (luminance) before use. If it's a tensor, it should contain one color channel (L)
976
+ instead of 3, so the expected shape would be `(B, H, W, 1)`.
977
+ strength (`float`, *optional*, defaults to 0.8):
978
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
979
+ will be used as a starting point, adding more noise to it the larger the `strength`. The number of
980
+ denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
981
+ be maximum and the denoising process will run for the full number of iterations specified in
982
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
983
+ num_inference_steps (`int`, *optional*, defaults to 50):
984
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
985
+ expense of slower inference.
986
+ guidance_scale (`float`, *optional*, defaults to 7.5):
987
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
988
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
989
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
990
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
991
+ usually at the expense of lower image quality.
992
+ negative_prompt (`str` or `List[str]`, *optional*):
993
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
994
+ `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
995
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
996
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
997
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
998
+ to make generation deterministic.
999
+
1000
+ """
1001
+ self.generator = generator
1002
+ self.denoising_steps = num_inference_steps
1003
+ self.guidance_scale = guidance_scale
1004
+
1005
+ # Pre-compute latent input scales and linear multistep coefficients
1006
+ self.scheduler.set_timesteps(self.denoising_steps, device=self.torch_device)
1007
+
1008
+ # Define call parameters
1009
+ if prompt is not None and isinstance(prompt, str):
1010
+ batch_size = 1
1011
+ prompt = [prompt]
1012
+ elif prompt is not None and isinstance(prompt, list):
1013
+ batch_size = len(prompt)
1014
+ else:
1015
+ raise ValueError(f"Expected prompt to be of type list or str but got {type(prompt)}")
1016
+
1017
+ if negative_prompt is None:
1018
+ negative_prompt = [""] * batch_size
1019
+
1020
+ if negative_prompt is not None and isinstance(negative_prompt, str):
1021
+ negative_prompt = [negative_prompt]
1022
+
1023
+ assert len(prompt) == len(negative_prompt)
1024
+
1025
+ if batch_size > self.max_batch_size:
1026
+ raise ValueError(
1027
+ f"Batch size {len(prompt)} is larger than allowed {self.max_batch_size}. If dynamic shape is used, then maximum batch size is 4"
1028
+ )
1029
+
1030
+ # Validate image dimensions
1031
+ mask_width, mask_height = mask_image.size
1032
+ if mask_height != self.image_height or mask_width != self.image_width:
1033
+ raise ValueError(
1034
+ f"Input image height and width {self.image_height} and {self.image_width} are not equal to "
1035
+ f"the respective dimensions of the mask image {mask_height} and {mask_width}"
1036
+ )
1037
+
1038
+ # load resources
1039
+ self.__loadResources(self.image_height, self.image_width, batch_size)
1040
+
1041
+ with torch.inference_mode(), torch.autocast("cuda"), trt.Runtime(TRT_LOGGER):
1042
+ # Spatial dimensions of latent tensor
1043
+ latent_height = self.image_height // 8
1044
+ latent_width = self.image_width // 8
1045
+
1046
+ # Pre-process input images
1047
+ mask, masked_image, init_image = self.__preprocess_images(
1048
+ batch_size,
1049
+ prepare_mask_and_masked_image(
1050
+ image,
1051
+ mask_image,
1052
+ self.image_height,
1053
+ self.image_width,
1054
+ return_image=True,
1055
+ ),
1056
+ )
1057
+
1058
+ mask = torch.nn.functional.interpolate(mask, size=(latent_height, latent_width))
1059
+ mask = torch.cat([mask] * 2)
1060
+
1061
+ # Initialize timesteps
1062
+ timesteps, t_start = self.__initialize_timesteps(self.denoising_steps, strength)
1063
+
1064
+ # at which timestep to set the initial noise (n.b. 50% if strength is 0.5)
1065
+ latent_timestep = timesteps[:1].repeat(batch_size)
1066
+ # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise
1067
+ is_strength_max = strength == 1.0
1068
+
1069
+ # Pre-initialize latents
1070
+ num_channels_latents = self.vae.config.latent_channels
1071
+ latents_outputs = self.prepare_latents(
1072
+ batch_size,
1073
+ num_channels_latents,
1074
+ self.image_height,
1075
+ self.image_width,
1076
+ torch.float32,
1077
+ self.torch_device,
1078
+ generator,
1079
+ image=init_image,
1080
+ timestep=latent_timestep,
1081
+ is_strength_max=is_strength_max,
1082
+ )
1083
+
1084
+ latents = latents_outputs[0]
1085
+
1086
+ # VAE encode masked image
1087
+ masked_latents = self.__encode_image(masked_image)
1088
+ masked_latents = torch.cat([masked_latents] * 2)
1089
+
1090
+ # CLIP text encoder
1091
+ text_embeddings = self.__encode_prompt(prompt, negative_prompt)
1092
+
1093
+ # UNet denoiser
1094
+ latents = self.__denoise_latent(
1095
+ latents,
1096
+ text_embeddings,
1097
+ timesteps=timesteps,
1098
+ step_offset=t_start,
1099
+ mask=mask,
1100
+ masked_image_latents=masked_latents,
1101
+ )
1102
+
1103
+ # VAE decode latent
1104
+ images = self.__decode_latent(latents)
1105
+
1106
+ images = self.numpy_to_pil(images)
1107
+ return StableDiffusionPipelineOutput(images=images, nsfw_content_detected=None)
v0.22.0/stable_diffusion_tensorrt_txt2img.py ADDED
@@ -0,0 +1,928 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright 2023 The HuggingFace Inc. team.
3
+ # SPDX-FileCopyrightText: Copyright (c) 1993-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
4
+ # SPDX-License-Identifier: Apache-2.0
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ import gc
19
+ import os
20
+ from collections import OrderedDict
21
+ from copy import copy
22
+ from typing import List, Optional, Union
23
+
24
+ import numpy as np
25
+ import onnx
26
+ import onnx_graphsurgeon as gs
27
+ import tensorrt as trt
28
+ import torch
29
+ from huggingface_hub import snapshot_download
30
+ from onnx import shape_inference
31
+ from polygraphy import cuda
32
+ from polygraphy.backend.common import bytes_from_path
33
+ from polygraphy.backend.onnx.loader import fold_constants
34
+ from polygraphy.backend.trt import (
35
+ CreateConfig,
36
+ Profile,
37
+ engine_from_bytes,
38
+ engine_from_network,
39
+ network_from_onnx_path,
40
+ save_engine,
41
+ )
42
+ from polygraphy.backend.trt import util as trt_util
43
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
44
+
45
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
46
+ from diffusers.pipelines.stable_diffusion import (
47
+ StableDiffusionPipeline,
48
+ StableDiffusionPipelineOutput,
49
+ StableDiffusionSafetyChecker,
50
+ )
51
+ from diffusers.schedulers import DDIMScheduler
52
+ from diffusers.utils import DIFFUSERS_CACHE, logging
53
+
54
+
55
+ """
56
+ Installation instructions
57
+ python3 -m pip install --upgrade transformers diffusers>=0.16.0
58
+ python3 -m pip install --upgrade tensorrt>=8.6.1
59
+ python3 -m pip install --upgrade polygraphy>=0.47.0 onnx-graphsurgeon --extra-index-url https://pypi.ngc.nvidia.com
60
+ python3 -m pip install onnxruntime
61
+ """
62
+
63
+ TRT_LOGGER = trt.Logger(trt.Logger.ERROR)
64
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
65
+
66
+ # Map of numpy dtype -> torch dtype
67
+ numpy_to_torch_dtype_dict = {
68
+ np.uint8: torch.uint8,
69
+ np.int8: torch.int8,
70
+ np.int16: torch.int16,
71
+ np.int32: torch.int32,
72
+ np.int64: torch.int64,
73
+ np.float16: torch.float16,
74
+ np.float32: torch.float32,
75
+ np.float64: torch.float64,
76
+ np.complex64: torch.complex64,
77
+ np.complex128: torch.complex128,
78
+ }
79
+ if np.version.full_version >= "1.24.0":
80
+ numpy_to_torch_dtype_dict[np.bool_] = torch.bool
81
+ else:
82
+ numpy_to_torch_dtype_dict[np.bool] = torch.bool
83
+
84
+ # Map of torch dtype -> numpy dtype
85
+ torch_to_numpy_dtype_dict = {value: key for (key, value) in numpy_to_torch_dtype_dict.items()}
86
+
87
+
88
+ def device_view(t):
89
+ return cuda.DeviceView(ptr=t.data_ptr(), shape=t.shape, dtype=torch_to_numpy_dtype_dict[t.dtype])
90
+
91
+
92
+ class Engine:
93
+ def __init__(self, engine_path):
94
+ self.engine_path = engine_path
95
+ self.engine = None
96
+ self.context = None
97
+ self.buffers = OrderedDict()
98
+ self.tensors = OrderedDict()
99
+
100
+ def __del__(self):
101
+ [buf.free() for buf in self.buffers.values() if isinstance(buf, cuda.DeviceArray)]
102
+ del self.engine
103
+ del self.context
104
+ del self.buffers
105
+ del self.tensors
106
+
107
+ def build(
108
+ self,
109
+ onnx_path,
110
+ fp16,
111
+ input_profile=None,
112
+ enable_preview=False,
113
+ enable_all_tactics=False,
114
+ timing_cache=None,
115
+ workspace_size=0,
116
+ ):
117
+ logger.warning(f"Building TensorRT engine for {onnx_path}: {self.engine_path}")
118
+ p = Profile()
119
+ if input_profile:
120
+ for name, dims in input_profile.items():
121
+ assert len(dims) == 3
122
+ p.add(name, min=dims[0], opt=dims[1], max=dims[2])
123
+
124
+ config_kwargs = {}
125
+
126
+ config_kwargs["preview_features"] = [trt.PreviewFeature.DISABLE_EXTERNAL_TACTIC_SOURCES_FOR_CORE_0805]
127
+ if enable_preview:
128
+ # Faster dynamic shapes made optional since it increases engine build time.
129
+ config_kwargs["preview_features"].append(trt.PreviewFeature.FASTER_DYNAMIC_SHAPES_0805)
130
+ if workspace_size > 0:
131
+ config_kwargs["memory_pool_limits"] = {trt.MemoryPoolType.WORKSPACE: workspace_size}
132
+ if not enable_all_tactics:
133
+ config_kwargs["tactic_sources"] = []
134
+
135
+ engine = engine_from_network(
136
+ network_from_onnx_path(onnx_path, flags=[trt.OnnxParserFlag.NATIVE_INSTANCENORM]),
137
+ config=CreateConfig(fp16=fp16, profiles=[p], load_timing_cache=timing_cache, **config_kwargs),
138
+ save_timing_cache=timing_cache,
139
+ )
140
+ save_engine(engine, path=self.engine_path)
141
+
142
+ def load(self):
143
+ logger.warning(f"Loading TensorRT engine: {self.engine_path}")
144
+ self.engine = engine_from_bytes(bytes_from_path(self.engine_path))
145
+
146
+ def activate(self):
147
+ self.context = self.engine.create_execution_context()
148
+
149
+ def allocate_buffers(self, shape_dict=None, device="cuda"):
150
+ for idx in range(trt_util.get_bindings_per_profile(self.engine)):
151
+ binding = self.engine[idx]
152
+ if shape_dict and binding in shape_dict:
153
+ shape = shape_dict[binding]
154
+ else:
155
+ shape = self.engine.get_binding_shape(binding)
156
+ dtype = trt.nptype(self.engine.get_binding_dtype(binding))
157
+ if self.engine.binding_is_input(binding):
158
+ self.context.set_binding_shape(idx, shape)
159
+ tensor = torch.empty(tuple(shape), dtype=numpy_to_torch_dtype_dict[dtype]).to(device=device)
160
+ self.tensors[binding] = tensor
161
+ self.buffers[binding] = cuda.DeviceView(ptr=tensor.data_ptr(), shape=shape, dtype=dtype)
162
+
163
+ def infer(self, feed_dict, stream):
164
+ start_binding, end_binding = trt_util.get_active_profile_bindings(self.context)
165
+ # shallow copy of ordered dict
166
+ device_buffers = copy(self.buffers)
167
+ for name, buf in feed_dict.items():
168
+ assert isinstance(buf, cuda.DeviceView)
169
+ device_buffers[name] = buf
170
+ bindings = [0] * start_binding + [buf.ptr for buf in device_buffers.values()]
171
+ noerror = self.context.execute_async_v2(bindings=bindings, stream_handle=stream.ptr)
172
+ if not noerror:
173
+ raise ValueError("ERROR: inference failed.")
174
+
175
+ return self.tensors
176
+
177
+
178
+ class Optimizer:
179
+ def __init__(self, onnx_graph):
180
+ self.graph = gs.import_onnx(onnx_graph)
181
+
182
+ def cleanup(self, return_onnx=False):
183
+ self.graph.cleanup().toposort()
184
+ if return_onnx:
185
+ return gs.export_onnx(self.graph)
186
+
187
+ def select_outputs(self, keep, names=None):
188
+ self.graph.outputs = [self.graph.outputs[o] for o in keep]
189
+ if names:
190
+ for i, name in enumerate(names):
191
+ self.graph.outputs[i].name = name
192
+
193
+ def fold_constants(self, return_onnx=False):
194
+ onnx_graph = fold_constants(gs.export_onnx(self.graph), allow_onnxruntime_shape_inference=True)
195
+ self.graph = gs.import_onnx(onnx_graph)
196
+ if return_onnx:
197
+ return onnx_graph
198
+
199
+ def infer_shapes(self, return_onnx=False):
200
+ onnx_graph = gs.export_onnx(self.graph)
201
+ if onnx_graph.ByteSize() > 2147483648:
202
+ raise TypeError("ERROR: model size exceeds supported 2GB limit")
203
+ else:
204
+ onnx_graph = shape_inference.infer_shapes(onnx_graph)
205
+
206
+ self.graph = gs.import_onnx(onnx_graph)
207
+ if return_onnx:
208
+ return onnx_graph
209
+
210
+
211
+ class BaseModel:
212
+ def __init__(self, model, fp16=False, device="cuda", max_batch_size=16, embedding_dim=768, text_maxlen=77):
213
+ self.model = model
214
+ self.name = "SD Model"
215
+ self.fp16 = fp16
216
+ self.device = device
217
+
218
+ self.min_batch = 1
219
+ self.max_batch = max_batch_size
220
+ self.min_image_shape = 256 # min image resolution: 256x256
221
+ self.max_image_shape = 1024 # max image resolution: 1024x1024
222
+ self.min_latent_shape = self.min_image_shape // 8
223
+ self.max_latent_shape = self.max_image_shape // 8
224
+
225
+ self.embedding_dim = embedding_dim
226
+ self.text_maxlen = text_maxlen
227
+
228
+ def get_model(self):
229
+ return self.model
230
+
231
+ def get_input_names(self):
232
+ pass
233
+
234
+ def get_output_names(self):
235
+ pass
236
+
237
+ def get_dynamic_axes(self):
238
+ return None
239
+
240
+ def get_sample_input(self, batch_size, image_height, image_width):
241
+ pass
242
+
243
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
244
+ return None
245
+
246
+ def get_shape_dict(self, batch_size, image_height, image_width):
247
+ return None
248
+
249
+ def optimize(self, onnx_graph):
250
+ opt = Optimizer(onnx_graph)
251
+ opt.cleanup()
252
+ opt.fold_constants()
253
+ opt.infer_shapes()
254
+ onnx_opt_graph = opt.cleanup(return_onnx=True)
255
+ return onnx_opt_graph
256
+
257
+ def check_dims(self, batch_size, image_height, image_width):
258
+ assert batch_size >= self.min_batch and batch_size <= self.max_batch
259
+ assert image_height % 8 == 0 or image_width % 8 == 0
260
+ latent_height = image_height // 8
261
+ latent_width = image_width // 8
262
+ assert latent_height >= self.min_latent_shape and latent_height <= self.max_latent_shape
263
+ assert latent_width >= self.min_latent_shape and latent_width <= self.max_latent_shape
264
+ return (latent_height, latent_width)
265
+
266
+ def get_minmax_dims(self, batch_size, image_height, image_width, static_batch, static_shape):
267
+ min_batch = batch_size if static_batch else self.min_batch
268
+ max_batch = batch_size if static_batch else self.max_batch
269
+ latent_height = image_height // 8
270
+ latent_width = image_width // 8
271
+ min_image_height = image_height if static_shape else self.min_image_shape
272
+ max_image_height = image_height if static_shape else self.max_image_shape
273
+ min_image_width = image_width if static_shape else self.min_image_shape
274
+ max_image_width = image_width if static_shape else self.max_image_shape
275
+ min_latent_height = latent_height if static_shape else self.min_latent_shape
276
+ max_latent_height = latent_height if static_shape else self.max_latent_shape
277
+ min_latent_width = latent_width if static_shape else self.min_latent_shape
278
+ max_latent_width = latent_width if static_shape else self.max_latent_shape
279
+ return (
280
+ min_batch,
281
+ max_batch,
282
+ min_image_height,
283
+ max_image_height,
284
+ min_image_width,
285
+ max_image_width,
286
+ min_latent_height,
287
+ max_latent_height,
288
+ min_latent_width,
289
+ max_latent_width,
290
+ )
291
+
292
+
293
+ def getOnnxPath(model_name, onnx_dir, opt=True):
294
+ return os.path.join(onnx_dir, model_name + (".opt" if opt else "") + ".onnx")
295
+
296
+
297
+ def getEnginePath(model_name, engine_dir):
298
+ return os.path.join(engine_dir, model_name + ".plan")
299
+
300
+
301
+ def build_engines(
302
+ models: dict,
303
+ engine_dir,
304
+ onnx_dir,
305
+ onnx_opset,
306
+ opt_image_height,
307
+ opt_image_width,
308
+ opt_batch_size=1,
309
+ force_engine_rebuild=False,
310
+ static_batch=False,
311
+ static_shape=True,
312
+ enable_preview=False,
313
+ enable_all_tactics=False,
314
+ timing_cache=None,
315
+ max_workspace_size=0,
316
+ ):
317
+ built_engines = {}
318
+ if not os.path.isdir(onnx_dir):
319
+ os.makedirs(onnx_dir)
320
+ if not os.path.isdir(engine_dir):
321
+ os.makedirs(engine_dir)
322
+
323
+ # Export models to ONNX
324
+ for model_name, model_obj in models.items():
325
+ engine_path = getEnginePath(model_name, engine_dir)
326
+ if force_engine_rebuild or not os.path.exists(engine_path):
327
+ logger.warning("Building Engines...")
328
+ logger.warning("Engine build can take a while to complete")
329
+ onnx_path = getOnnxPath(model_name, onnx_dir, opt=False)
330
+ onnx_opt_path = getOnnxPath(model_name, onnx_dir)
331
+ if force_engine_rebuild or not os.path.exists(onnx_opt_path):
332
+ if force_engine_rebuild or not os.path.exists(onnx_path):
333
+ logger.warning(f"Exporting model: {onnx_path}")
334
+ model = model_obj.get_model()
335
+ with torch.inference_mode(), torch.autocast("cuda"):
336
+ inputs = model_obj.get_sample_input(opt_batch_size, opt_image_height, opt_image_width)
337
+ torch.onnx.export(
338
+ model,
339
+ inputs,
340
+ onnx_path,
341
+ export_params=True,
342
+ opset_version=onnx_opset,
343
+ do_constant_folding=True,
344
+ input_names=model_obj.get_input_names(),
345
+ output_names=model_obj.get_output_names(),
346
+ dynamic_axes=model_obj.get_dynamic_axes(),
347
+ )
348
+ del model
349
+ torch.cuda.empty_cache()
350
+ gc.collect()
351
+ else:
352
+ logger.warning(f"Found cached model: {onnx_path}")
353
+
354
+ # Optimize onnx
355
+ if force_engine_rebuild or not os.path.exists(onnx_opt_path):
356
+ logger.warning(f"Generating optimizing model: {onnx_opt_path}")
357
+ onnx_opt_graph = model_obj.optimize(onnx.load(onnx_path))
358
+ onnx.save(onnx_opt_graph, onnx_opt_path)
359
+ else:
360
+ logger.warning(f"Found cached optimized model: {onnx_opt_path} ")
361
+
362
+ # Build TensorRT engines
363
+ for model_name, model_obj in models.items():
364
+ engine_path = getEnginePath(model_name, engine_dir)
365
+ engine = Engine(engine_path)
366
+ onnx_path = getOnnxPath(model_name, onnx_dir, opt=False)
367
+ onnx_opt_path = getOnnxPath(model_name, onnx_dir)
368
+
369
+ if force_engine_rebuild or not os.path.exists(engine.engine_path):
370
+ engine.build(
371
+ onnx_opt_path,
372
+ fp16=True,
373
+ input_profile=model_obj.get_input_profile(
374
+ opt_batch_size,
375
+ opt_image_height,
376
+ opt_image_width,
377
+ static_batch=static_batch,
378
+ static_shape=static_shape,
379
+ ),
380
+ enable_preview=enable_preview,
381
+ timing_cache=timing_cache,
382
+ workspace_size=max_workspace_size,
383
+ )
384
+ built_engines[model_name] = engine
385
+
386
+ # Load and activate TensorRT engines
387
+ for model_name, model_obj in models.items():
388
+ engine = built_engines[model_name]
389
+ engine.load()
390
+ engine.activate()
391
+
392
+ return built_engines
393
+
394
+
395
+ def runEngine(engine, feed_dict, stream):
396
+ return engine.infer(feed_dict, stream)
397
+
398
+
399
+ class CLIP(BaseModel):
400
+ def __init__(self, model, device, max_batch_size, embedding_dim):
401
+ super(CLIP, self).__init__(
402
+ model=model, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim
403
+ )
404
+ self.name = "CLIP"
405
+
406
+ def get_input_names(self):
407
+ return ["input_ids"]
408
+
409
+ def get_output_names(self):
410
+ return ["text_embeddings", "pooler_output"]
411
+
412
+ def get_dynamic_axes(self):
413
+ return {"input_ids": {0: "B"}, "text_embeddings": {0: "B"}}
414
+
415
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
416
+ self.check_dims(batch_size, image_height, image_width)
417
+ min_batch, max_batch, _, _, _, _, _, _, _, _ = self.get_minmax_dims(
418
+ batch_size, image_height, image_width, static_batch, static_shape
419
+ )
420
+ return {
421
+ "input_ids": [(min_batch, self.text_maxlen), (batch_size, self.text_maxlen), (max_batch, self.text_maxlen)]
422
+ }
423
+
424
+ def get_shape_dict(self, batch_size, image_height, image_width):
425
+ self.check_dims(batch_size, image_height, image_width)
426
+ return {
427
+ "input_ids": (batch_size, self.text_maxlen),
428
+ "text_embeddings": (batch_size, self.text_maxlen, self.embedding_dim),
429
+ }
430
+
431
+ def get_sample_input(self, batch_size, image_height, image_width):
432
+ self.check_dims(batch_size, image_height, image_width)
433
+ return torch.zeros(batch_size, self.text_maxlen, dtype=torch.int32, device=self.device)
434
+
435
+ def optimize(self, onnx_graph):
436
+ opt = Optimizer(onnx_graph)
437
+ opt.select_outputs([0]) # delete graph output#1
438
+ opt.cleanup()
439
+ opt.fold_constants()
440
+ opt.infer_shapes()
441
+ opt.select_outputs([0], names=["text_embeddings"]) # rename network output
442
+ opt_onnx_graph = opt.cleanup(return_onnx=True)
443
+ return opt_onnx_graph
444
+
445
+
446
+ def make_CLIP(model, device, max_batch_size, embedding_dim, inpaint=False):
447
+ return CLIP(model, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim)
448
+
449
+
450
+ class UNet(BaseModel):
451
+ def __init__(
452
+ self, model, fp16=False, device="cuda", max_batch_size=16, embedding_dim=768, text_maxlen=77, unet_dim=4
453
+ ):
454
+ super(UNet, self).__init__(
455
+ model=model,
456
+ fp16=fp16,
457
+ device=device,
458
+ max_batch_size=max_batch_size,
459
+ embedding_dim=embedding_dim,
460
+ text_maxlen=text_maxlen,
461
+ )
462
+ self.unet_dim = unet_dim
463
+ self.name = "UNet"
464
+
465
+ def get_input_names(self):
466
+ return ["sample", "timestep", "encoder_hidden_states"]
467
+
468
+ def get_output_names(self):
469
+ return ["latent"]
470
+
471
+ def get_dynamic_axes(self):
472
+ return {
473
+ "sample": {0: "2B", 2: "H", 3: "W"},
474
+ "encoder_hidden_states": {0: "2B"},
475
+ "latent": {0: "2B", 2: "H", 3: "W"},
476
+ }
477
+
478
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
479
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
480
+ (
481
+ min_batch,
482
+ max_batch,
483
+ _,
484
+ _,
485
+ _,
486
+ _,
487
+ min_latent_height,
488
+ max_latent_height,
489
+ min_latent_width,
490
+ max_latent_width,
491
+ ) = self.get_minmax_dims(batch_size, image_height, image_width, static_batch, static_shape)
492
+ return {
493
+ "sample": [
494
+ (2 * min_batch, self.unet_dim, min_latent_height, min_latent_width),
495
+ (2 * batch_size, self.unet_dim, latent_height, latent_width),
496
+ (2 * max_batch, self.unet_dim, max_latent_height, max_latent_width),
497
+ ],
498
+ "encoder_hidden_states": [
499
+ (2 * min_batch, self.text_maxlen, self.embedding_dim),
500
+ (2 * batch_size, self.text_maxlen, self.embedding_dim),
501
+ (2 * max_batch, self.text_maxlen, self.embedding_dim),
502
+ ],
503
+ }
504
+
505
+ def get_shape_dict(self, batch_size, image_height, image_width):
506
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
507
+ return {
508
+ "sample": (2 * batch_size, self.unet_dim, latent_height, latent_width),
509
+ "encoder_hidden_states": (2 * batch_size, self.text_maxlen, self.embedding_dim),
510
+ "latent": (2 * batch_size, 4, latent_height, latent_width),
511
+ }
512
+
513
+ def get_sample_input(self, batch_size, image_height, image_width):
514
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
515
+ dtype = torch.float16 if self.fp16 else torch.float32
516
+ return (
517
+ torch.randn(
518
+ 2 * batch_size, self.unet_dim, latent_height, latent_width, dtype=torch.float32, device=self.device
519
+ ),
520
+ torch.tensor([1.0], dtype=torch.float32, device=self.device),
521
+ torch.randn(2 * batch_size, self.text_maxlen, self.embedding_dim, dtype=dtype, device=self.device),
522
+ )
523
+
524
+
525
+ def make_UNet(model, device, max_batch_size, embedding_dim, inpaint=False):
526
+ return UNet(
527
+ model,
528
+ fp16=True,
529
+ device=device,
530
+ max_batch_size=max_batch_size,
531
+ embedding_dim=embedding_dim,
532
+ unet_dim=(9 if inpaint else 4),
533
+ )
534
+
535
+
536
+ class VAE(BaseModel):
537
+ def __init__(self, model, device, max_batch_size, embedding_dim):
538
+ super(VAE, self).__init__(
539
+ model=model, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim
540
+ )
541
+ self.name = "VAE decoder"
542
+
543
+ def get_input_names(self):
544
+ return ["latent"]
545
+
546
+ def get_output_names(self):
547
+ return ["images"]
548
+
549
+ def get_dynamic_axes(self):
550
+ return {"latent": {0: "B", 2: "H", 3: "W"}, "images": {0: "B", 2: "8H", 3: "8W"}}
551
+
552
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
553
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
554
+ (
555
+ min_batch,
556
+ max_batch,
557
+ _,
558
+ _,
559
+ _,
560
+ _,
561
+ min_latent_height,
562
+ max_latent_height,
563
+ min_latent_width,
564
+ max_latent_width,
565
+ ) = self.get_minmax_dims(batch_size, image_height, image_width, static_batch, static_shape)
566
+ return {
567
+ "latent": [
568
+ (min_batch, 4, min_latent_height, min_latent_width),
569
+ (batch_size, 4, latent_height, latent_width),
570
+ (max_batch, 4, max_latent_height, max_latent_width),
571
+ ]
572
+ }
573
+
574
+ def get_shape_dict(self, batch_size, image_height, image_width):
575
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
576
+ return {
577
+ "latent": (batch_size, 4, latent_height, latent_width),
578
+ "images": (batch_size, 3, image_height, image_width),
579
+ }
580
+
581
+ def get_sample_input(self, batch_size, image_height, image_width):
582
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
583
+ return torch.randn(batch_size, 4, latent_height, latent_width, dtype=torch.float32, device=self.device)
584
+
585
+
586
+ def make_VAE(model, device, max_batch_size, embedding_dim, inpaint=False):
587
+ return VAE(model, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim)
588
+
589
+
590
+ class TensorRTStableDiffusionPipeline(StableDiffusionPipeline):
591
+ r"""
592
+ Pipeline for text-to-image generation using TensorRT accelerated Stable Diffusion.
593
+
594
+ This model inherits from [`StableDiffusionPipeline`]. Check the superclass documentation for the generic methods the
595
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
596
+
597
+ Args:
598
+ vae ([`AutoencoderKL`]):
599
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
600
+ text_encoder ([`CLIPTextModel`]):
601
+ Frozen text-encoder. Stable Diffusion uses the text portion of
602
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
603
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
604
+ tokenizer (`CLIPTokenizer`):
605
+ Tokenizer of class
606
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
607
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
608
+ scheduler ([`SchedulerMixin`]):
609
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
610
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
611
+ safety_checker ([`StableDiffusionSafetyChecker`]):
612
+ Classification module that estimates whether generated images could be considered offensive or harmful.
613
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
614
+ feature_extractor ([`CLIPFeatureExtractor`]):
615
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
616
+ """
617
+
618
+ def __init__(
619
+ self,
620
+ vae: AutoencoderKL,
621
+ text_encoder: CLIPTextModel,
622
+ tokenizer: CLIPTokenizer,
623
+ unet: UNet2DConditionModel,
624
+ scheduler: DDIMScheduler,
625
+ safety_checker: StableDiffusionSafetyChecker,
626
+ feature_extractor: CLIPFeatureExtractor,
627
+ requires_safety_checker: bool = True,
628
+ stages=["clip", "unet", "vae"],
629
+ image_height: int = 768,
630
+ image_width: int = 768,
631
+ max_batch_size: int = 16,
632
+ # ONNX export parameters
633
+ onnx_opset: int = 17,
634
+ onnx_dir: str = "onnx",
635
+ # TensorRT engine build parameters
636
+ engine_dir: str = "engine",
637
+ build_preview_features: bool = True,
638
+ force_engine_rebuild: bool = False,
639
+ timing_cache: str = "timing_cache",
640
+ ):
641
+ super().__init__(
642
+ vae, text_encoder, tokenizer, unet, scheduler, safety_checker, feature_extractor, requires_safety_checker
643
+ )
644
+
645
+ self.vae.forward = self.vae.decode
646
+
647
+ self.stages = stages
648
+ self.image_height, self.image_width = image_height, image_width
649
+ self.inpaint = False
650
+ self.onnx_opset = onnx_opset
651
+ self.onnx_dir = onnx_dir
652
+ self.engine_dir = engine_dir
653
+ self.force_engine_rebuild = force_engine_rebuild
654
+ self.timing_cache = timing_cache
655
+ self.build_static_batch = False
656
+ self.build_dynamic_shape = False
657
+ self.build_preview_features = build_preview_features
658
+
659
+ self.max_batch_size = max_batch_size
660
+ # TODO: Restrict batch size to 4 for larger image dimensions as a WAR for TensorRT limitation.
661
+ if self.build_dynamic_shape or self.image_height > 512 or self.image_width > 512:
662
+ self.max_batch_size = 4
663
+
664
+ self.stream = None # loaded in loadResources()
665
+ self.models = {} # loaded in __loadModels()
666
+ self.engine = {} # loaded in build_engines()
667
+
668
+ def __loadModels(self):
669
+ # Load pipeline models
670
+ self.embedding_dim = self.text_encoder.config.hidden_size
671
+ models_args = {
672
+ "device": self.torch_device,
673
+ "max_batch_size": self.max_batch_size,
674
+ "embedding_dim": self.embedding_dim,
675
+ "inpaint": self.inpaint,
676
+ }
677
+ if "clip" in self.stages:
678
+ self.models["clip"] = make_CLIP(self.text_encoder, **models_args)
679
+ if "unet" in self.stages:
680
+ self.models["unet"] = make_UNet(self.unet, **models_args)
681
+ if "vae" in self.stages:
682
+ self.models["vae"] = make_VAE(self.vae, **models_args)
683
+
684
+ @classmethod
685
+ def set_cached_folder(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], **kwargs):
686
+ cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
687
+ resume_download = kwargs.pop("resume_download", False)
688
+ proxies = kwargs.pop("proxies", None)
689
+ local_files_only = kwargs.pop("local_files_only", False)
690
+ use_auth_token = kwargs.pop("use_auth_token", None)
691
+ revision = kwargs.pop("revision", None)
692
+
693
+ cls.cached_folder = (
694
+ pretrained_model_name_or_path
695
+ if os.path.isdir(pretrained_model_name_or_path)
696
+ else snapshot_download(
697
+ pretrained_model_name_or_path,
698
+ cache_dir=cache_dir,
699
+ resume_download=resume_download,
700
+ proxies=proxies,
701
+ local_files_only=local_files_only,
702
+ use_auth_token=use_auth_token,
703
+ revision=revision,
704
+ )
705
+ )
706
+
707
+ def to(self, torch_device: Optional[Union[str, torch.device]] = None, silence_dtype_warnings: bool = False):
708
+ super().to(torch_device, silence_dtype_warnings=silence_dtype_warnings)
709
+
710
+ self.onnx_dir = os.path.join(self.cached_folder, self.onnx_dir)
711
+ self.engine_dir = os.path.join(self.cached_folder, self.engine_dir)
712
+ self.timing_cache = os.path.join(self.cached_folder, self.timing_cache)
713
+
714
+ # set device
715
+ self.torch_device = self._execution_device
716
+ logger.warning(f"Running inference on device: {self.torch_device}")
717
+
718
+ # load models
719
+ self.__loadModels()
720
+
721
+ # build engines
722
+ self.engine = build_engines(
723
+ self.models,
724
+ self.engine_dir,
725
+ self.onnx_dir,
726
+ self.onnx_opset,
727
+ opt_image_height=self.image_height,
728
+ opt_image_width=self.image_width,
729
+ force_engine_rebuild=self.force_engine_rebuild,
730
+ static_batch=self.build_static_batch,
731
+ static_shape=not self.build_dynamic_shape,
732
+ enable_preview=self.build_preview_features,
733
+ timing_cache=self.timing_cache,
734
+ )
735
+
736
+ return self
737
+
738
+ def __encode_prompt(self, prompt, negative_prompt):
739
+ r"""
740
+ Encodes the prompt into text encoder hidden states.
741
+
742
+ Args:
743
+ prompt (`str` or `List[str]`, *optional*):
744
+ prompt to be encoded
745
+ negative_prompt (`str` or `List[str]`, *optional*):
746
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
747
+ `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
748
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
749
+ """
750
+ # Tokenize prompt
751
+ text_input_ids = (
752
+ self.tokenizer(
753
+ prompt,
754
+ padding="max_length",
755
+ max_length=self.tokenizer.model_max_length,
756
+ truncation=True,
757
+ return_tensors="pt",
758
+ )
759
+ .input_ids.type(torch.int32)
760
+ .to(self.torch_device)
761
+ )
762
+
763
+ text_input_ids_inp = device_view(text_input_ids)
764
+ # NOTE: output tensor for CLIP must be cloned because it will be overwritten when called again for negative prompt
765
+ text_embeddings = runEngine(self.engine["clip"], {"input_ids": text_input_ids_inp}, self.stream)[
766
+ "text_embeddings"
767
+ ].clone()
768
+
769
+ # Tokenize negative prompt
770
+ uncond_input_ids = (
771
+ self.tokenizer(
772
+ negative_prompt,
773
+ padding="max_length",
774
+ max_length=self.tokenizer.model_max_length,
775
+ truncation=True,
776
+ return_tensors="pt",
777
+ )
778
+ .input_ids.type(torch.int32)
779
+ .to(self.torch_device)
780
+ )
781
+ uncond_input_ids_inp = device_view(uncond_input_ids)
782
+ uncond_embeddings = runEngine(self.engine["clip"], {"input_ids": uncond_input_ids_inp}, self.stream)[
783
+ "text_embeddings"
784
+ ]
785
+
786
+ # Concatenate the unconditional and text embeddings into a single batch to avoid doing two forward passes for classifier free guidance
787
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings]).to(dtype=torch.float16)
788
+
789
+ return text_embeddings
790
+
791
+ def __denoise_latent(
792
+ self, latents, text_embeddings, timesteps=None, step_offset=0, mask=None, masked_image_latents=None
793
+ ):
794
+ if not isinstance(timesteps, torch.Tensor):
795
+ timesteps = self.scheduler.timesteps
796
+ for step_index, timestep in enumerate(timesteps):
797
+ # Expand the latents if we are doing classifier free guidance
798
+ latent_model_input = torch.cat([latents] * 2)
799
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, timestep)
800
+ if isinstance(mask, torch.Tensor):
801
+ latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1)
802
+
803
+ # Predict the noise residual
804
+ timestep_float = timestep.float() if timestep.dtype != torch.float32 else timestep
805
+
806
+ sample_inp = device_view(latent_model_input)
807
+ timestep_inp = device_view(timestep_float)
808
+ embeddings_inp = device_view(text_embeddings)
809
+ noise_pred = runEngine(
810
+ self.engine["unet"],
811
+ {"sample": sample_inp, "timestep": timestep_inp, "encoder_hidden_states": embeddings_inp},
812
+ self.stream,
813
+ )["latent"]
814
+
815
+ # Perform guidance
816
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
817
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
818
+
819
+ latents = self.scheduler.step(noise_pred, timestep, latents).prev_sample
820
+
821
+ latents = 1.0 / 0.18215 * latents
822
+ return latents
823
+
824
+ def __decode_latent(self, latents):
825
+ images = runEngine(self.engine["vae"], {"latent": device_view(latents)}, self.stream)["images"]
826
+ images = (images / 2 + 0.5).clamp(0, 1)
827
+ return images.cpu().permute(0, 2, 3, 1).float().numpy()
828
+
829
+ def __loadResources(self, image_height, image_width, batch_size):
830
+ self.stream = cuda.Stream()
831
+
832
+ # Allocate buffers for TensorRT engine bindings
833
+ for model_name, obj in self.models.items():
834
+ self.engine[model_name].allocate_buffers(
835
+ shape_dict=obj.get_shape_dict(batch_size, image_height, image_width), device=self.torch_device
836
+ )
837
+
838
+ @torch.no_grad()
839
+ def __call__(
840
+ self,
841
+ prompt: Union[str, List[str]] = None,
842
+ num_inference_steps: int = 50,
843
+ guidance_scale: float = 7.5,
844
+ negative_prompt: Optional[Union[str, List[str]]] = None,
845
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
846
+ ):
847
+ r"""
848
+ Function invoked when calling the pipeline for generation.
849
+
850
+ Args:
851
+ prompt (`str` or `List[str]`, *optional*):
852
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
853
+ instead.
854
+ num_inference_steps (`int`, *optional*, defaults to 50):
855
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
856
+ expense of slower inference.
857
+ guidance_scale (`float`, *optional*, defaults to 7.5):
858
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
859
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
860
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
861
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
862
+ usually at the expense of lower image quality.
863
+ negative_prompt (`str` or `List[str]`, *optional*):
864
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
865
+ `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
866
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
867
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
868
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
869
+ to make generation deterministic.
870
+
871
+ """
872
+ self.generator = generator
873
+ self.denoising_steps = num_inference_steps
874
+ self.guidance_scale = guidance_scale
875
+
876
+ # Pre-compute latent input scales and linear multistep coefficients
877
+ self.scheduler.set_timesteps(self.denoising_steps, device=self.torch_device)
878
+
879
+ # Define call parameters
880
+ if prompt is not None and isinstance(prompt, str):
881
+ batch_size = 1
882
+ prompt = [prompt]
883
+ elif prompt is not None and isinstance(prompt, list):
884
+ batch_size = len(prompt)
885
+ else:
886
+ raise ValueError(f"Expected prompt to be of type list or str but got {type(prompt)}")
887
+
888
+ if negative_prompt is None:
889
+ negative_prompt = [""] * batch_size
890
+
891
+ if negative_prompt is not None and isinstance(negative_prompt, str):
892
+ negative_prompt = [negative_prompt]
893
+
894
+ assert len(prompt) == len(negative_prompt)
895
+
896
+ if batch_size > self.max_batch_size:
897
+ raise ValueError(
898
+ f"Batch size {len(prompt)} is larger than allowed {self.max_batch_size}. If dynamic shape is used, then maximum batch size is 4"
899
+ )
900
+
901
+ # load resources
902
+ self.__loadResources(self.image_height, self.image_width, batch_size)
903
+
904
+ with torch.inference_mode(), torch.autocast("cuda"), trt.Runtime(TRT_LOGGER):
905
+ # CLIP text encoder
906
+ text_embeddings = self.__encode_prompt(prompt, negative_prompt)
907
+
908
+ # Pre-initialize latents
909
+ num_channels_latents = self.unet.in_channels
910
+ latents = self.prepare_latents(
911
+ batch_size,
912
+ num_channels_latents,
913
+ self.image_height,
914
+ self.image_width,
915
+ torch.float32,
916
+ self.torch_device,
917
+ generator,
918
+ )
919
+
920
+ # UNet denoiser
921
+ latents = self.__denoise_latent(latents, text_embeddings)
922
+
923
+ # VAE decode latent
924
+ images = self.__decode_latent(latents)
925
+
926
+ images, has_nsfw_concept = self.run_safety_checker(images, self.torch_device, text_embeddings.dtype)
927
+ images = self.numpy_to_pil(images)
928
+ return StableDiffusionPipelineOutput(images=images, nsfw_content_detected=has_nsfw_concept)
v0.22.0/stable_diffusion_xl_reference.py ADDED
@@ -0,0 +1,807 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Based on stable_diffusion_reference.py
2
+
3
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
4
+
5
+ import numpy as np
6
+ import PIL.Image
7
+ import torch
8
+
9
+ from diffusers import StableDiffusionXLPipeline
10
+ from diffusers.models.attention import BasicTransformerBlock
11
+ from diffusers.models.unet_2d_blocks import (
12
+ CrossAttnDownBlock2D,
13
+ CrossAttnUpBlock2D,
14
+ DownBlock2D,
15
+ UpBlock2D,
16
+ )
17
+ from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineOutput
18
+ from diffusers.utils import PIL_INTERPOLATION, logging
19
+ from diffusers.utils.torch_utils import randn_tensor
20
+
21
+
22
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
23
+
24
+ EXAMPLE_DOC_STRING = """
25
+ Examples:
26
+ ```py
27
+ >>> import torch
28
+ >>> from diffusers import UniPCMultistepScheduler
29
+ >>> from diffusers.utils import load_image
30
+
31
+ >>> input_image = load_image("https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png")
32
+
33
+ >>> pipe = StableDiffusionXLReferencePipeline.from_pretrained(
34
+ "stabilityai/stable-diffusion-xl-base-1.0",
35
+ torch_dtype=torch.float16,
36
+ use_safetensors=True,
37
+ variant="fp16").to('cuda:0')
38
+
39
+ >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
40
+ >>> result_img = pipe(ref_image=input_image,
41
+ prompt="1girl",
42
+ num_inference_steps=20,
43
+ reference_attn=True,
44
+ reference_adain=True).images[0]
45
+
46
+ >>> result_img.show()
47
+ ```
48
+ """
49
+
50
+
51
+ def torch_dfs(model: torch.nn.Module):
52
+ result = [model]
53
+ for child in model.children():
54
+ result += torch_dfs(child)
55
+ return result
56
+
57
+
58
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
59
+
60
+
61
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
62
+ """
63
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
64
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
65
+ """
66
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
67
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
68
+ # rescale the results from guidance (fixes overexposure)
69
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
70
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
71
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
72
+ return noise_cfg
73
+
74
+
75
+ class StableDiffusionXLReferencePipeline(StableDiffusionXLPipeline):
76
+ def _default_height_width(self, height, width, image):
77
+ # NOTE: It is possible that a list of images have different
78
+ # dimensions for each image, so just checking the first image
79
+ # is not _exactly_ correct, but it is simple.
80
+ while isinstance(image, list):
81
+ image = image[0]
82
+
83
+ if height is None:
84
+ if isinstance(image, PIL.Image.Image):
85
+ height = image.height
86
+ elif isinstance(image, torch.Tensor):
87
+ height = image.shape[2]
88
+
89
+ height = (height // 8) * 8 # round down to nearest multiple of 8
90
+
91
+ if width is None:
92
+ if isinstance(image, PIL.Image.Image):
93
+ width = image.width
94
+ elif isinstance(image, torch.Tensor):
95
+ width = image.shape[3]
96
+
97
+ width = (width // 8) * 8
98
+
99
+ return height, width
100
+
101
+ def prepare_image(
102
+ self,
103
+ image,
104
+ width,
105
+ height,
106
+ batch_size,
107
+ num_images_per_prompt,
108
+ device,
109
+ dtype,
110
+ do_classifier_free_guidance=False,
111
+ guess_mode=False,
112
+ ):
113
+ if not isinstance(image, torch.Tensor):
114
+ if isinstance(image, PIL.Image.Image):
115
+ image = [image]
116
+
117
+ if isinstance(image[0], PIL.Image.Image):
118
+ images = []
119
+
120
+ for image_ in image:
121
+ image_ = image_.convert("RGB")
122
+ image_ = image_.resize((width, height), resample=PIL_INTERPOLATION["lanczos"])
123
+ image_ = np.array(image_)
124
+ image_ = image_[None, :]
125
+ images.append(image_)
126
+
127
+ image = images
128
+
129
+ image = np.concatenate(image, axis=0)
130
+ image = np.array(image).astype(np.float32) / 255.0
131
+ image = (image - 0.5) / 0.5
132
+ image = image.transpose(0, 3, 1, 2)
133
+ image = torch.from_numpy(image)
134
+
135
+ elif isinstance(image[0], torch.Tensor):
136
+ image = torch.stack(image, dim=0)
137
+
138
+ image_batch_size = image.shape[0]
139
+
140
+ if image_batch_size == 1:
141
+ repeat_by = batch_size
142
+ else:
143
+ repeat_by = num_images_per_prompt
144
+
145
+ image = image.repeat_interleave(repeat_by, dim=0)
146
+
147
+ image = image.to(device=device, dtype=dtype)
148
+
149
+ if do_classifier_free_guidance and not guess_mode:
150
+ image = torch.cat([image] * 2)
151
+
152
+ return image
153
+
154
+ def prepare_ref_latents(self, refimage, batch_size, dtype, device, generator, do_classifier_free_guidance):
155
+ refimage = refimage.to(device=device)
156
+ if self.vae.dtype == torch.float16 and self.vae.config.force_upcast:
157
+ self.upcast_vae()
158
+ refimage = refimage.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
159
+ if refimage.dtype != self.vae.dtype:
160
+ refimage = refimage.to(dtype=self.vae.dtype)
161
+ # encode the mask image into latents space so we can concatenate it to the latents
162
+ if isinstance(generator, list):
163
+ ref_image_latents = [
164
+ self.vae.encode(refimage[i : i + 1]).latent_dist.sample(generator=generator[i])
165
+ for i in range(batch_size)
166
+ ]
167
+ ref_image_latents = torch.cat(ref_image_latents, dim=0)
168
+ else:
169
+ ref_image_latents = self.vae.encode(refimage).latent_dist.sample(generator=generator)
170
+ ref_image_latents = self.vae.config.scaling_factor * ref_image_latents
171
+
172
+ # duplicate mask and ref_image_latents for each generation per prompt, using mps friendly method
173
+ if ref_image_latents.shape[0] < batch_size:
174
+ if not batch_size % ref_image_latents.shape[0] == 0:
175
+ raise ValueError(
176
+ "The passed images and the required batch size don't match. Images are supposed to be duplicated"
177
+ f" to a total batch size of {batch_size}, but {ref_image_latents.shape[0]} images were passed."
178
+ " Make sure the number of images that you pass is divisible by the total requested batch size."
179
+ )
180
+ ref_image_latents = ref_image_latents.repeat(batch_size // ref_image_latents.shape[0], 1, 1, 1)
181
+
182
+ ref_image_latents = torch.cat([ref_image_latents] * 2) if do_classifier_free_guidance else ref_image_latents
183
+
184
+ # aligning device to prevent device errors when concating it with the latent model input
185
+ ref_image_latents = ref_image_latents.to(device=device, dtype=dtype)
186
+ return ref_image_latents
187
+
188
+ @torch.no_grad()
189
+ def __call__(
190
+ self,
191
+ prompt: Union[str, List[str]] = None,
192
+ prompt_2: Optional[Union[str, List[str]]] = None,
193
+ ref_image: Union[torch.FloatTensor, PIL.Image.Image] = None,
194
+ height: Optional[int] = None,
195
+ width: Optional[int] = None,
196
+ num_inference_steps: int = 50,
197
+ denoising_end: Optional[float] = None,
198
+ guidance_scale: float = 5.0,
199
+ negative_prompt: Optional[Union[str, List[str]]] = None,
200
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
201
+ num_images_per_prompt: Optional[int] = 1,
202
+ eta: float = 0.0,
203
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
204
+ latents: Optional[torch.FloatTensor] = None,
205
+ prompt_embeds: Optional[torch.FloatTensor] = None,
206
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
207
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
208
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
209
+ output_type: Optional[str] = "pil",
210
+ return_dict: bool = True,
211
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
212
+ callback_steps: int = 1,
213
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
214
+ guidance_rescale: float = 0.0,
215
+ original_size: Optional[Tuple[int, int]] = None,
216
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
217
+ target_size: Optional[Tuple[int, int]] = None,
218
+ attention_auto_machine_weight: float = 1.0,
219
+ gn_auto_machine_weight: float = 1.0,
220
+ style_fidelity: float = 0.5,
221
+ reference_attn: bool = True,
222
+ reference_adain: bool = True,
223
+ ):
224
+ assert reference_attn or reference_adain, "`reference_attn` or `reference_adain` must be True."
225
+
226
+ # 0. Default height and width to unet
227
+ # height, width = self._default_height_width(height, width, ref_image)
228
+
229
+ height = height or self.default_sample_size * self.vae_scale_factor
230
+ width = width or self.default_sample_size * self.vae_scale_factor
231
+ original_size = original_size or (height, width)
232
+ target_size = target_size or (height, width)
233
+
234
+ # 1. Check inputs. Raise error if not correct
235
+ self.check_inputs(
236
+ prompt,
237
+ prompt_2,
238
+ height,
239
+ width,
240
+ callback_steps,
241
+ negative_prompt,
242
+ negative_prompt_2,
243
+ prompt_embeds,
244
+ negative_prompt_embeds,
245
+ pooled_prompt_embeds,
246
+ negative_pooled_prompt_embeds,
247
+ )
248
+
249
+ # 2. Define call parameters
250
+ if prompt is not None and isinstance(prompt, str):
251
+ batch_size = 1
252
+ elif prompt is not None and isinstance(prompt, list):
253
+ batch_size = len(prompt)
254
+ else:
255
+ batch_size = prompt_embeds.shape[0]
256
+
257
+ device = self._execution_device
258
+
259
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
260
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
261
+ # corresponds to doing no classifier free guidance.
262
+ do_classifier_free_guidance = guidance_scale > 1.0
263
+
264
+ # 3. Encode input prompt
265
+ text_encoder_lora_scale = (
266
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
267
+ )
268
+ (
269
+ prompt_embeds,
270
+ negative_prompt_embeds,
271
+ pooled_prompt_embeds,
272
+ negative_pooled_prompt_embeds,
273
+ ) = self.encode_prompt(
274
+ prompt=prompt,
275
+ prompt_2=prompt_2,
276
+ device=device,
277
+ num_images_per_prompt=num_images_per_prompt,
278
+ do_classifier_free_guidance=do_classifier_free_guidance,
279
+ negative_prompt=negative_prompt,
280
+ negative_prompt_2=negative_prompt_2,
281
+ prompt_embeds=prompt_embeds,
282
+ negative_prompt_embeds=negative_prompt_embeds,
283
+ pooled_prompt_embeds=pooled_prompt_embeds,
284
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
285
+ lora_scale=text_encoder_lora_scale,
286
+ )
287
+ # 4. Preprocess reference image
288
+ ref_image = self.prepare_image(
289
+ image=ref_image,
290
+ width=width,
291
+ height=height,
292
+ batch_size=batch_size * num_images_per_prompt,
293
+ num_images_per_prompt=num_images_per_prompt,
294
+ device=device,
295
+ dtype=prompt_embeds.dtype,
296
+ )
297
+
298
+ # 5. Prepare timesteps
299
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
300
+
301
+ timesteps = self.scheduler.timesteps
302
+
303
+ # 6. Prepare latent variables
304
+ num_channels_latents = self.unet.config.in_channels
305
+ latents = self.prepare_latents(
306
+ batch_size * num_images_per_prompt,
307
+ num_channels_latents,
308
+ height,
309
+ width,
310
+ prompt_embeds.dtype,
311
+ device,
312
+ generator,
313
+ latents,
314
+ )
315
+ # 7. Prepare reference latent variables
316
+ ref_image_latents = self.prepare_ref_latents(
317
+ ref_image,
318
+ batch_size * num_images_per_prompt,
319
+ prompt_embeds.dtype,
320
+ device,
321
+ generator,
322
+ do_classifier_free_guidance,
323
+ )
324
+
325
+ # 8. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
326
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
327
+
328
+ # 9. Modify self attebtion and group norm
329
+ MODE = "write"
330
+ uc_mask = (
331
+ torch.Tensor([1] * batch_size * num_images_per_prompt + [0] * batch_size * num_images_per_prompt)
332
+ .type_as(ref_image_latents)
333
+ .bool()
334
+ )
335
+
336
+ def hacked_basic_transformer_inner_forward(
337
+ self,
338
+ hidden_states: torch.FloatTensor,
339
+ attention_mask: Optional[torch.FloatTensor] = None,
340
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
341
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
342
+ timestep: Optional[torch.LongTensor] = None,
343
+ cross_attention_kwargs: Dict[str, Any] = None,
344
+ class_labels: Optional[torch.LongTensor] = None,
345
+ ):
346
+ if self.use_ada_layer_norm:
347
+ norm_hidden_states = self.norm1(hidden_states, timestep)
348
+ elif self.use_ada_layer_norm_zero:
349
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
350
+ hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
351
+ )
352
+ else:
353
+ norm_hidden_states = self.norm1(hidden_states)
354
+
355
+ # 1. Self-Attention
356
+ cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}
357
+ if self.only_cross_attention:
358
+ attn_output = self.attn1(
359
+ norm_hidden_states,
360
+ encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
361
+ attention_mask=attention_mask,
362
+ **cross_attention_kwargs,
363
+ )
364
+ else:
365
+ if MODE == "write":
366
+ self.bank.append(norm_hidden_states.detach().clone())
367
+ attn_output = self.attn1(
368
+ norm_hidden_states,
369
+ encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
370
+ attention_mask=attention_mask,
371
+ **cross_attention_kwargs,
372
+ )
373
+ if MODE == "read":
374
+ if attention_auto_machine_weight > self.attn_weight:
375
+ attn_output_uc = self.attn1(
376
+ norm_hidden_states,
377
+ encoder_hidden_states=torch.cat([norm_hidden_states] + self.bank, dim=1),
378
+ # attention_mask=attention_mask,
379
+ **cross_attention_kwargs,
380
+ )
381
+ attn_output_c = attn_output_uc.clone()
382
+ if do_classifier_free_guidance and style_fidelity > 0:
383
+ attn_output_c[uc_mask] = self.attn1(
384
+ norm_hidden_states[uc_mask],
385
+ encoder_hidden_states=norm_hidden_states[uc_mask],
386
+ **cross_attention_kwargs,
387
+ )
388
+ attn_output = style_fidelity * attn_output_c + (1.0 - style_fidelity) * attn_output_uc
389
+ self.bank.clear()
390
+ else:
391
+ attn_output = self.attn1(
392
+ norm_hidden_states,
393
+ encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
394
+ attention_mask=attention_mask,
395
+ **cross_attention_kwargs,
396
+ )
397
+ if self.use_ada_layer_norm_zero:
398
+ attn_output = gate_msa.unsqueeze(1) * attn_output
399
+ hidden_states = attn_output + hidden_states
400
+
401
+ if self.attn2 is not None:
402
+ norm_hidden_states = (
403
+ self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)
404
+ )
405
+
406
+ # 2. Cross-Attention
407
+ attn_output = self.attn2(
408
+ norm_hidden_states,
409
+ encoder_hidden_states=encoder_hidden_states,
410
+ attention_mask=encoder_attention_mask,
411
+ **cross_attention_kwargs,
412
+ )
413
+ hidden_states = attn_output + hidden_states
414
+
415
+ # 3. Feed-forward
416
+ norm_hidden_states = self.norm3(hidden_states)
417
+
418
+ if self.use_ada_layer_norm_zero:
419
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
420
+
421
+ ff_output = self.ff(norm_hidden_states)
422
+
423
+ if self.use_ada_layer_norm_zero:
424
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
425
+
426
+ hidden_states = ff_output + hidden_states
427
+
428
+ return hidden_states
429
+
430
+ def hacked_mid_forward(self, *args, **kwargs):
431
+ eps = 1e-6
432
+ x = self.original_forward(*args, **kwargs)
433
+ if MODE == "write":
434
+ if gn_auto_machine_weight >= self.gn_weight:
435
+ var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)
436
+ self.mean_bank.append(mean)
437
+ self.var_bank.append(var)
438
+ if MODE == "read":
439
+ if len(self.mean_bank) > 0 and len(self.var_bank) > 0:
440
+ var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)
441
+ std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5
442
+ mean_acc = sum(self.mean_bank) / float(len(self.mean_bank))
443
+ var_acc = sum(self.var_bank) / float(len(self.var_bank))
444
+ std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5
445
+ x_uc = (((x - mean) / std) * std_acc) + mean_acc
446
+ x_c = x_uc.clone()
447
+ if do_classifier_free_guidance and style_fidelity > 0:
448
+ x_c[uc_mask] = x[uc_mask]
449
+ x = style_fidelity * x_c + (1.0 - style_fidelity) * x_uc
450
+ self.mean_bank = []
451
+ self.var_bank = []
452
+ return x
453
+
454
+ def hack_CrossAttnDownBlock2D_forward(
455
+ self,
456
+ hidden_states: torch.FloatTensor,
457
+ temb: Optional[torch.FloatTensor] = None,
458
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
459
+ attention_mask: Optional[torch.FloatTensor] = None,
460
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
461
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
462
+ ):
463
+ eps = 1e-6
464
+
465
+ # TODO(Patrick, William) - attention mask is not used
466
+ output_states = ()
467
+
468
+ for i, (resnet, attn) in enumerate(zip(self.resnets, self.attentions)):
469
+ hidden_states = resnet(hidden_states, temb)
470
+ hidden_states = attn(
471
+ hidden_states,
472
+ encoder_hidden_states=encoder_hidden_states,
473
+ cross_attention_kwargs=cross_attention_kwargs,
474
+ attention_mask=attention_mask,
475
+ encoder_attention_mask=encoder_attention_mask,
476
+ return_dict=False,
477
+ )[0]
478
+ if MODE == "write":
479
+ if gn_auto_machine_weight >= self.gn_weight:
480
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
481
+ self.mean_bank.append([mean])
482
+ self.var_bank.append([var])
483
+ if MODE == "read":
484
+ if len(self.mean_bank) > 0 and len(self.var_bank) > 0:
485
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
486
+ std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5
487
+ mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))
488
+ var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))
489
+ std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5
490
+ hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc
491
+ hidden_states_c = hidden_states_uc.clone()
492
+ if do_classifier_free_guidance and style_fidelity > 0:
493
+ hidden_states_c[uc_mask] = hidden_states[uc_mask]
494
+ hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc
495
+
496
+ output_states = output_states + (hidden_states,)
497
+
498
+ if MODE == "read":
499
+ self.mean_bank = []
500
+ self.var_bank = []
501
+
502
+ if self.downsamplers is not None:
503
+ for downsampler in self.downsamplers:
504
+ hidden_states = downsampler(hidden_states)
505
+
506
+ output_states = output_states + (hidden_states,)
507
+
508
+ return hidden_states, output_states
509
+
510
+ def hacked_DownBlock2D_forward(self, hidden_states, temb=None):
511
+ eps = 1e-6
512
+
513
+ output_states = ()
514
+
515
+ for i, resnet in enumerate(self.resnets):
516
+ hidden_states = resnet(hidden_states, temb)
517
+
518
+ if MODE == "write":
519
+ if gn_auto_machine_weight >= self.gn_weight:
520
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
521
+ self.mean_bank.append([mean])
522
+ self.var_bank.append([var])
523
+ if MODE == "read":
524
+ if len(self.mean_bank) > 0 and len(self.var_bank) > 0:
525
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
526
+ std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5
527
+ mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))
528
+ var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))
529
+ std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5
530
+ hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc
531
+ hidden_states_c = hidden_states_uc.clone()
532
+ if do_classifier_free_guidance and style_fidelity > 0:
533
+ hidden_states_c[uc_mask] = hidden_states[uc_mask]
534
+ hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc
535
+
536
+ output_states = output_states + (hidden_states,)
537
+
538
+ if MODE == "read":
539
+ self.mean_bank = []
540
+ self.var_bank = []
541
+
542
+ if self.downsamplers is not None:
543
+ for downsampler in self.downsamplers:
544
+ hidden_states = downsampler(hidden_states)
545
+
546
+ output_states = output_states + (hidden_states,)
547
+
548
+ return hidden_states, output_states
549
+
550
+ def hacked_CrossAttnUpBlock2D_forward(
551
+ self,
552
+ hidden_states: torch.FloatTensor,
553
+ res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],
554
+ temb: Optional[torch.FloatTensor] = None,
555
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
556
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
557
+ upsample_size: Optional[int] = None,
558
+ attention_mask: Optional[torch.FloatTensor] = None,
559
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
560
+ ):
561
+ eps = 1e-6
562
+ # TODO(Patrick, William) - attention mask is not used
563
+ for i, (resnet, attn) in enumerate(zip(self.resnets, self.attentions)):
564
+ # pop res hidden states
565
+ res_hidden_states = res_hidden_states_tuple[-1]
566
+ res_hidden_states_tuple = res_hidden_states_tuple[:-1]
567
+ hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
568
+ hidden_states = resnet(hidden_states, temb)
569
+ hidden_states = attn(
570
+ hidden_states,
571
+ encoder_hidden_states=encoder_hidden_states,
572
+ cross_attention_kwargs=cross_attention_kwargs,
573
+ attention_mask=attention_mask,
574
+ encoder_attention_mask=encoder_attention_mask,
575
+ return_dict=False,
576
+ )[0]
577
+
578
+ if MODE == "write":
579
+ if gn_auto_machine_weight >= self.gn_weight:
580
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
581
+ self.mean_bank.append([mean])
582
+ self.var_bank.append([var])
583
+ if MODE == "read":
584
+ if len(self.mean_bank) > 0 and len(self.var_bank) > 0:
585
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
586
+ std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5
587
+ mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))
588
+ var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))
589
+ std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5
590
+ hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc
591
+ hidden_states_c = hidden_states_uc.clone()
592
+ if do_classifier_free_guidance and style_fidelity > 0:
593
+ hidden_states_c[uc_mask] = hidden_states[uc_mask]
594
+ hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc
595
+
596
+ if MODE == "read":
597
+ self.mean_bank = []
598
+ self.var_bank = []
599
+
600
+ if self.upsamplers is not None:
601
+ for upsampler in self.upsamplers:
602
+ hidden_states = upsampler(hidden_states, upsample_size)
603
+
604
+ return hidden_states
605
+
606
+ def hacked_UpBlock2D_forward(self, hidden_states, res_hidden_states_tuple, temb=None, upsample_size=None):
607
+ eps = 1e-6
608
+ for i, resnet in enumerate(self.resnets):
609
+ # pop res hidden states
610
+ res_hidden_states = res_hidden_states_tuple[-1]
611
+ res_hidden_states_tuple = res_hidden_states_tuple[:-1]
612
+ hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
613
+ hidden_states = resnet(hidden_states, temb)
614
+
615
+ if MODE == "write":
616
+ if gn_auto_machine_weight >= self.gn_weight:
617
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
618
+ self.mean_bank.append([mean])
619
+ self.var_bank.append([var])
620
+ if MODE == "read":
621
+ if len(self.mean_bank) > 0 and len(self.var_bank) > 0:
622
+ var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)
623
+ std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5
624
+ mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))
625
+ var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))
626
+ std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5
627
+ hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc
628
+ hidden_states_c = hidden_states_uc.clone()
629
+ if do_classifier_free_guidance and style_fidelity > 0:
630
+ hidden_states_c[uc_mask] = hidden_states[uc_mask]
631
+ hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc
632
+
633
+ if MODE == "read":
634
+ self.mean_bank = []
635
+ self.var_bank = []
636
+
637
+ if self.upsamplers is not None:
638
+ for upsampler in self.upsamplers:
639
+ hidden_states = upsampler(hidden_states, upsample_size)
640
+
641
+ return hidden_states
642
+
643
+ if reference_attn:
644
+ attn_modules = [module for module in torch_dfs(self.unet) if isinstance(module, BasicTransformerBlock)]
645
+ attn_modules = sorted(attn_modules, key=lambda x: -x.norm1.normalized_shape[0])
646
+
647
+ for i, module in enumerate(attn_modules):
648
+ module._original_inner_forward = module.forward
649
+ module.forward = hacked_basic_transformer_inner_forward.__get__(module, BasicTransformerBlock)
650
+ module.bank = []
651
+ module.attn_weight = float(i) / float(len(attn_modules))
652
+
653
+ if reference_adain:
654
+ gn_modules = [self.unet.mid_block]
655
+ self.unet.mid_block.gn_weight = 0
656
+
657
+ down_blocks = self.unet.down_blocks
658
+ for w, module in enumerate(down_blocks):
659
+ module.gn_weight = 1.0 - float(w) / float(len(down_blocks))
660
+ gn_modules.append(module)
661
+
662
+ up_blocks = self.unet.up_blocks
663
+ for w, module in enumerate(up_blocks):
664
+ module.gn_weight = float(w) / float(len(up_blocks))
665
+ gn_modules.append(module)
666
+
667
+ for i, module in enumerate(gn_modules):
668
+ if getattr(module, "original_forward", None) is None:
669
+ module.original_forward = module.forward
670
+ if i == 0:
671
+ # mid_block
672
+ module.forward = hacked_mid_forward.__get__(module, torch.nn.Module)
673
+ elif isinstance(module, CrossAttnDownBlock2D):
674
+ module.forward = hack_CrossAttnDownBlock2D_forward.__get__(module, CrossAttnDownBlock2D)
675
+ elif isinstance(module, DownBlock2D):
676
+ module.forward = hacked_DownBlock2D_forward.__get__(module, DownBlock2D)
677
+ elif isinstance(module, CrossAttnUpBlock2D):
678
+ module.forward = hacked_CrossAttnUpBlock2D_forward.__get__(module, CrossAttnUpBlock2D)
679
+ elif isinstance(module, UpBlock2D):
680
+ module.forward = hacked_UpBlock2D_forward.__get__(module, UpBlock2D)
681
+ module.mean_bank = []
682
+ module.var_bank = []
683
+ module.gn_weight *= 2
684
+
685
+ # 10. Prepare added time ids & embeddings
686
+ add_text_embeds = pooled_prompt_embeds
687
+ add_time_ids = self._get_add_time_ids(
688
+ original_size, crops_coords_top_left, target_size, dtype=prompt_embeds.dtype
689
+ )
690
+
691
+ if do_classifier_free_guidance:
692
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
693
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
694
+ add_time_ids = torch.cat([add_time_ids, add_time_ids], dim=0)
695
+
696
+ prompt_embeds = prompt_embeds.to(device)
697
+ add_text_embeds = add_text_embeds.to(device)
698
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
699
+
700
+ # 11. Denoising loop
701
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
702
+
703
+ # 10.1 Apply denoising_end
704
+ if denoising_end is not None and isinstance(denoising_end, float) and denoising_end > 0 and denoising_end < 1:
705
+ discrete_timestep_cutoff = int(
706
+ round(
707
+ self.scheduler.config.num_train_timesteps
708
+ - (denoising_end * self.scheduler.config.num_train_timesteps)
709
+ )
710
+ )
711
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
712
+ timesteps = timesteps[:num_inference_steps]
713
+
714
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
715
+ for i, t in enumerate(timesteps):
716
+ # expand the latents if we are doing classifier free guidance
717
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
718
+
719
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
720
+
721
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
722
+
723
+ # ref only part
724
+ noise = randn_tensor(
725
+ ref_image_latents.shape, generator=generator, device=device, dtype=ref_image_latents.dtype
726
+ )
727
+ ref_xt = self.scheduler.add_noise(
728
+ ref_image_latents,
729
+ noise,
730
+ t.reshape(
731
+ 1,
732
+ ),
733
+ )
734
+ ref_xt = self.scheduler.scale_model_input(ref_xt, t)
735
+
736
+ MODE = "write"
737
+
738
+ self.unet(
739
+ ref_xt,
740
+ t,
741
+ encoder_hidden_states=prompt_embeds,
742
+ cross_attention_kwargs=cross_attention_kwargs,
743
+ added_cond_kwargs=added_cond_kwargs,
744
+ return_dict=False,
745
+ )
746
+
747
+ # predict the noise residual
748
+ MODE = "read"
749
+ noise_pred = self.unet(
750
+ latent_model_input,
751
+ t,
752
+ encoder_hidden_states=prompt_embeds,
753
+ cross_attention_kwargs=cross_attention_kwargs,
754
+ added_cond_kwargs=added_cond_kwargs,
755
+ return_dict=False,
756
+ )[0]
757
+
758
+ # perform guidance
759
+ if do_classifier_free_guidance:
760
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
761
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
762
+
763
+ if do_classifier_free_guidance and guidance_rescale > 0.0:
764
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
765
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
766
+
767
+ # compute the previous noisy sample x_t -> x_t-1
768
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
769
+
770
+ # call the callback, if provided
771
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
772
+ progress_bar.update()
773
+ if callback is not None and i % callback_steps == 0:
774
+ step_idx = i // getattr(self.scheduler, "order", 1)
775
+ callback(step_idx, t, latents)
776
+
777
+ if not output_type == "latent":
778
+ # make sure the VAE is in float32 mode, as it overflows in float16
779
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
780
+
781
+ if needs_upcasting:
782
+ self.upcast_vae()
783
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
784
+
785
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
786
+
787
+ # cast back to fp16 if needed
788
+ if needs_upcasting:
789
+ self.vae.to(dtype=torch.float16)
790
+ else:
791
+ image = latents
792
+ return StableDiffusionXLPipelineOutput(images=image)
793
+
794
+ # apply watermark if available
795
+ if self.watermark is not None:
796
+ image = self.watermark.apply_watermark(image)
797
+
798
+ image = self.image_processor.postprocess(image, output_type=output_type)
799
+
800
+ # Offload last model to CPU
801
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
802
+ self.final_offload_hook.offload()
803
+
804
+ if not return_dict:
805
+ return (image,)
806
+
807
+ return StableDiffusionXLPipelineOutput(images=image)
v0.22.0/stable_unclip.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import types
2
+ from typing import List, Optional, Tuple, Union
3
+
4
+ import torch
5
+ from transformers import CLIPTextModelWithProjection, CLIPTokenizer
6
+ from transformers.models.clip.modeling_clip import CLIPTextModelOutput
7
+
8
+ from diffusers.models import PriorTransformer
9
+ from diffusers.pipelines import DiffusionPipeline, StableDiffusionImageVariationPipeline
10
+ from diffusers.schedulers import UnCLIPScheduler
11
+ from diffusers.utils import logging
12
+ from diffusers.utils.torch_utils import randn_tensor
13
+
14
+
15
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
16
+
17
+
18
+ def _encode_image(self, image, device, num_images_per_prompt, do_classifier_free_guidance):
19
+ image = image.to(device=device)
20
+ image_embeddings = image # take image as image_embeddings
21
+ image_embeddings = image_embeddings.unsqueeze(1)
22
+
23
+ # duplicate image embeddings for each generation per prompt, using mps friendly method
24
+ bs_embed, seq_len, _ = image_embeddings.shape
25
+ image_embeddings = image_embeddings.repeat(1, num_images_per_prompt, 1)
26
+ image_embeddings = image_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
27
+
28
+ if do_classifier_free_guidance:
29
+ uncond_embeddings = torch.zeros_like(image_embeddings)
30
+
31
+ # For classifier free guidance, we need to do two forward passes.
32
+ # Here we concatenate the unconditional and text embeddings into a single batch
33
+ # to avoid doing two forward passes
34
+ image_embeddings = torch.cat([uncond_embeddings, image_embeddings])
35
+
36
+ return image_embeddings
37
+
38
+
39
+ class StableUnCLIPPipeline(DiffusionPipeline):
40
+ def __init__(
41
+ self,
42
+ prior: PriorTransformer,
43
+ tokenizer: CLIPTokenizer,
44
+ text_encoder: CLIPTextModelWithProjection,
45
+ prior_scheduler: UnCLIPScheduler,
46
+ decoder_pipe_kwargs: Optional[dict] = None,
47
+ ):
48
+ super().__init__()
49
+
50
+ decoder_pipe_kwargs = {"image_encoder": None} if decoder_pipe_kwargs is None else decoder_pipe_kwargs
51
+
52
+ decoder_pipe_kwargs["torch_dtype"] = decoder_pipe_kwargs.get("torch_dtype", None) or prior.dtype
53
+
54
+ self.decoder_pipe = StableDiffusionImageVariationPipeline.from_pretrained(
55
+ "lambdalabs/sd-image-variations-diffusers", **decoder_pipe_kwargs
56
+ )
57
+
58
+ # replace `_encode_image` method
59
+ self.decoder_pipe._encode_image = types.MethodType(_encode_image, self.decoder_pipe)
60
+
61
+ self.register_modules(
62
+ prior=prior,
63
+ tokenizer=tokenizer,
64
+ text_encoder=text_encoder,
65
+ prior_scheduler=prior_scheduler,
66
+ )
67
+
68
+ def _encode_prompt(
69
+ self,
70
+ prompt,
71
+ device,
72
+ num_images_per_prompt,
73
+ do_classifier_free_guidance,
74
+ text_model_output: Optional[Union[CLIPTextModelOutput, Tuple]] = None,
75
+ text_attention_mask: Optional[torch.Tensor] = None,
76
+ ):
77
+ if text_model_output is None:
78
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
79
+ # get prompt text embeddings
80
+ text_inputs = self.tokenizer(
81
+ prompt,
82
+ padding="max_length",
83
+ max_length=self.tokenizer.model_max_length,
84
+ return_tensors="pt",
85
+ )
86
+ text_input_ids = text_inputs.input_ids
87
+ text_mask = text_inputs.attention_mask.bool().to(device)
88
+
89
+ if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
90
+ removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :])
91
+ logger.warning(
92
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
93
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
94
+ )
95
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
96
+
97
+ text_encoder_output = self.text_encoder(text_input_ids.to(device))
98
+
99
+ text_embeddings = text_encoder_output.text_embeds
100
+ text_encoder_hidden_states = text_encoder_output.last_hidden_state
101
+
102
+ else:
103
+ batch_size = text_model_output[0].shape[0]
104
+ text_embeddings, text_encoder_hidden_states = text_model_output[0], text_model_output[1]
105
+ text_mask = text_attention_mask
106
+
107
+ text_embeddings = text_embeddings.repeat_interleave(num_images_per_prompt, dim=0)
108
+ text_encoder_hidden_states = text_encoder_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
109
+ text_mask = text_mask.repeat_interleave(num_images_per_prompt, dim=0)
110
+
111
+ if do_classifier_free_guidance:
112
+ uncond_tokens = [""] * batch_size
113
+
114
+ uncond_input = self.tokenizer(
115
+ uncond_tokens,
116
+ padding="max_length",
117
+ max_length=self.tokenizer.model_max_length,
118
+ truncation=True,
119
+ return_tensors="pt",
120
+ )
121
+ uncond_text_mask = uncond_input.attention_mask.bool().to(device)
122
+ uncond_embeddings_text_encoder_output = self.text_encoder(uncond_input.input_ids.to(device))
123
+
124
+ uncond_embeddings = uncond_embeddings_text_encoder_output.text_embeds
125
+ uncond_text_encoder_hidden_states = uncond_embeddings_text_encoder_output.last_hidden_state
126
+
127
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
128
+
129
+ seq_len = uncond_embeddings.shape[1]
130
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt)
131
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len)
132
+
133
+ seq_len = uncond_text_encoder_hidden_states.shape[1]
134
+ uncond_text_encoder_hidden_states = uncond_text_encoder_hidden_states.repeat(1, num_images_per_prompt, 1)
135
+ uncond_text_encoder_hidden_states = uncond_text_encoder_hidden_states.view(
136
+ batch_size * num_images_per_prompt, seq_len, -1
137
+ )
138
+ uncond_text_mask = uncond_text_mask.repeat_interleave(num_images_per_prompt, dim=0)
139
+
140
+ # done duplicates
141
+
142
+ # For classifier free guidance, we need to do two forward passes.
143
+ # Here we concatenate the unconditional and text embeddings into a single batch
144
+ # to avoid doing two forward passes
145
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
146
+ text_encoder_hidden_states = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states])
147
+
148
+ text_mask = torch.cat([uncond_text_mask, text_mask])
149
+
150
+ return text_embeddings, text_encoder_hidden_states, text_mask
151
+
152
+ @property
153
+ def _execution_device(self):
154
+ r"""
155
+ Returns the device on which the pipeline's models will be executed. After calling
156
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
157
+ hooks.
158
+ """
159
+ if self.device != torch.device("meta") or not hasattr(self.prior, "_hf_hook"):
160
+ return self.device
161
+ for module in self.prior.modules():
162
+ if (
163
+ hasattr(module, "_hf_hook")
164
+ and hasattr(module._hf_hook, "execution_device")
165
+ and module._hf_hook.execution_device is not None
166
+ ):
167
+ return torch.device(module._hf_hook.execution_device)
168
+ return self.device
169
+
170
+ def prepare_latents(self, shape, dtype, device, generator, latents, scheduler):
171
+ if latents is None:
172
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
173
+ else:
174
+ if latents.shape != shape:
175
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
176
+ latents = latents.to(device)
177
+
178
+ latents = latents * scheduler.init_noise_sigma
179
+ return latents
180
+
181
+ def to(self, torch_device: Optional[Union[str, torch.device]] = None):
182
+ self.decoder_pipe.to(torch_device)
183
+ super().to(torch_device)
184
+
185
+ @torch.no_grad()
186
+ def __call__(
187
+ self,
188
+ prompt: Optional[Union[str, List[str]]] = None,
189
+ height: Optional[int] = None,
190
+ width: Optional[int] = None,
191
+ num_images_per_prompt: int = 1,
192
+ prior_num_inference_steps: int = 25,
193
+ generator: Optional[torch.Generator] = None,
194
+ prior_latents: Optional[torch.FloatTensor] = None,
195
+ text_model_output: Optional[Union[CLIPTextModelOutput, Tuple]] = None,
196
+ text_attention_mask: Optional[torch.Tensor] = None,
197
+ prior_guidance_scale: float = 4.0,
198
+ decoder_guidance_scale: float = 8.0,
199
+ decoder_num_inference_steps: int = 50,
200
+ decoder_num_images_per_prompt: Optional[int] = 1,
201
+ decoder_eta: float = 0.0,
202
+ output_type: Optional[str] = "pil",
203
+ return_dict: bool = True,
204
+ ):
205
+ if prompt is not None:
206
+ if isinstance(prompt, str):
207
+ batch_size = 1
208
+ elif isinstance(prompt, list):
209
+ batch_size = len(prompt)
210
+ else:
211
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
212
+ else:
213
+ batch_size = text_model_output[0].shape[0]
214
+
215
+ device = self._execution_device
216
+
217
+ batch_size = batch_size * num_images_per_prompt
218
+
219
+ do_classifier_free_guidance = prior_guidance_scale > 1.0 or decoder_guidance_scale > 1.0
220
+
221
+ text_embeddings, text_encoder_hidden_states, text_mask = self._encode_prompt(
222
+ prompt, device, num_images_per_prompt, do_classifier_free_guidance, text_model_output, text_attention_mask
223
+ )
224
+
225
+ # prior
226
+
227
+ self.prior_scheduler.set_timesteps(prior_num_inference_steps, device=device)
228
+ prior_timesteps_tensor = self.prior_scheduler.timesteps
229
+
230
+ embedding_dim = self.prior.config.embedding_dim
231
+
232
+ prior_latents = self.prepare_latents(
233
+ (batch_size, embedding_dim),
234
+ text_embeddings.dtype,
235
+ device,
236
+ generator,
237
+ prior_latents,
238
+ self.prior_scheduler,
239
+ )
240
+
241
+ for i, t in enumerate(self.progress_bar(prior_timesteps_tensor)):
242
+ # expand the latents if we are doing classifier free guidance
243
+ latent_model_input = torch.cat([prior_latents] * 2) if do_classifier_free_guidance else prior_latents
244
+
245
+ predicted_image_embedding = self.prior(
246
+ latent_model_input,
247
+ timestep=t,
248
+ proj_embedding=text_embeddings,
249
+ encoder_hidden_states=text_encoder_hidden_states,
250
+ attention_mask=text_mask,
251
+ ).predicted_image_embedding
252
+
253
+ if do_classifier_free_guidance:
254
+ predicted_image_embedding_uncond, predicted_image_embedding_text = predicted_image_embedding.chunk(2)
255
+ predicted_image_embedding = predicted_image_embedding_uncond + prior_guidance_scale * (
256
+ predicted_image_embedding_text - predicted_image_embedding_uncond
257
+ )
258
+
259
+ if i + 1 == prior_timesteps_tensor.shape[0]:
260
+ prev_timestep = None
261
+ else:
262
+ prev_timestep = prior_timesteps_tensor[i + 1]
263
+
264
+ prior_latents = self.prior_scheduler.step(
265
+ predicted_image_embedding,
266
+ timestep=t,
267
+ sample=prior_latents,
268
+ generator=generator,
269
+ prev_timestep=prev_timestep,
270
+ ).prev_sample
271
+
272
+ prior_latents = self.prior.post_process_latents(prior_latents)
273
+
274
+ image_embeddings = prior_latents
275
+
276
+ output = self.decoder_pipe(
277
+ image=image_embeddings,
278
+ height=height,
279
+ width=width,
280
+ num_inference_steps=decoder_num_inference_steps,
281
+ guidance_scale=decoder_guidance_scale,
282
+ generator=generator,
283
+ output_type=output_type,
284
+ return_dict=return_dict,
285
+ num_images_per_prompt=decoder_num_images_per_prompt,
286
+ eta=decoder_eta,
287
+ )
288
+ return output
v0.22.0/text_inpainting.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, List, Optional, Union
2
+
3
+ import PIL.Image
4
+ import torch
5
+ from transformers import (
6
+ CLIPImageProcessor,
7
+ CLIPSegForImageSegmentation,
8
+ CLIPSegProcessor,
9
+ CLIPTextModel,
10
+ CLIPTokenizer,
11
+ )
12
+
13
+ from diffusers import DiffusionPipeline
14
+ from diffusers.configuration_utils import FrozenDict
15
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
16
+ from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline
17
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
18
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
19
+ from diffusers.utils import deprecate, is_accelerate_available, logging
20
+
21
+
22
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
23
+
24
+
25
+ class TextInpainting(DiffusionPipeline):
26
+ r"""
27
+ Pipeline for text based inpainting using Stable Diffusion.
28
+ Uses CLIPSeg to get a mask from the given text, then calls the Inpainting pipeline with the generated mask
29
+
30
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
31
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
32
+
33
+ Args:
34
+ segmentation_model ([`CLIPSegForImageSegmentation`]):
35
+ CLIPSeg Model to generate mask from the given text. Please refer to the [model card]() for details.
36
+ segmentation_processor ([`CLIPSegProcessor`]):
37
+ CLIPSeg processor to get image, text features to translate prompt to English, if necessary. Please refer to the
38
+ [model card](https://huggingface.co/docs/transformers/model_doc/clipseg) for details.
39
+ vae ([`AutoencoderKL`]):
40
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
41
+ text_encoder ([`CLIPTextModel`]):
42
+ Frozen text-encoder. Stable Diffusion uses the text portion of
43
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
44
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
45
+ tokenizer (`CLIPTokenizer`):
46
+ Tokenizer of class
47
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
48
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
49
+ scheduler ([`SchedulerMixin`]):
50
+ A scheduler to be used in combination with `unet` to denoise the encoded image latens. Can be one of
51
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
52
+ safety_checker ([`StableDiffusionSafetyChecker`]):
53
+ Classification module that estimates whether generated images could be considered offensive or harmful.
54
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
55
+ feature_extractor ([`CLIPImageProcessor`]):
56
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
57
+ """
58
+
59
+ def __init__(
60
+ self,
61
+ segmentation_model: CLIPSegForImageSegmentation,
62
+ segmentation_processor: CLIPSegProcessor,
63
+ vae: AutoencoderKL,
64
+ text_encoder: CLIPTextModel,
65
+ tokenizer: CLIPTokenizer,
66
+ unet: UNet2DConditionModel,
67
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
68
+ safety_checker: StableDiffusionSafetyChecker,
69
+ feature_extractor: CLIPImageProcessor,
70
+ ):
71
+ super().__init__()
72
+
73
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
74
+ deprecation_message = (
75
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
76
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
77
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
78
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
79
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
80
+ " file"
81
+ )
82
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, 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, "skip_prk_steps") and scheduler.config.skip_prk_steps is False:
88
+ deprecation_message = (
89
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration"
90
+ " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make"
91
+ " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to"
92
+ " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face"
93
+ " Hub, it would be very nice if you could open a Pull request for the"
94
+ " `scheduler/scheduler_config.json` file"
95
+ )
96
+ deprecate("skip_prk_steps not set", "1.0.0", deprecation_message, standard_warn=False)
97
+ new_config = dict(scheduler.config)
98
+ new_config["skip_prk_steps"] = True
99
+ scheduler._internal_dict = FrozenDict(new_config)
100
+
101
+ if safety_checker is None:
102
+ logger.warning(
103
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
104
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
105
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
106
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
107
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
108
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
109
+ )
110
+
111
+ self.register_modules(
112
+ segmentation_model=segmentation_model,
113
+ segmentation_processor=segmentation_processor,
114
+ vae=vae,
115
+ text_encoder=text_encoder,
116
+ tokenizer=tokenizer,
117
+ unet=unet,
118
+ scheduler=scheduler,
119
+ safety_checker=safety_checker,
120
+ feature_extractor=feature_extractor,
121
+ )
122
+
123
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
124
+ r"""
125
+ Enable sliced attention computation.
126
+
127
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
128
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
129
+
130
+ Args:
131
+ slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
132
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
133
+ a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
134
+ `attention_head_dim` must be a multiple of `slice_size`.
135
+ """
136
+ if slice_size == "auto":
137
+ # half the attention head size is usually a good trade-off between
138
+ # speed and memory
139
+ slice_size = self.unet.config.attention_head_dim // 2
140
+ self.unet.set_attention_slice(slice_size)
141
+
142
+ def disable_attention_slicing(self):
143
+ r"""
144
+ Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
145
+ back to computing attention in one step.
146
+ """
147
+ # set slice_size = `None` to disable `attention slicing`
148
+ self.enable_attention_slicing(None)
149
+
150
+ def enable_sequential_cpu_offload(self):
151
+ r"""
152
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
153
+ text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
154
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
155
+ """
156
+ if is_accelerate_available():
157
+ from accelerate import cpu_offload
158
+ else:
159
+ raise ImportError("Please install accelerate via `pip install accelerate`")
160
+
161
+ device = torch.device("cuda")
162
+
163
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]:
164
+ if cpu_offloaded_model is not None:
165
+ cpu_offload(cpu_offloaded_model, device)
166
+
167
+ @property
168
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
169
+ def _execution_device(self):
170
+ r"""
171
+ Returns the device on which the pipeline's models will be executed. After calling
172
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
173
+ hooks.
174
+ """
175
+ if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"):
176
+ return self.device
177
+ for module in self.unet.modules():
178
+ if (
179
+ hasattr(module, "_hf_hook")
180
+ and hasattr(module._hf_hook, "execution_device")
181
+ and module._hf_hook.execution_device is not None
182
+ ):
183
+ return torch.device(module._hf_hook.execution_device)
184
+ return self.device
185
+
186
+ @torch.no_grad()
187
+ def __call__(
188
+ self,
189
+ prompt: Union[str, List[str]],
190
+ image: Union[torch.FloatTensor, PIL.Image.Image],
191
+ text: str,
192
+ height: int = 512,
193
+ width: int = 512,
194
+ num_inference_steps: int = 50,
195
+ guidance_scale: float = 7.5,
196
+ negative_prompt: Optional[Union[str, List[str]]] = None,
197
+ num_images_per_prompt: Optional[int] = 1,
198
+ eta: float = 0.0,
199
+ generator: Optional[torch.Generator] = None,
200
+ latents: Optional[torch.FloatTensor] = None,
201
+ output_type: Optional[str] = "pil",
202
+ return_dict: bool = True,
203
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
204
+ callback_steps: int = 1,
205
+ **kwargs,
206
+ ):
207
+ r"""
208
+ Function invoked when calling the pipeline for generation.
209
+
210
+ Args:
211
+ prompt (`str` or `List[str]`):
212
+ The prompt or prompts to guide the image generation.
213
+ image (`PIL.Image.Image`):
214
+ `Image`, or tensor representing an image batch which will be inpainted, *i.e.* parts of the image will
215
+ be masked out with `mask_image` and repainted according to `prompt`.
216
+ text (`str``):
217
+ The text to use to generate the mask.
218
+ height (`int`, *optional*, defaults to 512):
219
+ The height in pixels of the generated image.
220
+ width (`int`, *optional*, defaults to 512):
221
+ The width in pixels of the generated image.
222
+ num_inference_steps (`int`, *optional*, defaults to 50):
223
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
224
+ expense of slower inference.
225
+ guidance_scale (`float`, *optional*, defaults to 7.5):
226
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
227
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
228
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
229
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
230
+ usually at the expense of lower image quality.
231
+ negative_prompt (`str` or `List[str]`, *optional*):
232
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
233
+ if `guidance_scale` is less than `1`).
234
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
235
+ The number of images to generate per prompt.
236
+ eta (`float`, *optional*, defaults to 0.0):
237
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
238
+ [`schedulers.DDIMScheduler`], will be ignored for others.
239
+ generator (`torch.Generator`, *optional*):
240
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
241
+ deterministic.
242
+ latents (`torch.FloatTensor`, *optional*):
243
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
244
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
245
+ tensor will ge generated by sampling using the supplied random `generator`.
246
+ output_type (`str`, *optional*, defaults to `"pil"`):
247
+ The output format of the generate image. Choose between
248
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
249
+ return_dict (`bool`, *optional*, defaults to `True`):
250
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
251
+ plain tuple.
252
+ callback (`Callable`, *optional*):
253
+ A function that will be called every `callback_steps` steps during inference. The function will be
254
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
255
+ callback_steps (`int`, *optional*, defaults to 1):
256
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
257
+ called at every step.
258
+
259
+ Returns:
260
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
261
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
262
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
263
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
264
+ (nsfw) content, according to the `safety_checker`.
265
+ """
266
+
267
+ # We use the input text to generate the mask
268
+ inputs = self.segmentation_processor(
269
+ text=[text], images=[image], padding="max_length", return_tensors="pt"
270
+ ).to(self.device)
271
+ outputs = self.segmentation_model(**inputs)
272
+ mask = torch.sigmoid(outputs.logits).cpu().detach().unsqueeze(-1).numpy()
273
+ mask_pil = self.numpy_to_pil(mask)[0].resize(image.size)
274
+
275
+ # Run inpainting pipeline with the generated mask
276
+ inpainting_pipeline = StableDiffusionInpaintPipeline(
277
+ vae=self.vae,
278
+ text_encoder=self.text_encoder,
279
+ tokenizer=self.tokenizer,
280
+ unet=self.unet,
281
+ scheduler=self.scheduler,
282
+ safety_checker=self.safety_checker,
283
+ feature_extractor=self.feature_extractor,
284
+ )
285
+ return inpainting_pipeline(
286
+ prompt=prompt,
287
+ image=image,
288
+ mask_image=mask_pil,
289
+ height=height,
290
+ width=width,
291
+ num_inference_steps=num_inference_steps,
292
+ guidance_scale=guidance_scale,
293
+ negative_prompt=negative_prompt,
294
+ num_images_per_prompt=num_images_per_prompt,
295
+ eta=eta,
296
+ generator=generator,
297
+ latents=latents,
298
+ output_type=output_type,
299
+ return_dict=return_dict,
300
+ callback=callback,
301
+ callback_steps=callback_steps,
302
+ )
v0.22.0/tiled_upscaling.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Peter Willemsen <peter@codebuffet.co>. 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 math
16
+ from typing import Callable, List, Optional, Union
17
+
18
+ import numpy as np
19
+ import PIL.Image
20
+ import torch
21
+ from PIL import Image
22
+ from transformers import CLIPTextModel, CLIPTokenizer
23
+
24
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
25
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline
26
+ from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler
27
+
28
+
29
+ def make_transparency_mask(size, overlap_pixels, remove_borders=[]):
30
+ size_x = size[0] - overlap_pixels * 2
31
+ size_y = size[1] - overlap_pixels * 2
32
+ for letter in ["l", "r"]:
33
+ if letter in remove_borders:
34
+ size_x += overlap_pixels
35
+ for letter in ["t", "b"]:
36
+ if letter in remove_borders:
37
+ size_y += overlap_pixels
38
+ mask = np.ones((size_y, size_x), dtype=np.uint8) * 255
39
+ mask = np.pad(mask, mode="linear_ramp", pad_width=overlap_pixels, end_values=0)
40
+
41
+ if "l" in remove_borders:
42
+ mask = mask[:, overlap_pixels : mask.shape[1]]
43
+ if "r" in remove_borders:
44
+ mask = mask[:, 0 : mask.shape[1] - overlap_pixels]
45
+ if "t" in remove_borders:
46
+ mask = mask[overlap_pixels : mask.shape[0], :]
47
+ if "b" in remove_borders:
48
+ mask = mask[0 : mask.shape[0] - overlap_pixels, :]
49
+ return mask
50
+
51
+
52
+ def clamp(n, smallest, largest):
53
+ return max(smallest, min(n, largest))
54
+
55
+
56
+ def clamp_rect(rect: [int], min: [int], max: [int]):
57
+ return (
58
+ clamp(rect[0], min[0], max[0]),
59
+ clamp(rect[1], min[1], max[1]),
60
+ clamp(rect[2], min[0], max[0]),
61
+ clamp(rect[3], min[1], max[1]),
62
+ )
63
+
64
+
65
+ def add_overlap_rect(rect: [int], overlap: int, image_size: [int]):
66
+ rect = list(rect)
67
+ rect[0] -= overlap
68
+ rect[1] -= overlap
69
+ rect[2] += overlap
70
+ rect[3] += overlap
71
+ rect = clamp_rect(rect, [0, 0], [image_size[0], image_size[1]])
72
+ return rect
73
+
74
+
75
+ def squeeze_tile(tile, original_image, original_slice, slice_x):
76
+ result = Image.new("RGB", (tile.size[0] + original_slice, tile.size[1]))
77
+ result.paste(
78
+ original_image.resize((tile.size[0], tile.size[1]), Image.BICUBIC).crop(
79
+ (slice_x, 0, slice_x + original_slice, tile.size[1])
80
+ ),
81
+ (0, 0),
82
+ )
83
+ result.paste(tile, (original_slice, 0))
84
+ return result
85
+
86
+
87
+ def unsqueeze_tile(tile, original_image_slice):
88
+ crop_rect = (original_image_slice * 4, 0, tile.size[0], tile.size[1])
89
+ tile = tile.crop(crop_rect)
90
+ return tile
91
+
92
+
93
+ def next_divisible(n, d):
94
+ divisor = n % d
95
+ return n - divisor
96
+
97
+
98
+ class StableDiffusionTiledUpscalePipeline(StableDiffusionUpscalePipeline):
99
+ r"""
100
+ Pipeline for tile-based text-guided image super-resolution using Stable Diffusion 2, trading memory for compute
101
+ to create gigantic images.
102
+
103
+ This model inherits from [`StableDiffusionUpscalePipeline`]. Check the superclass documentation for the generic methods the
104
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
105
+
106
+ Args:
107
+ vae ([`AutoencoderKL`]):
108
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
109
+ text_encoder ([`CLIPTextModel`]):
110
+ Frozen text-encoder. Stable Diffusion uses the text portion of
111
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
112
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
113
+ tokenizer (`CLIPTokenizer`):
114
+ Tokenizer of class
115
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
116
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
117
+ low_res_scheduler ([`SchedulerMixin`]):
118
+ A scheduler used to add initial noise to the low res conditioning image. It must be an instance of
119
+ [`DDPMScheduler`].
120
+ scheduler ([`SchedulerMixin`]):
121
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
122
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
123
+ """
124
+
125
+ def __init__(
126
+ self,
127
+ vae: AutoencoderKL,
128
+ text_encoder: CLIPTextModel,
129
+ tokenizer: CLIPTokenizer,
130
+ unet: UNet2DConditionModel,
131
+ low_res_scheduler: DDPMScheduler,
132
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
133
+ max_noise_level: int = 350,
134
+ ):
135
+ super().__init__(
136
+ vae=vae,
137
+ text_encoder=text_encoder,
138
+ tokenizer=tokenizer,
139
+ unet=unet,
140
+ low_res_scheduler=low_res_scheduler,
141
+ scheduler=scheduler,
142
+ max_noise_level=max_noise_level,
143
+ )
144
+
145
+ def _process_tile(self, original_image_slice, x, y, tile_size, tile_border, image, final_image, **kwargs):
146
+ torch.manual_seed(0)
147
+ crop_rect = (
148
+ min(image.size[0] - (tile_size + original_image_slice), x * tile_size),
149
+ min(image.size[1] - (tile_size + original_image_slice), y * tile_size),
150
+ min(image.size[0], (x + 1) * tile_size),
151
+ min(image.size[1], (y + 1) * tile_size),
152
+ )
153
+ crop_rect_with_overlap = add_overlap_rect(crop_rect, tile_border, image.size)
154
+ tile = image.crop(crop_rect_with_overlap)
155
+ translated_slice_x = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0]
156
+ translated_slice_x = translated_slice_x - (original_image_slice / 2)
157
+ translated_slice_x = max(0, translated_slice_x)
158
+ to_input = squeeze_tile(tile, image, original_image_slice, translated_slice_x)
159
+ orig_input_size = to_input.size
160
+ to_input = to_input.resize((tile_size, tile_size), Image.BICUBIC)
161
+ upscaled_tile = super(StableDiffusionTiledUpscalePipeline, self).__call__(image=to_input, **kwargs).images[0]
162
+ upscaled_tile = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4), Image.BICUBIC)
163
+ upscaled_tile = unsqueeze_tile(upscaled_tile, original_image_slice)
164
+ upscaled_tile = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4), Image.BICUBIC)
165
+ remove_borders = []
166
+ if x == 0:
167
+ remove_borders.append("l")
168
+ elif crop_rect[2] == image.size[0]:
169
+ remove_borders.append("r")
170
+ if y == 0:
171
+ remove_borders.append("t")
172
+ elif crop_rect[3] == image.size[1]:
173
+ remove_borders.append("b")
174
+ transparency_mask = Image.fromarray(
175
+ make_transparency_mask(
176
+ (upscaled_tile.size[0], upscaled_tile.size[1]), tile_border * 4, remove_borders=remove_borders
177
+ ),
178
+ mode="L",
179
+ )
180
+ final_image.paste(
181
+ upscaled_tile, (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4), transparency_mask
182
+ )
183
+
184
+ @torch.no_grad()
185
+ def __call__(
186
+ self,
187
+ prompt: Union[str, List[str]],
188
+ image: Union[PIL.Image.Image, List[PIL.Image.Image]],
189
+ num_inference_steps: int = 75,
190
+ guidance_scale: float = 9.0,
191
+ noise_level: int = 50,
192
+ negative_prompt: Optional[Union[str, List[str]]] = None,
193
+ num_images_per_prompt: Optional[int] = 1,
194
+ eta: float = 0.0,
195
+ generator: Optional[torch.Generator] = None,
196
+ latents: Optional[torch.FloatTensor] = None,
197
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
198
+ callback_steps: int = 1,
199
+ tile_size: int = 128,
200
+ tile_border: int = 32,
201
+ original_image_slice: int = 32,
202
+ ):
203
+ r"""
204
+ Function invoked when calling the pipeline for generation.
205
+
206
+ Args:
207
+ prompt (`str` or `List[str]`):
208
+ The prompt or prompts to guide the image generation.
209
+ image (`PIL.Image.Image` or List[`PIL.Image.Image`] or `torch.FloatTensor`):
210
+ `Image`, or tensor representing an image batch which will be upscaled. *
211
+ num_inference_steps (`int`, *optional*, defaults to 50):
212
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
213
+ expense of slower inference.
214
+ guidance_scale (`float`, *optional*, defaults to 7.5):
215
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
216
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
217
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
218
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
219
+ usually at the expense of lower image quality.
220
+ negative_prompt (`str` or `List[str]`, *optional*):
221
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
222
+ if `guidance_scale` is less than `1`).
223
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
224
+ The number of images to generate per prompt.
225
+ eta (`float`, *optional*, defaults to 0.0):
226
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
227
+ [`schedulers.DDIMScheduler`], will be ignored for others.
228
+ generator (`torch.Generator`, *optional*):
229
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
230
+ deterministic.
231
+ latents (`torch.FloatTensor`, *optional*):
232
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
233
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
234
+ tensor will ge generated by sampling using the supplied random `generator`.
235
+ tile_size (`int`, *optional*):
236
+ The size of the tiles. Too big can result in an OOM-error.
237
+ tile_border (`int`, *optional*):
238
+ The number of pixels around a tile to consider (bigger means less seams, too big can lead to an OOM-error).
239
+ original_image_slice (`int`, *optional*):
240
+ The amount of pixels of the original image to calculate with the current tile (bigger means more depth
241
+ is preserved, less blur occurs in the final image, too big can lead to an OOM-error or loss in detail).
242
+ callback (`Callable`, *optional*):
243
+ A function that take a callback function with a single argument, a dict,
244
+ that contains the (partially) processed image under "image",
245
+ as well as the progress (0 to 1, where 1 is completed) under "progress".
246
+
247
+ Returns: A PIL.Image that is 4 times larger than the original input image.
248
+
249
+ """
250
+
251
+ final_image = Image.new("RGB", (image.size[0] * 4, image.size[1] * 4))
252
+ tcx = math.ceil(image.size[0] / tile_size)
253
+ tcy = math.ceil(image.size[1] / tile_size)
254
+ total_tile_count = tcx * tcy
255
+ current_count = 0
256
+ for y in range(tcy):
257
+ for x in range(tcx):
258
+ self._process_tile(
259
+ original_image_slice,
260
+ x,
261
+ y,
262
+ tile_size,
263
+ tile_border,
264
+ image,
265
+ final_image,
266
+ prompt=prompt,
267
+ num_inference_steps=num_inference_steps,
268
+ guidance_scale=guidance_scale,
269
+ noise_level=noise_level,
270
+ negative_prompt=negative_prompt,
271
+ num_images_per_prompt=num_images_per_prompt,
272
+ eta=eta,
273
+ generator=generator,
274
+ latents=latents,
275
+ )
276
+ current_count += 1
277
+ if callback is not None:
278
+ callback({"progress": current_count / total_tile_count, "image": final_image})
279
+ return final_image
280
+
281
+
282
+ def main():
283
+ # Run a demo
284
+ model_id = "stabilityai/stable-diffusion-x4-upscaler"
285
+ pipe = StableDiffusionTiledUpscalePipeline.from_pretrained(model_id, revision="fp16", torch_dtype=torch.float16)
286
+ pipe = pipe.to("cuda")
287
+ image = Image.open("../../docs/source/imgs/diffusers_library.jpg")
288
+
289
+ def callback(obj):
290
+ print(f"progress: {obj['progress']:.4f}")
291
+ obj["image"].save("diffusers_library_progress.jpg")
292
+
293
+ final_image = pipe(image=image, prompt="Black font, white background, vector", noise_level=40, callback=callback)
294
+ final_image.save("diffusers_library.jpg")
295
+
296
+
297
+ if __name__ == "__main__":
298
+ main()
v0.22.0/unclip_image_interpolation.py ADDED
@@ -0,0 +1,496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import List, Optional, Union
3
+
4
+ import PIL.Image
5
+ import torch
6
+ from torch.nn import functional as F
7
+ from transformers import (
8
+ CLIPImageProcessor,
9
+ CLIPTextModelWithProjection,
10
+ CLIPTokenizer,
11
+ CLIPVisionModelWithProjection,
12
+ )
13
+
14
+ from diffusers import (
15
+ DiffusionPipeline,
16
+ ImagePipelineOutput,
17
+ UnCLIPScheduler,
18
+ UNet2DConditionModel,
19
+ UNet2DModel,
20
+ )
21
+ from diffusers.pipelines.unclip import UnCLIPTextProjModel
22
+ from diffusers.utils import is_accelerate_available, logging
23
+ from diffusers.utils.torch_utils import randn_tensor
24
+
25
+
26
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
27
+
28
+
29
+ def slerp(val, low, high):
30
+ """
31
+ Find the interpolation point between the 'low' and 'high' values for the given 'val'. See https://en.wikipedia.org/wiki/Slerp for more details on the topic.
32
+ """
33
+ low_norm = low / torch.norm(low)
34
+ high_norm = high / torch.norm(high)
35
+ omega = torch.acos((low_norm * high_norm))
36
+ so = torch.sin(omega)
37
+ res = (torch.sin((1.0 - val) * omega) / so) * low + (torch.sin(val * omega) / so) * high
38
+ return res
39
+
40
+
41
+ class UnCLIPImageInterpolationPipeline(DiffusionPipeline):
42
+ """
43
+ Pipeline to generate variations from an input image using unCLIP
44
+
45
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
46
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
47
+
48
+ Args:
49
+ text_encoder ([`CLIPTextModelWithProjection`]):
50
+ Frozen text-encoder.
51
+ tokenizer (`CLIPTokenizer`):
52
+ Tokenizer of class
53
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
54
+ feature_extractor ([`CLIPImageProcessor`]):
55
+ Model that extracts features from generated images to be used as inputs for the `image_encoder`.
56
+ image_encoder ([`CLIPVisionModelWithProjection`]):
57
+ Frozen CLIP image-encoder. unCLIP Image Variation uses the vision portion of
58
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPVisionModelWithProjection),
59
+ specifically the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
60
+ text_proj ([`UnCLIPTextProjModel`]):
61
+ Utility class to prepare and combine the embeddings before they are passed to the decoder.
62
+ decoder ([`UNet2DConditionModel`]):
63
+ The decoder to invert the image embedding into an image.
64
+ super_res_first ([`UNet2DModel`]):
65
+ Super resolution unet. Used in all but the last step of the super resolution diffusion process.
66
+ super_res_last ([`UNet2DModel`]):
67
+ Super resolution unet. Used in the last step of the super resolution diffusion process.
68
+ decoder_scheduler ([`UnCLIPScheduler`]):
69
+ Scheduler used in the decoder denoising process. Just a modified DDPMScheduler.
70
+ super_res_scheduler ([`UnCLIPScheduler`]):
71
+ Scheduler used in the super resolution denoising process. Just a modified DDPMScheduler.
72
+
73
+ """
74
+
75
+ decoder: UNet2DConditionModel
76
+ text_proj: UnCLIPTextProjModel
77
+ text_encoder: CLIPTextModelWithProjection
78
+ tokenizer: CLIPTokenizer
79
+ feature_extractor: CLIPImageProcessor
80
+ image_encoder: CLIPVisionModelWithProjection
81
+ super_res_first: UNet2DModel
82
+ super_res_last: UNet2DModel
83
+
84
+ decoder_scheduler: UnCLIPScheduler
85
+ super_res_scheduler: UnCLIPScheduler
86
+
87
+ # Copied from diffusers.pipelines.unclip.pipeline_unclip_image_variation.UnCLIPImageVariationPipeline.__init__
88
+ def __init__(
89
+ self,
90
+ decoder: UNet2DConditionModel,
91
+ text_encoder: CLIPTextModelWithProjection,
92
+ tokenizer: CLIPTokenizer,
93
+ text_proj: UnCLIPTextProjModel,
94
+ feature_extractor: CLIPImageProcessor,
95
+ image_encoder: CLIPVisionModelWithProjection,
96
+ super_res_first: UNet2DModel,
97
+ super_res_last: UNet2DModel,
98
+ decoder_scheduler: UnCLIPScheduler,
99
+ super_res_scheduler: UnCLIPScheduler,
100
+ ):
101
+ super().__init__()
102
+
103
+ self.register_modules(
104
+ decoder=decoder,
105
+ text_encoder=text_encoder,
106
+ tokenizer=tokenizer,
107
+ text_proj=text_proj,
108
+ feature_extractor=feature_extractor,
109
+ image_encoder=image_encoder,
110
+ super_res_first=super_res_first,
111
+ super_res_last=super_res_last,
112
+ decoder_scheduler=decoder_scheduler,
113
+ super_res_scheduler=super_res_scheduler,
114
+ )
115
+
116
+ # Copied from diffusers.pipelines.unclip.pipeline_unclip.UnCLIPPipeline.prepare_latents
117
+ def prepare_latents(self, shape, dtype, device, generator, latents, scheduler):
118
+ if latents is None:
119
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
120
+ else:
121
+ if latents.shape != shape:
122
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
123
+ latents = latents.to(device)
124
+
125
+ latents = latents * scheduler.init_noise_sigma
126
+ return latents
127
+
128
+ # Copied from diffusers.pipelines.unclip.pipeline_unclip_image_variation.UnCLIPImageVariationPipeline._encode_prompt
129
+ def _encode_prompt(self, prompt, device, num_images_per_prompt, do_classifier_free_guidance):
130
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
131
+
132
+ # get prompt text embeddings
133
+ text_inputs = self.tokenizer(
134
+ prompt,
135
+ padding="max_length",
136
+ max_length=self.tokenizer.model_max_length,
137
+ return_tensors="pt",
138
+ )
139
+ text_input_ids = text_inputs.input_ids
140
+ text_mask = text_inputs.attention_mask.bool().to(device)
141
+ text_encoder_output = self.text_encoder(text_input_ids.to(device))
142
+
143
+ prompt_embeds = text_encoder_output.text_embeds
144
+ text_encoder_hidden_states = text_encoder_output.last_hidden_state
145
+
146
+ prompt_embeds = prompt_embeds.repeat_interleave(num_images_per_prompt, dim=0)
147
+ text_encoder_hidden_states = text_encoder_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
148
+ text_mask = text_mask.repeat_interleave(num_images_per_prompt, dim=0)
149
+
150
+ if do_classifier_free_guidance:
151
+ uncond_tokens = [""] * batch_size
152
+
153
+ max_length = text_input_ids.shape[-1]
154
+ uncond_input = self.tokenizer(
155
+ uncond_tokens,
156
+ padding="max_length",
157
+ max_length=max_length,
158
+ truncation=True,
159
+ return_tensors="pt",
160
+ )
161
+ uncond_text_mask = uncond_input.attention_mask.bool().to(device)
162
+ negative_prompt_embeds_text_encoder_output = self.text_encoder(uncond_input.input_ids.to(device))
163
+
164
+ negative_prompt_embeds = negative_prompt_embeds_text_encoder_output.text_embeds
165
+ uncond_text_encoder_hidden_states = negative_prompt_embeds_text_encoder_output.last_hidden_state
166
+
167
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
168
+
169
+ seq_len = negative_prompt_embeds.shape[1]
170
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt)
171
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len)
172
+
173
+ seq_len = uncond_text_encoder_hidden_states.shape[1]
174
+ uncond_text_encoder_hidden_states = uncond_text_encoder_hidden_states.repeat(1, num_images_per_prompt, 1)
175
+ uncond_text_encoder_hidden_states = uncond_text_encoder_hidden_states.view(
176
+ batch_size * num_images_per_prompt, seq_len, -1
177
+ )
178
+ uncond_text_mask = uncond_text_mask.repeat_interleave(num_images_per_prompt, dim=0)
179
+
180
+ # done duplicates
181
+
182
+ # For classifier free guidance, we need to do two forward passes.
183
+ # Here we concatenate the unconditional and text embeddings into a single batch
184
+ # to avoid doing two forward passes
185
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
186
+ text_encoder_hidden_states = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states])
187
+
188
+ text_mask = torch.cat([uncond_text_mask, text_mask])
189
+
190
+ return prompt_embeds, text_encoder_hidden_states, text_mask
191
+
192
+ # Copied from diffusers.pipelines.unclip.pipeline_unclip_image_variation.UnCLIPImageVariationPipeline._encode_image
193
+ def _encode_image(self, image, device, num_images_per_prompt, image_embeddings: Optional[torch.Tensor] = None):
194
+ dtype = next(self.image_encoder.parameters()).dtype
195
+
196
+ if image_embeddings is None:
197
+ if not isinstance(image, torch.Tensor):
198
+ image = self.feature_extractor(images=image, return_tensors="pt").pixel_values
199
+
200
+ image = image.to(device=device, dtype=dtype)
201
+ image_embeddings = self.image_encoder(image).image_embeds
202
+
203
+ image_embeddings = image_embeddings.repeat_interleave(num_images_per_prompt, dim=0)
204
+
205
+ return image_embeddings
206
+
207
+ # Copied from diffusers.pipelines.unclip.pipeline_unclip_image_variation.UnCLIPImageVariationPipeline.enable_sequential_cpu_offload
208
+ def enable_sequential_cpu_offload(self, gpu_id=0):
209
+ r"""
210
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, the pipeline's
211
+ models have their state dicts saved to CPU and then are moved to a `torch.device('meta') and loaded to GPU only
212
+ when their specific submodule has its `forward` method called.
213
+ """
214
+ if is_accelerate_available():
215
+ from accelerate import cpu_offload
216
+ else:
217
+ raise ImportError("Please install accelerate via `pip install accelerate`")
218
+
219
+ device = torch.device(f"cuda:{gpu_id}")
220
+
221
+ models = [
222
+ self.decoder,
223
+ self.text_proj,
224
+ self.text_encoder,
225
+ self.super_res_first,
226
+ self.super_res_last,
227
+ ]
228
+ for cpu_offloaded_model in models:
229
+ if cpu_offloaded_model is not None:
230
+ cpu_offload(cpu_offloaded_model, device)
231
+
232
+ @property
233
+ # Copied from diffusers.pipelines.unclip.pipeline_unclip.UnCLIPPipeline._execution_device
234
+ def _execution_device(self):
235
+ r"""
236
+ Returns the device on which the pipeline's models will be executed. After calling
237
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
238
+ hooks.
239
+ """
240
+ if self.device != torch.device("meta") or not hasattr(self.decoder, "_hf_hook"):
241
+ return self.device
242
+ for module in self.decoder.modules():
243
+ if (
244
+ hasattr(module, "_hf_hook")
245
+ and hasattr(module._hf_hook, "execution_device")
246
+ and module._hf_hook.execution_device is not None
247
+ ):
248
+ return torch.device(module._hf_hook.execution_device)
249
+ return self.device
250
+
251
+ @torch.no_grad()
252
+ def __call__(
253
+ self,
254
+ image: Optional[Union[List[PIL.Image.Image], torch.FloatTensor]] = None,
255
+ steps: int = 5,
256
+ decoder_num_inference_steps: int = 25,
257
+ super_res_num_inference_steps: int = 7,
258
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
259
+ image_embeddings: Optional[torch.Tensor] = None,
260
+ decoder_latents: Optional[torch.FloatTensor] = None,
261
+ super_res_latents: Optional[torch.FloatTensor] = None,
262
+ decoder_guidance_scale: float = 8.0,
263
+ output_type: Optional[str] = "pil",
264
+ return_dict: bool = True,
265
+ ):
266
+ """
267
+ Function invoked when calling the pipeline for generation.
268
+
269
+ Args:
270
+ image (`List[PIL.Image.Image]` or `torch.FloatTensor`):
271
+ The images to use for the image interpolation. Only accepts a list of two PIL Images or If you provide a tensor, it needs to comply with the
272
+ configuration of
273
+ [this](https://huggingface.co/fusing/karlo-image-variations-diffusers/blob/main/feature_extractor/preprocessor_config.json)
274
+ `CLIPImageProcessor` while still having a shape of two in the 0th dimension. Can be left to `None` only when `image_embeddings` are passed.
275
+ steps (`int`, *optional*, defaults to 5):
276
+ The number of interpolation images to generate.
277
+ decoder_num_inference_steps (`int`, *optional*, defaults to 25):
278
+ The number of denoising steps for the decoder. More denoising steps usually lead to a higher quality
279
+ image at the expense of slower inference.
280
+ super_res_num_inference_steps (`int`, *optional*, defaults to 7):
281
+ The number of denoising steps for super resolution. More denoising steps usually lead to a higher
282
+ quality image at the expense of slower inference.
283
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
284
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
285
+ to make generation deterministic.
286
+ image_embeddings (`torch.Tensor`, *optional*):
287
+ Pre-defined image embeddings that can be derived from the image encoder. Pre-defined image embeddings
288
+ can be passed for tasks like image interpolations. `image` can the be left to `None`.
289
+ decoder_latents (`torch.FloatTensor` of shape (batch size, channels, height, width), *optional*):
290
+ Pre-generated noisy latents to be used as inputs for the decoder.
291
+ super_res_latents (`torch.FloatTensor` of shape (batch size, channels, super res height, super res width), *optional*):
292
+ Pre-generated noisy latents to be used as inputs for the decoder.
293
+ decoder_guidance_scale (`float`, *optional*, defaults to 4.0):
294
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
295
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
296
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
297
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
298
+ usually at the expense of lower image quality.
299
+ output_type (`str`, *optional*, defaults to `"pil"`):
300
+ The output format of the generated image. Choose between
301
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
302
+ return_dict (`bool`, *optional*, defaults to `True`):
303
+ Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple.
304
+ """
305
+
306
+ batch_size = steps
307
+
308
+ device = self._execution_device
309
+
310
+ if isinstance(image, List):
311
+ if len(image) != 2:
312
+ raise AssertionError(
313
+ f"Expected 'image' List to be of size 2, but passed 'image' length is {len(image)}"
314
+ )
315
+ elif not (isinstance(image[0], PIL.Image.Image) and isinstance(image[0], PIL.Image.Image)):
316
+ raise AssertionError(
317
+ f"Expected 'image' List to contain PIL.Image.Image, but passed 'image' contents are {type(image[0])} and {type(image[1])}"
318
+ )
319
+ elif isinstance(image, torch.FloatTensor):
320
+ if image.shape[0] != 2:
321
+ raise AssertionError(
322
+ f"Expected 'image' to be torch.FloatTensor of shape 2 in 0th dimension, but passed 'image' size is {image.shape[0]}"
323
+ )
324
+ elif isinstance(image_embeddings, torch.Tensor):
325
+ if image_embeddings.shape[0] != 2:
326
+ raise AssertionError(
327
+ f"Expected 'image_embeddings' to be torch.FloatTensor of shape 2 in 0th dimension, but passed 'image_embeddings' shape is {image_embeddings.shape[0]}"
328
+ )
329
+ else:
330
+ raise AssertionError(
331
+ f"Expected 'image' or 'image_embeddings' to be not None with types List[PIL.Image] or Torch.FloatTensor respectively. Received {type(image)} and {type(image_embeddings)} repsectively"
332
+ )
333
+
334
+ original_image_embeddings = self._encode_image(
335
+ image=image, device=device, num_images_per_prompt=1, image_embeddings=image_embeddings
336
+ )
337
+
338
+ image_embeddings = []
339
+
340
+ for interp_step in torch.linspace(0, 1, steps):
341
+ temp_image_embeddings = slerp(
342
+ interp_step, original_image_embeddings[0], original_image_embeddings[1]
343
+ ).unsqueeze(0)
344
+ image_embeddings.append(temp_image_embeddings)
345
+
346
+ image_embeddings = torch.cat(image_embeddings).to(device)
347
+
348
+ do_classifier_free_guidance = decoder_guidance_scale > 1.0
349
+
350
+ prompt_embeds, text_encoder_hidden_states, text_mask = self._encode_prompt(
351
+ prompt=["" for i in range(steps)],
352
+ device=device,
353
+ num_images_per_prompt=1,
354
+ do_classifier_free_guidance=do_classifier_free_guidance,
355
+ )
356
+
357
+ text_encoder_hidden_states, additive_clip_time_embeddings = self.text_proj(
358
+ image_embeddings=image_embeddings,
359
+ prompt_embeds=prompt_embeds,
360
+ text_encoder_hidden_states=text_encoder_hidden_states,
361
+ do_classifier_free_guidance=do_classifier_free_guidance,
362
+ )
363
+
364
+ if device.type == "mps":
365
+ # HACK: MPS: There is a panic when padding bool tensors,
366
+ # so cast to int tensor for the pad and back to bool afterwards
367
+ text_mask = text_mask.type(torch.int)
368
+ decoder_text_mask = F.pad(text_mask, (self.text_proj.clip_extra_context_tokens, 0), value=1)
369
+ decoder_text_mask = decoder_text_mask.type(torch.bool)
370
+ else:
371
+ decoder_text_mask = F.pad(text_mask, (self.text_proj.clip_extra_context_tokens, 0), value=True)
372
+
373
+ self.decoder_scheduler.set_timesteps(decoder_num_inference_steps, device=device)
374
+ decoder_timesteps_tensor = self.decoder_scheduler.timesteps
375
+
376
+ num_channels_latents = self.decoder.config.in_channels
377
+ height = self.decoder.config.sample_size
378
+ width = self.decoder.config.sample_size
379
+
380
+ # Get the decoder latents for 1 step and then repeat the same tensor for the entire batch to keep same noise across all interpolation steps.
381
+ decoder_latents = self.prepare_latents(
382
+ (1, num_channels_latents, height, width),
383
+ text_encoder_hidden_states.dtype,
384
+ device,
385
+ generator,
386
+ decoder_latents,
387
+ self.decoder_scheduler,
388
+ )
389
+ decoder_latents = decoder_latents.repeat((batch_size, 1, 1, 1))
390
+
391
+ for i, t in enumerate(self.progress_bar(decoder_timesteps_tensor)):
392
+ # expand the latents if we are doing classifier free guidance
393
+ latent_model_input = torch.cat([decoder_latents] * 2) if do_classifier_free_guidance else decoder_latents
394
+
395
+ noise_pred = self.decoder(
396
+ sample=latent_model_input,
397
+ timestep=t,
398
+ encoder_hidden_states=text_encoder_hidden_states,
399
+ class_labels=additive_clip_time_embeddings,
400
+ attention_mask=decoder_text_mask,
401
+ ).sample
402
+
403
+ if do_classifier_free_guidance:
404
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
405
+ noise_pred_uncond, _ = noise_pred_uncond.split(latent_model_input.shape[1], dim=1)
406
+ noise_pred_text, predicted_variance = noise_pred_text.split(latent_model_input.shape[1], dim=1)
407
+ noise_pred = noise_pred_uncond + decoder_guidance_scale * (noise_pred_text - noise_pred_uncond)
408
+ noise_pred = torch.cat([noise_pred, predicted_variance], dim=1)
409
+
410
+ if i + 1 == decoder_timesteps_tensor.shape[0]:
411
+ prev_timestep = None
412
+ else:
413
+ prev_timestep = decoder_timesteps_tensor[i + 1]
414
+
415
+ # compute the previous noisy sample x_t -> x_t-1
416
+ decoder_latents = self.decoder_scheduler.step(
417
+ noise_pred, t, decoder_latents, prev_timestep=prev_timestep, generator=generator
418
+ ).prev_sample
419
+
420
+ decoder_latents = decoder_latents.clamp(-1, 1)
421
+
422
+ image_small = decoder_latents
423
+
424
+ # done decoder
425
+
426
+ # super res
427
+
428
+ self.super_res_scheduler.set_timesteps(super_res_num_inference_steps, device=device)
429
+ super_res_timesteps_tensor = self.super_res_scheduler.timesteps
430
+
431
+ channels = self.super_res_first.config.in_channels // 2
432
+ height = self.super_res_first.config.sample_size
433
+ width = self.super_res_first.config.sample_size
434
+
435
+ super_res_latents = self.prepare_latents(
436
+ (batch_size, channels, height, width),
437
+ image_small.dtype,
438
+ device,
439
+ generator,
440
+ super_res_latents,
441
+ self.super_res_scheduler,
442
+ )
443
+
444
+ if device.type == "mps":
445
+ # MPS does not support many interpolations
446
+ image_upscaled = F.interpolate(image_small, size=[height, width])
447
+ else:
448
+ interpolate_antialias = {}
449
+ if "antialias" in inspect.signature(F.interpolate).parameters:
450
+ interpolate_antialias["antialias"] = True
451
+
452
+ image_upscaled = F.interpolate(
453
+ image_small, size=[height, width], mode="bicubic", align_corners=False, **interpolate_antialias
454
+ )
455
+
456
+ for i, t in enumerate(self.progress_bar(super_res_timesteps_tensor)):
457
+ # no classifier free guidance
458
+
459
+ if i == super_res_timesteps_tensor.shape[0] - 1:
460
+ unet = self.super_res_last
461
+ else:
462
+ unet = self.super_res_first
463
+
464
+ latent_model_input = torch.cat([super_res_latents, image_upscaled], dim=1)
465
+
466
+ noise_pred = unet(
467
+ sample=latent_model_input,
468
+ timestep=t,
469
+ ).sample
470
+
471
+ if i + 1 == super_res_timesteps_tensor.shape[0]:
472
+ prev_timestep = None
473
+ else:
474
+ prev_timestep = super_res_timesteps_tensor[i + 1]
475
+
476
+ # compute the previous noisy sample x_t -> x_t-1
477
+ super_res_latents = self.super_res_scheduler.step(
478
+ noise_pred, t, super_res_latents, prev_timestep=prev_timestep, generator=generator
479
+ ).prev_sample
480
+
481
+ image = super_res_latents
482
+ # done super res
483
+
484
+ # post processing
485
+
486
+ image = image * 0.5 + 0.5
487
+ image = image.clamp(0, 1)
488
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
489
+
490
+ if output_type == "pil":
491
+ image = self.numpy_to_pil(image)
492
+
493
+ if not return_dict:
494
+ return (image,)
495
+
496
+ return ImagePipelineOutput(images=image)
v0.22.0/unclip_text_interpolation.py ADDED
@@ -0,0 +1,574 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import List, Optional, Tuple, Union
3
+
4
+ import torch
5
+ from torch.nn import functional as F
6
+ from transformers import CLIPTextModelWithProjection, CLIPTokenizer
7
+ from transformers.models.clip.modeling_clip import CLIPTextModelOutput
8
+
9
+ from diffusers import (
10
+ DiffusionPipeline,
11
+ ImagePipelineOutput,
12
+ PriorTransformer,
13
+ UnCLIPScheduler,
14
+ UNet2DConditionModel,
15
+ UNet2DModel,
16
+ )
17
+ from diffusers.pipelines.unclip import UnCLIPTextProjModel
18
+ from diffusers.utils import is_accelerate_available, logging
19
+ from diffusers.utils.torch_utils import randn_tensor
20
+
21
+
22
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
23
+
24
+
25
+ def slerp(val, low, high):
26
+ """
27
+ Find the interpolation point between the 'low' and 'high' values for the given 'val'. See https://en.wikipedia.org/wiki/Slerp for more details on the topic.
28
+ """
29
+ low_norm = low / torch.norm(low)
30
+ high_norm = high / torch.norm(high)
31
+ omega = torch.acos((low_norm * high_norm))
32
+ so = torch.sin(omega)
33
+ res = (torch.sin((1.0 - val) * omega) / so) * low + (torch.sin(val * omega) / so) * high
34
+ return res
35
+
36
+
37
+ class UnCLIPTextInterpolationPipeline(DiffusionPipeline):
38
+
39
+ """
40
+ Pipeline for prompt-to-prompt interpolation on CLIP text embeddings and using the UnCLIP / Dall-E to decode them to images.
41
+
42
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
43
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
44
+
45
+ Args:
46
+ text_encoder ([`CLIPTextModelWithProjection`]):
47
+ Frozen text-encoder.
48
+ tokenizer (`CLIPTokenizer`):
49
+ Tokenizer of class
50
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
51
+ prior ([`PriorTransformer`]):
52
+ The canonincal unCLIP prior to approximate the image embedding from the text embedding.
53
+ text_proj ([`UnCLIPTextProjModel`]):
54
+ Utility class to prepare and combine the embeddings before they are passed to the decoder.
55
+ decoder ([`UNet2DConditionModel`]):
56
+ The decoder to invert the image embedding into an image.
57
+ super_res_first ([`UNet2DModel`]):
58
+ Super resolution unet. Used in all but the last step of the super resolution diffusion process.
59
+ super_res_last ([`UNet2DModel`]):
60
+ Super resolution unet. Used in the last step of the super resolution diffusion process.
61
+ prior_scheduler ([`UnCLIPScheduler`]):
62
+ Scheduler used in the prior denoising process. Just a modified DDPMScheduler.
63
+ decoder_scheduler ([`UnCLIPScheduler`]):
64
+ Scheduler used in the decoder denoising process. Just a modified DDPMScheduler.
65
+ super_res_scheduler ([`UnCLIPScheduler`]):
66
+ Scheduler used in the super resolution denoising process. Just a modified DDPMScheduler.
67
+
68
+ """
69
+
70
+ prior: PriorTransformer
71
+ decoder: UNet2DConditionModel
72
+ text_proj: UnCLIPTextProjModel
73
+ text_encoder: CLIPTextModelWithProjection
74
+ tokenizer: CLIPTokenizer
75
+ super_res_first: UNet2DModel
76
+ super_res_last: UNet2DModel
77
+
78
+ prior_scheduler: UnCLIPScheduler
79
+ decoder_scheduler: UnCLIPScheduler
80
+ super_res_scheduler: UnCLIPScheduler
81
+
82
+ # Copied from diffusers.pipelines.unclip.pipeline_unclip.UnCLIPPipeline.__init__
83
+ def __init__(
84
+ self,
85
+ prior: PriorTransformer,
86
+ decoder: UNet2DConditionModel,
87
+ text_encoder: CLIPTextModelWithProjection,
88
+ tokenizer: CLIPTokenizer,
89
+ text_proj: UnCLIPTextProjModel,
90
+ super_res_first: UNet2DModel,
91
+ super_res_last: UNet2DModel,
92
+ prior_scheduler: UnCLIPScheduler,
93
+ decoder_scheduler: UnCLIPScheduler,
94
+ super_res_scheduler: UnCLIPScheduler,
95
+ ):
96
+ super().__init__()
97
+
98
+ self.register_modules(
99
+ prior=prior,
100
+ decoder=decoder,
101
+ text_encoder=text_encoder,
102
+ tokenizer=tokenizer,
103
+ text_proj=text_proj,
104
+ super_res_first=super_res_first,
105
+ super_res_last=super_res_last,
106
+ prior_scheduler=prior_scheduler,
107
+ decoder_scheduler=decoder_scheduler,
108
+ super_res_scheduler=super_res_scheduler,
109
+ )
110
+
111
+ # Copied from diffusers.pipelines.unclip.pipeline_unclip.UnCLIPPipeline.prepare_latents
112
+ def prepare_latents(self, shape, dtype, device, generator, latents, scheduler):
113
+ if latents is None:
114
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
115
+ else:
116
+ if latents.shape != shape:
117
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
118
+ latents = latents.to(device)
119
+
120
+ latents = latents * scheduler.init_noise_sigma
121
+ return latents
122
+
123
+ # Copied from diffusers.pipelines.unclip.pipeline_unclip.UnCLIPPipeline._encode_prompt
124
+ def _encode_prompt(
125
+ self,
126
+ prompt,
127
+ device,
128
+ num_images_per_prompt,
129
+ do_classifier_free_guidance,
130
+ text_model_output: Optional[Union[CLIPTextModelOutput, Tuple]] = None,
131
+ text_attention_mask: Optional[torch.Tensor] = None,
132
+ ):
133
+ if text_model_output is None:
134
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
135
+ # get prompt text embeddings
136
+ text_inputs = self.tokenizer(
137
+ prompt,
138
+ padding="max_length",
139
+ max_length=self.tokenizer.model_max_length,
140
+ truncation=True,
141
+ return_tensors="pt",
142
+ )
143
+ text_input_ids = text_inputs.input_ids
144
+ text_mask = text_inputs.attention_mask.bool().to(device)
145
+
146
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
147
+
148
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
149
+ text_input_ids, untruncated_ids
150
+ ):
151
+ removed_text = self.tokenizer.batch_decode(
152
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
153
+ )
154
+ logger.warning(
155
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
156
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
157
+ )
158
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
159
+
160
+ text_encoder_output = self.text_encoder(text_input_ids.to(device))
161
+
162
+ prompt_embeds = text_encoder_output.text_embeds
163
+ text_encoder_hidden_states = text_encoder_output.last_hidden_state
164
+
165
+ else:
166
+ batch_size = text_model_output[0].shape[0]
167
+ prompt_embeds, text_encoder_hidden_states = text_model_output[0], text_model_output[1]
168
+ text_mask = text_attention_mask
169
+
170
+ prompt_embeds = prompt_embeds.repeat_interleave(num_images_per_prompt, dim=0)
171
+ text_encoder_hidden_states = text_encoder_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
172
+ text_mask = text_mask.repeat_interleave(num_images_per_prompt, dim=0)
173
+
174
+ if do_classifier_free_guidance:
175
+ uncond_tokens = [""] * batch_size
176
+
177
+ uncond_input = self.tokenizer(
178
+ uncond_tokens,
179
+ padding="max_length",
180
+ max_length=self.tokenizer.model_max_length,
181
+ truncation=True,
182
+ return_tensors="pt",
183
+ )
184
+ uncond_text_mask = uncond_input.attention_mask.bool().to(device)
185
+ negative_prompt_embeds_text_encoder_output = self.text_encoder(uncond_input.input_ids.to(device))
186
+
187
+ negative_prompt_embeds = negative_prompt_embeds_text_encoder_output.text_embeds
188
+ uncond_text_encoder_hidden_states = negative_prompt_embeds_text_encoder_output.last_hidden_state
189
+
190
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
191
+
192
+ seq_len = negative_prompt_embeds.shape[1]
193
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt)
194
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len)
195
+
196
+ seq_len = uncond_text_encoder_hidden_states.shape[1]
197
+ uncond_text_encoder_hidden_states = uncond_text_encoder_hidden_states.repeat(1, num_images_per_prompt, 1)
198
+ uncond_text_encoder_hidden_states = uncond_text_encoder_hidden_states.view(
199
+ batch_size * num_images_per_prompt, seq_len, -1
200
+ )
201
+ uncond_text_mask = uncond_text_mask.repeat_interleave(num_images_per_prompt, dim=0)
202
+
203
+ # done duplicates
204
+
205
+ # For classifier free guidance, we need to do two forward passes.
206
+ # Here we concatenate the unconditional and text embeddings into a single batch
207
+ # to avoid doing two forward passes
208
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
209
+ text_encoder_hidden_states = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states])
210
+
211
+ text_mask = torch.cat([uncond_text_mask, text_mask])
212
+
213
+ return prompt_embeds, text_encoder_hidden_states, text_mask
214
+
215
+ # Copied from diffusers.pipelines.unclip.pipeline_unclip.UnCLIPPipeline.enable_sequential_cpu_offload
216
+ def enable_sequential_cpu_offload(self, gpu_id=0):
217
+ r"""
218
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, the pipeline's
219
+ models have their state dicts saved to CPU and then are moved to a `torch.device('meta') and loaded to GPU only
220
+ when their specific submodule has its `forward` method called.
221
+ """
222
+ if is_accelerate_available():
223
+ from accelerate import cpu_offload
224
+ else:
225
+ raise ImportError("Please install accelerate via `pip install accelerate`")
226
+
227
+ device = torch.device(f"cuda:{gpu_id}")
228
+
229
+ # TODO: self.prior.post_process_latents is not covered by the offload hooks, so it fails if added to the list
230
+ models = [
231
+ self.decoder,
232
+ self.text_proj,
233
+ self.text_encoder,
234
+ self.super_res_first,
235
+ self.super_res_last,
236
+ ]
237
+ for cpu_offloaded_model in models:
238
+ if cpu_offloaded_model is not None:
239
+ cpu_offload(cpu_offloaded_model, device)
240
+
241
+ @property
242
+ # Copied from diffusers.pipelines.unclip.pipeline_unclip.UnCLIPPipeline._execution_device
243
+ def _execution_device(self):
244
+ r"""
245
+ Returns the device on which the pipeline's models will be executed. After calling
246
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
247
+ hooks.
248
+ """
249
+ if self.device != torch.device("meta") or not hasattr(self.decoder, "_hf_hook"):
250
+ return self.device
251
+ for module in self.decoder.modules():
252
+ if (
253
+ hasattr(module, "_hf_hook")
254
+ and hasattr(module._hf_hook, "execution_device")
255
+ and module._hf_hook.execution_device is not None
256
+ ):
257
+ return torch.device(module._hf_hook.execution_device)
258
+ return self.device
259
+
260
+ @torch.no_grad()
261
+ def __call__(
262
+ self,
263
+ start_prompt: str,
264
+ end_prompt: str,
265
+ steps: int = 5,
266
+ prior_num_inference_steps: int = 25,
267
+ decoder_num_inference_steps: int = 25,
268
+ super_res_num_inference_steps: int = 7,
269
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
270
+ prior_guidance_scale: float = 4.0,
271
+ decoder_guidance_scale: float = 8.0,
272
+ enable_sequential_cpu_offload=True,
273
+ gpu_id=0,
274
+ output_type: Optional[str] = "pil",
275
+ return_dict: bool = True,
276
+ ):
277
+ """
278
+ Function invoked when calling the pipeline for generation.
279
+
280
+ Args:
281
+ start_prompt (`str`):
282
+ The prompt to start the image generation interpolation from.
283
+ end_prompt (`str`):
284
+ The prompt to end the image generation interpolation at.
285
+ steps (`int`, *optional*, defaults to 5):
286
+ The number of steps over which to interpolate from start_prompt to end_prompt. The pipeline returns
287
+ the same number of images as this value.
288
+ prior_num_inference_steps (`int`, *optional*, defaults to 25):
289
+ The number of denoising steps for the prior. More denoising steps usually lead to a higher quality
290
+ image at the expense of slower inference.
291
+ decoder_num_inference_steps (`int`, *optional*, defaults to 25):
292
+ The number of denoising steps for the decoder. More denoising steps usually lead to a higher quality
293
+ image at the expense of slower inference.
294
+ super_res_num_inference_steps (`int`, *optional*, defaults to 7):
295
+ The number of denoising steps for super resolution. More denoising steps usually lead to a higher
296
+ quality image at the expense of slower inference.
297
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
298
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
299
+ to make generation deterministic.
300
+ prior_guidance_scale (`float`, *optional*, defaults to 4.0):
301
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
302
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
303
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
304
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
305
+ usually at the expense of lower image quality.
306
+ decoder_guidance_scale (`float`, *optional*, defaults to 4.0):
307
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
308
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
309
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
310
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
311
+ usually at the expense of lower image quality.
312
+ output_type (`str`, *optional*, defaults to `"pil"`):
313
+ The output format of the generated image. Choose between
314
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
315
+ enable_sequential_cpu_offload (`bool`, *optional*, defaults to `True`):
316
+ If True, offloads all models to CPU using accelerate, significantly reducing memory usage. When called, the pipeline's
317
+ models have their state dicts saved to CPU and then are moved to a `torch.device('meta') and loaded to GPU only
318
+ when their specific submodule has its `forward` method called.
319
+ gpu_id (`int`, *optional*, defaults to `0`):
320
+ The gpu_id to be passed to enable_sequential_cpu_offload. Only works when enable_sequential_cpu_offload is set to True.
321
+ return_dict (`bool`, *optional*, defaults to `True`):
322
+ Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple.
323
+ """
324
+
325
+ if not isinstance(start_prompt, str) or not isinstance(end_prompt, str):
326
+ raise ValueError(
327
+ f"`start_prompt` and `end_prompt` should be of type `str` but got {type(start_prompt)} and"
328
+ f" {type(end_prompt)} instead"
329
+ )
330
+
331
+ if enable_sequential_cpu_offload:
332
+ self.enable_sequential_cpu_offload(gpu_id=gpu_id)
333
+
334
+ device = self._execution_device
335
+
336
+ # Turn the prompts into embeddings.
337
+ inputs = self.tokenizer(
338
+ [start_prompt, end_prompt],
339
+ padding="max_length",
340
+ truncation=True,
341
+ max_length=self.tokenizer.model_max_length,
342
+ return_tensors="pt",
343
+ )
344
+ inputs.to(device)
345
+ text_model_output = self.text_encoder(**inputs)
346
+
347
+ text_attention_mask = torch.max(inputs.attention_mask[0], inputs.attention_mask[1])
348
+ text_attention_mask = torch.cat([text_attention_mask.unsqueeze(0)] * steps).to(device)
349
+
350
+ # Interpolate from the start to end prompt using slerp and add the generated images to an image output pipeline
351
+ batch_text_embeds = []
352
+ batch_last_hidden_state = []
353
+
354
+ for interp_val in torch.linspace(0, 1, steps):
355
+ text_embeds = slerp(interp_val, text_model_output.text_embeds[0], text_model_output.text_embeds[1])
356
+ last_hidden_state = slerp(
357
+ interp_val, text_model_output.last_hidden_state[0], text_model_output.last_hidden_state[1]
358
+ )
359
+ batch_text_embeds.append(text_embeds.unsqueeze(0))
360
+ batch_last_hidden_state.append(last_hidden_state.unsqueeze(0))
361
+
362
+ batch_text_embeds = torch.cat(batch_text_embeds)
363
+ batch_last_hidden_state = torch.cat(batch_last_hidden_state)
364
+
365
+ text_model_output = CLIPTextModelOutput(
366
+ text_embeds=batch_text_embeds, last_hidden_state=batch_last_hidden_state
367
+ )
368
+
369
+ batch_size = text_model_output[0].shape[0]
370
+
371
+ do_classifier_free_guidance = prior_guidance_scale > 1.0 or decoder_guidance_scale > 1.0
372
+
373
+ prompt_embeds, text_encoder_hidden_states, text_mask = self._encode_prompt(
374
+ prompt=None,
375
+ device=device,
376
+ num_images_per_prompt=1,
377
+ do_classifier_free_guidance=do_classifier_free_guidance,
378
+ text_model_output=text_model_output,
379
+ text_attention_mask=text_attention_mask,
380
+ )
381
+
382
+ # prior
383
+
384
+ self.prior_scheduler.set_timesteps(prior_num_inference_steps, device=device)
385
+ prior_timesteps_tensor = self.prior_scheduler.timesteps
386
+
387
+ embedding_dim = self.prior.config.embedding_dim
388
+
389
+ prior_latents = self.prepare_latents(
390
+ (batch_size, embedding_dim),
391
+ prompt_embeds.dtype,
392
+ device,
393
+ generator,
394
+ None,
395
+ self.prior_scheduler,
396
+ )
397
+
398
+ for i, t in enumerate(self.progress_bar(prior_timesteps_tensor)):
399
+ # expand the latents if we are doing classifier free guidance
400
+ latent_model_input = torch.cat([prior_latents] * 2) if do_classifier_free_guidance else prior_latents
401
+
402
+ predicted_image_embedding = self.prior(
403
+ latent_model_input,
404
+ timestep=t,
405
+ proj_embedding=prompt_embeds,
406
+ encoder_hidden_states=text_encoder_hidden_states,
407
+ attention_mask=text_mask,
408
+ ).predicted_image_embedding
409
+
410
+ if do_classifier_free_guidance:
411
+ predicted_image_embedding_uncond, predicted_image_embedding_text = predicted_image_embedding.chunk(2)
412
+ predicted_image_embedding = predicted_image_embedding_uncond + prior_guidance_scale * (
413
+ predicted_image_embedding_text - predicted_image_embedding_uncond
414
+ )
415
+
416
+ if i + 1 == prior_timesteps_tensor.shape[0]:
417
+ prev_timestep = None
418
+ else:
419
+ prev_timestep = prior_timesteps_tensor[i + 1]
420
+
421
+ prior_latents = self.prior_scheduler.step(
422
+ predicted_image_embedding,
423
+ timestep=t,
424
+ sample=prior_latents,
425
+ generator=generator,
426
+ prev_timestep=prev_timestep,
427
+ ).prev_sample
428
+
429
+ prior_latents = self.prior.post_process_latents(prior_latents)
430
+
431
+ image_embeddings = prior_latents
432
+
433
+ # done prior
434
+
435
+ # decoder
436
+
437
+ text_encoder_hidden_states, additive_clip_time_embeddings = self.text_proj(
438
+ image_embeddings=image_embeddings,
439
+ prompt_embeds=prompt_embeds,
440
+ text_encoder_hidden_states=text_encoder_hidden_states,
441
+ do_classifier_free_guidance=do_classifier_free_guidance,
442
+ )
443
+
444
+ if device.type == "mps":
445
+ # HACK: MPS: There is a panic when padding bool tensors,
446
+ # so cast to int tensor for the pad and back to bool afterwards
447
+ text_mask = text_mask.type(torch.int)
448
+ decoder_text_mask = F.pad(text_mask, (self.text_proj.clip_extra_context_tokens, 0), value=1)
449
+ decoder_text_mask = decoder_text_mask.type(torch.bool)
450
+ else:
451
+ decoder_text_mask = F.pad(text_mask, (self.text_proj.clip_extra_context_tokens, 0), value=True)
452
+
453
+ self.decoder_scheduler.set_timesteps(decoder_num_inference_steps, device=device)
454
+ decoder_timesteps_tensor = self.decoder_scheduler.timesteps
455
+
456
+ num_channels_latents = self.decoder.config.in_channels
457
+ height = self.decoder.config.sample_size
458
+ width = self.decoder.config.sample_size
459
+
460
+ decoder_latents = self.prepare_latents(
461
+ (batch_size, num_channels_latents, height, width),
462
+ text_encoder_hidden_states.dtype,
463
+ device,
464
+ generator,
465
+ None,
466
+ self.decoder_scheduler,
467
+ )
468
+
469
+ for i, t in enumerate(self.progress_bar(decoder_timesteps_tensor)):
470
+ # expand the latents if we are doing classifier free guidance
471
+ latent_model_input = torch.cat([decoder_latents] * 2) if do_classifier_free_guidance else decoder_latents
472
+
473
+ noise_pred = self.decoder(
474
+ sample=latent_model_input,
475
+ timestep=t,
476
+ encoder_hidden_states=text_encoder_hidden_states,
477
+ class_labels=additive_clip_time_embeddings,
478
+ attention_mask=decoder_text_mask,
479
+ ).sample
480
+
481
+ if do_classifier_free_guidance:
482
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
483
+ noise_pred_uncond, _ = noise_pred_uncond.split(latent_model_input.shape[1], dim=1)
484
+ noise_pred_text, predicted_variance = noise_pred_text.split(latent_model_input.shape[1], dim=1)
485
+ noise_pred = noise_pred_uncond + decoder_guidance_scale * (noise_pred_text - noise_pred_uncond)
486
+ noise_pred = torch.cat([noise_pred, predicted_variance], dim=1)
487
+
488
+ if i + 1 == decoder_timesteps_tensor.shape[0]:
489
+ prev_timestep = None
490
+ else:
491
+ prev_timestep = decoder_timesteps_tensor[i + 1]
492
+
493
+ # compute the previous noisy sample x_t -> x_t-1
494
+ decoder_latents = self.decoder_scheduler.step(
495
+ noise_pred, t, decoder_latents, prev_timestep=prev_timestep, generator=generator
496
+ ).prev_sample
497
+
498
+ decoder_latents = decoder_latents.clamp(-1, 1)
499
+
500
+ image_small = decoder_latents
501
+
502
+ # done decoder
503
+
504
+ # super res
505
+
506
+ self.super_res_scheduler.set_timesteps(super_res_num_inference_steps, device=device)
507
+ super_res_timesteps_tensor = self.super_res_scheduler.timesteps
508
+
509
+ channels = self.super_res_first.config.in_channels // 2
510
+ height = self.super_res_first.config.sample_size
511
+ width = self.super_res_first.config.sample_size
512
+
513
+ super_res_latents = self.prepare_latents(
514
+ (batch_size, channels, height, width),
515
+ image_small.dtype,
516
+ device,
517
+ generator,
518
+ None,
519
+ self.super_res_scheduler,
520
+ )
521
+
522
+ if device.type == "mps":
523
+ # MPS does not support many interpolations
524
+ image_upscaled = F.interpolate(image_small, size=[height, width])
525
+ else:
526
+ interpolate_antialias = {}
527
+ if "antialias" in inspect.signature(F.interpolate).parameters:
528
+ interpolate_antialias["antialias"] = True
529
+
530
+ image_upscaled = F.interpolate(
531
+ image_small, size=[height, width], mode="bicubic", align_corners=False, **interpolate_antialias
532
+ )
533
+
534
+ for i, t in enumerate(self.progress_bar(super_res_timesteps_tensor)):
535
+ # no classifier free guidance
536
+
537
+ if i == super_res_timesteps_tensor.shape[0] - 1:
538
+ unet = self.super_res_last
539
+ else:
540
+ unet = self.super_res_first
541
+
542
+ latent_model_input = torch.cat([super_res_latents, image_upscaled], dim=1)
543
+
544
+ noise_pred = unet(
545
+ sample=latent_model_input,
546
+ timestep=t,
547
+ ).sample
548
+
549
+ if i + 1 == super_res_timesteps_tensor.shape[0]:
550
+ prev_timestep = None
551
+ else:
552
+ prev_timestep = super_res_timesteps_tensor[i + 1]
553
+
554
+ # compute the previous noisy sample x_t -> x_t-1
555
+ super_res_latents = self.super_res_scheduler.step(
556
+ noise_pred, t, super_res_latents, prev_timestep=prev_timestep, generator=generator
557
+ ).prev_sample
558
+
559
+ image = super_res_latents
560
+ # done super res
561
+
562
+ # post processing
563
+
564
+ image = image * 0.5 + 0.5
565
+ image = image.clamp(0, 1)
566
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
567
+
568
+ if output_type == "pil":
569
+ image = self.numpy_to_pil(image)
570
+
571
+ if not return_dict:
572
+ return (image,)
573
+
574
+ return ImagePipelineOutput(images=image)