Skip to content

Score DPO, KTO, ORPO and CPO log-probs from hidden states with a chunked head - #13934

Closed
danielhanchen wants to merge 16 commits into
mainfrom
chunked-logprob-preference
Closed

danielhanchen wants to merge 16 commits into
mainfrom
chunked-logprob-preference

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

Fixes #5291

Needs unslothai/unsloth-zoo#1803 for the kernel. With an older unsloth_zoo every patched trainer keeps TRL's stock path.

Problem

ORPO, CPO, DPO and KTO under Unsloth score log-probs from the full [2B, S, V] logits tensor (TRL's own concatenated_forward / forward), so the head dominates memory on long sequences. TRL 1.15 fixed DPO and KTO with its own fused head, but ORPO and CPO (now trl.experimental) still materialize full logits on every TRL version, and DPO / KTO do on every TRL older than 1.15, which most notebooks pin.

Measured under Unsloth main, Qwen3-0.6B LoRA, about 4k-token completions, 2 steps:

trainer TRL 0.25.1 peak TRL 1.15 peak
ORPO 17.69 GiB 13.02 GiB
CPO 17.69 GiB 13.02 GiB
DPO 15.34 GiB 1.80 GiB (TRL fused head)
KTO 20.01 GiB 1.80 GiB (TRL fused head)

What this does

The model call inside the trainer sets UNSLOTH_RETURN_HIDDEN_STATES for that call only, the existing GRPO check confirms the forward really returned hidden states, and per-token log-probs come from zoo's unsloth_chunked_logprobs / unsloth_masked_logprobs (chunked head, backward recomputes logits per chunk). Anything not reproduced exactly runs TRL's own code on real logits.

  • ORPO / CPO (concatenated_forward, TRL 0.25.1 and 1.15 trl.experimental): log-probs (sum or average as stock), the NLL term (ORPO over prompt + response from input_ids; CPO over chosen labels), and logits/chosen / logits/rejected from per-position vocab means, so x.detach().mean() equals stock.
  • DPO (TRL 0.18.2 to 0.28, concatenated_forward): log-probs for completion tokens only, rpo_alpha / sft NLL rebuilt from the same per-token log-probs, logits metrics exact. TRL >= 0.29 has no concatenated_forward and 1.15 has its own fused head: untouched.
  • KTO (TRL 0.18.2 to 1.5): the policy pass.
  • Rewrites apply only when every anchor in TRL's source matches exactly once (checked at 11 DPO and 14 KTO release tags); otherwise TRL's source is returned unchanged.
  • Stock path, decided before the forward: encoder-decoder, aux loss, padding_free, use_weighting, vision inputs, FSDP / DeepSpeed, quantized / PEFT-wrapped / ZeRO-3 heads, MiniCPM3, DDP find_unused_parameters with a trainable head, a forward that ignored the flag, a subclass overriding get_batch_logps (or, for ORPO / CPO / KTO, get_batch_loss_metrics, which would see stand-in logits) below the rewritten method, or UNSLOTH_PREFERENCE_CHUNKED=0 / UNSLOTH_DPO_CHUNKED=0.
  • Logit scale and softcap come from the same resolver GKD uses.

Results

Same setup as above, this PR + unsloth-zoo#1803:

trainer TRL peak before peak after step 1 loss before / after kernel calls
ORPO 0.25.1 17.69 GiB 2.89 GiB 3.745351 / 3.745343 2
ORPO 1.15 13.02 GiB 2.89 GiB 3.745351 / 3.745343 2
CPO 0.25.1 17.69 GiB 2.89 GiB 3.665111 / 3.665140 2
CPO 1.15 13.02 GiB 2.89 GiB 3.665111 / 3.665140 2
DPO 0.25.1 15.34 GiB 3.32 GiB 0.693147 / 0.693147 4
KTO 0.25.1 20.01 GiB 8.36 GiB 0.5 / 0.5 4
DPO / KTO 1.15 1.80 GiB 1.80 GiB (TRL head, unchanged) same 0

The small loss differences come from the kernel computing logits in fp32 (its per-token log-probs match fp64 to about 6e-8; TRL's bf16 logits do not). DPO / KTO sit at ln 2 / 0.5 in these 2-step runs because the policy still equals the reference; a 6-step run at lr 2e-4 matches base at steps 1-2 (log-probs to 4 significant digits, grad norm within 0.2%) and later steps stay inside the base-vs-base spread.

AMD Strix Halo (gfx1151, ROCm), DPO head + loss + backward through the zoo kernel, base and head in one job: extra peak at 8k tokens 2.40 GiB -> 0.52 GiB, step time 983 -> 974 ms.

Tests

  • tests/python/test_preference_chunked_logprobs.py: runs TRL's installed ORPO / CPO source with and without the rewrite and compares loss, every metric and every parameter gradient in fp32 (ORPO; CPO sigmoid with label smoothing, hinge, ipo, simpo; AlphaPO; cpo_alpha=0), on a LoRA-wrapped tiny Qwen3 and a toy model with head bias, logit scale and softcap; fallbacks, idempotence and the generated trainer file.
  • tests/test_dpo_chunked_logprobs.py: the same against TRL's own unmodified DPO / KTO trainer (re-executed from TRL's file, since importing unsloth swaps the classes), for sigmoid, ipo, hinge + rpo, sft, robust + label smoothing, precomputed ref log-probs and two KTO configs; rewrite applies and compiles at every DPO / KTO release tag.
  • Linux and Windows CPU runners (TRL 0.25.1, torch 2.8): 33 passed each.
  • TRL 0.25.1: 191 passed across these plus the existing GRPO / GKD / DPO / CPO tests; TRL 1.15: 183 passed, 10 skipped (DPO / KTO parity, which 1.15 does not need).

Not covered

DPO on TRL 0.29 to 1.14 still scores full logits (those versions read entropy and argmax accuracy from them); KTO's reference and KL passes still build full logits under no grad. The chosen / rejected "logits" ORPO and CPO return are per-position vocab means, which only matters to a subclass that reads their shape. Softcap / scale models end to end, multi-GPU and vision models have not been run.

concatenated_forward asks the forward for hidden states and computes the per-token
log-probs, the NLL term and the logits metrics through unsloth_zoo's chunked
log-prob kernel, whose backward recomputes logits per chunk, so the [2B, S, V]
logits tensor is never materialized. A forward that ignores the flag, an older
unsloth_zoo without the kernel, encoder-decoder models, aux loss, FSDP/DeepSpeed
and non-dense heads keep TRL's own body.
… head

On TRL < 0.29 DPOTrainer.concatenated_forward and TRL < 1.10 KTOTrainer.forward
materialise the full [B, S, V] logits and keep them for backward. Ask the
forward for hidden states and score them with unsloth_zoo's chunked
log-prob kernel instead. NLL (rpo_alpha, sft) and the logits metrics are
rebuilt from per-token log-probs and vocab means; padding_free,
use_weighting, vision inputs, encoder-decoder, FSDP/DeepSpeed and forwards
that ignore the flag keep TRL's path. An unsloth_zoo without the kernel
leaves the TRL source untouched; UNSLOTH_DPO_CHUNKED=0 opts out.
# Conflicts:
#	unsloth/models/rl_replacements.py
conftest imports unsloth, which swaps TRL's DPOTrainer and KTOTrainer for the
generated classes; re-execute TRL's module file so the reference is stock.
Keep dataset maps in process and skip KTO parity where the installed
trainer has no rewritable forward (TRL >= 1.10).
@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 ✅ Completed 2026-10-16T07:42:06.350137Z 6a39725 Manual request
🔒 Security Review ⚠️ Failed 2026-10-15T20:18:38.324817Z 7f0317e 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[bot]

This comment was marked as resolved.

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

ℹ️ 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 +4804 to +4805
per_token, mean_logits = unsloth_chunked_logprobs(
rows, head.weight, targets, return_mean_logits = True, **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.

P1 Badge Move preference hidden states to the output-head device

When an Accelerate-dispatched model spans devices, its top-level hook can return hidden states on the input device while head.weight remains on the output device; the GKD path explicitly handles this case by moving states to the head device, and the DPO helper does likewise. This ORPO/CPO call passes rows and targets unchanged, so the chunked projection fails with a cross-device tensor error (including the second NLL pass) instead of training. Move the states and associated targets to head.weight.device before invoking the kernel.

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.

unsloth_chunked_logprobs moves the rows and targets to lm_head.device itself and returns the log-probs on the caller's device (unsloth_zoo fused_losses/chunked_logprob.py), and both calls here (including the split NLL pass) go through it, so a split model does not hit a cross-device error.

Comment on lines +4754 to +4757
unwrapped = self.accelerator.unwrap_model(model)
multiply, divide, softcap = _unsloth_pref_logit_transforms(unwrapped)
if not _unsloth_grpo_returns_hidden_states(unwrapped, states, head.weight):
return None, states

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 without a support signal

For a model whose vocabulary size equals its hidden size and whose forward does not honor UNSLOTH_RETURN_HIDDEN_STATES, this check cannot distinguish the returned logits from hidden states: _unsloth_grpo_returns_hidden_states treats an absent support signal as success when the head is square. The chunked path then projects the already-computed logits through the head a second time, silently changing all preference log-probabilities and gradients. In this ambiguous shape case, fall back unless the model provides a positive hidden-state support signal.

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.

Same rule as the GRPO path this reuses: the shape is decisive whenever vocab_size != hidden_size, which holds for every real LM; a square head with no marker is not a reachable configuration.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Oct 15, 2026
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Oct 15, 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: b31bb33359

ℹ️ 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/rl_replacements.py Outdated
owner = klass
if hook is None and "get_batch_logps" in vars(klass):
hook = klass
return hook is None or owner is None or hook in owner.__mro__

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 Detect instance-level log-prob overrides

The new MRO-only guard still misses a custom get_batch_logps bound directly on a trainer instance: no class in the MRO contains that override, so hook is either the stock class or None and this returns true. In that scenario TRL's stock body would dynamically call the instance hook, while the ORPO/CPO/DPO/KTO chunked paths bypass it and silently optimize different log-probabilities; reject instance-level overrides before enabling the shortcut.

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.

Binding get_batch_logps onto a trainer instance is not a supported extension point; subclass overrides are the documented route and are detected.

danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Oct 15, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 9e05adc45f

ℹ️ 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[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 16, 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. Delightful!

Reviewed commit: d18199a70e

ℹ️ 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. Hooray!

Reviewed commit: 6a39725935

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

Closing in favour of #14185, which contains every commit of this PR (chunked hidden-state log-probs for DPO / KTO / ORPO / CPO, the same rl_replacements symbols and both test files) and extends it with the zoo fused linear head routing. Review and testing continue there.

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 25, 2026
…linear kernel (unslothai#14185)

## Summary

Routes the remaining TRL preference and RL losses to the unsloth-zoo
fused linear kernel (unslothai/unsloth-zoo#1866), so they never build
`tokens x vocab` logits. Builds on unslothai#13934 (contains its commits, merged
with current main).

- **ORPO / CPO / KTO:** score only the loss and NLL positions through
the fused op. The `logits/*` metrics come from the op's mean-logits
output. KTO's KL pass runs through the op too.
- **DPO on TRL 0.29 to 1.14:** `_compute_loss` and the reference
log-prob precompute (`compute_ref_log_probs` / `_compute_ref_log_probs`)
read log-probs, entropy, mean logits and argmax hits from the op instead
of full logits, with TRL's temperature convention and masks. Vision
batches keep TRL's own path on these versions.
- **KTO on TRL 1.6 to 1.14:** `_compute_kl_logps` and `_compute_loss`
likewise, covering the four source layouts TRL used in that range.
- **KTO reference precompute on TRL 0.22 to 1.14**
(`compute_reference_log_probs` / `compute_ref_log_probs` /
`_compute_ref_log_probs`): the completion and KL forwards score from
hidden states. On one batch at V = 131072 with KL, peak memory goes from
4.1 - 4.6 GiB to 282 MiB, with log-probs equal to 1e-7. TRL's statement
stays as the fallback branch, and its text matches the previous rewrite
chain on all 26 historical layouts (TRL 1.6's truncation clamp
included).
- **TRL 1.15's fused head:** `ChunkedLogProbFunction` is routed to the
op when the requested outputs are supported. The adapter also handles
the two-output kernel of TRL 1.1 to 1.14, which used to crash TRL 1.14's
own `patch_chunked_lm_head` ("too many values to unpack"). TRL 1.15 DPO
/ KTO only log the entropy, so the adapter asks the op for a lazy
entropy gradient (a zoo with the v4 op): a frozen head keeps the
forward-gradient path, 0.80-0.88x TRL there, while a GRPO entropy bonus
still gets its gradient. Calls with TRL main's `support_ids` (truncated
support) go to TRL's own kernel, and `UNSLOTH_FUSED_LINEAR=0` set after
the adapter is installed still restores TRL's kernel.
- **GRPO:** old / reference log-probs are scored by the same function as
the policy pass in zoo's `grpo_accumulated_loss`, so the importance
ratio of identical policies starts at 1 (exactly for a LoRA / frozen
head).
- **Fallbacks:** every rewrite keeps TRL's source as the fallback branch
and only applies when each anchor matches exactly once. At run time
TRL's path is used for the kill switch, `use_weighting`, aux loss,
vision, FSDP / DeepSpeed, liger, `return_outputs`, and output heads with
forward or backward hooks (incl. pre-hooks), a patched `forward` or an
accelerate hook, and square heads (vocab size == hidden size) whose
forward gives no hidden-state marker. `UNSLOTH_FUSED_LINEAR=0` restores
TRL's paths everywhere.
- **DPO reference pass:** projected with grad disabled, as in TRL's
no_grad reference forward, so a trainable or shared head gets no
reference gradient.
- **TRL 1.1 to 1.13:** their `_ChunkedLogProbFunction` takes no `bias`,
so the adapter is not installed there.
- **`UNSLOTH_COMPILE_DISABLE=1`:** the sentence-transformer fast encoder
path stays on; only its `torch.compile` is skipped. An 8-bit encoder
request keeps the fallback loader, which is the one that forwards
`load_in_8bit`.

## Testing

- **TRL vs rewrite:** new tests
`tests/python/test_fused_linear_dpo_compute_loss.py`,
`test_fused_linear_kto_compute_loss.py` and
`test_fused_linear_trl_routes.py` run TRL's real methods against the
rewritten ones. They compare loss, every gradient and every logged
metric to 1e-5. Deliberately broken variants (wrong mask, perturbed
entropy or metric) fail.
- **Results across TRL versions:**

  | TRL | passed | skipped |
  |---|---|---|
  | 0.25.1 | 10 | 17 |
  | 0.29.1 | 17 | 10 |
  | 1.6.0 to 1.7.1 | 25 | 2 |
  | 1.8.0 to 1.14.2 | 26 | 1 |
  | 1.15.0 | 9 | 18 |

On 0.25.1 and 1.15 nothing is rewritten. After the review fixes, the
full fused-linear set (GPU) is 0 failed on TRL 0.25.1, 0.29.1, 1.14.2,
1.15.0 and 1.16.0, and on the floor stack (transformers 4.57.6, TRL
0.22.2, PEFT 0.18.0).
- **Cross-platform CPU CI** with torch, TRL 1.14.2 and the zoo branch
installed: ubuntu-latest and windows-latest 64 passed / 51 skipped each.
- **End to end:** Unsloth LoRA on a tiny Qwen3.
- KTO on TRL 1.6, 1.10 and 1.14.2: step-1 relative difference vs TRL's
path is at most 2.6e-4, with 0 graph breaks.
  - DPO on 0.29.1, 1.10, 1.14.2 and 1.15: at most 7.2e-4.
  - DPO precompute on 1.14.2: step-1 loss 0.693147 on both arms.
- **Graph breaks on stock TRL 1.15 with `torch_compile`:** the adapter
arm has fewer than TRL's own kernel (8 vs 10 for SFT, 18 vs 22 for DPO).
Every remaining break is TRL's own boolean indexing.
- **Final heads with unslothai/unsloth-zoo#1866, before / after vs
main:** 13 of 13 jobs show no regression (Kaggle T4 fp16 and A100: SFT,
4-bit SFT, DPO, 4-bit DPO, KTO, GRPO, 4-bit inference on Qwen3-0.6B /
Qwen3.5-0.8B / gemma-4-E2B), 0 graph breaks, peaks equal or lower.
Version corners (transformers 4.57.6 / TRL 0.22.2 / PEFT 0.18.0, TRL
1.16.0 / PEFT 0.20.0, TRL main), vLLM fast_inference GRPO and vision
GRPO / 4-bit vision SFT also show no regression.
- **Vision DPO:** on TRL 1.15 the adapter takes vision DPO through the
fused op (tiny Gemma3 / Gemma4 / Qwen2.5-VL / Qwen3-VL and Qwen3-VL-2B:
no regression vs main). On TRL 0.25.1 to 1.14 vision batches stay on
TRL's path, bit-identical to main.
- **Multi-GPU (Kaggle T4x2, device-mapped Qwen3.8-27B and Muse Glimmer
30B GRPO notebooks):** both run before and after with the op on the
second card; no OOM, peak memory equal or lower (numbers in
unslothai/unsloth-zoo#1866).
- **Routing suites:** 132 passed / 22 skipped on TRL 0.25.1 and 128 / 26
on TRL 1.15.0 (sentence-transformers installed).
- **Studio regression run:** functional NO_REGRESSION (45 SAME; one
visual diff on the hub listing page, which this PR does not touch).
- **Speed and memory:** the numbers are in unslothai/unsloth-zoo#1866.
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.

[Feature] Port GRPO chunked/hidden-state optimizations to ORPO/DPO/CPO trainers

1 participant