Skip to content

[Enhancement] Add cache-dit force_refresh support for Helios and GLM-Image#2

Open
SamitHuang wants to merge 24 commits into
mainfrom
feat/cache-dit-helios-glm-image
Open

[Enhancement] Add cache-dit force_refresh support for Helios and GLM-Image#2
SamitHuang wants to merge 24 commits into
mainfrom
feat/cache-dit-helios-glm-image

Conversation

@SamitHuang
Copy link
Copy Markdown
Owner

@SamitHuang SamitHuang commented Mar 12, 2026

Purpose

Add force_refresh_step_hint and force_refresh_step_policy support from cache-dit 1.3.0 for Helios and GLM-Image models, aligning with the cache-dit example usage. Also adds --cache-backend CLI support to the GLM-Image end2end example script.

Why these models need special handling

  • Helios (HeliosPipeline, HeliosPyramidPipeline): Uses a multi-chunk denoise loop where num_frames are split into overlapping chunks. Each chunk goes through the full denoising step loop. Without force-refresh, stale cache from the previous chunk leaks into the next. The fix sets force_refresh_step_hint = num_inference_steps with force_refresh_step_policy = "repeat" so the cache is reset at the boundary of each chunk.

  • GLM-Image (GlmImagePipeline): In editing mode, the transformer is called once to process the input image before the denoising loop begins. Setting force_refresh_step_hint = 1 ensures the cache is force-refreshed after this preprocessing call, discarding stale hidden states before actual denoising. For text-to-image mode, force_refresh_step_hint = None (no force refresh needed).

Changes

  1. vllm_omni/diffusion/data.py: Added force_refresh_step_hint and force_refresh_step_policy fields to DiffusionCacheConfig
  2. vllm_omni/diffusion/cache/cache_dit_backend.py:
    • Pass new fields through _build_db_cache_config() to DBCacheConfig
    • Added enable_cache_for_helios() custom enabler
    • Added enable_cache_for_glm_image() custom enabler
    • Registered both in CUSTOM_DIT_ENABLERS
  3. examples/offline_inference/glm_image/end2end.py: Added --cache-backend and --enable-cache-dit-summary CLI arguments

Dependency

This PR depends on vllm-project/vllm-omni#1834 (cache-dit 1.3.0 upgrade) being merged first.

Test Plan

  • Pre-commit check passes (ruff check, ruff format, typos)
  • Verify GLM-Image T2I inference with cache-dit acceleration
  • Verify Helios inference with cache-dit acceleration (model weights not available)

Test Commands (GLM-Image)

# Baseline (no cache-dit)
CUDA_VISIBLE_DEVICES=1,6 python examples/offline_inference/glm_image/end2end.py \
  --model-path zai-org/GLM-Image \
  --config-path examples/offline_inference/glm_image/glm_image.yaml \
  --prompt "A photo of an astronaut riding a horse on mars" \
  --height 1024 --width 1024 --num-inference-steps 50 --seed 42 \
  --output glm_image_baseline.png --verbose

# With cache-dit
CUDA_VISIBLE_DEVICES=1,6 python examples/offline_inference/glm_image/end2end.py \
  --model-path zai-org/GLM-Image \
  --config-path examples/offline_inference/glm_image/glm_image.yaml \
  --prompt "A photo of an astronaut riding a horse on mars" \
  --height 1024 --width 1024 --num-inference-steps 50 --seed 42 \
  --cache-backend cache_dit --enable-cache-dit-summary \
  --output glm_image_cachedit.png --verbose

Test Result

Benchmark on dual NVIDIA H800 GPUs (AR on GPU 1, Diffusion on GPU 6), GLM-Image T2I, 1024x1024, 50 steps:

Metric Without Cache-DiT With Cache-DiT 1.3.0 Speedup
Total generation time (AR+Diffusion) 45.86s 35.74s 1.28x
Diffusion stage time ~15s ~5s ~3x
Cached steps / total steps 0/50 35/50 (70%)

Cache-dit DBCache config: F1B0_W4_threshold=0.24_MC3

Note: The total generation time is dominated by the AR stage (~27s), so the diffusion-stage speedup (~3x) translates to a more modest ~1.28x end-to-end speedup. For workloads with longer diffusion steps or batch processing, the speedup would be more pronounced.

Cache-dit summary (from the accelerated run):

[Cache-DiT] ⚡️Cache Steps and Residual Diffs Statistics: GlmImageTransformerBlock
| Cache Steps | Diffs P50 | Diffs P95 | Diffs Max |
|-------------|-----------|-----------|-----------|
| 35          | 0.057     | 0.13      | 0.157     |

Essential Elements of an Effective PR Description Checklist
  • The purpose of the PR
  • The test plan — GLM-Image T2I benchmark with/without cache-dit
  • The test results — 3x diffusion speedup, 1.28x e2e speedup
  • (Optional) Documentation update — N/A

Signed-off-by: samithuang <285365963@qq.com>
Signed-off-by: samithuang <285365963@qq.com>
Two optimizations that eliminate ~6.5s of IPC serialization overhead
for single-stage diffusion pipelines (e.g. Wan2.2 I2V/T2V) in online
serving mode:

Phase 1 – Inline diffusion (eliminate Hop3):
When there is exactly one diffusion stage in async mode, initialize
OmniDiffusion directly in the orchestrator process instead of spawning
a stage worker subprocess. This removes the entire Hop3 serialization
path (pickle + mp.Queue/SHM) between the stage worker and orchestrator.
GPU workers for tensor parallelism are still spawned by DiffusionExecutor.

Phase 2 – SHM tensor transfer (optimize Hop1):
Replace pickle-based serialization of large tensors through MessageQueue
with POSIX shared memory. The worker copies tensor data into a named SHM
segment and enqueues only lightweight metadata; the scheduler reconstructs
the tensor from SHM. This reduces Hop1 overhead from ~3.4s to ~1.5s.

Measured on Wan2.2-I2V-A14B (TP=2, 1280x720, 5s@16fps, 1 step):
  Before:  e2e = 37.5s
  Phase 1: e2e = 33.1s  (−4.4s)
  Phase 2: e2e = 31.0s  (−2.1s)
  Total:   e2e = 31.0s  (−6.5s, −17.5%)

Made-with: Cursor

Signed-off-by: samithuang <285365963@qq.com>
…17.5%)

perf: reduce IPC overhead for single-stage diffusion serving (~6.5s, 17.5%)
Signed-off-by: Samit <285365963@qq.com>
Signed-off-by: samithuang <285365963@qq.com>
Signed-off-by: samithuang <285365963@qq.com>
Signed-off-by: Samit <285365963@qq.com>
Signed-off-by: samithuang <285365963@qq.com>
Signed-off-by: samithuang <285365963@qq.com>
Signed-off-by: samithuang <285365963@qq.com>
Signed-off-by: samithuang <285365963@qq.com>
Signed-off-by: samithuang <285365963@qq.com>
Signed-off-by: samithuang <285365963@qq.com>
Signed-off-by: samithuang <285365963@qq.com>
Upgrade cache-dit dependency to the latest release (1.3.0). All existing
imports and APIs remain compatible. Verified with Qwen-Image offline
inference showing ~2x speedup with cache-dit acceleration.

Signed-off-by: yx <yx@users.noreply.github.com>
Made-with: Cursor

Signed-off-by: samithuang <285365963@qq.com>
…Image

Add force_refresh_step_hint and force_refresh_step_policy to
DiffusionCacheConfig and wire them through to DBCacheConfig. Register
custom cache-dit enablers for HeliosPipeline, HeliosPyramidPipeline,
and GlmImagePipeline.

- Helios: multi-chunk denoise loop requires cache reset between chunks,
  so force_refresh_step_hint defaults to num_inference_steps and
  force_refresh_step_policy defaults to "repeat".
- GLM-Image: editing mode preprocesses input image in one extra
  transformer call; force_refresh_step_hint=1 discards stale state.

Signed-off-by: yx <yx@users.noreply.github.com>
Made-with: Cursor

Signed-off-by: samithuang <285365963@qq.com>
@gemini-code-assist
Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request focuses on enhancing the capabilities and performance of vLLM-Omni. It introduces cache management improvements for diffusion models, expands the functionality of the ComfyUI extension with video generation support, and adds comprehensive benchmarking for Qwen3-TTS. Additionally, it refactors and improves the CI/CD pipeline.

Highlights

  • Cache-DiT Force Refresh Support: This enhancement introduces force_refresh_step_hint and force_refresh_step_policy to the cache-dit integration for Helios and GLM-Image models, ensuring cache consistency across denoising steps.
  • Buildkite Configuration: The pull request adds a new test job for diffusion models on H100 GPUs and enhances nightly performance reporting with test case statistics.
  • ComfyUI Integration: A new 'Generate Video' node is added to the ComfyUI extension, enabling text-to-video and image-to-video tasks, along with LoRA support and Wan video parameters.
  • Qwen3-TTS Benchmarking: Introduces benchmark scripts and configurations for Qwen3-TTS, comparing vLLM-Omni's streaming serving against Hugging Face Transformers for text-to-speech tasks.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • .buildkite/test-nightly.yml
    • Added a new test job for diffusion models on H100 GPUs.
    • Enhanced nightly performance reporting with test case statistics.
  • .pre-commit-config.yaml
    • Excluded the Helm chart templates from YAML checks.
  • README.md
    • Added a news item about joining the vLLM HK First Meetup.
  • apps/ComfyUI-vLLM-Omni/README.md
    • Added documentation for the new 'Generate Video' node and updated instructions for multimedia file preview nodes.
  • apps/ComfyUI-vLLM-Omni/init.py
    • Registered the 'Generate Video' node, LoRA node, and Wan Video Params node in ComfyUI.
    • Added display name mappings for the new nodes.
  • apps/ComfyUI-vLLM-Omni/comfyui_vllm_omni/nodes.py
    • Added the 'Generate Video' node with input types for video generation parameters.
    • Added a 'RemoteLoRA' node for specifying LoRA models.
    • Added a 'WanParams' node for specifying Wan video parameters.
    • Modified the 'GenerateImage' node to include LoRA parameters.
  • apps/ComfyUI-vLLM-Omni/comfyui_vllm_omni/utils/api_client.py
    • Added support for video generation to the VLLMOmniClient, including handling LoRA parameters.
    • Added json import
  • apps/ComfyUI-vLLM-Omni/comfyui_vllm_omni/utils/format.py
    • Added functions for encoding and decoding videos to and from base64 strings.
  • apps/ComfyUI-vLLM-Omni/comfyui_vllm_omni/utils/types.py
    • Added a 'WanModelSpecificParams' class for video parameters.
  • apps/ComfyUI-vLLM-Omni/comfyui_vllm_omni/utils/validators.py
    • Added model name to log message when skipping sampling params check.
  • apps/ComfyUI-vLLM-Omni/example_workflows/vLLM-Omni Video Generation.json
    • Added a workflow example for video generation.
  • benchmarks/qwen3-tts/README.md
    • Added documentation for benchmarking Qwen3-TTS models.
  • benchmarks/qwen3-tts/plot_results.py
    • Added a script for plotting Qwen3-TTS benchmark results.
  • benchmarks/qwen3-tts/results/.gitignore
    • Added a .gitignore file to exclude benchmark results from version control.
  • benchmarks/qwen3-tts/run_benchmark.sh
    • Added a script for running Qwen3-TTS benchmarks.
  • benchmarks/qwen3-tts/transformers/bench_tts_hf.py
    • Added a script for benchmarking Qwen3-TTS using Hugging Face Transformers.
  • benchmarks/qwen3-tts/vllm_omni/bench_tts_serve.py
    • Added a script for benchmarking Qwen3-TTS online serving.
  • benchmarks/qwen3-tts/vllm_omni/configs/qwen3_tts_bs1.yaml
    • Added a stage config for Qwen3-TTS with batch size 1.
  • benchmarks/qwen3-tts/vllm_omni/configs/qwen3_tts_bs4.yaml
    • Added a stage config for Qwen3-TTS with batch size 4.
  • docker/Dockerfile.ci
    • Installed espeak-ng in the CI Dockerfile.
  • docker/Dockerfile.rocm
    • Installed espeak-ng in the ROCm Dockerfile.
  • docker/Dockerfile.xpu
    • Installed espeak-ng in the XPU Dockerfile.
  • docs/configuration/stage_configs.md
    • Corrected the class name in the offline example.
  • docs/contributing/ci/CI_5levels.md
    • Updated test file paths and added details on request execution and validation.
    • Clarified hardware marks usage.
  • docs/contributing/ci/tests_markers.md
    • Clarified hardware marks usage and added hardware_marks function documentation.
  • docs/design/feature/async_chunk_design.md
    • Clarified the usage of initial_codec_chunk_frames.
  • docs/features/comfyui.md
    • Added documentation for the new 'Generate Video' node.
  • docs/features/custom_pipeline.md
    • Fixed a typo in the num-inference-steps argument.
  • docs/getting_started/installation/gpu/cuda.inc.md
    • Updated vLLM version to 0.17.0.
  • docs/getting_started/installation/gpu/rocm.inc.md
    • Updated vLLM version to 0.17.0.
  • docs/getting_started/quickstart.md
    • Updated vLLM version to 0.17.0.
  • docs/models/supported_models.md
    • Added FLUX.2-dev to the list of supported models.
  • docs/serving/speech_api.md
    • Clarified the usage of initial_codec_chunk_frames and added documentation for streaming text input via WebSocket.
  • docs/user_guide/diffusion/parallelism_acceleration.md
    • Added Expert Parallelism to the list of supported parallelism methods and updated the table of supported models.
    • Added a note about TP limitations for diffusion models.
  • docs/user_guide/diffusion/quantization/gguf.md
    • Fixed typos in the command-line arguments.
  • docs/user_guide/diffusion_acceleration.md
    • Added FLUX.2-dev to the table of supported models.
  • docs/user_guide/examples/offline_inference/qwen3_tts.md
    • Clarified the usage of codec_chunk_frames and initial_codec_chunk_frames.
  • docs/user_guide/examples/online_serving/qwen3_tts.md
    • Added documentation for the Gradio demo and updated the list of command-line arguments.
  • examples/offline_inference/bagel/end2end.py
    • Added a seed argument for reproducibility.
  • examples/offline_inference/custom_pipeline/image_to_image/image_edit.py
    • Reformatted command-line arguments for consistency.
  • examples/offline_inference/custom_pipeline/image_to_image/run.sh
    • Reformatted command-line arguments for consistency.
  • examples/offline_inference/image_to_video/image_to_video.py
    • Reformatted command-line arguments for consistency.
  • examples/online_serving/chart-helm/.helmignore
    • Added a .helmignore file to exclude unnecessary files from the Helm chart.
  • examples/online_serving/chart-helm/Chart.yaml
    • Added a Helm chart for deploying vLLM-Omni on Kubernetes.
  • examples/online_serving/chart-helm/README.md
    • Added a README file for the Helm chart.
  • examples/online_serving/chart-helm/ct.yaml
    • Added a configuration file for chart testing.
  • examples/online_serving/chart-helm/lintconf.yaml
    • Added a configuration file for chart linting.
  • examples/online_serving/chart-helm/templates/_helpers.tpl
    • Added helper templates for the Helm chart.
  • examples/online_serving/chart-helm/templates/configmap.yaml
    • Added a template for creating a ConfigMap in the Helm chart.
  • examples/online_serving/chart-helm/templates/custom-objects.yaml
    • Added a template for creating custom Kubernetes objects in the Helm chart.
  • examples/online_serving/chart-helm/templates/deployment.yaml
    • Added a template for creating a Deployment in the Helm chart.
  • examples/online_serving/chart-helm/templates/hpa.yaml
    • Added a template for creating a HorizontalPodAutoscaler in the Helm chart.
  • examples/online_serving/chart-helm/templates/ingress.yaml
    • Added a template for creating an Ingress in the Helm chart.
  • examples/online_serving/chart-helm/templates/poddisruptionbudget.yaml
    • Added a template for creating a PodDisruptionBudget in the Helm chart.
  • examples/online_serving/chart-helm/templates/pvc.yaml
    • Added a template for creating a PersistentVolumeClaim in the Helm chart.
  • examples/online_serving/chart-helm/templates/secrets.yaml
    • Added a template for creating Secrets in the Helm chart.
  • examples/online_serving/chart-helm/tests/deployment_test.yaml
    • Added a test for the Deployment template in the Helm chart.
  • examples/online_serving/chart-helm/tests/ingress_test.yaml
    • Added a test for the Ingress template in the Helm chart.
  • examples/online_serving/chart-helm/tests/pvc_test.yaml
    • Added a test for the PersistentVolumeClaim template in the Helm chart.
  • examples/online_serving/chart-helm/tests/secrets_test.yaml
    • Added a test for the Secrets template in the Helm chart.
  • examples/online_serving/qwen3_tts/gradio_demo.py
    • Added a Gradio demo for Qwen3-TTS online serving.
  • examples/online_serving/qwen3_tts/gradio_fastrtc_demo.py
    • Added a Gradio demo for Qwen3-TTS using FastRTC for gapless streaming audio.
  • examples/online_serving/qwen3_tts/openai_speech_client.py
    • No significant changes.
  • examples/online_serving/qwen3_tts/run_gradio_demo.sh
    • Added a script for launching both the vLLM server and the Gradio demo for Qwen3-TTS.
  • examples/online_serving/qwen3_tts/run_server.sh
    • No significant changes.
  • examples/online_serving/qwen3_tts/streaming_speech_client.py
    • Added a WebSocket client for streaming text-input TTS.
  • examples/online_serving/qwen3_tts/tts_common.py
    • Added common constants, helpers, and payload building for Qwen3-TTS Gradio demos.
  • pyproject.toml
    • Added pyttsx3 as a dev dependency.
  • requirements/common.txt
    • Updated cache-dit version to 1.3.0.
  • tests/benchmarks/test_serve_cli.py
    • Updated test parameters to use OmniServerParams.
  • tests/comfyui/conftest.py
    • Added mock modules for video support.
  • tests/comfyui/test_comfyui_integration.py
    • Added a test for the video generation node and updated imports.
    • Added core_model and cpu marks
  • tests/conftest.py
    • Added OmniServerParams NamedTuple.
    • Added helper functions for validating images, videos, and audio.
    • Added a fixture for the model path prefix.
    • Added helper functions for sending omni and diffusion requests
  • tests/diffusion/attention/test_attention_sp.py
    • Added a description of the test and updated the dtype parameter.
    • Used seed_everything function instead of setting the seed on the current omni platform
  • tests/diffusion/distributed/test_hsdp.py
    • Added core_model mark
  • tests/diffusion/distributed/test_parallel_state_sp_groups.py
    • Added core_model mark
  • tests/diffusion/distributed/test_sp_plan_hooks.py
    • Added core_model mark
  • tests/diffusion/distributed/test_vae_patch_parallel.py
    • Added core_model mark
  • tests/diffusion/models/flux2/test_flux2_transformer_tp.py
    • Added tests for Flux2Transformer weight loading and RoPE position embedding.
    • Added setup_tp_group fixture
  • tests/e2e/offline_inference/stage_configs/bagel_mooncake_ci.yaml
    • Updated gpu_memory_utilization
  • tests/e2e/offline_inference/stage_configs/bagel_sharedmemory_ci.yaml
    • Updated gpu_memory_utilization
  • tests/e2e/offline_inference/test_diffusion_cpu_offload.py
    • Updated the memory monitor and added a platform-specific VRAM saving threshold.
    • Used current_omni_platform instead of torch
  • tests/e2e/offline_inference/test_expert_parallel.py
    • Added a test for Expert Parallelism.
  • tests/e2e/offline_inference/test_qwen2_5_omni.py
    • Updated test parameters to use OmniServerParams.
  • tests/e2e/online_serving/test_qwen3_omni.py
    • Updated test parameters to use OmniServerParams and added a test for the video generation node.
  • tests/entrypoints/openai_api/test_image_server.py
    • No significant changes.
  • tests/entrypoints/openai_api/test_serving_speech.py
    • Added a test for the API server create speech function and updated imports.
  • tests/entrypoints/openai_api/test_serving_speech_stream.py
    • Added tests for the streaming speech WebSocket endpoint.
  • tests/entrypoints/openai_api/text_splitter.py
    • Added tests for the text splitter.
Activity
  • Added cache-dit force_refresh support for Helios and GLM-Image
  • Added a new test job for diffusion models on H100 GPUs and enhanced nightly performance reporting with test case statistics
  • Added a 'Generate Video' node to the ComfyUI extension, enabling text-to-video and image-to-video tasks, along with LoRA support and Wan video parameters
  • Introduced benchmark scripts and configurations for Qwen3-TTS, comparing vLLM-Omni's streaming serving against Hugging Face Transformers for text-to-speech tasks
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request adds support for force_refresh in cache-dit for Helios and GLM-Image models, which is a valuable enhancement. The changes to DiffusionCacheConfig and the new model-specific enablers are well-aligned with the goal.

However, I've identified a critical bug in both new enabler functions (enable_cache_for_helios and enable_cache_for_glm_image). When creating a refreshed cache context, the code incorrectly uses DBCacheConfig().reset() instead of basing the new configuration on the existing one. This causes all original cache settings (like Fn_compute_blocks, max_warmup_steps, etc.) to be lost and reset to defaults, which will lead to incorrect caching behavior. I've provided suggestions to fix this.

Additionally, there's an opportunity to refactor duplicated code between the two new enabler functions to improve maintainability.

Comment on lines +1020 to +1051
hint = cache_config.force_refresh_step_hint
if hint is None:
hint = num_inference_steps
policy = cache_config.force_refresh_step_policy
if policy == "once":
policy = "repeat"
if cache_config.scm_steps_mask_policy is None:
cache_dit.refresh_context(
pipeline.transformer,
cache_config=DBCacheConfig().reset(
num_inference_steps=num_inference_steps,
force_refresh_step_hint=hint,
force_refresh_step_policy=policy,
),
verbose=verbose,
)
else:
cache_dit.refresh_context(
pipeline.transformer,
cache_config=DBCacheConfig().reset(
num_inference_steps=num_inference_steps,
force_refresh_step_hint=hint,
force_refresh_step_policy=policy,
steps_computation_mask=cache_dit.steps_mask(
mask_policy=cache_config.scm_steps_mask_policy,
total_steps=num_inference_steps,
),
steps_computation_policy=cache_config.scm_steps_policy,
),
verbose=verbose,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

There's a critical issue in refresh_cache_context. Using DBCacheConfig().reset(...) creates a new configuration from defaults, which causes all the original cache settings (like Fn_compute_blocks, max_warmup_steps, etc.) from db_cache_config to be lost. This will lead to incorrect and inefficient caching behavior.

The fix is to use db_cache_config.reset(...) to ensure the refreshed configuration is based on the original settings. I've also refactored the logic slightly to remove duplication within the function.

        hint = cache_config.force_refresh_step_hint
        if hint is None:
            hint = num_inference_steps
        policy = cache_config.force_refresh_step_policy
        if policy == "once":
            policy = "repeat"

        reset_kwargs = {
            "num_inference_steps": num_inference_steps,
            "force_refresh_step_hint": hint,
            "force_refresh_step_policy": policy,
        }

        if cache_config.scm_steps_mask_policy is not None:
            reset_kwargs["steps_computation_mask"] = cache_dit.steps_mask(
                mask_policy=cache_config.scm_steps_mask_policy,
                total_steps=num_inference_steps,
            )
            reset_kwargs["steps_computation_policy"] = cache_config.scm_steps_policy

        # Use db_cache_config.reset to preserve the original cache settings
        # when creating the refreshed configuration.
        refreshed_config = db_cache_config.reset(**reset_kwargs)

        cache_dit.refresh_context(
            pipeline.transformer,
            cache_config=refreshed_config,
            verbose=verbose,
        )

Comment on lines +1092 to +1103
cache_dit.refresh_context(
pipeline.transformer,
cache_config=DBCacheConfig().reset(
num_inference_steps=num_inference_steps,
steps_computation_mask=cache_dit.steps_mask(
mask_policy=cache_config.scm_steps_mask_policy,
total_steps=num_inference_steps,
),
steps_computation_policy=cache_config.scm_steps_policy,
),
verbose=verbose,
)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

Similar to the issue in the Helios enabler, this else block has a critical bug. By using DBCacheConfig().reset(...), you are creating a new cache configuration from defaults whenever SCM is enabled. This discards all the original settings from db_cache_config, including Fn_compute_blocks, max_warmup_steps, and the force_refresh_step_hint that is crucial for GLM-Image.

The fix is to base the refreshed configuration on the existing db_cache_config by using db_cache_config.reset(...).

        else:
            # Use db_cache_config.reset to preserve original settings
            refreshed_config = db_cache_config.reset(
                num_inference_steps=num_inference_steps,
                steps_computation_mask=cache_dit.steps_mask(
                    mask_policy=cache_config.scm_steps_mask_policy,
                    total_steps=num_inference_steps,
                ),
                steps_computation_policy=cache_config.scm_steps_policy,
            )
            cache_dit.refresh_context(
                pipeline.transformer,
                cache_config=refreshed_config,
                verbose=verbose,
            )

Comment on lines +989 to +1106
def enable_cache_for_helios(pipeline: Any, cache_config: Any) -> Callable[[int], None]:
"""Enable cache-dit for Helios pipeline (multi-chunk denoise loop).

Helios splits num_frames into multiple chunks and runs multiple passes of the
transformer denoise loop. The cache context must be refreshed at the end of each
loop to prevent stale cache from the previous chunk leaking into the next one.
This is achieved by setting force_refresh_step_hint = num_inference_steps with
force_refresh_step_policy = "repeat".
"""
db_cache_config = _build_db_cache_config(cache_config)

calibrator_config = None
if cache_config.enable_taylorseer:
calibrator_config = TaylorSeerCalibratorConfig(taylorseer_order=cache_config.taylorseer_order)
logger.info(f"TaylorSeer enabled with order={cache_config.taylorseer_order}")

logger.info(
f"Enabling cache-dit on Helios transformer: "
f"Fn={db_cache_config.Fn_compute_blocks}, "
f"Bn={db_cache_config.Bn_compute_blocks}, "
f"W={db_cache_config.max_warmup_steps}, "
f"force_refresh_step_policy={db_cache_config.force_refresh_step_policy}, "
)

cache_dit.enable_cache(
pipeline.transformer,
cache_config=db_cache_config,
calibrator_config=calibrator_config,
)

def refresh_cache_context(pipeline: Any, num_inference_steps: int, verbose: bool = True) -> None:
hint = cache_config.force_refresh_step_hint
if hint is None:
hint = num_inference_steps
policy = cache_config.force_refresh_step_policy
if policy == "once":
policy = "repeat"
if cache_config.scm_steps_mask_policy is None:
cache_dit.refresh_context(
pipeline.transformer,
cache_config=DBCacheConfig().reset(
num_inference_steps=num_inference_steps,
force_refresh_step_hint=hint,
force_refresh_step_policy=policy,
),
verbose=verbose,
)
else:
cache_dit.refresh_context(
pipeline.transformer,
cache_config=DBCacheConfig().reset(
num_inference_steps=num_inference_steps,
force_refresh_step_hint=hint,
force_refresh_step_policy=policy,
steps_computation_mask=cache_dit.steps_mask(
mask_policy=cache_config.scm_steps_mask_policy,
total_steps=num_inference_steps,
),
steps_computation_policy=cache_config.scm_steps_policy,
),
verbose=verbose,
)

return refresh_cache_context


def enable_cache_for_glm_image(pipeline: Any, cache_config: Any) -> Callable[[int], None]:
"""Enable cache-dit for GLM-Image pipeline.

GLM-Image processes prompt and image by calling the transformer before the
denoising loop. When an input image is provided (editing mode), the cache must
be force-refreshed after the preprocessing step so stale hidden states are
discarded. Set force_refresh_step_hint = 1 for editing, None for text-to-image.
"""
db_cache_config = _build_db_cache_config(cache_config)

calibrator_config = None
if cache_config.enable_taylorseer:
calibrator_config = TaylorSeerCalibratorConfig(taylorseer_order=cache_config.taylorseer_order)
logger.info(f"TaylorSeer enabled with order={cache_config.taylorseer_order}")

logger.info(
f"Enabling cache-dit on GLM-Image transformer: "
f"Fn={db_cache_config.Fn_compute_blocks}, "
f"Bn={db_cache_config.Bn_compute_blocks}, "
f"W={db_cache_config.max_warmup_steps}, "
f"force_refresh_step_hint={db_cache_config.force_refresh_step_hint}, "
)

cache_dit.enable_cache(
pipeline.transformer,
cache_config=db_cache_config,
calibrator_config=calibrator_config,
)

def refresh_cache_context(pipeline: Any, num_inference_steps: int, verbose: bool = True) -> None:
if cache_config.scm_steps_mask_policy is None:
cache_dit.refresh_context(
pipeline.transformer,
num_inference_steps=num_inference_steps,
verbose=verbose,
)
else:
cache_dit.refresh_context(
pipeline.transformer,
cache_config=DBCacheConfig().reset(
num_inference_steps=num_inference_steps,
steps_computation_mask=cache_dit.steps_mask(
mask_policy=cache_config.scm_steps_mask_policy,
total_steps=num_inference_steps,
),
steps_computation_policy=cache_config.scm_steps_policy,
),
verbose=verbose,
)

return refresh_cache_context

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

There is significant code duplication between enable_cache_for_helios and enable_cache_for_glm_image. The logic for building db_cache_config, setting up calibrator_config, logging, and calling cache_dit.enable_cache is nearly identical.

To improve maintainability and reduce redundancy, consider extracting this common setup logic into a shared helper function. This would make the code easier to manage and prevent potential inconsistencies in the future.

SamitHuang and others added 4 commits March 12, 2026 07:41
Add --cache-backend and --enable-cache-dit-summary CLI arguments to the
GLM-Image offline inference example, enabling cache-dit acceleration for
the diffusion stage.

Signed-off-by: yx <yx@users.noreply.github.com>
Made-with: Cursor

Signed-off-by: samithuang <285365963@qq.com>
Made-with: Cursor

Signed-off-by: samithuang <285365963@qq.com>
Signed-off-by: Samit <285365963@qq.com>
Signed-off-by: Didan Deng <33117903+wtomin@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants