Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion docs/source/en/api/modular_diffusers/pipeline_blocks.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,8 @@

## ConditionalPipelineBlocks

[[autodoc]] diffusers.modular_pipelines.modular_pipeline.ConditionalPipelineBlocks
[[autodoc]] diffusers.modular_pipelines.modular_pipeline.ConditionalPipelineBlocks

## insert_step_callback

[[autodoc]] diffusers.modular_pipelines.step_callback.insert_step_callback
9 changes: 4 additions & 5 deletions docs/source/en/api/pipelines/flux3.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,13 +209,12 @@ print(t2i.blocks.doc)

## Per-step callbacks

To use an existing callback function, insert a block into the denoising loop. The [callbacks guide](../../using-diffusers/callback#modular-pipelines) has a simple example with the `CallbackOnStepEnd` block and the `walk_denoise_loops` helper:
To use an existing callback function, call [`~modular_pipelines.insert_step_callback`] on the pipeline. See the [callbacks guide](../../using-diffusers/callback#modular-pipelines) for details:

```python
blocks = Flux3AutoBlocks() # or Flux3DistilledAutoBlocks
for loop in walk_denoise_loops(blocks):
loop.sub_blocks["callback"] = CallbackOnStepEnd()
pipe = blocks.init_pipeline("black-forest-labs/flux-3-image-klein-base")
from diffusers.modular_pipelines import insert_step_callback

insert_step_callback(pipe)

image = pipe(prompt=caption, callback_on_step_end=my_callback, output="images")[0]
```
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@ If you are familiar with [`DiffusionPipeline`] and are working with a [`ModularP
- **[`ModularPipeline`] reads a different index, `modular_model_index.json`**, but it also works with a repository that only has a `model_index.json`, as long as the model has a modular pipeline. The reverse is not true: [`DiffusionPipeline`] and the `AutoPipeline` classes don't work with a repository that only has a `modular_model_index.json`.
- **A call returns the pipeline state**, which holds the intermediate values too (`prompt_embeds`, `latents`, ...). Ask for what you need with the `output` argument, `output="images"` or `output=["images", "latents"]`, or read an attribute of the state, as in the [quickstart](./quickstart#run-a-pipeline). See [States](./modular_diffusers_states).
- **Classifier-free guidance is supported in the `guider` component**, not a `guidance_scale` call argument: `pipe.update_components(guider=ClassifierFreeGuidance(guidance_scale=5.0))`. See the [guiders guide](../using-diffusers/guiders).
- **There is no `callback_on_step_end`**; however, you can insert a block into the denoising loop to use your existing callback functions. See [Modular pipelines](../using-diffusers/callback#modular-pipelines) in the callbacks guide.
- **There is no `callback_on_step_end`**; however, [`~modular_pipelines.insert_step_callback`] adds it to a pipeline so you can use your existing callback functions. See [Modular pipelines](../using-diffusers/callback#modular-pipelines) in the callbacks guide.
- **The pipeline is a graph of blocks** that you can change (pop, insert, replace) before building it with [`~ModularPipelineBlocks.init_pipeline`]; `pipe.blocks` returns a copy, so edit the blocks first. See [Compose new workflows](./quickstart#compose-new-workflows).
- **Offloading is handled by a [`ComponentsManager`]**, which can serve several pipelines that share components. See the [ComponentsManager guide](./components_manager#offloading).
83 changes: 39 additions & 44 deletions docs/source/en/using-diffusers/callback.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,53 +140,15 @@ image = pipeline(

## Modular pipelines

Modular pipelines don't carry the `callback_on_step_end` and `interrupt` mechanism. It will come with first-class streaming support instead: [huggingface/diffusers#14159](https://github.com/huggingface/diffusers/pull/14159), not merged yet, adds `pipe.stream()`, which yields the pipeline state at every denoising step and ends the run when you stop iterating. For now, to reuse your existing callback functions, insert a block into the denoising loop: it receives the loop's `BlockState` with the step index and timestep, and can read or edit `latents`.

> [!TIP]
> Edit the blocks *before* [`~modular_pipelines.ModularPipelineBlocks.init_pipeline`]: `pipe.blocks` returns a copy, so changing it after the pipeline exists has no effect.

The block below takes the callback as a pipeline input and calls it with the same signature as above: the pipeline, the step index, the timestep and a dict of tensors, whose returned values are written back. `walk_denoise_loops` finds every denoising loop in the blocks, whichever workflow it belongs to, so the same snippet works for any modular pipeline.
Modular pipelines don't carry the `callback_on_step_end` and `interrupt` mechanism. It will come with first-class streaming support instead: [huggingface/diffusers#14159](https://github.com/huggingface/diffusers/pull/14159), not merged yet, adds `pipe.stream()`, which yields the pipeline state at every denoising step and ends the run when you stop iterating. For now, to reuse your existing callback functions, call [`~modular_pipelines.insert_step_callback`] on the pipeline. It adds a block to the end of every denoising loop that calls your function.

```py
from typing import Callable

import torch
from diffusers import ModularPipeline
from diffusers.modular_pipelines import InputParam, LoopSequentialPipelineBlocks, ModularPipelineBlocks


class CallbackOnStepEnd(ModularPipelineBlocks):
@property
def inputs(self):
return [
InputParam(
"callback_on_step_end",
type_hint=Callable,
description="Called after each scheduler step as `callback(pipe, i, t, {'latents': ...})`; the dict it returns is written back.",
),
InputParam("latents", required=True),
]

def __call__(self, components, block_state, i, t):
if block_state.callback_on_step_end is not None:
outputs = block_state.callback_on_step_end(components, i, t, {"latents": block_state.latents})
block_state.latents = outputs.get("latents", block_state.latents)
return components, block_state


def walk_denoise_loops(block):
"""Every denoising loop in the blocks, whichever workflow it belongs to."""
if isinstance(block, LoopSequentialPipelineBlocks) and "denoiser" in block.sub_blocks:
yield block
for sub in getattr(block, "sub_blocks", {}).values():
yield from walk_denoise_loops(sub)


repo_id = "stabilityai/stable-diffusion-xl-base-1.0"
blocks = ModularPipeline.from_pretrained(repo_id).blocks
for loop in walk_denoise_loops(blocks):
loop.sub_blocks["callback"] = CallbackOnStepEnd() # appended after the last step of the loop
pipe = blocks.init_pipeline(repo_id)
from diffusers.modular_pipelines import insert_step_callback

pipe = ModularPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0")
insert_step_callback(pipe)
pipe.load_components(dtype=torch.float16)
pipe.to("cuda")
```
Expand All @@ -197,6 +159,39 @@ pipe.to("cuda")
image = pipe(prompt="A croissant shaped like a cute bear.", callback_on_step_end=decode_tensors, output="images")[0]
```

The callback is called with the same signature as above: the pipeline, the step index, the timestep and `callback_kwargs`. There are two differences from a [`DiffusionPipeline`]:

- There is no `callback_on_step_end_tensor_inputs`. `callback_kwargs` holds every value of the denoising loop, such as `latents`, and the values the callback returns are written back.
- A modular pipeline has no `num_timesteps` attribute, so the number of steps is in `callback_kwargs["num_timesteps"]`.

[Early stopping](#early-stopping) works differently: a block cannot skip the loop it runs in, so setting `_interrupt` has no effect. Raise from the callback instead: the exception propagates out of `pipe(...)` (no image is decoded), and the pipeline stays usable afterwards.

This works for every modular pipeline except the inner loop of nested loops (autoregressive video models such as Helios and Wan-Animate-2 denoise each chunk inside a block of the outer loop). There, insert the block into the outer loop instead: it runs once per chunk and receives the chunk index `k` in place of `i` and `t`.
A stopped run returns nothing, so save the intermediate values you want to keep in the callback before raising.

```py
class StopGeneration(BaseException):
pass


partial = {}


def interrupt_callback(pipeline, i, t, callback_kwargs):
stop_idx = 10
if i == stop_idx:
partial["latents"] = callback_kwargs["latents"]
raise StopGeneration
return callback_kwargs


try:
image = pipe(prompt="A photo of a cat", callback_on_step_end=interrupt_callback, output="images")[0]
except StopGeneration:
print("stopped early")
```

`StopGeneration` subclasses `BaseException` so that the blocks don't log it as an error on the way out. A subclass of `Exception` stops the run too, but each block it passes through logs a traceback.

The saved latents are in the form the denoising loop uses, which for many models is packed. To get an image, you may need to unpack before running the decode step.

This works for every modular pipeline whose denoising loop runs its steps as blocks. Autoregressive models such as Helios and Wan-Animate-2 denoise each chunk inside one block of an outer loop, so there is no place for the callback and [`~modular_pipelines.insert_step_callback`] raises a `ValueError`.
2 changes: 2 additions & 0 deletions src/diffusers/modular_pipelines/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"PipelineState",
"BlockState",
]
_import_structure["step_callback"] = ["insert_step_callback"]
_import_structure["modular_pipeline_utils"] = [
"ComponentSpec",
"ConfigSpec",
Expand Down Expand Up @@ -302,6 +303,7 @@
)
from .stable_diffusion_3 import StableDiffusion3AutoBlocks, StableDiffusion3ModularPipeline
from .stable_diffusion_xl import StableDiffusionXLAutoBlocks, StableDiffusionXLModularPipeline
from .step_callback import insert_step_callback
from .wan import (
Wan22Blocks,
Wan22Image2VideoBlocks,
Expand Down
122 changes: 122 additions & 0 deletions src/diffusers/modular_pipelines/step_callback.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
# Copyright 2026 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import inspect
from typing import Callable

import torch

from .modular_pipeline import BlockState, LoopSequentialPipelineBlocks, ModularPipeline, ModularPipelineBlocks
from .modular_pipeline_utils import InputParam


class StepCallbackBlock(ModularPipelineBlocks):
"""
A loop sub-block that calls `callback_on_step_end` at the end of each denoising step, as a [`DiffusionPipeline`]
does. Add it to a pipeline with [`insert_step_callback`].
"""

@property
def description(self) -> str:
return "Step within the denoising loop that calls `callback_on_step_end`."

@property
def inputs(self) -> list[InputParam]:
return [
InputParam(
"callback_on_step_end",
type_hint=Callable,
description=(
"A function called at the end of each denoising step with `(pipeline, step, timestep, "
"callback_kwargs)`. `callback_kwargs` holds the values of the denoising loop, such as `latents`, "
"and the values the function returns replace them."
),
),
]

def __call__(
self, components: ModularPipeline, block_state: BlockState, i: int, t: torch.Tensor
) -> tuple[ModularPipeline, BlockState]:
if block_state.callback_on_step_end is None:
return components, block_state

callback_kwargs = block_state.as_dict()
# A callback for a standard pipeline reads the number of steps from `pipeline.num_timesteps`. A modular
# pipeline has no such attribute, so the callback gets it here.
callback_kwargs["num_timesteps"] = len(block_state.timesteps)
callback_outputs = block_state.callback_on_step_end(components, i, t, callback_kwargs) or {}
# Only the values already in the loop are written back, so a callback cannot add a new one.
for name, value in callback_outputs.items():
if hasattr(block_state, name):
setattr(block_state, name, value)

return components, block_state


def insert_step_callback(pipeline_or_blocks: ModularPipeline | ModularPipelineBlocks):
"""
Add a [`StepCallbackBlock`] to the end of every denoising loop of a modular pipeline, in place. The pipeline then
accepts `callback_on_step_end`, as a [`DiffusionPipeline`] does.

To stop a generation early, raise an exception from the callback. Setting `pipeline._interrupt` has no effect on a
modular pipeline.

Args:
pipeline_or_blocks ([`ModularPipeline`] or [`ModularPipelineBlocks`]):
A pipeline, or the blocks to build one from.

Example:
```python
from diffusers import ModularPipeline
from diffusers.modular_pipelines import insert_step_callback


def log_step(pipeline, step, timestep, callback_kwargs):
print(f"step {step + 1} of {callback_kwargs['num_timesteps']}")
return callback_kwargs


pipe = ModularPipeline.from_pretrained("Qwen/Qwen-Image-2.1")
insert_step_callback(pipe)
pipe.load_components()

image = pipe(prompt="a cat", callback_on_step_end=log_step, output="images")[0]
```
"""
if isinstance(pipeline_or_blocks, ModularPipeline):
blocks = pipeline_or_blocks._blocks
else:
blocks = pipeline_or_blocks

loops = []
pending = [blocks]
while pending:
block = pending.pop()
pending.extend(block.sub_blocks.values())
# A denoising loop passes the step index `i` and the timestep `t` to its sub-blocks. A loop over chunks or
# segments passes `k` and runs its denoising steps inside one sub-block, so it has no place for the callback.
if isinstance(block, LoopSequentialPipelineBlocks) and all(
{"i", "t"} <= set(inspect.signature(sub_block.__call__).parameters)
for sub_block in block.sub_blocks.values()
):
loops.append(block)

if not loops:
raise ValueError(
f"{blocks.__class__.__name__} has no denoising loop that runs its steps as sub-blocks, so a step "
"callback cannot be added."
)

for loop in loops:
loop.sub_blocks["step_callback"] = StepCallbackBlock()
8 changes: 8 additions & 0 deletions tests/modular_pipelines/echo/test_modular_pipeline_echo.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,14 @@


class TestEchoModularPipelineFast(EchoModularPipelineTesterConfig, ModularPipelineTesterMixin):
@pytest.mark.skip(reason="The denoising loop steps over `sigma`; `insert_step_callback` is not supported.")
def test_step_callback(self):
pass

@pytest.mark.skip(reason="The denoising loop steps over `sigma`; `insert_step_callback` is not supported.")
def test_step_callback_early_stop(self):
pass

def test_multi_prompt_multi_video(self):
pipe = self.get_pipeline()
inputs = self.get_dummy_inputs()
Expand Down
16 changes: 16 additions & 0 deletions tests/modular_pipelines/helios/test_modular_pipeline_helios.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,14 @@ def get_dummy_inputs(self, seed=0):


class TestHeliosModularPipelineFast(HeliosModularPipelineTesterConfig, ModularPipelineTesterMixin):
@pytest.mark.skip(reason="Nested denoising loop; `insert_step_callback` is not supported.")
def test_step_callback(self):
pass

@pytest.mark.skip(reason="Nested denoising loop; `insert_step_callback` is not supported.")
def test_step_callback_early_stop(self):
pass

@pytest.mark.skip(reason="num_videos_per_prompt")
def test_num_images_per_prompt(self):
pass
Expand Down Expand Up @@ -171,6 +179,14 @@ def get_dummy_inputs(self, seed=0):


class TestHeliosPyramidModularPipelineFast(HeliosPyramidModularPipelineTesterConfig, ModularPipelineTesterMixin):
@pytest.mark.skip(reason="Nested denoising loop; `insert_step_callback` is not supported.")
def test_step_callback(self):
pass

@pytest.mark.skip(reason="Nested denoising loop; `insert_step_callback` is not supported.")
def test_step_callback_early_stop(self):
pass

def test_inference_batch_single_identical(self):
# Pyramid pipeline injects noise at each stage, so batch vs single can differ more
super().test_inference_batch_single_identical(expected_max_diff=5e-1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,14 @@ def get_dummy_inputs(self, seed=0):


class TestKandinskyS2VModularPipelineFast(KandinskyS2VModularPipelineTesterConfig, ModularPipelineTesterMixin):
@pytest.mark.skip(reason="Nested denoising loop; `insert_step_callback` is not supported.")
def test_step_callback(self):
pass

@pytest.mark.skip(reason="Nested denoising loop; `insert_step_callback` is not supported.")
def test_step_callback_early_stop(self):
pass

@pytest.mark.skip(reason="The pipeline takes one prompt at a time; batching is not supported")
def test_inference_batch_consistent(self):
pass
Expand Down Expand Up @@ -240,6 +248,14 @@ def get_dummy_inputs(self, seed=0):
class TestKandinskyS2VDistilledModularPipelineFast(
KandinskyS2VDistilledModularPipelineTesterConfig, ModularPipelineTesterMixin
):
@pytest.mark.skip(reason="Nested denoising loop; `insert_step_callback` is not supported.")
def test_step_callback(self):
pass

@pytest.mark.skip(reason="Nested denoising loop; `insert_step_callback` is not supported.")
def test_step_callback_early_stop(self):
pass

@pytest.mark.skip(reason=FAST_SKIPS["test_inference_batch_consistent"])
def test_inference_batch_consistent(self):
pass
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,14 @@ def get_dummy_inputs(self, seed=0):


class TestMiniMaxMusic3ModularPipelineFast(MiniMaxMusic3ModularPipelineTesterConfig, ModularPipelineTesterMixin):
@pytest.mark.skip(reason="Nested denoising loop; `insert_step_callback` is not supported.")
def test_step_callback(self):
pass

@pytest.mark.skip(reason="Nested denoising loop; `insert_step_callback` is not supported.")
def test_step_callback_early_stop(self):
pass

@pytest.mark.skip(reason="The pipeline generates a single waveform per call; there is no num_images_per_prompt.")
def test_num_images_per_prompt(self):
pass
Expand Down
Loading