Repository navigation
Diffusion LM training: compiled chunked loss with 0 graph breaks, plus per-family samplers - #13341
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
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
There was a problem hiding this comment.
💡 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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| 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, | ||
| ) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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
|
Codex Review: Didn't find any major issues. 🚀 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". |
…f re-exporting it
|
Codex Review: Didn't find any major issues. Can't wait for the next one! 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". |
|
That runner has no GPU. The optimizer-group test builds a trainer with bf16 on. Setting |
… 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.
|
Codex Review: Didn't find any major issues. 🚀 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". |
# 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).
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. 🚀 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". |
|
pre-commit.ci run |
# Conflicts: # unsloth/models/loader.py
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)
diffusion_loss.py: a chunked, weighted linear cross-entropy with a custom backward. It computeshidden @ lm_headper row chunk and never materialises full[tokens, vocab]logits. The per-chunk kernels are compiled withfullgraph=True, dynamic=Falseand padded to a power of two, so a run compiles a handful of graphs and never recompiles per sequence length..item(), no data-dependent shapes. Logging metrics stay tensors untillog().DiffusionConfig.diffusion_compile:"auto"(default; compiled loss chunks on CUDA, except DiffusionGemma),"loss","full"(adds per-layer backbone compile for LLaDA, Dream and Nemotron), orFalse.UNSLOTH_COMPILE_DISABLE=1turns it off.Correctness fixes found while doing this
inverse_tweighting no longer divides 0 by 0 when the noise floor is 0.lm_headis re-checked before reusing the fused head path."full"hit a checkpoint recompute metadata mismatch.SlidingWindowCache, which some transformers 5.x releases (including 5.5) do not ship. A stand-in is provided only while that file imports.is_remote_code()from_auto_classalone, so the class's own_init_weightsran over the checkpoint (step-1 loss 23 / 44 instead of ~1). The class is now registered for its auto class, asAutoModeldoes.eos_token_idis<|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_inferenceandFastModel.get_peft_modelnow dispatch diffusion models to the diffusion path. Before this, they crashed with_saved_temp_tokenizerfor all 7 families.get_peft_model:use_rsloraand seeds fromrandom_state;use_doraandloftq_config, and warns on options it ignores;diffusion_samplers.py: per-family denoising samplers behindFastDiffusionModel.generate_text. They support cancellation (DiffusionGenerationCancelled) and restore Nemotron's attention mode afterwards.is_diffusion_modelexport.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.fullwas measured in a later session (after the RoPE warm-up fix), whereautoran at 254 ms/step on that card. Compare it against that, not against the other columns."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)._init_weightswould overwrite it) and the end-of-turn stop.