Repository navigation
Train text-diffusion LMs: DiffusionTrainer with recipes for DiffusionGemma, LLaDA, LLaDA-MoE, LLaDA2, Dream, Nemotron and SDAR - #13157
Conversation
…r DiffusionGemma, LLaDA, LLaDA-MoE, LLaDA2, Dream, Nemotron and SDAR
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 |
|
@codex security review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ce91d51acb
ℹ️ 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".
| if self.pad_with_eos and attention_mask is not None and eos_id is not None: | ||
| padding = ~attention_mask.bool() | ||
| input_ids = input_ids.masked_fill(padding, eos_id) | ||
| if inputs.get("labels") is not None: | ||
| maskable = maskable | padding |
There was a problem hiding this comment.
Reject or normalize left-padded masked-diffusion batches
If the processing tokenizer uses left padding, this branch converts those leading pads to attended, supervised EOS tokens and removes the attention mask, even though the family recipes treat EOS padding as an answer tail after the response. This silently changes sequence order and trains the model to emit EOS before the prompt; either enforce right padding as the block objective already does or move/handle padding before supervising it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reachable: DiffusionTrainer batches come from TRL's DataCollatorForLanguageModeling, which pads right regardless of tokenizer.padding_side (left padding is only in the vision collator).
… on adapter reload, skip EOS tails on clipped rows, record the remote-code class loader
…y per-step losses
|
@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: 1865fa1ae9
ℹ️ 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".
| lm_head = base.get_output_embeddings() | ||
| hidden_states = outputs.encoder_last_hidden_state.to(lm_head.weight.dtype) | ||
| with _gather_lm_head(lm_head.weight, lm_head.bias): |
There was a problem hiding this comment.
Gather the output head before the FSDP AR projection
When DiffusionGemma is trained under FSDP, the wrapped forward may reshard parameters before returning, but the encoder co-loss then reads lm_head.weight from the unwrapped module and performs a manual matrix multiplication. _gather_lm_head only gathers DeepSpeed ZeRO-3 parameters, so an FSDP-sharded head can be empty or have its local flattened shape here, causing the first distributed loss to fail. The earlier wrapper-attribute fix does not cover this newly visible direct parameter access; project through an FSDP-aware forward or explicitly summon the full head parameters.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
FastDiffusionModel runs single process or DDP, not FSDP; the head access matches TRL's reference recipe, which gathers only for ZeRO-3.
| loss = self.compute_loss(model, inputs) | ||
| return (loss.detach(), None, None) |
There was a problem hiding this comment.
Return predictions when prediction loss only is false
When callers provide compute_metrics or use trainer.predict(), Transformers invokes this method with prediction_loss_only=False, but the override ignores that argument and unconditionally returns None for both logits and labels. Consequently the evaluation loop cannot call compute_metrics, and predict() silently returns no predictions even for DiffusionGemma, whose objective already returns model outputs. Preserve loss-only behavior only when requested and otherwise return the available predictions and labels, or explicitly reject unsupported prediction modes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Intentional: a diffusion forward depends on freshly sampled noise, so there is no fixed prediction to pair with labels; eval reports the objective's loss, the supported metric.
… aux coef, adapter tokenizer from Hub repos, DeepSpeed keeps its forward
|
@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: ec22ce06bf
ℹ️ 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".
| # the longest row so every supervised row gets at least one EOS. | ||
| block = self.block_size(model, args) | ||
| batch, length = input_ids.shape | ||
| new_length = -(-(length + 1) // block) * block |
There was a problem hiding this comment.
Keep clipped batches within the configured maximum length
When an LLaDA2 batch already has input_ids.shape[1] == args.max_length, this still rounds length + 1 up to another block before the later truncated check merely disables supervision on that tail. The fresh implementation therefore still forwards the extra block and emits position IDs beyond max_length; if that value is the model's positional limit, training can fail despite the earlier review fix claiming clipped rows no longer receive a tail. Avoid extending the batch when every row reaching the current boundary is truncated.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
LLaDA2 and SDAR use RoPE with no position table, and the extra columns are unattended padding outside the loss, so nothing indexes past a limit.
| else: | ||
| loss = token_loss.sum() / masked.sum() |
There was a problem hiding this comment.
Normalize masked-token loss across all ranks
Under DDP, Dream and Nemotron take this branch and divide by each rank's independently sampled masked-token count before DDP averages the rank losses. Since those counts vary with the noise draw and sequence lengths, a rank with few masked tokens is weighted as heavily as one with many, rather than reproducing Nemotron's global (loss_sum, token_count) normalization; multi-GPU experiments therefore optimize a different objective from single-GPU runs. Aggregate the numerator and denominator across ranks, with the appropriate gradient-preserving scaling.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Per-rank normalisation is what the Trainer does for every custom loss under DDP; it is an unbiased estimate of the same objective, not a different one.
| canvas_ids = torch.where(corrupt, random_tokens, canvas_target) | ||
|
|
||
| cache_mask = positions < encoder_len[:, None] | ||
| canvas_mask = torch.ones(batch_size, block_size, dtype = torch.bool, device = device) |
There was a problem hiding this comment.
Hide synthetic EOS tails in truncated Gemma canvases
When a clipped DiffusionGemma response selects its final partial block, canvas_target still fills the remainder with EOS and this mask exposes every one of those positions to the bidirectional decoder. The later diffusion_target masking only removes their direct cross-entropy terms; genuine response positions can still attend to the fabricated EOS tokens, and the self-conditioning pass is derived from the same contaminated canvas. Mask those tail positions from decoder attention for truncated rows so real-token predictions are not conditioned on an artificial endpoint.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This matches the reference recipe (TRL examples/sft_diffusion_gemma), which keeps the full canvas visible and only drops the fill from the cross-entropy for truncated rows.
…ct unknown block time weighting
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
unsloth/unsloth/models/loader.py
Line 2068 in 8657420
When callers pass config= to FastModel.from_pretrained, it is removed from kwargs into user_config before this dispatch, but _dispatch_diffusion neither forwards that object nor otherwise applies it. The diffusion loader consequently reloads the repository config and silently loses caller overrides such as modified architecture or attention settings, unlike the normal FastModel path. Pass user_config through and use it for both profile resolution and the eventual model load.
unsloth/unsloth/models/diffusion.py
Lines 344 to 350 in 8657420
When an LLaDA2 or SDAR caller supplies a code_revision distinct from the weights revision, that value reaches the planner but is omitted from the actual AutoModelForCausalLM.from_pretrained call assembled here. Those profiles return an AutoModel loader rather than the masked-family class resolver, so Transformers fetches remote modeling code from the weights revision instead of the explicitly pinned code revision, defeating reproducible loading and potentially running incompatible code. Add code_revision to load_kwargs for the final load.
ℹ️ 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".
| mode = "train" if model.training else "eval" | ||
| for key, value in (metrics or {}).items(): | ||
| self._diffusion_metrics[f"{mode}/{key}"].append(float(value)) |
There was a problem hiding this comment.
Aggregate diffusion metrics across distributed ranks
Under DDP or DeepSpeed, each rank appends only its locally sampled diffusion metrics here, while the logger ultimately publishes the main process's list without a distributed reduction. User-visible values such as masked_fraction, masked_ce, and the component losses therefore describe rank 0 rather than the global batch, even though the Trainer's primary loss is aggregated separately. Reduce metric sums and counts across ranks before adding them to the logs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Logging only: the optimised loss is reduced by the Trainer; these per-rank diagnostics do not change training.
…ffusion load, no EOS targets for response-less or clipped rows
|
@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: 4606fc3c80
ℹ️ 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".
| def model_class(self, config, trust_remote_code, **hub_kwargs): | ||
| from transformers import AutoModelForCausalLM | ||
| class _Loader: | ||
| @staticmethod | ||
| def from_pretrained(*args, **kwargs): | ||
| with _sdar_remote_code_imports(): | ||
| return AutoModelForCausalLM.from_pretrained(*args, **kwargs) |
There was a problem hiding this comment.
Forward code_revision through the SDAR loader
When an SDAR caller supplies a code_revision distinct from the weights revision, this profile discards the received Hub kwargs and delegates to AutoModelForCausalLM.from_pretrained, while the later load_kwargs also omit code_revision. The earlier forwarding through MaskedDiffusionProfile.model_class therefore does not cover SDAR: its remote Python code is fetched from the default or weights revision rather than the caller's pin, undermining reproducibility and potentially pairing the planned model with different code. Forward code_revision to the actual AutoModel load.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
No SDAR checkpoint loads with a code_revision distinct from its weights revision; out of scope for this path.
| ar_mask = attention_mask[:, :-1].bool() & attention_mask[:, 1:].bool() | ||
| ar_targets = torch.where(ar_mask, input_ids[:, 1:], -100) | ||
| ar_loss = F.cross_entropy( | ||
| encoder_logits[:, :-1].flatten(0, 1), ar_targets.flatten(), ignore_index = -100 | ||
| ) |
There was a problem hiding this comment.
Return a zero AR co-loss when no next-token pair exists
When every row in a batch has no adjacent attended tokens—for example with max_length=1 or a batch of one-token samples—ar_targets is empty or entirely -100, so mean-reduced cross_entropy returns NaN. That NaN contaminates the total loss even when diffusion_encoder_ar_weight is zero, breaking an otherwise valid diffusion step. Guard this call as the diffusion loss is guarded above and produce a differentiable zero when there is no valid AR target.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reachable in SFT: every row has a prompt and a response, so at least one next-token pair exists.
| for key, value in (metrics or {}).items(): | ||
| self._diffusion_metrics[f"{mode}/{key}"].append(float(value)) |
There was a problem hiding this comment.
Bound diffusion metric accumulation between log calls
When logging is disabled with logging_strategy="no" or configured with a very large interval, every training step appends Python floats to these lists and nothing removes them until a later log() call, which may only happen after training finishes. Long diffusion runs therefore consume memory linearly with the number of steps even though only each metric's mean is needed. Store a running sum and count, or otherwise bound the retained samples.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
A handful of floats per step is negligible even over very long runs; not worth the extra state.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
unsloth/unsloth/models/diffusion.py
Line 469 in 8767d59
When callers rely on random_state to reproduce an experiment but the process RNG is in a different state, this argument has no effect because it is never used before PEFT initializes the adapter matrices. The regular Unsloth LoRA paths explicitly seed at this point, so diffusion runs with the same advertised random_state can start from different adapters and diverge.
unsloth/unsloth/models/diffusion.py
Lines 538 to 539 in 8767d59
If LoRA setup previously enabled gradient checkpointing—the default—and the caller later invokes FastModel.for_training(model, use_gradient_checkpointing=False), this branch does nothing, leaving checkpointing active despite the explicit setting. This is especially visible for LLaDA, whose compatibility bridge leaves native whole-layer activation checkpointing enabled until gradient_checkpointing_disable() is called, so runs unexpectedly retain checkpoint recomputation overhead.
unsloth/unsloth/models/diffusion.py
Lines 133 to 140 in 8767d59
When dense LLaDA and LLaDA-MoE checkpoints are loaded sequentially in one process, both remote config implementations register the shared llada model type globally, so the first registration can shadow the second and make this AutoConfig probe instantiate the wrong family config before profile and model-class selection. The added integration test explicitly avoids this by running each family in a separate process (test_diffusion_masked.py:467), but ordinary applications receive no such isolation; resolve the checkpoint's declared remote config without leaving the competing registration active globally.
ℹ️ 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".
| if not return_tokenizer: | ||
| if profile is not None: | ||
| profile.prepare_model(unwrap_diffusion_model(model), None) | ||
| return model, None |
There was a problem hiding this comment.
Retain Dream's mask token when skipping tokenizer return
For Dream checkpoints loaded with return_tokenizer=False, preparing the profile with None cannot record the tokenizer's mask token; Dream's config may leave mask_token_id null and its profile supplies no family default. A caller that already owns a tokenizer and passes it to DiffusionTrainer will therefore still fail on the first loss with “needs a [MASK] token id,” because the trainer never reruns prepare_model; resolve or retain the tokenizer metadata before this early return.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Dream's config.json ships mask_token_id 151666 and the profile falls back to the config, so the id resolves without a tokenizer.
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. 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". |
|
@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". |
Adds supervised fine-tuning for text-diffusion language models through one API:
FastModel.from_pretrainedroutes any supported diffusion checkpoint toFastDiffusionModel,FastModel.get_peft_modelattaches LoRA, and the newDiffusionTrainer/DiffusionConfig(built onSFTTrainer, so the usual chat / prompt-completion datasets andcompletion_only_loss/assistant_only_losswork) trains with each family's own denoising objective.Supported families
Each family is a
DiffusionProfile(model types, loader class, LoRA targets, bitsandbytes skip list, objective). The objectives are ported from each family's official training code and checked against it on the same batch and seed.google/diffusiongemma-26B-A4B-itexamples/sft_diffusion_gemma(EOS-filled canvas, two-pass self-conditioning, encoder AR co-loss,mean/mean_loo); rows with no supervised token are skipped instead of trained as an all-EOS canvasGSAI-ML/LLaDA-8B-Instruct,-Base,LLaDA-1.5GUIDELINES.mdSFTinclusionAI/LLaDA-MoE-7B-A1B-InstructDream-org/Dream-v0-Instruct-7B, DiffuCodernvidia/Nemotron-Labs-Diffusion-3B/-8BinclusionAI/LLaDA2.0-mini,LLaDA2.1-miniJetLM/SDAR-1.7B-Chat,SDAR-8B-ChatDiffusionGemma fixes
model(..., canvas_ids = ...).DiffusionGemmaForBlockDiffusion.forwardhas nocanvas_idsargument (the canvas isdecoder_input_ids), so it was swallowed by**kwargsand every step denoised a fresh uniform random canvas. Output withcanvas_idsis identical to passing no canvas at all ([Bug] How does canvas_ids reach the model in the DiffusionGemma training loop? #7515). The notebook is fixed in unslothai/notebooks separately; this PR adds the objective it now uses.merge_and_unloadon DiffusionGemma silently corrupted weights: the encoder and decoder layers share tied base tensors but get independent adapters, so merging adds both deltas into the shared tensor. On the tiny model the merged logits differ from the PEFT model by 0.615, more than the adapter's own effect (0.599). Merging now raises with a clear message; the unmerged adapter saves and reloads exactly.gate_proj/up_proj/down_proj.Real 26B-A4B run on one B200 (bf16, LoRA r=64, 60 steps x grad accum 4, Sudoku, 30 held-out puzzles, greedy, single seed, so directional only):
canvas_ids)DiffusionTrainerRemote code on transformers 5
The remote-code families were written for transformers 4.x and break silently on 5.x. Fixes, all idempotent and applied at load:
inv_freqcomes back zeroed: transformers 5 builds on the meta device and refills non-persistent buffers through_init_weights, which these classes override, so every position looks alike. LLaDA-MoE started training at loss 2.5 instead of 0.17.restore_rotary_buffersrecomputes it from each module's ownrope_init_fn.all_tied_weights_keys(nopost_init),use_cachedefault, and gradient checkpointing bridged to its ownset_activation_checkpointing.GenerationConfig.validaterejecting 5.x keywords anddiffusion_generatecrashing without a generation config (mask_token_id: null).flash_attnimports during module load only,fuse_cross_entropyoff (a train-mode forward otherwise returns no logits), and legacypast_key_value[layer]cache indexing.inspect.signature(create_causal_mask); the unsloth_zoo mask wrapper is(*args, **kwargs), so it passed nothing. Fixed in unsloth-zoo, with a fallback here for older zoo versions.Other changes
FastModel.from_pretrainedon a saved diffusion LoRA directory loads the base and attaches the adapter.model_type = "nemotron"after the loader's type resolution, so routing matches the raw config against the profiles instead (matching onnemotronwould misroute the autoregressive Nemotron models).DiffusionConfigforcespacking = Falseandpadding_free = False: packed rows share one bidirectional attention window, so documents would see each other.DiffusionConfigsets TRL'srouter_aux_loss_coefto 0: TRL 1.x otherwise turns on MoE router logits for LLaDA-MoE / LLaDA2, and no diffusion objective uses that term.full_finetuning = Truemakesget_peft_modela no-op, a caller'sconfig/quantization_configis honoured, and loading a diffusion model restores Hugging Face progress bars.Tests
tests/diffusion/(68 tests): mask layouts, noise ranges, EOS fill, padding isolation, no leakage from future blocks, RoPE repair, merge refusal with a negative control, and loss parity against each reference. End-to-endDiffusionTrainerruns on tiny random copies of every family check that the loss falls, the LoRA weights move, and the saved adapter reloads with identical logits. Two DiffusionGemma parity tests need TRL's example file (UNSLOTH_TRL_DIFFUSION_GEMMA_EXAMPLE) and skip otherwise.The suite passes on transformers 4.57.6 (DiffusionGemma skipped, not in that release), 5.17 and 5.19, and on TRL 0.22.2, 0.25.1, 1.13 and 1.15. The
regression/smoke tier (103 cases) is identical on base and head: 66 passed, 13 xpass, 24 skipped, no regressions or metric moves.import unslothtime is unchanged (16.24 s vs 16.07 s median of 5).Real checkpoints, bf16 LoRA, 30 steps, batch 4, on a shared B200 (step times indicative only):
These are instruct models already, so 30 steps shows stable training and intact decoding, not a quality gain.
Not included
RL for diffusion models (diffu-GRPO) needs its own rollout and log-probability estimator and is left for a follow up. Fast-dLLM v2, iLLaDA and the dllm A2D checkpoints are not profiled yet.
Related: #3375, #7515. Companion PRs: unslothai/unsloth-zoo#1656 (mask builder signature) and unslothai/notebooks#393 (DiffusionGemma Sudoku notebook, which needs this PR merged first).