Vijish commited on
Commit
222c766
·
verified ·
1 Parent(s): 4bc720f

Upload 2 files

Browse files
lib_layerdiffuse/pipeline_flux_img2img.py ADDED
@@ -0,0 +1,860 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Black Forest Labs 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
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+ from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
21
+
22
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
23
+ from diffusers.loaders import FluxLoraLoaderMixin, FromSingleFileMixin, TextualInversionLoaderMixin
24
+ from diffusers.models.autoencoders import AutoencoderKL
25
+ from diffusers.models.transformers import FluxTransformer2DModel
26
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
27
+ from diffusers.utils import (
28
+ USE_PEFT_BACKEND,
29
+ is_torch_xla_available,
30
+ logging,
31
+ replace_example_docstring,
32
+ scale_lora_layers,
33
+ unscale_lora_layers,
34
+ )
35
+ from diffusers.utils.torch_utils import randn_tensor
36
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
37
+ from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
38
+
39
+
40
+ if is_torch_xla_available():
41
+ import torch_xla.core.xla_model as xm
42
+
43
+ XLA_AVAILABLE = True
44
+ else:
45
+ XLA_AVAILABLE = False
46
+
47
+
48
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
49
+
50
+ EXAMPLE_DOC_STRING = """
51
+ Examples:
52
+ ```py
53
+ >>> import torch
54
+
55
+ >>> from diffusers import FluxImg2ImgPipeline
56
+ >>> from diffusers.utils import load_image
57
+
58
+ >>> device = "cuda"
59
+ >>> pipe = FluxImg2ImgPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16)
60
+ >>> pipe = pipe.to(device)
61
+
62
+ >>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
63
+ >>> init_image = load_image(url).resize((1024, 1024))
64
+
65
+ >>> prompt = "cat wizard, gandalf, lord of the rings, detailed, fantasy, cute, adorable, Pixar, Disney, 8k"
66
+
67
+ >>> images = pipe(
68
+ ... prompt=prompt, image=init_image, num_inference_steps=4, strength=0.95, guidance_scale=0.0
69
+ ... ).images[0]
70
+ ```
71
+ """
72
+
73
+
74
+ # Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift
75
+ def calculate_shift(
76
+ image_seq_len,
77
+ base_seq_len: int = 256,
78
+ max_seq_len: int = 4096,
79
+ base_shift: float = 0.5,
80
+ max_shift: float = 1.16,
81
+ ):
82
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
83
+ b = base_shift - m * base_seq_len
84
+ mu = image_seq_len * m + b
85
+ return mu
86
+
87
+
88
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
89
+ def retrieve_latents(
90
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
91
+ ):
92
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
93
+ return encoder_output.latent_dist.sample(generator)
94
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
95
+ return encoder_output.latent_dist.mode()
96
+ elif hasattr(encoder_output, "latents"):
97
+ return encoder_output.latents
98
+ else:
99
+ raise AttributeError("Could not access latents of provided encoder_output")
100
+
101
+
102
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
103
+ def retrieve_timesteps(
104
+ scheduler,
105
+ num_inference_steps: Optional[int] = None,
106
+ device: Optional[Union[str, torch.device]] = None,
107
+ timesteps: Optional[List[int]] = None,
108
+ sigmas: Optional[List[float]] = None,
109
+ **kwargs,
110
+ ):
111
+ r"""
112
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
113
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
114
+
115
+ Args:
116
+ scheduler (`SchedulerMixin`):
117
+ The scheduler to get timesteps from.
118
+ num_inference_steps (`int`):
119
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
120
+ must be `None`.
121
+ device (`str` or `torch.device`, *optional*):
122
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
123
+ timesteps (`List[int]`, *optional*):
124
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
125
+ `num_inference_steps` and `sigmas` must be `None`.
126
+ sigmas (`List[float]`, *optional*):
127
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
128
+ `num_inference_steps` and `timesteps` must be `None`.
129
+
130
+ Returns:
131
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
132
+ second element is the number of inference steps.
133
+ """
134
+ if timesteps is not None and sigmas is not None:
135
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
136
+ if timesteps is not None:
137
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
138
+ if not accepts_timesteps:
139
+ raise ValueError(
140
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
141
+ f" timestep schedules. Please check whether you are using the correct scheduler."
142
+ )
143
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
144
+ timesteps = scheduler.timesteps
145
+ num_inference_steps = len(timesteps)
146
+ elif sigmas is not None:
147
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
148
+ if not accept_sigmas:
149
+ raise ValueError(
150
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
151
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
152
+ )
153
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
154
+ timesteps = scheduler.timesteps
155
+ num_inference_steps = len(timesteps)
156
+ else:
157
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
158
+ timesteps = scheduler.timesteps
159
+ return timesteps, num_inference_steps
160
+
161
+
162
+ class FluxImg2ImgPipeline(DiffusionPipeline, FluxLoraLoaderMixin, FromSingleFileMixin):
163
+ r"""
164
+ The Flux pipeline for image inpainting.
165
+
166
+ Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
167
+
168
+ Args:
169
+ transformer ([`FluxTransformer2DModel`]):
170
+ Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
171
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
172
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
173
+ vae ([`AutoencoderKL`]):
174
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
175
+ text_encoder ([`CLIPTextModel`]):
176
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
177
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
178
+ text_encoder_2 ([`T5EncoderModel`]):
179
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
180
+ the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
181
+ tokenizer (`CLIPTokenizer`):
182
+ Tokenizer of class
183
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
184
+ tokenizer_2 (`T5TokenizerFast`):
185
+ Second Tokenizer of class
186
+ [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
187
+ """
188
+
189
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
190
+ _optional_components = []
191
+ _callback_tensor_inputs = ["latents", "prompt_embeds"]
192
+
193
+ def __init__(
194
+ self,
195
+ scheduler: FlowMatchEulerDiscreteScheduler,
196
+ vae: AutoencoderKL,
197
+ text_encoder: CLIPTextModel,
198
+ tokenizer: CLIPTokenizer,
199
+ text_encoder_2: T5EncoderModel,
200
+ tokenizer_2: T5TokenizerFast,
201
+ transformer: FluxTransformer2DModel,
202
+ ):
203
+ super().__init__()
204
+
205
+ self.register_modules(
206
+ vae=vae,
207
+ text_encoder=text_encoder,
208
+ text_encoder_2=text_encoder_2,
209
+ tokenizer=tokenizer,
210
+ tokenizer_2=tokenizer_2,
211
+ transformer=transformer,
212
+ scheduler=scheduler,
213
+ )
214
+ self.vae_scale_factor = (
215
+ 2 ** (len(self.vae.config.block_out_channels) - 1) if hasattr(self, "vae") and self.vae is not None else 8
216
+ )
217
+ # Flux latents are turned into 2x2 patches and packed. This means the latent width and height has to be divisible
218
+ # by the patch size. So the vae scale factor is multiplied by the patch size to account for this
219
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor * 2)
220
+ self.tokenizer_max_length = (
221
+ self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
222
+ )
223
+ self.default_sample_size = 128
224
+
225
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._get_t5_prompt_embeds
226
+ def _get_t5_prompt_embeds(
227
+ self,
228
+ prompt: Union[str, List[str]] = None,
229
+ num_images_per_prompt: int = 1,
230
+ max_sequence_length: int = 512,
231
+ device: Optional[torch.device] = None,
232
+ dtype: Optional[torch.dtype] = None,
233
+ ):
234
+ device = device or self._execution_device
235
+ dtype = dtype or self.text_encoder.dtype
236
+
237
+ prompt = [prompt] if isinstance(prompt, str) else prompt
238
+ batch_size = len(prompt)
239
+
240
+ if isinstance(self, TextualInversionLoaderMixin):
241
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer_2)
242
+
243
+ text_inputs = self.tokenizer_2(
244
+ prompt,
245
+ padding="max_length",
246
+ max_length=max_sequence_length,
247
+ truncation=True,
248
+ return_length=False,
249
+ return_overflowing_tokens=False,
250
+ return_tensors="pt",
251
+ )
252
+ text_input_ids = text_inputs.input_ids
253
+ untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
254
+
255
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
256
+ removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
257
+ logger.warning(
258
+ "The following part of your input was truncated because `max_sequence_length` is set to "
259
+ f" {max_sequence_length} tokens: {removed_text}"
260
+ )
261
+
262
+ prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False)[0]
263
+
264
+ dtype = self.text_encoder_2.dtype
265
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
266
+
267
+ _, seq_len, _ = prompt_embeds.shape
268
+
269
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
270
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
271
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
272
+
273
+ return prompt_embeds
274
+
275
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._get_clip_prompt_embeds
276
+ def _get_clip_prompt_embeds(
277
+ self,
278
+ prompt: Union[str, List[str]],
279
+ num_images_per_prompt: int = 1,
280
+ device: Optional[torch.device] = None,
281
+ ):
282
+ device = device or self._execution_device
283
+
284
+ prompt = [prompt] if isinstance(prompt, str) else prompt
285
+ batch_size = len(prompt)
286
+
287
+ if isinstance(self, TextualInversionLoaderMixin):
288
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
289
+
290
+ text_inputs = self.tokenizer(
291
+ prompt,
292
+ padding="max_length",
293
+ max_length=self.tokenizer_max_length,
294
+ truncation=True,
295
+ return_overflowing_tokens=False,
296
+ return_length=False,
297
+ return_tensors="pt",
298
+ )
299
+
300
+ text_input_ids = text_inputs.input_ids
301
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
302
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
303
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
304
+ logger.warning(
305
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
306
+ f" {self.tokenizer_max_length} tokens: {removed_text}"
307
+ )
308
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), output_hidden_states=False)
309
+
310
+ # Use pooled output of CLIPTextModel
311
+ prompt_embeds = prompt_embeds.pooler_output
312
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
313
+
314
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
315
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt)
316
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
317
+
318
+ return prompt_embeds
319
+
320
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.encode_prompt
321
+ def encode_prompt(
322
+ self,
323
+ prompt: Union[str, List[str]],
324
+ prompt_2: Union[str, List[str]],
325
+ device: Optional[torch.device] = None,
326
+ num_images_per_prompt: int = 1,
327
+ prompt_embeds: Optional[torch.FloatTensor] = None,
328
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
329
+ max_sequence_length: int = 512,
330
+ lora_scale: Optional[float] = None,
331
+ ):
332
+ r"""
333
+
334
+ Args:
335
+ prompt (`str` or `List[str]`, *optional*):
336
+ prompt to be encoded
337
+ prompt_2 (`str` or `List[str]`, *optional*):
338
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
339
+ used in all text-encoders
340
+ device: (`torch.device`):
341
+ torch device
342
+ num_images_per_prompt (`int`):
343
+ number of images that should be generated per prompt
344
+ prompt_embeds (`torch.FloatTensor`, *optional*):
345
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
346
+ provided, text embeddings will be generated from `prompt` input argument.
347
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
348
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
349
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
350
+ lora_scale (`float`, *optional*):
351
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
352
+ """
353
+ device = device or self._execution_device
354
+
355
+ # set lora scale so that monkey patched LoRA
356
+ # function of text encoder can correctly access it
357
+ if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
358
+ self._lora_scale = lora_scale
359
+
360
+ # dynamically adjust the LoRA scale
361
+ if self.text_encoder is not None and USE_PEFT_BACKEND:
362
+ scale_lora_layers(self.text_encoder, lora_scale)
363
+ if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
364
+ scale_lora_layers(self.text_encoder_2, lora_scale)
365
+
366
+ prompt = [prompt] if isinstance(prompt, str) else prompt
367
+
368
+ if prompt_embeds is None:
369
+ prompt_2 = prompt_2 or prompt
370
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
371
+
372
+ # We only use the pooled prompt output from the CLIPTextModel
373
+ pooled_prompt_embeds = self._get_clip_prompt_embeds(
374
+ prompt=prompt,
375
+ device=device,
376
+ num_images_per_prompt=num_images_per_prompt,
377
+ )
378
+ prompt_embeds = self._get_t5_prompt_embeds(
379
+ prompt=prompt_2,
380
+ num_images_per_prompt=num_images_per_prompt,
381
+ max_sequence_length=max_sequence_length,
382
+ device=device,
383
+ )
384
+
385
+ if self.text_encoder is not None:
386
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
387
+ # Retrieve the original scale by scaling back the LoRA layers
388
+ unscale_lora_layers(self.text_encoder, lora_scale)
389
+
390
+ if self.text_encoder_2 is not None:
391
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
392
+ # Retrieve the original scale by scaling back the LoRA layers
393
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
394
+
395
+ dtype = self.text_encoder.dtype if self.text_encoder is not None else self.transformer.dtype
396
+ text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
397
+
398
+ return prompt_embeds, pooled_prompt_embeds, text_ids
399
+
400
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_inpaint.StableDiffusion3InpaintPipeline._encode_vae_image
401
+ def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
402
+ if isinstance(generator, list):
403
+ image_latents = [
404
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
405
+ for i in range(image.shape[0])
406
+ ]
407
+ image_latents = torch.cat(image_latents, dim=0)
408
+ else:
409
+ image_latents = retrieve_latents(self.vae.encode(image), generator=generator)
410
+
411
+ image_latents = (image_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
412
+
413
+ return image_latents
414
+
415
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_img2img.StableDiffusion3Img2ImgPipeline.get_timesteps
416
+ def get_timesteps(self, num_inference_steps, strength, device):
417
+ # get the original timestep using init_timestep
418
+ init_timestep = min(num_inference_steps * strength, num_inference_steps)
419
+
420
+ t_start = int(max(num_inference_steps - init_timestep, 0))
421
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
422
+ if hasattr(self.scheduler, "set_begin_index"):
423
+ self.scheduler.set_begin_index(t_start * self.scheduler.order)
424
+
425
+ return timesteps, num_inference_steps - t_start
426
+
427
+ def check_inputs(
428
+ self,
429
+ prompt,
430
+ prompt_2,
431
+ strength,
432
+ height,
433
+ width,
434
+ prompt_embeds=None,
435
+ pooled_prompt_embeds=None,
436
+ callback_on_step_end_tensor_inputs=None,
437
+ max_sequence_length=None,
438
+ ):
439
+ if strength < 0 or strength > 1:
440
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
441
+
442
+ if height % (self.vae_scale_factor * 2) != 0 or width % (self.vae_scale_factor * 2) != 0:
443
+ logger.warning(
444
+ f"`height` and `width` have to be divisible by {self.vae_scale_factor * 2} but are {height} and {width}. Dimensions will be resized accordingly"
445
+ )
446
+
447
+ if callback_on_step_end_tensor_inputs is not None and not all(
448
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
449
+ ):
450
+ raise ValueError(
451
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
452
+ )
453
+
454
+ if prompt is not None and prompt_embeds is not None:
455
+ raise ValueError(
456
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
457
+ " only forward one of the two."
458
+ )
459
+ elif prompt_2 is not None and prompt_embeds is not None:
460
+ raise ValueError(
461
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
462
+ " only forward one of the two."
463
+ )
464
+ elif prompt is None and prompt_embeds is None:
465
+ raise ValueError(
466
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
467
+ )
468
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
469
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
470
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
471
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
472
+
473
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
474
+ raise ValueError(
475
+ "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`."
476
+ )
477
+
478
+ if max_sequence_length is not None and max_sequence_length > 512:
479
+ raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
480
+
481
+ @staticmethod
482
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._prepare_latent_image_ids
483
+ def _prepare_latent_image_ids(batch_size, height, width, device, dtype):
484
+ latent_image_ids = torch.zeros(height, width, 3)
485
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height)[:, None]
486
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width)[None, :]
487
+
488
+ latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
489
+
490
+ latent_image_ids = latent_image_ids.reshape(
491
+ latent_image_id_height * latent_image_id_width, latent_image_id_channels
492
+ )
493
+
494
+ return latent_image_ids.to(device=device, dtype=dtype)
495
+
496
+ @staticmethod
497
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._pack_latents
498
+ def _pack_latents(latents, batch_size, num_channels_latents, height, width):
499
+ latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
500
+ latents = latents.permute(0, 2, 4, 1, 3, 5)
501
+ latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
502
+
503
+ return latents
504
+
505
+ @staticmethod
506
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._unpack_latents
507
+ def _unpack_latents(latents, height, width, vae_scale_factor):
508
+ batch_size, num_patches, channels = latents.shape
509
+
510
+ # VAE applies 8x compression on images but we must also account for packing which requires
511
+ # latent height and width to be divisible by 2.
512
+ height = 2 * (int(height) // (vae_scale_factor * 2))
513
+ width = 2 * (int(width) // (vae_scale_factor * 2))
514
+
515
+ latents = latents.view(batch_size, height // 2, width // 2, channels // 4, 2, 2)
516
+ latents = latents.permute(0, 3, 1, 4, 2, 5)
517
+
518
+ latents = latents.reshape(batch_size, channels // (2 * 2), height, width)
519
+
520
+ return latents
521
+
522
+ def prepare_latents(
523
+ self,
524
+ image,
525
+ timestep,
526
+ batch_size,
527
+ num_channels_latents,
528
+ height,
529
+ width,
530
+ dtype,
531
+ device,
532
+ generator,
533
+ latents=None,
534
+ ):
535
+ if isinstance(generator, list) and len(generator) != batch_size:
536
+ raise ValueError(
537
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
538
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
539
+ )
540
+
541
+ # VAE applies 8x compression on images but we must also account for packing which requires
542
+ # latent height and width to be divisible by 2.
543
+ height = 2 * (int(height) // (self.vae_scale_factor * 2))
544
+ width = 2 * (int(width) // (self.vae_scale_factor * 2))
545
+ shape = (batch_size, num_channels_latents, height, width)
546
+ latent_image_ids = self._prepare_latent_image_ids(batch_size, height // 2, width // 2, device, dtype)
547
+
548
+ # if latents is not None:
549
+ # return latents.to(device=device, dtype=dtype), latent_image_ids
550
+
551
+ image = image.to(device=device, dtype=dtype)
552
+ if latents is not None:
553
+ image_latents = latents.to(device=device, dtype=dtype)
554
+ else:
555
+ image_latents = self._encode_vae_image(image=image, generator=generator)
556
+ if batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] == 0:
557
+ # expand init_latents for batch_size
558
+ additional_image_per_prompt = batch_size // image_latents.shape[0]
559
+ image_latents = torch.cat([image_latents] * additional_image_per_prompt, dim=0)
560
+ elif batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] != 0:
561
+ raise ValueError(
562
+ f"Cannot duplicate `image` of batch size {image_latents.shape[0]} to {batch_size} text prompts."
563
+ )
564
+ else:
565
+ image_latents = torch.cat([image_latents], dim=0)
566
+
567
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
568
+ latents = self.scheduler.scale_noise(image_latents, timestep, noise)
569
+ latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width)
570
+ return latents, latent_image_ids
571
+
572
+ @property
573
+ def guidance_scale(self):
574
+ return self._guidance_scale
575
+
576
+ @property
577
+ def joint_attention_kwargs(self):
578
+ return self._joint_attention_kwargs
579
+
580
+ @property
581
+ def num_timesteps(self):
582
+ return self._num_timesteps
583
+
584
+ @property
585
+ def interrupt(self):
586
+ return self._interrupt
587
+
588
+ @torch.no_grad()
589
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
590
+ def __call__(
591
+ self,
592
+ prompt: Union[str, List[str]] = None,
593
+ prompt_2: Optional[Union[str, List[str]]] = None,
594
+ image: PipelineImageInput = None,
595
+ height: Optional[int] = None,
596
+ width: Optional[int] = None,
597
+ strength: float = 0.6,
598
+ num_inference_steps: int = 28,
599
+ timesteps: List[int] = None,
600
+ guidance_scale: float = 7.0,
601
+ num_images_per_prompt: Optional[int] = 1,
602
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
603
+ latents: Optional[torch.FloatTensor] = None,
604
+ prompt_embeds: Optional[torch.FloatTensor] = None,
605
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
606
+ output_type: Optional[str] = "pil",
607
+ return_dict: bool = True,
608
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
609
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
610
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
611
+ max_sequence_length: int = 512,
612
+ ):
613
+ r"""
614
+ Function invoked when calling the pipeline for generation.
615
+
616
+ Args:
617
+ prompt (`str` or `List[str]`, *optional*):
618
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
619
+ instead.
620
+ prompt_2 (`str` or `List[str]`, *optional*):
621
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
622
+ will be used instead
623
+ image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
624
+ `Image`, numpy array or tensor representing an image batch to be used as the starting point. For both
625
+ numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list
626
+ or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a
627
+ list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image
628
+ latents as `image`, but if passing latents directly it is not encoded again.
629
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
630
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
631
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
632
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
633
+ strength (`float`, *optional*, defaults to 1.0):
634
+ Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
635
+ starting point and more noise is added the higher the `strength`. The number of denoising steps depends
636
+ on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
637
+ process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
638
+ essentially ignores `image`.
639
+ num_inference_steps (`int`, *optional*, defaults to 50):
640
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
641
+ expense of slower inference.
642
+ timesteps (`List[int]`, *optional*):
643
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
644
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
645
+ passed will be used. Must be in descending order.
646
+ guidance_scale (`float`, *optional*, defaults to 7.0):
647
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
648
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
649
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
650
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
651
+ usually at the expense of lower image quality.
652
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
653
+ The number of images to generate per prompt.
654
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
655
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
656
+ to make generation deterministic.
657
+ latents (`torch.FloatTensor`, *optional*):
658
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
659
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
660
+ tensor will ge generated by sampling using the supplied random `generator`.
661
+ prompt_embeds (`torch.FloatTensor`, *optional*):
662
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
663
+ provided, text embeddings will be generated from `prompt` input argument.
664
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
665
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
666
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
667
+ output_type (`str`, *optional*, defaults to `"pil"`):
668
+ The output format of the generate image. Choose between
669
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
670
+ return_dict (`bool`, *optional*, defaults to `True`):
671
+ Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
672
+ joint_attention_kwargs (`dict`, *optional*):
673
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
674
+ `self.processor` in
675
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
676
+ callback_on_step_end (`Callable`, *optional*):
677
+ A function that calls at the end of each denoising steps during the inference. The function is called
678
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
679
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
680
+ `callback_on_step_end_tensor_inputs`.
681
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
682
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
683
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
684
+ `._callback_tensor_inputs` attribute of your pipeline class.
685
+ max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
686
+
687
+ Examples:
688
+
689
+ Returns:
690
+ [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
691
+ is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
692
+ images.
693
+ """
694
+
695
+ height = height or self.default_sample_size * self.vae_scale_factor
696
+ width = width or self.default_sample_size * self.vae_scale_factor
697
+
698
+ # 1. Check inputs. Raise error if not correct
699
+ self.check_inputs(
700
+ prompt,
701
+ prompt_2,
702
+ strength,
703
+ height,
704
+ width,
705
+ prompt_embeds=prompt_embeds,
706
+ pooled_prompt_embeds=pooled_prompt_embeds,
707
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
708
+ max_sequence_length=max_sequence_length,
709
+ )
710
+
711
+ self._guidance_scale = guidance_scale
712
+ self._joint_attention_kwargs = joint_attention_kwargs
713
+ self._interrupt = False
714
+
715
+ # 2. Preprocess image
716
+ init_image = self.image_processor.preprocess(image, height=height, width=width)
717
+ init_image = init_image.to(dtype=torch.float32)
718
+
719
+ # 3. Define call parameters
720
+ if prompt is not None and isinstance(prompt, str):
721
+ batch_size = 1
722
+ elif prompt is not None and isinstance(prompt, list):
723
+ batch_size = len(prompt)
724
+ else:
725
+ batch_size = prompt_embeds.shape[0]
726
+
727
+ device = self._execution_device
728
+
729
+ lora_scale = (
730
+ self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
731
+ )
732
+ (
733
+ prompt_embeds,
734
+ pooled_prompt_embeds,
735
+ text_ids,
736
+ ) = self.encode_prompt(
737
+ prompt=prompt,
738
+ prompt_2=prompt_2,
739
+ prompt_embeds=prompt_embeds,
740
+ pooled_prompt_embeds=pooled_prompt_embeds,
741
+ device=device,
742
+ num_images_per_prompt=num_images_per_prompt,
743
+ max_sequence_length=max_sequence_length,
744
+ lora_scale=lora_scale,
745
+ )
746
+
747
+ # 4.Prepare timesteps
748
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
749
+ image_seq_len = (int(height) // self.vae_scale_factor // 2) * (int(width) // self.vae_scale_factor // 2)
750
+ mu = calculate_shift(
751
+ image_seq_len,
752
+ self.scheduler.config.base_image_seq_len,
753
+ self.scheduler.config.max_image_seq_len,
754
+ self.scheduler.config.base_shift,
755
+ self.scheduler.config.max_shift,
756
+ )
757
+ timesteps, num_inference_steps = retrieve_timesteps(
758
+ self.scheduler,
759
+ num_inference_steps,
760
+ device,
761
+ timesteps,
762
+ sigmas,
763
+ mu=mu,
764
+ )
765
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
766
+
767
+ if num_inference_steps < 1:
768
+ raise ValueError(
769
+ f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline"
770
+ f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline."
771
+ )
772
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
773
+
774
+ # 5. Prepare latent variables
775
+ num_channels_latents = self.transformer.config.in_channels // 4
776
+
777
+ latents, latent_image_ids = self.prepare_latents(
778
+ init_image,
779
+ latent_timestep,
780
+ batch_size * num_images_per_prompt,
781
+ num_channels_latents,
782
+ height,
783
+ width,
784
+ prompt_embeds.dtype,
785
+ device,
786
+ generator,
787
+ latents,
788
+ )
789
+
790
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
791
+ self._num_timesteps = len(timesteps)
792
+
793
+ # handle guidance
794
+ if self.transformer.config.guidance_embeds:
795
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
796
+ guidance = guidance.expand(latents.shape[0])
797
+ else:
798
+ guidance = None
799
+
800
+ # 6. Denoising loop
801
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
802
+ for i, t in enumerate(timesteps):
803
+ if self.interrupt:
804
+ continue
805
+
806
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
807
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
808
+ noise_pred = self.transformer(
809
+ hidden_states=latents,
810
+ timestep=timestep / 1000,
811
+ guidance=guidance,
812
+ pooled_projections=pooled_prompt_embeds,
813
+ encoder_hidden_states=prompt_embeds,
814
+ txt_ids=text_ids,
815
+ img_ids=latent_image_ids,
816
+ joint_attention_kwargs=self.joint_attention_kwargs,
817
+ return_dict=False,
818
+ )[0]
819
+
820
+ # compute the previous noisy sample x_t -> x_t-1
821
+ latents_dtype = latents.dtype
822
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
823
+
824
+ if latents.dtype != latents_dtype:
825
+ if torch.backends.mps.is_available():
826
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
827
+ latents = latents.to(latents_dtype)
828
+
829
+ if callback_on_step_end is not None:
830
+ callback_kwargs = {}
831
+ for k in callback_on_step_end_tensor_inputs:
832
+ callback_kwargs[k] = locals()[k]
833
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
834
+
835
+ latents = callback_outputs.pop("latents", latents)
836
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
837
+
838
+ # call the callback, if provided
839
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
840
+ progress_bar.update()
841
+
842
+ if XLA_AVAILABLE:
843
+ xm.mark_step()
844
+
845
+ if output_type == "latent":
846
+ image = latents
847
+
848
+ else:
849
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
850
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
851
+ image = self.vae.decode(latents, return_dict=False)[0]
852
+ image = self.image_processor.postprocess(image, output_type=output_type)
853
+
854
+ # Offload all models
855
+ self.maybe_free_model_hooks()
856
+
857
+ if not return_dict:
858
+ return (image,)
859
+
860
+ return FluxPipelineOutput(images=image)
lib_layerdiffuse/vae.py ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ import torch
3
+ import cv2
4
+ import numpy as np
5
+ import safetensors.torch as sf
6
+ from accelerate.logging import get_logger
7
+ logger = get_logger(__name__, log_level="INFO")
8
+
9
+ from tqdm import tqdm
10
+ from typing import Optional, Tuple
11
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
12
+ from diffusers.models.modeling_utils import ModelMixin
13
+ from diffusers.models.unets.unet_2d_blocks import UNetMidBlock2D, get_down_block, get_up_block
14
+ from diffusers.models.autoencoders.vae import DiagonalGaussianDistribution
15
+
16
+ import torchvision
17
+
18
+
19
+ def zero_module(module):
20
+ """
21
+ Zero out the parameters of a module and return it.
22
+ """
23
+ for p in module.parameters():
24
+ p.detach().zero_()
25
+ return module
26
+
27
+
28
+ class LatentTransparencyOffsetEncoder(torch.nn.Module):
29
+ def __init__(self, latent_c=4, *args, **kwargs):
30
+ super().__init__(*args, **kwargs)
31
+ self.blocks = torch.nn.Sequential(
32
+ torch.nn.Conv2d(4, 32, kernel_size=3, padding=1, stride=1),
33
+ nn.SiLU(),
34
+ torch.nn.Conv2d(32, 32, kernel_size=3, padding=1, stride=1),
35
+ nn.SiLU(),
36
+ torch.nn.Conv2d(32, 64, kernel_size=3, padding=1, stride=2),
37
+ nn.SiLU(),
38
+ torch.nn.Conv2d(64, 64, kernel_size=3, padding=1, stride=1),
39
+ nn.SiLU(),
40
+ torch.nn.Conv2d(64, 128, kernel_size=3, padding=1, stride=2),
41
+ nn.SiLU(),
42
+ torch.nn.Conv2d(128, 128, kernel_size=3, padding=1, stride=1),
43
+ nn.SiLU(),
44
+ torch.nn.Conv2d(128, 256, kernel_size=3, padding=1, stride=2),
45
+ nn.SiLU(),
46
+ torch.nn.Conv2d(256, 256, kernel_size=3, padding=1, stride=1),
47
+ nn.SiLU(),
48
+ zero_module(torch.nn.Conv2d(256, latent_c, kernel_size=3, padding=1, stride=1)),
49
+ )
50
+
51
+ def __call__(self, x):
52
+ return self.blocks(x)
53
+
54
+
55
+ # 1024 * 1024 * 3 -> 16 * 16 * 512 -> 1024 * 1024 * 3
56
+ class UNet1024(ModelMixin, ConfigMixin):
57
+ @register_to_config
58
+ def __init__(
59
+ self,
60
+ in_channels: int = 3,
61
+ out_channels: int = 3,
62
+ down_block_types: Tuple[str] = ("DownBlock2D", "DownBlock2D", "DownBlock2D", "DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D"),
63
+ up_block_types: Tuple[str] = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D", "UpBlock2D", "UpBlock2D", "UpBlock2D"),
64
+ block_out_channels: Tuple[int] = (32, 32, 64, 128, 256, 512, 512),
65
+ layers_per_block: int = 2,
66
+ mid_block_scale_factor: float = 1,
67
+ downsample_padding: int = 1,
68
+ downsample_type: str = "conv",
69
+ upsample_type: str = "conv",
70
+ dropout: float = 0.0,
71
+ act_fn: str = "silu",
72
+ attention_head_dim: Optional[int] = 8,
73
+ norm_num_groups: int = 4,
74
+ norm_eps: float = 1e-5,
75
+ latent_c: int = 4,
76
+ ):
77
+ super().__init__()
78
+
79
+ # input
80
+ self.conv_in = nn.Conv2d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1))
81
+ self.latent_conv_in = zero_module(nn.Conv2d(latent_c, block_out_channels[2], kernel_size=1))
82
+
83
+ self.down_blocks = nn.ModuleList([])
84
+ self.mid_block = None
85
+ self.up_blocks = nn.ModuleList([])
86
+
87
+ # down
88
+ output_channel = block_out_channels[0]
89
+ for i, down_block_type in enumerate(down_block_types):
90
+ input_channel = output_channel
91
+ output_channel = block_out_channels[i]
92
+ is_final_block = i == len(block_out_channels) - 1
93
+
94
+ down_block = get_down_block(
95
+ down_block_type,
96
+ num_layers=layers_per_block,
97
+ in_channels=input_channel,
98
+ out_channels=output_channel,
99
+ temb_channels=None,
100
+ add_downsample=not is_final_block,
101
+ resnet_eps=norm_eps,
102
+ resnet_act_fn=act_fn,
103
+ resnet_groups=norm_num_groups,
104
+ attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel,
105
+ downsample_padding=downsample_padding,
106
+ resnet_time_scale_shift="default",
107
+ downsample_type=downsample_type,
108
+ dropout=dropout,
109
+ )
110
+ self.down_blocks.append(down_block)
111
+
112
+ # mid
113
+ self.mid_block = UNetMidBlock2D(
114
+ in_channels=block_out_channels[-1],
115
+ temb_channels=None,
116
+ dropout=dropout,
117
+ resnet_eps=norm_eps,
118
+ resnet_act_fn=act_fn,
119
+ output_scale_factor=mid_block_scale_factor,
120
+ resnet_time_scale_shift="default",
121
+ attention_head_dim=attention_head_dim if attention_head_dim is not None else block_out_channels[-1],
122
+ resnet_groups=norm_num_groups,
123
+ attn_groups=None,
124
+ add_attention=True,
125
+ )
126
+
127
+ # up
128
+ reversed_block_out_channels = list(reversed(block_out_channels))
129
+ output_channel = reversed_block_out_channels[0]
130
+ for i, up_block_type in enumerate(up_block_types):
131
+ prev_output_channel = output_channel
132
+ output_channel = reversed_block_out_channels[i]
133
+ input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
134
+
135
+ is_final_block = i == len(block_out_channels) - 1
136
+
137
+ up_block = get_up_block(
138
+ up_block_type,
139
+ num_layers=layers_per_block + 1,
140
+ in_channels=input_channel,
141
+ out_channels=output_channel,
142
+ prev_output_channel=prev_output_channel,
143
+ temb_channels=None,
144
+ add_upsample=not is_final_block,
145
+ resnet_eps=norm_eps,
146
+ resnet_act_fn=act_fn,
147
+ resnet_groups=norm_num_groups,
148
+ attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel,
149
+ resnet_time_scale_shift="default",
150
+ upsample_type=upsample_type,
151
+ dropout=dropout,
152
+ )
153
+ self.up_blocks.append(up_block)
154
+ prev_output_channel = output_channel
155
+
156
+ # out
157
+ self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps)
158
+ self.conv_act = nn.SiLU()
159
+ self.conv_out = nn.Conv2d(block_out_channels[0], out_channels, kernel_size=3, padding=1)
160
+
161
+ def forward(self, x, latent):
162
+ sample_latent = self.latent_conv_in(latent)
163
+ sample = self.conv_in(x)
164
+ emb = None
165
+
166
+ down_block_res_samples = (sample,)
167
+ for i, downsample_block in enumerate(self.down_blocks):
168
+ if i == 3:
169
+ sample = sample + sample_latent
170
+
171
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
172
+ down_block_res_samples += res_samples
173
+
174
+ sample = self.mid_block(sample, emb)
175
+
176
+ for upsample_block in self.up_blocks:
177
+ res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
178
+ down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
179
+ sample = upsample_block(sample, res_samples, emb)
180
+
181
+ sample = self.conv_norm_out(sample)
182
+ sample = self.conv_act(sample)
183
+ sample = self.conv_out(sample)
184
+ return sample
185
+
186
+
187
+ def checkerboard(shape):
188
+ return np.indices(shape).sum(axis=0) % 2
189
+
190
+
191
+ def build_alpha_pyramid(color, alpha, dk=1.2):
192
+ # Written by lvmin at Stanford
193
+ # Massive iterative Gaussian filters are mathematically consistent to pyramid.
194
+
195
+ pyramid = []
196
+ current_premultiplied_color = color * alpha
197
+ current_alpha = alpha
198
+
199
+ while True:
200
+ pyramid.append((current_premultiplied_color, current_alpha))
201
+
202
+ H, W, C = current_alpha.shape
203
+ if min(H, W) == 1:
204
+ break
205
+
206
+ current_premultiplied_color = cv2.resize(current_premultiplied_color, (int(W / dk), int(H / dk)), interpolation=cv2.INTER_AREA)
207
+ current_alpha = cv2.resize(current_alpha, (int(W / dk), int(H / dk)), interpolation=cv2.INTER_AREA)[:, :, None]
208
+ return pyramid[::-1]
209
+
210
+
211
+ def pad_rgb(np_rgba_hwc_uint8):
212
+ # Written by lvmin at Stanford
213
+ # Massive iterative Gaussian filters are mathematically consistent to pyramid.
214
+
215
+ np_rgba_hwc = np_rgba_hwc_uint8.astype(np.float32) #/ 255.0
216
+ pyramid = build_alpha_pyramid(color=np_rgba_hwc[..., :3], alpha=np_rgba_hwc[..., 3:])
217
+
218
+ top_c, top_a = pyramid[0]
219
+ fg = np.sum(top_c, axis=(0, 1), keepdims=True) / np.sum(top_a, axis=(0, 1), keepdims=True).clip(1e-8, 1e32)
220
+
221
+ for layer_c, layer_a in pyramid:
222
+ layer_h, layer_w, _ = layer_c.shape
223
+ fg = cv2.resize(fg, (layer_w, layer_h), interpolation=cv2.INTER_LINEAR)
224
+ fg = layer_c + fg * (1.0 - layer_a)
225
+
226
+ return fg
227
+
228
+
229
+ def dist_sample_deterministic(dist: DiagonalGaussianDistribution, perturbation: torch.Tensor):
230
+ # Modified from diffusers.models.autoencoders.vae.DiagonalGaussianDistribution.sample()
231
+ x = dist.mean + dist.std * perturbation.to(dist.std)
232
+ return x
233
+
234
+ class TransparentVAE(torch.nn.Module):
235
+ def __init__(self, sd_vae, dtype=torch.float16, encoder_file=None, decoder_file=None, alpha=300.0, latent_c=16, *args, **kwargs):
236
+ super().__init__(*args, **kwargs)
237
+ self.dtype = dtype
238
+
239
+ self.sd_vae = sd_vae
240
+ self.sd_vae.to(dtype=self.dtype)
241
+ self.sd_vae.requires_grad_(False)
242
+
243
+ self.encoder = LatentTransparencyOffsetEncoder(latent_c=latent_c)
244
+ if encoder_file is not None:
245
+ temp = sf.load_file(encoder_file)
246
+ # del temp['blocks.16.weight']
247
+ # del temp['blocks.16.bias']
248
+ self.encoder.load_state_dict(temp, strict=True)
249
+ del temp
250
+ self.encoder.to(dtype=self.dtype)
251
+ self.alpha = alpha
252
+
253
+ self.decoder = UNet1024(in_channels=3, out_channels=4, latent_c=latent_c)
254
+ if decoder_file is not None:
255
+ temp = sf.load_file(decoder_file)
256
+ # del temp['latent_conv_in.weight']
257
+ # del temp['latent_conv_in.bias']
258
+ self.decoder.load_state_dict(temp, strict=True)
259
+ del temp
260
+ self.decoder.to(dtype=self.dtype)
261
+ self.latent_c = latent_c
262
+
263
+
264
+ def sd_decode(self, latent):
265
+ return self.sd_vae.decode(latent)
266
+
267
+ def decode(self, latent, aug=True):
268
+ origin_pixel = self.sd_vae.decode(latent).sample
269
+ origin_pixel = (origin_pixel * 0.5 + 0.5)
270
+ if not aug:
271
+ y = self.decoder(origin_pixel.to(self.dtype), latent.to(self.dtype))
272
+ return origin_pixel, y
273
+ list_y = []
274
+ for i in range(int(latent.shape[0])):
275
+ y = self.estimate_augmented(origin_pixel[i:i + 1].to(self.dtype), latent[i:i + 1].to(self.dtype))
276
+ list_y.append(y)
277
+ y = torch.concat(list_y, dim=0)
278
+ return origin_pixel, y
279
+
280
+ def encode(self, img_rgba, img_rgb, padded_img_rgb, use_offset=True):
281
+ a_bchw_01 = img_rgba[:, 3:, :, :]
282
+ vae_feed = img_rgb.to(device=self.sd_vae.device, dtype=self.sd_vae.dtype)
283
+ latent_dist = self.sd_vae.encode(vae_feed).latent_dist
284
+ offset_feed = torch.cat([padded_img_rgb, a_bchw_01], dim=1).to(device=self.sd_vae.device, dtype=self.dtype)
285
+ offset = self.encoder(offset_feed) * self.alpha
286
+ if use_offset:
287
+ latent = dist_sample_deterministic(dist=latent_dist, perturbation=offset)
288
+ latent = self.sd_vae.config.scaling_factor * (latent - self.sd_vae.config.shift_factor)
289
+ else:
290
+ latent = latent_dist.sample()
291
+ latent = self.sd_vae.config.scaling_factor * (latent - self.sd_vae.config.shift_factor)
292
+ return latent
293
+
294
+ def forward(self, img_rgba, img_rgb, padded_img_rgb, use_offset=True):
295
+ return self.decode(self.encode(img_rgba, img_rgb, padded_img_rgb, use_offset))
296
+
297
+ @property
298
+ def device(self):
299
+ return next(self.parameters()).device
300
+
301
+ @torch.no_grad()
302
+ def estimate_augmented(self, pixel, latent):
303
+ args = [
304
+ [False, 0], [False, 1], [False, 2], [False, 3], [True, 0], [True, 1], [True, 2], [True, 3],
305
+ ]
306
+
307
+ result = []
308
+
309
+ for flip, rok in tqdm(args):
310
+ feed_pixel = pixel.clone()
311
+ feed_latent = latent.clone()
312
+
313
+ if flip:
314
+ feed_pixel = torch.flip(feed_pixel, dims=(3,))
315
+ feed_latent = torch.flip(feed_latent, dims=(3,))
316
+
317
+ feed_pixel = torch.rot90(feed_pixel, k=rok, dims=(2, 3))
318
+ feed_latent = torch.rot90(feed_latent, k=rok, dims=(2, 3))
319
+
320
+ eps = self.decoder(feed_pixel, feed_latent).clip(0, 1)
321
+ eps = torch.rot90(eps, k=-rok, dims=(2, 3))
322
+
323
+ if flip:
324
+ eps = torch.flip(eps, dims=(3,))
325
+
326
+ result += [eps]
327
+
328
+ result = torch.stack(result, dim=0)
329
+ median = torch.median(result, dim=0).values
330
+ return median
331
+
332
+
333
+
334
+ class TransparentVAEDecoder(torch.nn.Module):
335
+ def __init__(self, filename, dtype=torch.float16, *args, **kwargs):
336
+ super().__init__(*args, **kwargs)
337
+ sd = sf.load_file(filename)
338
+ model = UNet1024(in_channels=3, out_channels=4)
339
+ model.load_state_dict(sd, strict=True)
340
+ model.to(dtype=dtype)
341
+ model.eval()
342
+ self.model = model
343
+ self.dtype = dtype
344
+ return
345
+
346
+ @torch.no_grad()
347
+ def estimate_single_pass(self, pixel, latent):
348
+ y = self.model(pixel, latent)
349
+ return y
350
+
351
+ @torch.no_grad()
352
+ def estimate_augmented(self, pixel, latent):
353
+ args = [
354
+ [False, 0], [False, 1], [False, 2], [False, 3], [True, 0], [True, 1], [True, 2], [True, 3],
355
+ ]
356
+
357
+ result = []
358
+
359
+ for flip, rok in tqdm(args):
360
+ feed_pixel = pixel.clone()
361
+ feed_latent = latent.clone()
362
+
363
+ if flip:
364
+ feed_pixel = torch.flip(feed_pixel, dims=(3,))
365
+ feed_latent = torch.flip(feed_latent, dims=(3,))
366
+
367
+ feed_pixel = torch.rot90(feed_pixel, k=rok, dims=(2, 3))
368
+ feed_latent = torch.rot90(feed_latent, k=rok, dims=(2, 3))
369
+
370
+ eps = self.estimate_single_pass(feed_pixel, feed_latent).clip(0, 1)
371
+ eps = torch.rot90(eps, k=-rok, dims=(2, 3))
372
+
373
+ if flip:
374
+ eps = torch.flip(eps, dims=(3,))
375
+
376
+ result += [eps]
377
+
378
+ result = torch.stack(result, dim=0)
379
+ median = torch.median(result, dim=0).values
380
+ return median
381
+
382
+ @torch.no_grad()
383
+ def forward(self, sd_vae, latent):
384
+ pixel = sd_vae.decode(latent).sample
385
+ pixel = (pixel * 0.5 + 0.5).clip(0, 1).to(self.dtype)
386
+ latent = latent.to(self.dtype)
387
+ result_list = []
388
+ vis_list = []
389
+
390
+ for i in range(int(latent.shape[0])):
391
+ y = self.estimate_augmented(pixel[i:i + 1], latent[i:i + 1])
392
+
393
+ y = y.clip(0, 1).movedim(1, -1)
394
+ alpha = y[..., :1]
395
+ fg = y[..., 1:]
396
+
397
+ B, H, W, C = fg.shape
398
+ cb = checkerboard(shape=(H // 64, W // 64))
399
+ cb = cv2.resize(cb, (W, H), interpolation=cv2.INTER_NEAREST)
400
+ cb = (0.5 + (cb - 0.5) * 0.1)[None, ..., None]
401
+ cb = torch.from_numpy(cb).to(fg)
402
+
403
+ vis = (fg * alpha + cb * (1 - alpha))[0]
404
+ vis = (vis * 255.0).detach().cpu().float().numpy().clip(0, 255).astype(np.uint8)
405
+ vis_list.append(vis)
406
+
407
+ png = torch.cat([fg, alpha], dim=3)[0]
408
+ png = (png * 255.0).detach().cpu().float().numpy().clip(0, 255).astype(np.uint8)
409
+ result_list.append(png)
410
+
411
+ return result_list, vis_list
412
+
413
+
414
+ class TransparentVAEEncoder(torch.nn.Module):
415
+ def __init__(self, filename, dtype=torch.float16, alpha=300.0, *args, **kwargs):
416
+ super().__init__(*args, **kwargs)
417
+ sd = sf.load_file(filename)
418
+ self.dtype = dtype
419
+
420
+ model = LatentTransparencyOffsetEncoder()
421
+ model.load_state_dict(sd, strict=True)
422
+ model.to(dtype=self.dtype)
423
+ model.eval()
424
+
425
+ self.model = model
426
+
427
+ # similar to LoRA's alpha to avoid initial zero-initialized outputs being too small
428
+ self.alpha = alpha
429
+ return
430
+
431
+ @torch.no_grad()
432
+ def forward(self, sd_vae, list_of_np_rgba_hwc_uint8, use_offset=True):
433
+ list_of_np_rgb_padded = [pad_rgb(x) for x in list_of_np_rgba_hwc_uint8]
434
+ rgb_padded_bchw_01 = torch.from_numpy(np.stack(list_of_np_rgb_padded, axis=0)).float().movedim(-1, 1)
435
+ rgba_bchw_01 = torch.from_numpy(np.stack(list_of_np_rgba_hwc_uint8, axis=0)).float().movedim(-1, 1) / 255.0
436
+ rgb_bchw_01 = rgba_bchw_01[:, :3, :, :]
437
+ a_bchw_01 = rgba_bchw_01[:, 3:, :, :]
438
+ vae_feed = (rgb_bchw_01 * 2.0 - 1.0) * a_bchw_01
439
+ vae_feed = vae_feed.to(device=sd_vae.device, dtype=sd_vae.dtype)
440
+ latent_dist = sd_vae.encode(vae_feed).latent_dist
441
+ offset_feed = torch.cat([a_bchw_01, rgb_padded_bchw_01], dim=1).to(device=sd_vae.device, dtype=self.dtype)
442
+ offset = self.model(offset_feed) * self.alpha
443
+ if use_offset:
444
+ latent = dist_sample_deterministic(dist=latent_dist, perturbation=offset)
445
+ else:
446
+ latent = latent_dist.sample()
447
+ return latent