Skip to content

Diffusion LM training: compiled chunked loss with 0 graph breaks, plus per-family samplers - #13341

Merged
danielhanchen merged 22 commits into
mainfrom
diffusion-compile-core
Oct 13, 2026
Merged

danielhanchen merged 22 commits into
mainfrom
diffusion-compile-core

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 11, 2026 •

Copy link
Copy Markdown
Member

Follow-up to #13157. It makes text-diffusion training compile cleanly and faster, and adds the pieces Unsloth Studio needs to train and chat with every supported diffusion family (Studio wiring is in the companion PR).

What changes

Loss path (all families)

  • New diffusion_loss.py: a chunked, weighted linear cross-entropy with a custom backward. It computes hidden @ lm_head per row chunk and never materialises full [tokens, vocab] logits. The per-chunk kernels are compiled with fullgraph=True, dynamic=False and padded to a power of two, so a run compiles a handful of graphs and never recompiles per sequence length.
  • Masked (LLaDA, LLaDA-MoE, Dream, Nemotron-Labs-Diffusion), block (LLaDA2, SDAR) and DiffusionGemma objectives now build fixed-shape targets and weights with no host syncs: no boolean indexing, no .item(), no data-dependent shapes. Logging metrics stay tensors until log().
  • DiffusionConfig.diffusion_compile: "auto" (default; compiled loss chunks on CUDA, except DiffusionGemma), "loss", "full" (adds per-layer backbone compile for LLaDA, Dream and Nemotron), or False. UNSLOTH_COMPILE_DISABLE=1 turns it off.
  • DiffusionGemma: the encoder AR loss now uses sum / count reductions, which fixes a NaN when a batch has no AR targets. Under ZeRO-3 it gathers the head and projects inside the gather.

Correctness fixes found while doing this

  • fp16: the chunk backward zeroes the gradient of ignored rows, which could otherwise overflow.
  • Block inverse_t weighting no longer divides 0 by 0 when the noise floor is 0.
  • The block right-padding check now runs on the first padded batch instead of only on the first batch.
  • A replaced lm_head is re-checked before reusing the fused head path.
  • LLaDA: the RoPE cache is warmed on the model device before the backbone is compiled. Without this, "full" hit a checkpoint recompute metadata mismatch.
  • SDAR's remote code imports SlidingWindowCache, which some transformers 5.x releases (including 5.5) do not ship. A stand-in is provided only while that file imports.
  • LLaDA-MoE and Dream loaded with random weights on transformers < 5.17 (5.5 is the tier Studio uses for them). The masked profile loads the hub class directly, and those releases decide is_remote_code() from _auto_class alone, so the class's own _init_weights ran over the checkpoint (step-1 loss 23 / 44 instead of ~1). The class is now registered for its auto class, as AutoModel does.
  • Chat generation also stops at the chat template's end-of-turn token. Dream's eos_token_id is <|endoftext|>, but its template closes a turn with <|im_end|>, so a reply ran on past the answer.

Entry points

  • FastLanguageModel.get_peft_model / for_training / for_inference and FastModel.get_peft_model now dispatch diffusion models to the diffusion path. Before this, they crashed with _saved_temp_tokenizer for all 7 families.
  • Diffusion get_peft_model:
    • honours use_rslora and seeds from random_state;
    • raises on use_dora and loftq_config, and warns on options it ignores;
    • keeps an adapter that is already attached instead of stacking a second one.
  • Models without a pad token use EOS as pad, mirrored to the processor and the generation config.
  • New diffusion_samplers.py: per-family denoising samplers behind FastDiffusionModel.generate_text. They support cancellation (DiffusionGenerationCancelled) and restore Nemotron's attention mode afterwards.
  • New is_diffusion_model export.

Results

B200, exclusive GPU, ABBA order, fresh process and compile cache per run, 30 steps (MoE 20), seq 512, batch 2, LoRA bf16. Ranges are medians across runs. main = current main; off / auto / full = this PR.

Model main ms/step off auto full Peak memory main -> auto Graph breaks
Nemotron-Labs-Diffusion-3B 253-267 256-277 224-254 139-164 9.60 -> 8.72 GB 0
LLaDA-8B-Instruct 330-369 334-361 331-352 151-158 * 18.24 -> 17.37 GB 0
Dream-v0-Instruct-7B 290-382 288-313 306-308 195-197 17.57 -> 16.28 GB 0
SDAR-1.7B-Chat 331-355 326-335 332-361 - 5.41 -> 4.96 GB 0
LLaDA-MoE-7B-A1B 1178-1247 1093-1191 1082-1201 - 16.62 -> 15.24 GB 0
LLaDA2.0-mini 5123-5476 4891-5083 4731-4951 - 33.85 -> 33.24 GB 0
DiffusionGemma-26B-A4B 1001-1004 990-996 same as off (eager) - 66.67 -> 63.48 GB 0
  • * LLaDA full was measured in a later session (after the RoPE warm-up fix), where auto ran at 254 ms/step on that card. Compare it against that, not against the other columns.
  • Step 1 loss is bit-identical to main on every model. Later steps stay within bf16 rounding. SDAR moves more because the noise is now drawn with fixed shapes, so the RNG stream differs.
  • DiffusionGemma keeps its loss eager under "auto". Compiled loss chunks were 5-10% slower per step there in 4 of 4 ABBA pairs (1085-1143 vs 990-1040 ms), at equal memory. "loss" / "full" still compile it.
  • "full" is opt-in. It is 35-50% faster on the dense models but compiles every decoder layer up front.

Tests

  • tests/diffusion/: 108 passed, 8 skipped with a GPU (98 passed on CPU; CUDA-only cases skip).
  • Real checkpoints through Unsloth Studio (30 LoRA steps, greedy chat "Question 3: what is 3 plus 3?"): LLaDA, Nemotron, DiffusionGemma, SDAR and LLaDA-MoE answer with 6.
  • New tests cover:
    • chunked CE against a naive reference, including fp16 overflow, empty input and the 0/0 noise floor;
    • the dispatch wrappers and PEFT options;
    • all samplers, including cancellation;
    • the SDAR import shim.
    • hub-class weight loading (a local remote-code checkpoint whose _init_weights would overwrite it) and the end-of-turn stop.
  • Each new behavioural test fails on main.

…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
@danielhanchen danielhanchen self-assigned this Oct 11, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-13T16:26:41.901892Z 5ee126b New commits
ℹ️ 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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ca3aea827d

ℹ️ 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".

torch.arange(steps_per_block, device = x.device)[None, :] < remaining % steps_per_block
)
for step in range(steps_per_block):
mask_index = x == mask_id

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve mask tokens in the prompt

When a prompt explicitly contains the tokenizer's mask special token, this global mask selects that prompt position as if it were a generation slot. Because only positions after the current block are excluded from confidence selection, the prompt token can be overwritten and the conditioning context changes during decoding. Restrict the mask to generated positions in the current block; the analogous window mask in _block_sample has the same issue when the prompt shares its first decoding block.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This matches the reference LLaDA sampler (ML-GSAI/LLaDA generate.py selects from mask_index = (x == mask_id) over the whole sequence too), and it needs the literal mask special token typed into the prompt. Leaving it as is.

Comment on lines +347 to +355
device = next(model.parameters()).device
except StopIteration:
return
for module in model.modules():
rotary = getattr(module, "get_rotary_embedding", None)
config = getattr(module, "config", None)
length = getattr(config, "max_sequence_length", None)
if callable(rotary) and isinstance(length, int) and length > 0:
rotary(length, device)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Warm each rotary cache on its owning device

With diffusion_compile="full" on a model sharded by device_map="auto", this chooses the device of the model's first parameter and uses it for every rotary module. Layers placed on other GPUs therefore get a cache on the wrong device and can fail on their first compiled forward or lazily relocate the cache during checkpoint recomputation, recreating the metadata mismatch this warm-up is intended to prevent. Derive the device from each rotary module or its containing layer instead.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LLaDA keeps one BufferCache shared by every block's rotary module, so warming per module device would overwrite the same rope_pos_sin/cos slot and cannot hold one copy per GPU. The cross-device case also moves that shared cache on every block in eager LLaDA. This only touches the opt-in diffusion_compile='full' on a model split across devices; single-device and 'auto' are unaffected. Leaving it as is.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ca3aea827d

ℹ️ 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".

Comment on lines +392 to +399
output_ids, _nfe = base.generate(
input_ids,
max_new_tokens = _round_up(max_new_tokens, block_length),
block_length = block_length,
threshold = threshold,
temperature = temperature,
eos_token_id = eos_ids[0] if eos_ids else None,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Honor the requested Nemotron denoising steps

When generate_text(..., steps=N) is used with a Nemotron-Labs-Diffusion model, _nemotron_sample accepts the value but this call never forwards or otherwise uses it, so every non-default request is silently ignored while the public API claims steps controls the family sampler. This can make generation run substantially more denoising work than requested; either implement the requested schedule or reject unsupported steps values instead of discarding them.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Nemotron-Labs-Diffusion's own generate (modeling_nemotron_labs_diffusion.py) has no step count: it unmasks each block by confidence threshold until the block is filled, so there is no schedule to forward steps into. The sampler uses the model's published decoder as is; block_length and threshold are what it exposes.

… checkpointing on a reused adapter, fork the RNG on every CUDA device a sharded model uses
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 6b9fffb191

ℹ️ 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".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 618f683133

ℹ️ 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

Repo tests (CPU, rest) fails on this head (618f683133) in two of the diffusion tests this PR adds or changes. The run merged onto fcee6485fe, which already has #13336, so it is not the stale main red.

FAILED tests/diffusion/test_diffusion_compile.py::test_embedding_learning_rate_gets_its_own_optimizer_group
  ValueError: Your setup doesn't support bf16/gpu. You need to assign use_cpu if you want to train the model on CPU.
FAILED tests/diffusion/test_diffusion_samplers.py::test_tiny_family_routes_and_generates[trl-internal-testing/tiny-DiffusionGemmaForBlockDiffusion]
  NotImplementedError: Unsloth cannot find any torch accelerator? You need a GPU.   (from the subprocess)

That runner has no GPU. The optimizer-group test builds a trainer with bf16 on. Setting use_cpu = True, bf16 = False in its TrainingArguments, or building the optimizer without a full trainer, would let it run there. The sampler test spawns a fresh Python that imports unsloth, and outside the in-process CUDA spoof that import refuses. It needs a requires_gpu style skip, or the spoof has to be imported in the child too.

…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.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 375f52a67d

ℹ️ 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".

# 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).
@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. 🚀

Reviewed commit: 71bfdbdf03

ℹ️ 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

pre-commit.ci run

# Conflicts:
#	unsloth/models/loader.py
@danielhanchen
danielhanchen merged commit 6a70df3 into main Oct 13, 2026
@danielhanchen
danielhanchen deleted the diffusion-compile-core branch October 13, 2026 16:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant