Repository navigation
Diffusion LMs: fast inference, live denoising frames and in-loop cancellation - #13592
Merged
Merged
Conversation
…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.
…s and add per-family samplers
… fused head when it is replaced
…he diffusion path ignores
…block 0/0, ZeRO-3 head, kept adapters, FastModel positional args, sampler cancellation
…nsformers releases without it
… checkpointing on a reused adapter, fork the RNG on every CUDA device a sharded model uses
…f re-exporting it
… the optimizer-group test off bf16
…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.
…d frame per block
…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).
…n explicit compile="graphs"
…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.
# Conflicts: # tests/diffusion/test_diffusion_samplers.py # unsloth/models/diffusion_samplers.py # unsloth/models/loader.py
… 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.
Member
Author
|
@codex review |
1 similar comment
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stacked on #13341 (base
diffusion-compile-core); retarget tomainonce #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)[B, L, V]logits tensor.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)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_mmon 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|0overrides.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)entropy/maskgit_plus/topk_margindecoding computes logits for the generated region only. Every other setting, and the rare run where the model proposes its own mask token, goes todiffusion_generateas before.Nemotron-Labs-Diffusion keeps its own
generate; a forward pre-hook streams its canvas.generate_textAPI (backwards compatible, all new arguments optional)on_frame(frame)receives{"block", "step", "total", "tokens", "mask_id"}while the canvas denoises: at most once perframe_interval_s(default 0.1 s) plus exactly onestep == totalframe per finished block, never after return. Frames are copied into a pinned buffer without blocking the GPU.stop_callbackis 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 atorch.compilemode such as"reduce-overhead"(fused kernels, so greedy output can drift; opt-in only).UNSLOTH_DIFFUSION_KV_CACHE=0andUNSLOTH_DIFFUSION_CUDA_GRAPHS=0restore 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: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
cudagraphsbackend. The official LLaDAgenerate.pyparity test still passes.diffusion_generate; 16/16 bit-identical cases on a tiny fp32 Dream across all three algorithms, batch 1 to 3.on_frame.Not changed / not adopted
torch.compileof decoder layers stays opt-in: on SDAR and Nemotron it was slower, on DiffusionGemma and Dream it changed greedy output.generate(it already has its own canvas in Studio).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 (newtest_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.