Skip to content

Train text-diffusion LMs: DiffusionTrainer with recipes for DiffusionGemma, LLaDA, LLaDA-MoE, LLaDA2, Dream, Nemotron and SDAR - #13157

Merged
danielhanchen merged 11 commits into
mainfrom
diffusion-lm-training
Oct 10, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
diffusion-lm-training

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 9, 2026 •

Copy link
Copy Markdown
Member

Adds supervised fine-tuning for text-diffusion language models through one API: FastModel.from_pretrained routes any supported diffusion checkpoint to FastDiffusionModel, FastModel.get_peft_model attaches LoRA, and the new DiffusionTrainer / DiffusionConfig (built on SFTTrainer, so the usual chat / prompt-completion datasets and completion_only_loss / assistant_only_loss work) trains with each family's own denoising objective.

from unsloth import FastModel, DiffusionTrainer, DiffusionConfig

model, tokenizer = FastModel.from_pretrained("GSAI-ML/LLaDA-8B-Instruct", trust_remote_code = True)
model = FastModel.get_peft_model(model, r = 16, lora_alpha = 32)
trainer = DiffusionTrainer(
    model = model,
    processing_class = tokenizer,
    train_dataset = dataset,  # prompt / completion or messages
    args = DiffusionConfig(completion_only_loss = True, max_steps = 60, output_dir = "outputs"),
)
trainer.train()

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.

Family Checkpoints Noise / layout Objective follows Loss parity vs reference (fp32)
DiffusionGemma google/diffusiongemma-26B-A4B-it uniform token noise, causal encoder + bidirectional canvas TRL examples/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 canvas 0.0 (loss and grads)
LLaDA GSAI-ML/LLaDA-8B-Instruct, -Base, LLaDA-1.5 absorbing mask, full sequence LLaDA GUIDELINES.md SFT 0.0
LLaDA-MoE inclusionAI/LLaDA-MoE-7B-A1B-Instruct absorbing mask, full sequence LLaDA SFT 0.0
Dream Dream-org/Dream-v0-Instruct-7B, DiffuCoder absorbing mask, shifted logits Dream trainer 1.7e-7
Nemotron-Labs-Diffusion nvidia/Nemotron-Labs-Diffusion-3B / -8B absorbing mask, full sequence its own forward loss 0.0
LLaDA2.x inclusionAI/LLaDA2.0-mini, LLaDA2.1-mini block diffusion, [noisy ; clean] dFactory 1.9e-6
SDAR JetLM/SDAR-1.7B-Chat, SDAR-8B-Chat block diffusion SDAR training code 9.5e-7

DiffusionGemma fixes

  1. The Sudoku notebook trained with model(..., canvas_ids = ...). DiffusionGemmaForBlockDiffusion.forward has no canvas_ids argument (the canvas is decoder_input_ids), so it was swallowed by **kwargs and every step denoised a fresh uniform random canvas. Output with canvas_ids is 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.
  2. merge_and_unload on 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.
  3. The default LoRA targets no longer wrap the self-conditioning block's 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):

Arm Train time Peak memory Cell accuracy at 32 denoising steps
base - - 82.8%
old notebook loop (canvas_ids) 149.7 s 59.9 GB 18.1%
DiffusionTrainer 177.8 s 61.9 GB 85.8%

Remote 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:

  • RoPE inv_freq comes 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_buffers recomputes it from each module's own rope_init_fn.
  • LLaDA: missing all_tied_weights_keys (no post_init), use_cache default, and gradient checkpointing bridged to its own set_activation_checkpointing.
  • Dream: GenerationConfig.validate rejecting 5.x keywords and diffusion_generate crashing without a generation config (mask_token_id: null).
  • SDAR: torch stand-ins for its flash_attn imports during module load only, fuse_cross_entropy off (a train-mode forward otherwise returns no logits), and legacy past_key_value[layer] cache indexing.
  • Nemotron-Labs-Diffusion: its prefill filters arguments by 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_pretrained on a saved diffusion LoRA directory loads the base and attaches the adapter.
  • Nemotron reports model_type = "nemotron" after the loader's type resolution, so routing matches the raw config against the profiles instead (matching on nemotron would misroute the autoregressive Nemotron models).
  • DiffusionConfig forces packing = False and padding_free = False: packed rows share one bidirectional attention window, so documents would see each other.
  • The vision exclude regex is only passed to PEFT when the model has a vision tower.
  • DiffusionConfig sets TRL's router_aux_loss_coef to 0: TRL 1.x otherwise turns on MoE router logits for LLaDA-MoE / LLaDA2, and no diffusion objective uses that term.
  • full_finetuning = True makes get_peft_model a no-op, a caller's config / quantization_config is honoured, and loading a diffusion model restores Hugging Face progress bars.
  • Under DDP / FSDP the recipes read config and heads from the unwrapped module and keep the wrapper for the forward, and evaluation runs under the same autocast context as training.

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-end DiffusionTrainer runs 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 unsloth time 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):

Model Loss, first 10 vs last 10 steps s / step Peak GB Generation after training
LLaDA-8B-Instruct 1.063 -> 0.983 0.45 19.4 coherent
LLaDA-MoE-7B-A1B-Instruct 0.749 -> 0.786 1.86 17.8 coherent
Dream-v0-Instruct-7B 0.845 -> 0.830 0.38 19.2 coherent
Dream-v0-Instruct-7B (4bit) 0.861 -> 0.860 0.69 9.5 coherent
LLaDA-8B-Instruct (4bit) 0.273 -> 0.242 (masked CE 0.284 -> 0.246) 0.43 9.1 coherent
Nemotron-Labs-Diffusion-3B 1.230 -> 0.955 0.47 10.7 coherent
LLaDA2.0-mini (16B MoE) 0.705 -> 0.781 11.2 35.4 coherent
SDAR-1.7B-Chat fixed-noise loss 1.314 -> 1.259 0.30 6.1 coherent

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).

…r DiffusionGemma, LLaDA, LLaDA-MoE, LLaDA2, Dream, Nemotron and SDAR
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 9, 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 ✅ Completed 2026-10-09T19:54:18.183821Z 64e4055 Manual request
ℹ️ 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

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

@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: 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".

Comment thread unsloth/models/diffusion_masked.py Outdated
Comment on lines +243 to +247
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

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 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 👍 / 👎.

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.

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
@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: 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".

Comment on lines +169 to +171
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):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

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.

FastDiffusionModel runs single process or DDP, not FSDP; the head access matches TRL's reference recipe, which gathers only for ZeRO-3.

Comment on lines +123 to +124
loss = self.compute_loss(model, inputs)
return (loss.detach(), None, 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 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 👍 / 👎.

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.

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
@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: 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

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.

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.

Comment on lines +281 to +282
else:
loss = token_loss.sum() / masked.sum()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

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.

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

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 recipe (TRL examples/sft_diffusion_gemma), which keeps the full canvas visible and only drops the fill from the cross-entropy for truncated rows.

@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

model, tokenizer = FastDiffusionModel.from_pretrained(

P2 Badge Forward the caller's model config into diffusion loading

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.


load_kwargs = dict(
dtype = dtype,
device_map = device_map,
token = token,
trust_remote_code = trust_remote_code,
attn_implementation = attn_implementation,
revision = revision,

P2 Badge Forward code_revision to the remote block-model load

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

Comment on lines +113 to +115
mode = "train" if model.training else "eval"
for key, value in (metrics or {}).items():
self._diffusion_metrics[f"{mode}/{key}"].append(float(value))

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 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 👍 / 👎.

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.

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
@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: 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".

Comment on lines +456 to +462
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)

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 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 👍 / 👎.

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.

No SDAR checkpoint loads with a code_revision distinct from its weights revision; out of scope for this path.

Comment on lines +177 to +181
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
)

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 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 👍 / 👎.

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.

Not reachable in SFT: every row has a prompt and a response, so at least one next-token pair exists.

Comment on lines +114 to +115
for key, value in (metrics or {}).items():
self._diffusion_metrics[f"{mode}/{key}"].append(float(value))

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 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 👍 / 👎.

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.

A handful of floats per step is negligible even over very long runs; not worth the extra state.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 9, 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 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

random_state = 3407,

P2 Badge Honor random_state when initializing diffusion LoRA

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.


if use_gradient_checkpointing and hasattr(model, "gradient_checkpointing_enable"):
model.gradient_checkpointing_enable()

P2 Badge Disable checkpointing when explicitly requested

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.


return AutoConfig.from_pretrained(
model_name,
token = token,
trust_remote_code = trust_remote_code,
revision = revision,
local_files_only = local_files_only,
cache_dir = cache_dir,
)

P2 Badge Isolate LLaDA config registrations across loads

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

Comment on lines 409 to 412
if not return_tokenizer:
if profile is not None:
profile.prepare_model(unwrap_diffusion_model(model), None)
return model, 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 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 👍 / 👎.

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.

Dream's config.json ships mask_token_id 151666 and the profile falls back to the config, so the id resolves without a tokenizer.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: aa78d6acf8

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

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 9, 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. 🚀

Reviewed commit: 64e4055f5a

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

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