Skip to content

Studio diffusion: HiDream experts run only on their routed tokens - #18793

Merged
danielhanchen merged 2 commits into
mainfrom
studio-hidream-grouped-moe
Nov 21, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
studio-hidream-grouped-moe

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

HiDream's MoE layers route each token to 2 of 4 experts. Studio's traceable replacement for diffusers' moe_infer (_moe_infer_dense, which avoids the bincount().cpu() host sync that broke every block's graph) runs every expert on every token and masks the result. So half of the routed-expert GEMMs do no useful work.

Change

  • diffusion_regional_compile._moe_infer_dense takes a grouped path first when the denoiser is bf16 on an sm80+ NVIDIA card and every expert is a stock bias-free SwiGLU of plain nn.Linear / nn.Parameter, with no hooks.
    • Tokens are sorted by expert, and three torch._grouped_mm calls (gate, up, down) run each expert only on its own rows.
    • The offsets come from a static-shape compare-and-sum, not bincount, so there is no graph break. On sm90 / sm100 the grouped GEMM is one fused kernel with no host sync. On other cards torch 2.9+ runs its per-group fallback, which copies the offsets to the host per call; that path is not CUDA-graph capturable, and the denoiser graph's warm-up then runs eager (HiDream's graph did not capture on main either).
    • The gate runs one tiny torch._grouped_mm on the denoiser's card at install and keeps the dense experts if it raises (torch 2.8 ships the op but raises off sm90).
    • The expert weights are stacked per call (a transient copy, about 0.26 GiB peak). There is no second resident copy of the 20 GB of routed experts.
    • The two picked contributions are added in the dense path's order.
  • LoRA'd, quantized or hooked experts, cards where the probe raises, fp32 / fp16, ROCm and torch without _grouped_mm keep the dense path. UNSLOTH_DIFFUSION_HIDREAM_GROUPED_MOE=0 turns it off.

Results

One layer at HiDream-I1 dims (dim 2560, expert hidden 6912, 4 experts, top 2, 4224 tokens, random bf16 weights). Inductor, fullgraph=True, 0 graph breaks on both arms, median of 5 interleaved rounds:

card MoE layer dense -> grouped single block dense -> grouped
A100 9.38 -> 6.63 ms (1.41x) 11.78 -> 8.74 ms (1.35x)
L4 40.0 -> 25.1 ms (1.60x) 50.2 -> 35.2 ms (1.43x)
RTX PRO 6000 5.65 -> 4.30 ms (1.31x) 7.04 -> 5.75 ms (1.22x)

Accuracy is rel L2 1.9-2.6e-3 against dense. That is GEMM reduction order; the released diffusers loop is 4.5e-3 from dense.

Tests

tests/test_diffusion_hidream_grouped_moe.py (7, CPU, torch._grouped_mm CPU kernel):

  • The grouped path equals per-token math in the dense sum order (fp32 1e-5).
  • The whole tiny HiDream matches dense in bf16.
  • It traces fullgraph with no breaks.
  • The install marks layers and honours the switch.
  • CPU / fp32 / biased / hooked / LoRA-typed experts keep the dense path.

tests/test_diffusion_regional_compile.py is unchanged and passes.

Not proven here

  • A real HiDream-I1 render (17B weights) was not run, so there is no s/step or LPIPS number end to end.
  • Quantized HiDream loads (they keep dense) and multi-card layer splits were not measured.

Real render

HiDream-I1-Fast, 1024x1024, 16 steps, RTX PRO 6000, torch 2.14.1, bf16 resident and compiled, interleaved in one process: 0.372-0.380 -> 0.288-0.289 s/step, 6.08-6.13 -> 4.68-4.69 s/image (1.30x); the grouped path engaged on 48 of 48 MoE layers; peak 57.63 -> 57.60 GiB. A separate merge-base run on another VM gave 0.372-0.374 s/step, matching the dense arm. HiDream renders are not reproducible run to run here even at a fixed seed (same-arm LPIPS 0.34-0.57), so image metrics cannot separate the arms; grouped vs dense measured 0.40 / 0.57 with matching composition, and the per-layer relative L2 is 1.4e-3.

…ouped GEMMs, no host sync) on bf16 CUDA denoisers
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-21T19:26:47.827117Z 217ab1f Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: dfd3fbb375

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 217ab1f239

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 43b45e5 into main Nov 21, 2026
@danielhanchen
danielhanchen deleted the studio-hidream-grouped-moe branch November 21, 2026 22:40
danielhanchen added a commit that referenced this pull request Nov 22, 2026
…DMD diffusers skip, risky loader lint) (#18824)

## Summary

Four checks are red on `main` itself, so every open PR currently
inherits them in the Backend CI shards and the risky loader lint. Each
was reproduced on a clean `main` checkout before fixing.

| Failing check | Introduced by | Which side was wrong | Fix |
|---|---|---|---|
|
`tests/test_diffusion_rocm_tag_detect.py::test_no_diffusion_or_video_gate_reads_version_hip_directly`
| #18793 (`diffusion_regional_compile.py`) and #18792
(`diffusion_vae_strips.py`) | Code. Both new gates read
`torch.version.hip` directly, which the ROCm tag guard exists to forbid
(a CUDA wheel with a stray `hip` attribute, or a ROCm wheel reporting it
differently, takes the wrong branch). | Route both through the shared
`is_rocm_torch(torch)` helper from `rocm_bf16`. Behaviour on CUDA and
ROCm is unchanged. |
|
`tests/test_h3_quantised_offload.py::test_a_streamed_torchao_render_runs_under_no_grad_and_the_rest_keep_inference_mode`
| #18780 added `draft_ctx` to the denoise `with` | Test. The invariant
(the denoise loop enters `grad_ctx` together with its progress context)
still holds; the test pinned one exact spelling of the `with` line. |
Parse the `with` statements and assert `grad_ctx` and `progress_ctx()`
are entered together, regardless of what other contexts join them.
Verified it still fails when `grad_ctx` is dropped from the statement. |
| `tests/test_video_dmd.py::test_dmd_scheduler_reseeds_per_render`,
`::test_renoise_stream_is_independent_of_the_initial_latent_noise` |
#18779 | Test. `make_dmd_scheduler` builds on a diffusers scheduler, but
these two tests only skipped on missing torch, so they error with `No
module named 'diffusers'` in the shard that runs without diffusers. |
`pytest.importorskip("diffusers")`, matching the existing scheduler test
in the same file. |
| `scripts/lint_risky_loaders.py` (`diffusion_ddp.py:440
[dynamic-import] __import__`) | #18771 | Code. The rank bootstrap
imported two fixed modules through `__import__` in a loop. | Import
`utils.native_tls` and `utils.happy_eyeballs` by name, each in its own
`try`, so a failure in one still does not stop the rank or skip the
other. No baseline entry needed. |

## Testing

- `tests/test_diffusion_rocm_tag_detect.py`,
`tests/test_h3_quantised_offload.py`, `tests/test_video_dmd.py`,
`tests/test_diffusion_ddp.py`, `tests/test_diffusion_training.py`, the
native TLS and happy eyeballs suites, and the regional compile and VAE
strip suites: all pass.
- `tests/test_video_dmd.py` with diffusers blocked from import: 26
passed, 7 skipped (previously 2 errors).
- `python scripts/lint_risky_loaders.py`: all call sites recorded.
- Sabotage: restoring either original `torch.version.hip` read makes the
ROCm tag guard fail; restoring the `__import__` loop makes the risky
loader lint fail.
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.

1 participant