Skip to content

Route PPO, RLOO, BCO, Online DPO, XPO, Nash-MD and GKD to the zoo fused linear kernels - #15244

Merged
danielhanchen merged 46 commits into
mainfrom
fused-linear-more-trainers
Oct 25, 2026
Merged

danielhanchen merged 46 commits into
mainfrom
fused-linear-more-trainers

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Routes the remaining TRL trainers to the unsloth-zoo fused linear kernels, so their log-prob and distillation losses never build tokens x vocab logits. Follows #14185 (DPO, KTO, ORPO, CPO and TRL 1.15's fused head) and uses the same machinery: the model's forward returns hidden states (UNSLOTH_RETURN_HIDDEN_STATES) and the zoo op scores them.

  • PPO (TRL 0.22 to 1.10, trl.experimental included): old, reference and training log-probs and the entropy metric are scored from hidden states; the value head still reads the critic backbone. Rollouts generate without output_scores, so the B x T x V fp32 score tensor is never kept; the old log-probs come from one no-grad policy forward with the same formula (log_softmax(z / (T + 1e-7))[response]). Side effect: objective/kl at step 1 with policy == reference is now exactly 0 (stock reads about 0.11 from generation-time numerics).
  • RLOO (TRL < 1.15; 1.15 already uses TRL's fused head, which Route ORPO, CPO, KTO, DPO and TRL 1.15's fused head to the zoo fused linear kernel #14185 routes): _get_per_token_logps_and_entropies goes through the kernel for text batches, keeping TRL's batching, logits_to_keep + 1, temperature, detached entropy, return arity and 1.14's row_mask.
  • BCO (TRL 0.22 to 1.10): the policy and reference passes reuse the KTO route; the precomputed reference pass gets a completion-only variant. The UDM classifier reads prompt embeddings, not logits, so it is untouched.
  • Online DPO, XPO, Nash-MD: policy and reference passes score every completion position from hidden states (TRL's KL / entropy metrics read padding positions too, so no mask is applied there; no temperature, as in TRL).
  • GKD: compute_loss uses unsloth-zoo's fused two-head generalized JSD (fused_linear_jsd, Fused two-head generalized JSD for GKD: lighter and faster than the chunked JSD, TRL and Liger unsloth-zoo#2079) when the installed zoo has it, else the existing chunked JSD.

Kill switches: UNSLOTH_FUSED_LINEAR=0 (all of the above; for GKD it now restores TRL's dense loss), UNSLOTH_PREFERENCE_CHUNKED=0 (BCO / Online DPO family), UNSLOTH_GKD_CHUNKED=0 (GKD). Vision inputs, encoder-decoder models, hooked or non-linear heads, FSDP / DeepSpeed and forwards that ignore the hidden-states flag keep TRL's path.

Numbers

Tiny Qwen3, LoRA, bf16, a few steps, base = main:

trainer (TRL) peak memory, base -> this PR loss / grad-norm vs base
PPO (0.25.1) 498 -> 206 MiB value loss within 0.5% (the KL change above enters the rewards)
RLOO (0.25.1) 312 -> 145 MiB grad norm within 0.3%
BCO (0.25.1) 1022 -> 216 MiB loss within 5e-5, grad norm within 0.3%
Online DPO (0.25.1, 1.15) 1480 -> 349 MiB loss equal at 4 decimals, grad norm within 0.16%
GKD, beta 0.5 (0.25.1) 1183 -> 442 MiB loss within 7.5e-6, grad norm within 0.45%

fp64 parity against TRL's own code on tiny models: log-probs, losses and gradients agree within 1e-6 to 1e-5 (XPO / Nash-MD gradients within 1e-4). With the kill switch every arm is bit-identical to base.

Tests

New: tests/test_ppo_fused_logprobs.py, tests/test_rloo_fused_logprobs.py, tests/python/test_fused_linear_bco.py, tests/python/test_fused_linear_online_dpo.py, tests/python/test_fused_linear_xpo_nash_md.py, tests/python/test_gkd_fused_linear_jsd.py; all fail on the parent and pass here. Rewrites are checked to apply, compile and be idempotent on the TRL sources of 0.22.2, 0.25.1, 0.29.1, 1.4, 1.6, 1.9.2, 1.10, 1.14, 1.15 and 1.16.

GPU run of the new files plus the existing DPO / KTO / GRPO / TRL-route suites against unsloth-zoo main: 207 passed, 50 skipped on TRL 0.25.1; 166 passed, 91 skipped on TRL 1.15 (skips are version-gated tests for the other TRL range).

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).
…o the zoo fused linear kernel

- ORPO / CPO / KTO score only the loss positions through the fused op; KTO's KL pass too.
- DPO on TRL 0.29-1.14: _compute_loss and the reference log-prob precompute read log-probs, entropy, mean logits
  and argmax hits from the op instead of full logits.
- KTO on TRL 1.6-1.14: _compute_kl_logps and _compute_loss likewise.
- TRL 1.15's ChunkedLogProbFunction is routed to the op; the adapter also handles the 2-output kernel of TRL 1.1-1.14.
- Every rewrite keeps TRL's source as the fallback and only applies when each anchor matches exactly once.
  UNSLOTH_FUSED_LINEAR=0 restores TRL's paths.
…LE_DISABLE; only torch.compile is skipped

[skip ci]
The generated _get_per_token_logps_and_entropies kept the legacy chunked helper while zoo's
grpo_accumulated_loss scores the policy with grpo_chunked_hidden_states_logprobs (or the
recompute function), so the importance ratio of identical policies did not start at 1.

[skip ci]
- DPO: the reference pass is projected with grad disabled, as TRL's no_grad reference forward
  (a trainable or shared head got a reference gradient).
- The ORPO / CPO and legacy DPO / KTO selectors honour UNSLOTH_FUSED_LINEAR=0.
- Both selectors keep TRL's path for a head with forward hooks, pre-hooks, a patched forward
  or an accelerate hook (the kernel reads weight / bias directly).
- The TRL fused-head adapter is not installed over a kernel without a bias argument (TRL 1.1 - 1.13).
- KTO test fixture passes max_prompt_length only when the config has it (TRL 0.29).

[skip ci]
TRL 0.22 - 1.14's KTO reference precompute (compute_reference_log_probs / compute_ref_log_probs /
_compute_ref_log_probs) built full tokens x vocab logits for the completion and KL batches. Each
forward now goes through unsloth_zoo's fused linear op when the fused path applies, with TRL's
statement kept as the fallback branch (the TRL 1.6 truncation clamp included). One batch at
V = 131072 with KL: peak 4.1 - 4.6 GiB -> 282 MiB, log-probs equal to 1e-7.

[skip ci]
TRL's ChunkedLogProbFunction projects [min(N, TOKEN_CHUNK_SIZE=4096), chunk_size]
tiles (chunk_size = vocab columns, 32768 by default), so its logits buffer is
min(N, 4096) * chunk_size * itemsize(compute dtype) bytes. The adapter now keeps
the zoo kernel's buffer within that: the chunked [rows, V] forward gets
max_rows_per_chunk = budget // (V * 4), and shapes whose recompute tiles
(min(N x V, 256 MiB)) exceed the budget go to TRL's kernel, decided from the
shapes alone so no-grad and gradient passes of a batch use the same kernel.
At the default (32768 columns) the zoo kernel's whole-call peak is already below TRL's for frozen and
trainable heads, and a per-buffer cap there cost the no-grad pass about 20%. Only an explicitly smaller
chunk_size, a memory request, now bounds the buffer or hands the call to TRL.

[skip ci]
TRL main passes a 10th argument to _ChunkedLogProbFunction.apply,
support_ids, to score over a per-row kept set. The zoo kernel scores the
full vocabulary, so those calls go to TRL's kernel with every argument;
the adapter used to take 9 and would raise TypeError.

[skip ci]
- The DPO / KTO and ORPO / CPO head selectors also keep TRL's path for an
  output head with backward or backward-pre hooks: the fused kernel reads
  the weight directly, so those hooks would never see the gradient.
- The TRL fused head adapter checks UNSLOTH_FUSED_LINEAR on every call, so
  turning it off after the adapter was installed restores TRL's kernel.
- The GRPO scorer parity test asks the zoo's public scorer for its own
  chunked path (fused_linear=False) as the legacy control.
…r visibility

- The KTO _compute_kl_logps rewrite builds its TRL branch the way the
  reference rewrite does, so TRL 1.6's truncation clamp (added by
  kto_trainer_align_completion_logps) survives on the fallback path.
- The subclass check also recognises rewritten methods that only call the
  fused-pass helpers, so an overridden get_batch_logps below them is seen.
- The split-model device wrapper and the fused head adapter expose the
  wrapped kernel's attributes, so patching again neither nests them nor
  wraps a TRL 1.1 - 1.13 kernel (no bias) with the adapter.
…preference routes; 8-bit encoders keep the fallback loader under UNSLOTH_COMPILE_DISABLE=1

[skip ci]
TRL 1.15's DPO and KTO request the entropy only to log it, and TRL's own
kernel skips the entropy gradient when none arrives. With an unsloth_zoo
whose log-prob op is v4+, the adapter passes entropy_requires_grad=None,
so a frozen head keeps the forward-gradient path instead of the recompute
backward; a GRPO entropy bonus still gets its gradient.

[skip ci]
…rnel

PPO: rollout, reference and training log-probs and the entropy metric are scored from hidden
states; rollouts skip the stacked generation scores. The value head is unchanged.
RLOO: _get_per_token_logps_and_entropies scores text-only batches from hidden states and
keeps TRL's body for vision, MoE aux loss and heads the kernel cannot read. TRL >= 1.15 RLOO
already goes through the fused lm_head adapter.
…s from hidden states

BCO reuses the KTO (TRL < 1.6) forward rewrite and a completion-only variant of the KTO precompute rewrite. Online DPO _forward slices hidden states with TRL's slice or Unsloth's right-align gather and scores every completion position with fused_linear_logprobs. XPO / Nash-MD _compute_logprobs score each pass from hidden states, padding rows 0 as TRL masks them. UNSLOTH_FUSED_LINEAR=0 and UNSLOTH_PREFERENCE_CHUNKED=0 keep TRL's path.
compute_loss now calls unsloth_zoo fused_linear_jsd when available, falls
back to distillation_chunked_jsd on an older zoo, and UNSLOTH_FUSED_LINEAR=0
restores TRL's dense generalized_jsd_loss. GradScaler scale is passed as
scaling; _unsloth_gkd_fused_calls counts engagement.
# Conflicts:
#	unsloth/models/rl_replacements.py
@danielhanchen danielhanchen self-assigned this Oct 25, 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 commented Oct 25, 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-25T12:05:50.104954Z 40c6238 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 added a commit to Datta0/unsloth-staging-3 that referenced this pull request Oct 25, 2026
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Oct 25, 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

Here are some automated review suggestions for this pull request.

Reviewed commit: f1c70fafeb

ℹ️ 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/_fused_rl_logprobs.py Outdated
Comment on lines +214 to +215
with hidden_states_forward(route is not None):
return forward(model, query_responses, pad_token_id)

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 Check the reference head before requesting hidden states

When the policy has a supported head but a separate Unsloth reference model has an unsupported head (for example, an lm_head with an Accelerate hook), ppo_route enables fusion based only on the policy. This forward then requests hidden states from the reference unconditionally, but ppo_score rejects its head and returns None. The rewritten reference-scoring fallback applies selective_log_softmax directly to those hidden states as though they were vocabulary logits, causing out-of-bounds token indexing or silently incorrect reference probabilities and KL rewards. Check the actual model's head before enabling the hidden-state flag so unsupported reference models retain their dense 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 40c6238: ppo_forward now asks for hidden states only when fused_head accepts that model's own head (the same check ppo_score applies), so a reference model with a hooked or non-dense head keeps its dense forward and TRL's lines score real logits. Added test_ppo_reference_with_hooked_head_keeps_trl, which fails without the fix (the hooked reference returned hidden states) and passes with it.

@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. Breezy!

Reviewed commit: 40c623867c

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

[skip ci]
@danielhanchen
danielhanchen merged commit 8fec282 into main Oct 25, 2026
@danielhanchen
danielhanchen deleted the fused-linear-more-trainers branch October 25, 2026 12:49
lonexreb added a commit to lonexreb/unsloth that referenced this pull request Oct 27, 2026
…trainers too

8fec282 (unslothai#15244) routed BCO, Online DPO, XPO and Nash-MD through
_unsloth_dpo_chunked_head after this branch was cut. Their generated source
copies the guard but not _unsloth_global_module_hooks, which the guard now
calls, so every Online DPO fused pass raised NameError
(tests/python/test_fused_linear_online_dpo.py, 6 failures on this PR's run).

Add the helper to that copy list, and a test that every generated trainer
carrying a chunked-head guard also defines the helper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
lonexreb added a commit to lonexreb/unsloth that referenced this pull request Oct 31, 2026
…trainers too

8fec282 (unslothai#15244) routed BCO, Online DPO, XPO and Nash-MD through
_unsloth_dpo_chunked_head after this branch was cut. Their generated source
copies the guard but not _unsloth_global_module_hooks, which the guard now
calls, so every Online DPO fused pass raised NameError
(tests/python/test_fused_linear_online_dpo.py, 6 failures on this PR's run).

Add the helper to that copy list, and a test that every generated trainer
carrying a chunked-head guard also defines the helper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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