Skip to content

DPO, ORPO, CPO: opt-in fused preference loss (UNSLOTH_FUSED_PREFERENCE_LOSS=1) - #13870

Merged
danielhanchen merged 7 commits into
mainfrom
dh/fused-preference-loss
Oct 16, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
dh/fused-preference-loss

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Needs unslothai/unsloth-zoo#1782 (the chunked kernel).

With UNSLOTH_FUSED_PREFERENCE_LOSS=1, the generated DPO (TRL 0.22 to 0.28), ORPO and CPO trainers score completions from the model's final hidden states through the new unsloth_zoo chunked kernel, instead of materialising full logits for the policy and reference passes.

What is reproduced from TRL's concatenated_forward:

  • Truncation, padding-free, logits_to_keep, ipo normalisation, ld_alpha, the RPO and SFT NLL, WPO weights and the logits metrics.
  • The loss itself, every loss_type and all logged metrics remain TRL's own code.

Fallbacks: any input the reimplementation does not cover returns None and TRL's original forward runs:

  • vision batches, encoder-decoder, MoE aux loss
  • a LoRA, quantized or sharded output head, or unknown logit transforms

With the flag unset, the generated trainer files are byte-identical to before.

Results:

  • On a T4 in fp16 with Qwen2.5-0.5B LoRA at 8192 tokens per step, peak allocated memory goes from 10.9 GB to 1.35 GB for DPO and from 12.6 GB to 1.7 GB for ORPO (identical across three repeats).
  • At a fixed bf16 model state the DPO loss error against a float64 oracle drops from 2.3e-3 to 6e-7.
  • Tests run TRL's own get_batch_loss_metrics with both forwards on a float64 model and match loss, metrics and gradients to 1e-9 across 25 DPO and 10 ORPO/CPO configurations. They cover TRL 0.22.2 and 0.24 to 0.28, plus ORPO/CPO on 1.15.

TRL 1.15 already fuses the DPO head upstream, and 0.29 to 1.14 DPO has no concatenated_forward, so the flag does not touch DPO on those versions.

Training curves: step 1 is identical (exactly log 2), after that DPO losses depart from the unfused run because the fused path no longer rounds logits to bf16 and Adam's early steps amplify small gradient differences (unfused repeats already differ by up to 0.016 on a T4). There is no long-run final-quality comparison yet, which is one reason this is opt-in.

Not covered: DDP / multi-GPU, softcap and logit-scaling models on GPU (CPU tests only), torch below 2.8 (falls back to half-precision logits with an fp32 softmax), KTO.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 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-16T03:54:47.746802Z ce856de New commits
🔒 Security Review ⚠️ Failed 2026-10-15T15:34:33.981040Z ab60c2f PR opened
ℹ️ 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.

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

ℹ️ 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/dpo.py
Comment on lines +157 to +160
out = fused_linear_token_logps(
hidden_or_logits,
head[0],
head[1],

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 Fall back before scoring outside a DDP forward

When model is wrapped in DDP with find_unused_parameters=True and the output head is untied and trainable, DDP finishes traversing the hidden-state output at the end of model(...) and marks the head parameter unused; invoking the fused kernel on the unwrapped head afterward then makes its autograd hook mark that parameter ready a second time, causing backward to fail with DDP's “Expected to mark a variable ready only once” error. This configuration is used by Transformers for non-checkpointed distributed training unless overridden, so the fused path should decline it or perform the head operation inside the wrapped forward.

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.

Fixed in ac660ac: reproduced with gloo (one and two ranks). Under DistributedDataParallel(find_unused_parameters=True), a trainable untied head applied after model(...) returns fails backward with "Expected to mark a variable ready only once". The fused path now returns None, so TRL's concatenated_forward runs, when the model is DDP-wrapped with find_unused_parameters set and the head weight or bias requires grad; find_unused_parameters=False and frozen heads keep the fused path. Added test_orpo_under_ddp_find_unused_falls_back, checking both settings against TRL's loss, metrics and gradients.

Comment thread unsloth/models/dpo.py
Comment on lines +130 to +134
from .rl_replacements import _unsloth_grpo_returns_hidden_states

is_hidden = _unsloth_grpo_returns_hidden_states(unwrapped, tensor, head_weight)
except Exception:
is_hidden = tensor.shape[-1] == head_weight.shape[1] != head_weight.shape[0]

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 ambiguous square output heads

When an otherwise supported model ignores UNSLOTH_RETURN_HIDDEN_STATES and has vocab_size == hidden_size, its real logits have the same trailing width as hidden states. In that ambiguous case _unsloth_grpo_returns_hidden_states returns true when the unpatched model has no explicit signal, so this call classifies the logits as hidden states and the fused path applies the output head a second time, silently changing every loss and gradient. Require an explicit positive hidden-state signal for square heads or fall back to TRL; the fallback test currently avoids this case by using unequal dimensions.

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.

Fixed in ac660ac: when the output head is square (vocab_size == hidden_size) the fused path now requires an explicit positive signal from _unsloth_grpo_hidden_states_signal (the compiler marker or the hidden states wrapper) before running the forward, and otherwise returns None so TRL's own concatenated_forward runs. Added test_square_head_needs_explicit_hidden_states_signal with a square 64 x 64 head, covering a forward that ignores the flag (falls back, matches TRL) and a marked forward (fused, matches TRL).

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

ℹ️ 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/dpo.py Outdated
Comment on lines +90 to +91
if isinstance(model, torch.nn.parallel.DistributedDataParallel) and getattr(
model, "find_unused_parameters", False

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 Detect DDP beneath torch.compile

When Accelerate's Dynamo integration wraps DDP(find_unused_parameters=True) in torch.compile, model is an OptimizedModule, so this direct isinstance check is false even though _orig_mod is DDP. A trainable untied head is then scored outside the wrapped forward and backward can again fail with DDP's “mark a variable ready only once” error. The fresh evidence beyond the resolved direct-DDP thread is this _orig_mod wrapper case; the repository's _unsloth_find_ddp already traverses that chain, so use equivalent detection before enabling the fused path.

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.

Fixed in 10886a2: the find_unused_parameters check now walks the _orig_mod chain (as _unsloth_find_ddp does), so DDP under torch.compile is detected and a trainable untied head falls back to TRL's forward. Added test_orpo_under_compiled_ddp_find_unused_falls_back, which raised "marked as ready twice" before.

Comment thread unsloth/models/dpo.py
Comment on lines +65 to +68
try:
unwrapped = trainer.accelerator.unwrap_model(model)
except Exception:
unwrapped = model

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 Fall back before unwrapping FSDP models

When model is an FSDP1 wrapper, accelerator.unwrap_model removes the wrapper and this helper can accept the output head's 2-D parameter view. The fused kernel then reads that saved view after the FSDP forward has resharded or freed the full parameter, outside FSDP's managed module call, which can produce invalid storage/shape errors or bypass correct gradient synchronization; the DTensor check only covers FSDP2-style parameters. Detect FSDP before unwrapping and fall back to TRL's forward.

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.

Fixed in 10886a2: _output_head now returns no head when the model contains any FSDP1 FullyShardedDataParallel module (checked before unwrap_model, cached per model), so FSDP1 runs use TRL's forward. Added test_orpo_under_fsdp1_falls_back.

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

ℹ️ 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/dpo.py
Comment on lines +100 to +103
if head is None or hasattr(head, "base_layer") or hasattr(head, "modules_to_save"):
return None, None
weight = getattr(head, "weight", None)
if not isinstance(weight, torch.Tensor) or weight.dim() != 2:

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 Require an unhooked plain linear output head

When get_output_embeddings() returns a custom nn.Linear subclass or a linear carrying an Accelerate _hf_hook/forward hook, these checks still accept it based only on its 2-D weight. The normal model forward invokes that custom behavior (and offload hooks may materialize the weight only during head.forward), whereas the fused kernel later reads the saved weight and bias directly, causing incorrect log-probabilities or meta/wrong-device failures. Restrict this path to a plain, unhooked linear projection, as the existing is_plain_linear validation in unsloth/models/diffusion_loss.py does, and otherwise fall back to TRL.

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.

Fixed in 8a83cbd: _output_head now accepts only type(head) is torch.nn.Linear with no _hf_hook, no instance-level forward, and no forward or forward-pre hooks, the same rule as is_plain_linear in diffusion_loss.py. Anything else falls back to TRL. test_hooked_or_custom_head_falls_back covers a forward hook, a pre hook, _hf_hook and a Linear subclass, and checks the fused path does not engage and the loss equals TRL's.

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

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

@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. You're on a roll.

Reviewed commit: 417f88e88a

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

danielhanchen added a commit to danielhanchen/unsloth-zoo-staging that referenced this pull request Oct 15, 2026
…hai#1782)

Preference trainers only need one log probability per completion token,
but they build batch x seq_len x vocab logits for the chosen and
rejected rows and again for the reference. At long context with a large
vocabulary that tensor and its gradient dominate peak memory.

This adds `unsloth_zoo/fused_losses/preference_loss.py`:
- `fused_linear_token_logps` takes the final hidden states plus the
output head weight and bias. It projects only the scored positions, a
chunk of rows at a time, and recomputes each chunk in backward, so peak
memory holds one rows x vocab chunk.
- It supports logit scaling, division and final soft capping, and a head
bias. It also returns the vocab mean of the logits and log sum p^2
without gradient, for trainer metrics and WPO weights.
- On fp16 and bf16 heads it asks the GEMM for float32 output where torch
supports it (2.8+), so the softmax no longer sees half-precision-rounded
logits. An out-of-memory error there is raised as usual rather than
turning the float32 path off for the rest of the process.
- `linear_mean_logits` gives the vocab mean of the logits for the
trainer metrics without building full logits.

The losses themselves stay TRL's own code: the companion
unslothai/unsloth#13870 feeds these log probabilities into TRL's
`dpo_loss`, `odds_ratio_loss` and `cpo_loss`, and only when
`UNSLOTH_FUSED_PREFERENCE_LOSS=1` is set. Nothing calls the new module
otherwise.

Measured at 8192 tokens, 152k vocab, bf16, forward and backward: extra
peak 4.67 GiB with full logits, 1.33 GiB with the chunked path.

Tests compare against a float64 full-logits oracle (values and gradients
to 1e-12, gradcheck, empty mask, large logits, out-of-memory handling).
@danielhanchen
danielhanchen merged commit 85d7482 into main Oct 16, 2026
@danielhanchen
danielhanchen deleted the dh/fused-preference-loss branch October 16, 2026 05:18
bestoffersdirect-fork-sync Bot pushed a commit to BestOffersDirect/unsloth that referenced this pull request Oct 16, 2026
…nslothai#13979)

## Summary
With `UNSLOTH_OFFLOAD_OPTIMIZER_STATE=1` and more than one chunk,
Q-GaLore with `weight_quant=True` crashed on the first step:

```
RuntimeError: attempting to assign a gradient of size '[256, 256]' to a tensor of size '[1]'
```

The chunked step hides gradients between chunks and restores them
afterwards, but Q-GaLore weight quantization swaps `p.data` for a one
element placeholder inside `step`, so the original gradient can no
longer be assigned back.

## Change
- `_chunk_safe` now returns False when any param group sets
`weight_quant`. Such optimizers use the existing unchunked route: state
is restored, one normal step runs, and state is offloaded again.
Offloading between steps still applies.
- Nothing changes when the env var is unset, and other optimizers are
unaffected.

## Tests
- `test_weight_quant_q_galore_steps_unchunked` (CPU) checks the gate.
- `test_q_galore_multi_chunk_offload[False|True]` (CUDA, bitsandbytes)
runs the real `QGaLoreAdamW8bit` with a 256 KiB chunk budget for two
steps and checks INT8 weights, scales and gradients match a run without
offload bitwise, with state left on CPU. It failed with the error above
before the change.
- `tests/test_optimizer_state_offload.py`,
`tests/test_formatter_fixed_point.py`,
`tests/test_source_read_encoding.py`: 64 passed, 2 skipped on GPU.

# unslothai#13870: opt-in fused preference loss, trainable head, short-sequence
peak VRAM

Verdict: the regression is real, but it comes from the zoo kernel and
zoo PR unslothai#1824 already fixes it. With unslothai#1824 applied, the leftover
short-sequence overhead is a small, bounded trade-off on the unsloth
side. That overhead is set by the 256 MiB fp32 chunk budget, does not
grow with vocab x hidden, and also exists for frozen heads. I made no
change to the unsloth gate and created no branch. I made a throwaway
worktree `wt_pm_fused_pref_gate`, then removed it and deleted its branch
without committing anything.
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