Skip to content

Commit 9c24d1f

Browse files
authored
Merge branch 'main' into cache-non-lora-outputs
2 parents 2c47a2f + 55f0b3d commit 9c24d1f

38 files changed

+5694
-52
lines changed

docs/source/en/api/image_processor.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,12 @@ All pipelines with [`VaeImageProcessor`] accept PIL Image, PyTorch tensor, or Nu
2020

2121
[[autodoc]] image_processor.VaeImageProcessor
2222

23+
## InpaintProcessor
24+
25+
The [`InpaintProcessor`] accepts `mask` and `image` inputs and process them together. Optionally, it can accept padding_mask_crop and apply mask overlay.
26+
27+
[[autodoc]] image_processor.InpaintProcessor
28+
2329
## VaeImageProcessorLDM3D
2430

2531
The [`VaeImageProcessorLDM3D`] accepts RGB and depth inputs and returns RGB and depth outputs.

docs/source/en/api/pipelines/cogvideox.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ from diffusers.utils import export_to_video
5050
pipeline_quant_config = PipelineQuantizationConfig(
5151
quant_backend="torchao",
5252
quant_kwargs={"quant_type": "int8wo"},
53-
components_to_quantize=["transformer"]
53+
components_to_quantize="transformer"
5454
)
5555

5656
# fp8 layerwise weight-casting

docs/source/en/api/pipelines/hunyuan_video.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ pipeline_quant_config = PipelineQuantizationConfig(
5454
"bnb_4bit_quant_type": "nf4",
5555
"bnb_4bit_compute_dtype": torch.bfloat16
5656
},
57-
components_to_quantize=["transformer"]
57+
components_to_quantize="transformer"
5858
)
5959

6060
pipeline = HunyuanVideoPipeline.from_pretrained(
@@ -91,7 +91,7 @@ pipeline_quant_config = PipelineQuantizationConfig(
9191
"bnb_4bit_quant_type": "nf4",
9292
"bnb_4bit_compute_dtype": torch.bfloat16
9393
},
94-
components_to_quantize=["transformer"]
94+
components_to_quantize="transformer"
9595
)
9696

9797
pipeline = HunyuanVideoPipeline.from_pretrained(
@@ -139,7 +139,7 @@ export_to_video(video, "output.mp4", fps=15)
139139
"bnb_4bit_quant_type": "nf4",
140140
"bnb_4bit_compute_dtype": torch.bfloat16
141141
},
142-
components_to_quantize=["transformer"]
142+
components_to_quantize="transformer"
143143
)
144144

145145
pipeline = HunyuanVideoPipeline.from_pretrained(

docs/source/en/optimization/memory.md

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -291,13 +291,53 @@ Group offloading moves groups of internal layers ([torch.nn.ModuleList](https://
291291
> [!WARNING]
292292
> Group offloading may not work with all models if the forward implementation contains weight-dependent device casting of inputs because it may clash with group offloading's device casting mechanism.
293293
294-
Call [`~ModelMixin.enable_group_offload`] to enable it for standard Diffusers model components that inherit from [`ModelMixin`]. For other model components that don't inherit from [`ModelMixin`], such as a generic [torch.nn.Module](https://pytorch.org/docs/stable/generated/torch.nn.Module.html), use [`~hooks.apply_group_offloading`] instead.
295-
296-
The `offload_type` parameter can be set to `block_level` or `leaf_level`.
294+
Enable group offloading by configuring the `offload_type` parameter to `block_level` or `leaf_level`.
297295

298296
- `block_level` offloads groups of layers based on the `num_blocks_per_group` parameter. For example, if `num_blocks_per_group=2` on a model with 40 layers, 2 layers are onloaded and offloaded at a time (20 total onloads/offloads). This drastically reduces memory requirements.
299297
- `leaf_level` offloads individual layers at the lowest level and is equivalent to [CPU offloading](#cpu-offloading). But it can be made faster if you use streams without giving up inference speed.
300298

299+
Group offloading is supported for entire pipelines or individual models. Applying group offloading to the entire pipeline is the easiest option while selectively applying it to individual models gives users more flexibility to use different offloading techniques for different models.
300+
301+
<hfoptions id="group-offloading">
302+
<hfoption id="pipeline">
303+
304+
Call [`~DiffusionPipeline.enable_group_offload`] on a pipeline.
305+
306+
```py
307+
import torch
308+
from diffusers import CogVideoXPipeline
309+
from diffusers.hooks import apply_group_offloading
310+
from diffusers.utils import export_to_video
311+
312+
onload_device = torch.device("cuda")
313+
offload_device = torch.device("cpu")
314+
315+
pipeline = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", torch_dtype=torch.bfloat16)
316+
pipeline.enable_group_offload(
317+
onload_device=onload_device,
318+
offload_device=offload_device,
319+
offload_type="leaf_level",
320+
use_stream=True
321+
)
322+
323+
prompt = (
324+
"A panda, dressed in a small, red jacket and a tiny hat, sits on a wooden stool in a serene bamboo forest. "
325+
"The panda's fluffy paws strum a miniature acoustic guitar, producing soft, melodic tunes. Nearby, a few other "
326+
"pandas gather, watching curiously and some clapping in rhythm. Sunlight filters through the tall bamboo, "
327+
"casting a gentle glow on the scene. The panda's face is expressive, showing concentration and joy as it plays. "
328+
"The background includes a small, flowing stream and vibrant green foliage, enhancing the peaceful and magical "
329+
"atmosphere of this unique musical performance."
330+
)
331+
video = pipeline(prompt=prompt, guidance_scale=6, num_inference_steps=50).frames[0]
332+
print(f"Max memory reserved: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
333+
export_to_video(video, "output.mp4", fps=8)
334+
```
335+
336+
</hfoption>
337+
<hfoption id="model">
338+
339+
Call [`~ModelMixin.enable_group_offload`] on standard Diffusers model components that inherit from [`ModelMixin`]. For other model components that don't inherit from [`ModelMixin`], such as a generic [torch.nn.Module](https://pytorch.org/docs/stable/generated/torch.nn.Module.html), use [`~hooks.apply_group_offloading`] instead.
340+
301341
```py
302342
import torch
303343
from diffusers import CogVideoXPipeline
@@ -328,6 +368,9 @@ print(f"Max memory reserved: {torch.cuda.max_memory_allocated() / 1024**3:.2f} G
328368
export_to_video(video, "output.mp4", fps=8)
329369
```
330370

371+
</hfoption>
372+
</hfoptions>
373+
331374
#### CUDA stream
332375

333376
The `use_stream` parameter can be activated for CUDA devices that support asynchronous data transfer streams to reduce overall execution time compared to [CPU offloading](#cpu-offloading). It overlaps data transfer and computation by using layer prefetching. The next layer to be executed is loaded onto the GPU while the current layer is still being executed. It can increase CPU memory significantly so ensure you have 2x the amount of memory as the model size.

docs/source/en/quantization/overview.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,9 @@ Initialize [`~quantizers.PipelineQuantizationConfig`] with the following paramet
3434
> [!TIP]
3535
> These `quant_kwargs` arguments are different for each backend. Refer to the [Quantization API](../api/quantization) docs to view the arguments for each backend.
3636
37-
- `components_to_quantize` specifies which components of the pipeline to quantize. Typically, you should quantize the most compute intensive components like the transformer. The text encoder is another component to consider quantizing if a pipeline has more than one such as [`FluxPipeline`]. The example below quantizes the T5 text encoder in [`FluxPipeline`] while keeping the CLIP model intact.
37+
- `components_to_quantize` specifies which component(s) of the pipeline to quantize. Typically, you should quantize the most compute intensive components like the transformer. The text encoder is another component to consider quantizing if a pipeline has more than one such as [`FluxPipeline`]. The example below quantizes the T5 text encoder in [`FluxPipeline`] while keeping the CLIP model intact.
38+
39+
`components_to_quantize` accepts either a list for multiple models or a string for a single model.
3840

3941
The example below loads the bitsandbytes backend with the following arguments from [`~quantizers.quantization_config.BitsAndBytesConfig`], `load_in_4bit`, `bnb_4bit_quant_type`, and `bnb_4bit_compute_dtype`.
4042

@@ -62,6 +64,7 @@ pipe = DiffusionPipeline.from_pretrained(
6264
image = pipe("photo of a cute dog").images[0]
6365
```
6466

67+
6568
### Advanced quantization
6669

6770
The `quant_mapping` argument provides more options for how to quantize each individual component in a pipeline, like combining different quantization backends.

docs/source/en/using-diffusers/text-img2vid.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ pipeline_quant_config = PipelineQuantizationConfig(
9898
"bnb_4bit_quant_type": "nf4",
9999
"bnb_4bit_compute_dtype": torch.bfloat16
100100
},
101-
components_to_quantize=["transformer"]
101+
components_to_quantize="transformer"
102102
)
103103

104104
pipeline = HunyuanVideoPipeline.from_pretrained(

examples/dreambooth/train_dreambooth_lora_flux_kontext.py

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,9 @@
2929
import numpy as np
3030
import torch
3131
import transformers
32-
from accelerate import Accelerator
32+
from accelerate import Accelerator, DistributedType
3333
from accelerate.logging import get_logger
34+
from accelerate.state import AcceleratorState
3435
from accelerate.utils import DistributedDataParallelKwargs, ProjectConfiguration, set_seed
3536
from huggingface_hub import create_repo, upload_folder
3637
from huggingface_hub.utils import insecure_hashlib
@@ -1222,6 +1223,9 @@ def main(args):
12221223
kwargs_handlers=[kwargs],
12231224
)
12241225

1226+
if accelerator.distributed_type == DistributedType.DEEPSPEED:
1227+
AcceleratorState().deepspeed_plugin.deepspeed_config["train_micro_batch_size_per_gpu"] = args.train_batch_size
1228+
12251229
# Disable AMP for MPS.
12261230
if torch.backends.mps.is_available():
12271231
accelerator.native_amp = False
@@ -1438,17 +1442,20 @@ def save_model_hook(models, weights, output_dir):
14381442
text_encoder_one_lora_layers_to_save = None
14391443
modules_to_save = {}
14401444
for model in models:
1441-
if isinstance(model, type(unwrap_model(transformer))):
1445+
if isinstance(unwrap_model(model), type(unwrap_model(transformer))):
1446+
model = unwrap_model(model)
14421447
transformer_lora_layers_to_save = get_peft_model_state_dict(model)
14431448
modules_to_save["transformer"] = model
1444-
elif isinstance(model, type(unwrap_model(text_encoder_one))):
1449+
elif isinstance(unwrap_model(model), type(unwrap_model(text_encoder_one))):
1450+
model = unwrap_model(model)
14451451
text_encoder_one_lora_layers_to_save = get_peft_model_state_dict(model)
14461452
modules_to_save["text_encoder"] = model
14471453
else:
14481454
raise ValueError(f"unexpected save model: {model.__class__}")
14491455

14501456
# make sure to pop weight so that corresponding model is not saved again
1451-
weights.pop()
1457+
if weights:
1458+
weights.pop()
14521459

14531460
FluxKontextPipeline.save_lora_weights(
14541461
output_dir,
@@ -1461,15 +1468,25 @@ def load_model_hook(models, input_dir):
14611468
transformer_ = None
14621469
text_encoder_one_ = None
14631470

1464-
while len(models) > 0:
1465-
model = models.pop()
1471+
if not accelerator.distributed_type == DistributedType.DEEPSPEED:
1472+
while len(models) > 0:
1473+
model = models.pop()
14661474

1467-
if isinstance(model, type(unwrap_model(transformer))):
1468-
transformer_ = model
1469-
elif isinstance(model, type(unwrap_model(text_encoder_one))):
1470-
text_encoder_one_ = model
1471-
else:
1472-
raise ValueError(f"unexpected save model: {model.__class__}")
1475+
if isinstance(unwrap_model(model), type(unwrap_model(transformer))):
1476+
transformer_ = unwrap_model(model)
1477+
elif isinstance(unwrap_model(model), type(unwrap_model(text_encoder_one))):
1478+
text_encoder_one_ = unwrap_model(model)
1479+
else:
1480+
raise ValueError(f"unexpected save model: {model.__class__}")
1481+
1482+
else:
1483+
transformer_ = FluxTransformer2DModel.from_pretrained(
1484+
args.pretrained_model_name_or_path, subfolder="transformer"
1485+
)
1486+
transformer_.add_adapter(transformer_lora_config)
1487+
text_encoder_one_ = text_encoder_cls_one.from_pretrained(
1488+
args.pretrained_model_name_or_path, subfolder="text_encoder"
1489+
)
14731490

14741491
lora_state_dict = FluxKontextPipeline.lora_state_dict(input_dir)
14751492

@@ -2069,7 +2086,7 @@ def get_sigmas(timesteps, n_dim=4, dtype=torch.float32):
20692086
progress_bar.update(1)
20702087
global_step += 1
20712088

2072-
if accelerator.is_main_process:
2089+
if accelerator.is_main_process or accelerator.distributed_type == DistributedType.DEEPSPEED:
20732090
if global_step % args.checkpointing_steps == 0:
20742091
# _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
20752092
if args.checkpoints_total_limit is not None:

src/diffusers/__init__.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -385,6 +385,10 @@
385385
[
386386
"FluxAutoBlocks",
387387
"FluxModularPipeline",
388+
"QwenImageAutoBlocks",
389+
"QwenImageEditAutoBlocks",
390+
"QwenImageEditModularPipeline",
391+
"QwenImageModularPipeline",
388392
"StableDiffusionXLAutoBlocks",
389393
"StableDiffusionXLModularPipeline",
390394
"WanAutoBlocks",
@@ -506,6 +510,7 @@
506510
"PixArtAlphaPipeline",
507511
"PixArtSigmaPAGPipeline",
508512
"PixArtSigmaPipeline",
513+
"QwenImageControlNetInpaintPipeline",
509514
"QwenImageControlNetPipeline",
510515
"QwenImageEditInpaintPipeline",
511516
"QwenImageEditPipeline",
@@ -1038,6 +1043,10 @@
10381043
from .modular_pipelines import (
10391044
FluxAutoBlocks,
10401045
FluxModularPipeline,
1046+
QwenImageAutoBlocks,
1047+
QwenImageEditAutoBlocks,
1048+
QwenImageEditModularPipeline,
1049+
QwenImageModularPipeline,
10411050
StableDiffusionXLAutoBlocks,
10421051
StableDiffusionXLModularPipeline,
10431052
WanAutoBlocks,
@@ -1155,6 +1164,7 @@
11551164
PixArtAlphaPipeline,
11561165
PixArtSigmaPAGPipeline,
11571166
PixArtSigmaPipeline,
1167+
QwenImageControlNetInpaintPipeline,
11581168
QwenImageControlNetPipeline,
11591169
QwenImageEditInpaintPipeline,
11601170
QwenImageEditPipeline,

src/diffusers/hooks/_helpers.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ def _register_attention_processors_metadata():
108108
from ..models.attention_processor import AttnProcessor2_0
109109
from ..models.transformers.transformer_cogview4 import CogView4AttnProcessor
110110
from ..models.transformers.transformer_flux import FluxAttnProcessor
111+
from ..models.transformers.transformer_qwenimage import QwenDoubleStreamAttnProcessor2_0
111112
from ..models.transformers.transformer_wan import WanAttnProcessor2_0
112113

113114
# AttnProcessor2_0
@@ -140,6 +141,14 @@ def _register_attention_processors_metadata():
140141
metadata=AttentionProcessorMetadata(skip_processor_output_fn=_skip_proc_output_fn_Attention_FluxAttnProcessor),
141142
)
142143

144+
# QwenDoubleStreamAttnProcessor2
145+
AttentionProcessorRegistry.register(
146+
model_class=QwenDoubleStreamAttnProcessor2_0,
147+
metadata=AttentionProcessorMetadata(
148+
skip_processor_output_fn=_skip_proc_output_fn_Attention_QwenDoubleStreamAttnProcessor2_0
149+
),
150+
)
151+
143152

144153
def _register_transformer_blocks_metadata():
145154
from ..models.attention import BasicTransformerBlock
@@ -298,4 +307,5 @@ def _skip_attention___ret___hidden_states___encoder_hidden_states(self, *args, *
298307
_skip_proc_output_fn_Attention_WanAttnProcessor2_0 = _skip_attention___ret___hidden_states
299308
# not sure what this is yet.
300309
_skip_proc_output_fn_Attention_FluxAttnProcessor = _skip_attention___ret___hidden_states
310+
_skip_proc_output_fn_Attention_QwenDoubleStreamAttnProcessor2_0 = _skip_attention___ret___hidden_states
301311
# fmt: on

0 commit comments

Comments
 (0)