From cc6069a60be6bf3f6aad86c788644455e6934a42 Mon Sep 17 00:00:00 2001 From: yiyixuxu Date: Fri, 27 Nov 2026 23:08:11 +0100 Subject: [PATCH 1/3] [Modular] add insert_step_callback Adds a step callback block to every denoising loop of a modular pipeline, so it accepts `callback_on_step_end` like a standard pipeline. Co-Authored-By: Claude Fable 5.2 --- src/diffusers/modular_pipelines/__init__.py | 2 + .../modular_pipelines/step_callback.py | 120 ++++++++++++++++++ .../modular_pipelines/testing_utils/common.py | 22 ++++ 3 files changed, 144 insertions(+) create mode 100644 src/diffusers/modular_pipelines/step_callback.py diff --git a/src/diffusers/modular_pipelines/__init__.py b/src/diffusers/modular_pipelines/__init__.py index 06c26d70b65f..07030cb7c8dc 100644 --- a/src/diffusers/modular_pipelines/__init__.py +++ b/src/diffusers/modular_pipelines/__init__.py @@ -32,6 +32,7 @@ "PipelineState", "BlockState", ] + _import_structure["step_callback"] = ["insert_step_callback"] _import_structure["modular_pipeline_utils"] = [ "ComponentSpec", "ConfigSpec", @@ -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, diff --git a/src/diffusers/modular_pipelines/step_callback.py b/src/diffusers/modular_pipelines/step_callback.py new file mode 100644 index 000000000000..6504f561a79c --- /dev/null +++ b/src/diffusers/modular_pipelines/step_callback.py @@ -0,0 +1,120 @@ +# 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, block_state: BlockState, i: int, t: torch.Tensor): + 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() diff --git a/tests/modular_pipelines/testing_utils/common.py b/tests/modular_pipelines/testing_utils/common.py index 38c4631cb915..f90f33b6268e 100644 --- a/tests/modular_pipelines/testing_utils/common.py +++ b/tests/modular_pipelines/testing_utils/common.py @@ -21,6 +21,7 @@ import diffusers from diffusers import ModularPipeline, ModularPipelineBlocks +from diffusers.modular_pipelines import insert_step_callback from diffusers.utils import logging from ...pipelines.testing_utils.common import cast_pipeline_to_dtype @@ -357,6 +358,27 @@ def test_inference_is_not_nan_cpu(self): def test_inference_is_not_nan(self, base_pipe_output): assert torch.isnan(base_pipe_output).sum() == 0, "Accelerator Inference returns NaN" + def test_step_callback(self, base_pipe_output): + pipe = self.get_pipeline().to(torch_device) + try: + insert_step_callback(pipe) + except ValueError: + pytest.skip("The pipeline has no denoising loop that runs its steps as sub-blocks.") + + calls = [] + + def callback(pipeline, step, timestep, callback_kwargs): + calls.append((step, callback_kwargs["num_timesteps"], "latents" in callback_kwargs)) + return callback_kwargs + + output = self.run_pipe(pipe, callback_on_step_end=callback) + + assert len(calls) > 0, "The callback was never called" + num_timesteps = calls[0][1] + assert [step for step, _, _ in calls] == list(range(num_timesteps)) + assert all(has_latents for _, _, has_latents in calls) + assert torch.abs(base_pipe_output - output).max() < 1e-3, "The callback changed the output" + def test_num_images_per_prompt(self, batch_sizes=[1, 2], num_images_per_prompts=[1, 2]): pipe = self.get_pipeline().to(torch_device) From 0a270d09960da4afb74da4918b63b53a55ad5da4 Mon Sep 17 00:00:00 2001 From: yiyixuxu Date: Fri, 27 Nov 2026 23:59:15 +0100 Subject: [PATCH 2/3] [Modular] add early stop test and docs for insert_step_callback Co-Authored-By: Claude Fable 5.2 --- .../api/modular_diffusers/pipeline_blocks.md | 6 +- docs/source/en/api/pipelines/flux3.md | 9 +- .../coming_from_diffusion_pipeline.md | 2 +- docs/source/en/using-diffusers/callback.md | 83 +++++++++---------- .../echo/test_modular_pipeline_echo.py | 8 ++ .../helios/test_modular_pipeline_helios.py | 16 ++++ .../test_modular_pipeline_kandinsky_s2v.py | 16 ++++ .../test_modular_pipeline_minimax_music3.py | 8 ++ .../modular_pipelines/testing_utils/common.py | 26 +++++- .../test_modular_pipeline_wan_animate_2.py | 8 ++ 10 files changed, 127 insertions(+), 55 deletions(-) diff --git a/docs/source/en/api/modular_diffusers/pipeline_blocks.md b/docs/source/en/api/modular_diffusers/pipeline_blocks.md index 4808f2cf3bbe..de0aad93b50d 100644 --- a/docs/source/en/api/modular_diffusers/pipeline_blocks.md +++ b/docs/source/en/api/modular_diffusers/pipeline_blocks.md @@ -18,4 +18,8 @@ ## ConditionalPipelineBlocks -[[autodoc]] diffusers.modular_pipelines.modular_pipeline.ConditionalPipelineBlocks \ No newline at end of file +[[autodoc]] diffusers.modular_pipelines.modular_pipeline.ConditionalPipelineBlocks + +## insert_step_callback + +[[autodoc]] diffusers.modular_pipelines.step_callback.insert_step_callback diff --git a/docs/source/en/api/pipelines/flux3.md b/docs/source/en/api/pipelines/flux3.md index 034a08ed6bc1..52b3adb28f73 100644 --- a/docs/source/en/api/pipelines/flux3.md +++ b/docs/source/en/api/pipelines/flux3.md @@ -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] ``` diff --git a/docs/source/en/modular_diffusers/coming_from_diffusion_pipeline.md b/docs/source/en/modular_diffusers/coming_from_diffusion_pipeline.md index b7a991d2d6a8..d186cf6e34ab 100644 --- a/docs/source/en/modular_diffusers/coming_from_diffusion_pipeline.md +++ b/docs/source/en/modular_diffusers/coming_from_diffusion_pipeline.md @@ -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). diff --git a/docs/source/en/using-diffusers/callback.md b/docs/source/en/using-diffusers/callback.md index d1e9ea2f9e20..69ebe4cda119 100644 --- a/docs/source/en/using-diffusers/callback.md +++ b/docs/source/en/using-diffusers/callback.md @@ -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") ``` @@ -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`. diff --git a/tests/modular_pipelines/echo/test_modular_pipeline_echo.py b/tests/modular_pipelines/echo/test_modular_pipeline_echo.py index 68a18d2e5078..2e63f9df0d8e 100644 --- a/tests/modular_pipelines/echo/test_modular_pipeline_echo.py +++ b/tests/modular_pipelines/echo/test_modular_pipeline_echo.py @@ -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() diff --git a/tests/modular_pipelines/helios/test_modular_pipeline_helios.py b/tests/modular_pipelines/helios/test_modular_pipeline_helios.py index f3e7b43335fb..ca7605e5e0e6 100644 --- a/tests/modular_pipelines/helios/test_modular_pipeline_helios.py +++ b/tests/modular_pipelines/helios/test_modular_pipeline_helios.py @@ -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 @@ -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) diff --git a/tests/modular_pipelines/kandinsky_s2v/test_modular_pipeline_kandinsky_s2v.py b/tests/modular_pipelines/kandinsky_s2v/test_modular_pipeline_kandinsky_s2v.py index 66ee09f297a8..e2d8e97b9146 100644 --- a/tests/modular_pipelines/kandinsky_s2v/test_modular_pipeline_kandinsky_s2v.py +++ b/tests/modular_pipelines/kandinsky_s2v/test_modular_pipeline_kandinsky_s2v.py @@ -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 @@ -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 diff --git a/tests/modular_pipelines/minimax_music3/test_modular_pipeline_minimax_music3.py b/tests/modular_pipelines/minimax_music3/test_modular_pipeline_minimax_music3.py index a0d48904fc0e..9add384626f9 100644 --- a/tests/modular_pipelines/minimax_music3/test_modular_pipeline_minimax_music3.py +++ b/tests/modular_pipelines/minimax_music3/test_modular_pipeline_minimax_music3.py @@ -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 diff --git a/tests/modular_pipelines/testing_utils/common.py b/tests/modular_pipelines/testing_utils/common.py index f90f33b6268e..515c9005e25d 100644 --- a/tests/modular_pipelines/testing_utils/common.py +++ b/tests/modular_pipelines/testing_utils/common.py @@ -360,10 +360,7 @@ def test_inference_is_not_nan(self, base_pipe_output): def test_step_callback(self, base_pipe_output): pipe = self.get_pipeline().to(torch_device) - try: - insert_step_callback(pipe) - except ValueError: - pytest.skip("The pipeline has no denoising loop that runs its steps as sub-blocks.") + insert_step_callback(pipe) calls = [] @@ -379,6 +376,27 @@ def callback(pipeline, step, timestep, callback_kwargs): assert all(has_latents for _, _, has_latents in calls) assert torch.abs(base_pipe_output - output).max() < 1e-3, "The callback changed the output" + def test_step_callback_early_stop(self, base_pipe_output): + pipe = self.get_pipeline().to(torch_device) + insert_step_callback(pipe) + + class StopGeneration(BaseException): + pass + + steps = [] + + def callback(pipeline, step, timestep, callback_kwargs): + steps.append(step) + raise StopGeneration + + with pytest.raises(StopGeneration): + self.run_pipe(pipe, callback_on_step_end=callback) + assert steps == [0], "The run did not stop at the first step" + + # the pipeline stays usable after a stopped run + output = self.run_pipe(pipe) + assert torch.abs(base_pipe_output - output).max() < 1e-3 + def test_num_images_per_prompt(self, batch_sizes=[1, 2], num_images_per_prompts=[1, 2]): pipe = self.get_pipeline().to(torch_device) diff --git a/tests/modular_pipelines/wan_animate_2/test_modular_pipeline_wan_animate_2.py b/tests/modular_pipelines/wan_animate_2/test_modular_pipeline_wan_animate_2.py index e7906dfb6187..1a5f50c72cf8 100644 --- a/tests/modular_pipelines/wan_animate_2/test_modular_pipeline_wan_animate_2.py +++ b/tests/modular_pipelines/wan_animate_2/test_modular_pipeline_wan_animate_2.py @@ -115,6 +115,14 @@ def get_dummy_inputs(self, seed=0): class WanAnimate2ModularPipelineFastTesterMixin(ModularPipelineTesterMixin): """`ModularPipelineTesterMixin` minus the tests that assume a batchable pipeline; shared by both presets.""" + @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="Wan-Animate-2 decodes inside its segment loop and leaves no latents in the state.") def test_latents_output_in_canonical_form(self): pass From 483352c3dfa689abeb96e5dcd1b4055b8bb1d354 Mon Sep 17 00:00:00 2001 From: yiyixuxu Date: Sat, 28 Nov 2026 00:21:41 +0100 Subject: [PATCH 3/3] add return type annotation to StepCallbackBlock.__call__ Co-Authored-By: Claude Fable 5.2 --- src/diffusers/modular_pipelines/step_callback.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/diffusers/modular_pipelines/step_callback.py b/src/diffusers/modular_pipelines/step_callback.py index 6504f561a79c..063f80c48ccd 100644 --- a/src/diffusers/modular_pipelines/step_callback.py +++ b/src/diffusers/modular_pipelines/step_callback.py @@ -45,7 +45,9 @@ def inputs(self) -> list[InputParam]: ), ] - def __call__(self, components, block_state: BlockState, i: int, t: torch.Tensor): + 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