Repository navigation
Route PPO, RLOO, BCO, Online DPO, XPO, Nash-MD and GKD to the zoo fused linear kernels - #15244
Conversation
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).
[skip ci]
…; clamp KTO to the model's length [skip ci]
…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
|
@codex review |
1 similar comment
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 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".
| with hidden_states_forward(route is not None): | ||
| return forward(model, query_responses, pad_token_id) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…rer takes [skip ci]
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
[skip ci]
…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]>
…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]>
Summary
Routes the remaining TRL trainers to the unsloth-zoo fused linear kernels, so their log-prob and distillation losses never build
tokens x vocablogits. 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.trl.experimentalincluded): 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 withoutoutput_scores, so theB x T x Vfp32 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/klat step 1 with policy == reference is now exactly 0 (stock reads about 0.11 from generation-time numerics)._get_per_token_logps_and_entropiesgoes through the kernel for text batches, keeping TRL's batching,logits_to_keep + 1, temperature, detached entropy, return arity and 1.14'srow_mask.compute_lossuses 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:
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).