Skip to content

Diffusion LMs: fast inference, live denoising frames and in-loop cancellation - #13592

Merged
danielhanchen merged 46 commits into
mainfrom
diffusion-infer-core
Oct 13, 2026
Merged

danielhanchen merged 46 commits into
mainfrom
diffusion-infer-core

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

Stacked on #13341 (base diffusion-compile-core); retarget to main once #13341 merges.

This makes diffusion LM inference fast for every family #13341 supports, adds live denoising frames and in-loop cancellation to generate_text, and keeps greedy outputs the same as the current samplers.

What changes

LLaDA / LLaDA-MoE (_llada_sample)

  • Only the active block is projected to the vocabulary. The backbone still sees the full bidirectional canvas, but there is no [B, L, V] logits tensor.
  • The step loop has no host syncs: the per-step transfer counts are computed once on the host, top-k selection stays on device, and EOS is checked once per block.
  • The backbone forward is replayed from a CUDA Graph by default (compile="auto"): the same eager kernels, so the same numbers, without per-kernel launch overhead. A forward that cannot be captured (LLaDA-MoE's expert loop) falls back to eager and the model remembers it, so later calls skip the capture.

SDAR / LLaDA2 (diffusion_infer_block.py)

  • Exact prefix KV cache: committed blocks keep their keys / values and each step forwards only the active block. A finished block is committed in the same forward as the next block's first step, so the number of forwards matches the previous sampler.
  • LLaDA2's eval MoE (moe_infer, which copied expert counts to the host in every layer) runs as three grouped GEMMs with the counts on device. The grouped GEMM is picked per GPU: torch._grouped_mm on sm90 / sm100 / ROCm, unsloth_zoo's Triton grouped GEMM on sm80+ elsewhere (on those GPUs torch's version loops over host-copied offsets), each probed once against a plain matmul. Expert weights are stacked once and the existing Parameters point into the stack, so nothing is held twice and an optimizer built earlier still owns them. Training, adapters, quantized experts and fp32 keep the original path. UNSLOTH_MOE_INFER_GROUPED=torch|triton|0 overrides.
  • LLaDA2's cached block forward is captured once per shape into a CUDA Graph. It is cleared when any parameter or buffer moves (model.to(...), reloads) or adapters appear, one generate uses it at a time, and no capture is attempted over an expert loop that syncs with the host.

Dream (diffusion_infer_dream.py)

  • Greedy entropy / maskgit_plus / topk_margin decoding computes logits for the generated region only. Every other setting, and the rare run where the model proposes its own mask token, goes to diffusion_generate as before.

Nemotron-Labs-Diffusion keeps its own generate; a forward pre-hook streams its canvas.

generate_text API (backwards compatible, all new arguments optional)

  • on_frame(frame) receives {"block", "step", "total", "tokens", "mask_id"} while the canvas denoises: at most once per frame_interval_s (default 0.1 s) plus exactly one step == total frame per finished block, never after return. Frames are copied into a pinned buffer without blocking the GPU.
  • stop_callback is now checked inside every step loop, so cancellation also works under CUDA Graph replay (forward hooks do not fire there).
  • compile: "auto" (default; CUDA Graph replay on CUDA, eager on CPU), True / "graphs", False, or a torch.compile mode such as "reduce-overhead" (fused kernels, so greedy output can drift; opt-in only).
  • UNSLOTH_DIFFUSION_KV_CACHE=0 and UNSLOTH_DIFFUSION_CUDA_GRAPHS=0 restore the previous block sampler / turn graphs off.

Results

Dedicated A100, ABBA (base, head, head, base; fresh process per arm), greedy, 8 prompts x 128 tokens, base = #13341 f270d53b9. The head arms stream canvas frames (on_frame) as Studio does. Median seconds per prompt:

Model Base This PR Change Peak memory
LLaDA-8B-Instruct 1.262 / 1.259 0.850 / 0.839 1.49x faster 15.06 -> 14.97 GB
LLaDA2.0-mini 8.20 / 8.25 0.966 / 0.967 8.5x faster 30.54 -> 30.37 GB
Dream-v0-Instruct-7B 4.61 / 4.53 4.39 / 4.34 1.04x faster 14.39 -> 14.34 GB
LLaDA-MoE-7B-A1B-Instruct 13.92 / 13.49 13.27 / 13.57 same 13.86 -> 13.73 GB
SDAR-1.7B-Chat 1.26 / 1.22 1.25 / 1.28 same 3.84 -> 3.82 GB
Nemotron-Labs-Diffusion-3B 1.71 (warm) 1.87 / 1.74 same 7.20 -> 7.21 GB
diffusiongemma-26B-A4B-it (unchanged path) 0.828 / 0.839 0.837 / 0.847 same 49.99 -> 49.99 GB

LLaDA2 on other GPUs (4 chat prompts, base vs this PR on the same dedicated card): RTX PRO 6000 12.6 s -> 2.64 s with the Triton grouped GEMM on all 19 MoE layers and the block graph captured.

Parity

  • LLaDA-8B and LLaDA-MoE: greedy token ids identical to the previous sampler on 8/8 prompts for eager, CUDA Graph replay and the cudagraphs backend. The official LLaDA generate.py parity test still passes.
  • Dream: 6/6 identical to diffusion_generate; 16/16 bit-identical cases on a tiny fp32 Dream across all three algorithms, batch 1 to 3.
  • SDAR and LLaDA2 (prefix cache): fp32 end to end on the real checkpoints is 9/9 identical with the same number of forwards, including prompts ending exactly on, one before and one after a block boundary. In bf16 longer answers can reword part way through (bf16 accumulation order); cached vs recomputed logits differ less than recomputing the same prefix at two lengths.
  • Answer quality, 40 short-answer questions (arithmetic, capitals, facts), base vs this PR: 40/40 correct on both and 40/40 identical text for SDAR, LLaDA2 (with the Triton grouped GEMM), LLaDA-8B and Dream.
  • Nemotron live canvas on the real 3B model: one frame per step, one block-end frame per block, canvas fills from 63 masks to 0, text identical with and without on_frame.
  • 0 graph breaks on every path that compiles.

Not changed / not adopted

  • torch.compile of decoder layers stays opt-in: on SDAR and Nemotron it was slower, on DiffusionGemma and Dream it changed greedy output.
  • DiffusionGemma keeps transformers' generate (it already has its own canvas in Studio).
  • 8-bit (torchao int8 / fp8 dynamic) is not part of this PR. Compiled it was 1.3x to 1.5x faster with 43% less memory and 40/40 on the short-answer set, but it drifts on open-ended prompts, so it is not a default.

Tests

tests/diffusion/: 194 passed, 9 skipped on CPU; the diffusion tests also pass on transformers 4.57.6 (TRL 0.22.2, PEFT 0.18.0), 5.17.0 and 5.19.0 (new test_diffusion_infer.py, test_diffusion_infer_block.py), covering frame contracts, cancellation during capture, graph lifetime, prefix cache vs recompute on toy SDAR / LLaDA2 models, the MoE shim across LoRA / reload / model.to, and the grouped GEMM choice per GPU.

…ompiled cross entropy

Objectives no longer index logits by mask, branch on tensor values or call .item() per step. Every
family computes its loss through a chunked weighted cross entropy that takes pre-head hidden states
where the head is a plain Linear, so [B, L, V] fp32 logits are never built, and whose fixed-size chunk
kernels compile without graph breaks or recompiles. Also fixes the DiffusionGemma encoder AR co-loss
returning NaN on a batch with no next-token pair, keeps the Nemotron diffusion head 16-bit under 4-bit
loading, and adds DiffusionConfig(diffusion_compile) with per-layer backbone compile for dense families.
…block 0/0, ZeRO-3 head, kept adapters, FastModel positional args, sampler cancellation
… checkpointing on a reused adapter, fork the RNG on every CUDA device a sharded model uses
…ormers < 5.17 keeps the loaded weights

transformers 5.5 keys is_remote_code() on _auto_class, which only the Auto classes set. LLaDA-MoE and Dream
were loaded through their hub class directly, so their own _init_weights ran over the checkpoint and Studio
(transformers 5.5 tier) trained them from random weights.
# Conflicts:
#	tests/diffusion/test_diffusion_masked.py
Dream's eos_token_id is <|endoftext|> only while its template closes a turn with <|im_end|>, so a chat reply ran
on past the answer (same for SDAR, LLaDA, LLaDA2 and DiffusionGemma, whose turn markers differ from EOS).
…port, grouped LLaDA2 eval routing

SDAR and LLaDA2 are block-causal, so committed blocks keep their keys and values: each denoising step forwards
only the active block, and a finished block is committed in the same forward as the next block's first step
(same forward count as the recompute sampler). Token selection stays on the device. UNSLOTH_DIFFUSION_KV_CACHE=0
keeps the recompute sampler.

Dream's greedy entropy / maskgit_plus / topk_margin path projects only the generated region and precomputes the
transfer schedule; other settings, or a model that proposes its own mask token, use diffusion_generate, which
now reports frames and stop checks through generation_tokens_hook_func.

The LLaDA2 eval moe_infer copied expert counts to the host per layer and looped over experts; the grouped
dispatch keeps counts on the device and computes every routed token in three grouped GEMMs.
…h backbone, on_frame and in-loop stop

- New unsloth/models/diffusion_infer.py: Progress / make_progress (in-loop stop checks, throttled
  pinned-buffer canvas frames), BlockHead (projects only the active block to the vocabulary),
  GraphedForward (eager backbone captured into CUDA Graphs per canvas shape, eager fallback that is
  remembered on the model), resolve_compile and inference_compile (regional torch.compile modes).
- LLaDA / LLaDA-MoE sampler: block-only head with fp64 Gumbel on block rows, host-known transfer
  schedule, no per-step host syncs, EOS checked once per block, frames and stop checks per step.
- generate_text: on_frame, frame_interval_s and compile ('auto' = CUDA Graphs on CUDA, eager on CPU).
- Greedy ids identical to the previous sampler on LLaDA-8B-Instruct and LLaDA-MoE-7B-A1B-Instruct.
The block forward has fixed shapes over a fixed-capacity cache (block-causal mask over absolute positions,
keys / values written at the block's rows), and with the grouped MoE dispatch it has no host sync, so it is
captured once per (batch, block, capacity) and replayed for every step and commit. Adapters, CPU, a failed
capture or UNSLOTH_DIFFUSION_CUDA_GRAPHS=0 keep the eager cached path.
On a dedicated G4 card (LLaDA-8B-Instruct, 8 prompts, 128 tokens, ABBA, all
arms 8/8 identical ids) graph replay was only 4% faster than eager for 0.7 GB
more reserved memory, so True / "graphs" opt in and "auto" stays eager.
…s progress

generate_text hands samplers its Progress, not on_frame, so the SDAR / LLaDA2 /
Dream canvas frames were dropped after the masked and block samplers met. They
now use Progress.frame (own throttle, non-blocking host copy) when it is given
and keep the direct on_frame path otherwise.
…ys.modules

The dynamic __import__ tripped the risky-loader lint; the module is always loaded
already, since the model's class is defined in it.
time.monotonic() can be smaller than the frame interval right after boot, so a
zero start time dropped the first canvas frame (seen on CI runners).
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…mote code, document compile scope

- Captures share one side stream per device, so first-time captures from two
  threads now take a per-device lock instead of interleaving on it.
- LLaDA2.1's remote code dropped _prepare_4d_causal_attention_mask_for_sdpa; the
  eager cached path passes the additive block mask to its layers as the graph
  path already does.
- generate_text's compile docstring says which families a torch.compile mode
  applies to.
Base automatically changed from diffusion-compile-core to main October 13, 2026 16:27
# Conflicts:
#	tests/diffusion/test_diffusion_samplers.py
#	unsloth/models/diffusion_samplers.py
#	unsloth/models/loader.py
chatgpt-codex-connector[bot]

This comment was marked as resolved.

… stacking, stop before a graphed commit

- The grouped expert stack and the LLaDA2 graph cache are plain attributes that
  Module.to / cpu / half do not move; the module class's _apply now drops them,
  so offloading a model releases that VRAM right away.
- Lazy expert stacking runs under one lock, so two first-time generates never
  capture a graph over half re-pointed expert weights.
- The graphed LLaDA2 path checks for a stop right before a block's commit replay.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 1117b5b2ba

ℹ️ 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 f798045 into main Oct 13, 2026
@danielhanchen
danielhanchen deleted the diffusion-infer-core branch October 13, 2026 18:53
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