Repository navigation
Route ORPO, CPO, KTO, DPO and TRL 1.15's fused head to the zoo fused linear kernel - #14185
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.
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. |
…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]
|
Codex Review: Didn't find any major issues. Can't wait for the next one! 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". |
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]
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
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]
[skip ci]
CPO scores its NLL against its own labels, so it never needs the second head pass and no longer checks for one. ORPO keeps the eager check; a compiled graph takes the second pass instead of syncing on the host. The NLL mask is built with torch.cat rather than a boolean slice assignment, which CPU Inductor fails to compile. Adds a CPU test for zero graph breaks and parity with TRL's math, and lifts _unsloth_pref_returns_hidden_states into the DPO test harness that calls it. [skip ci]
[skip ci]
…er than TRL, 0 graph breaks (unslothai#1866) ## Summary A fused linear + loss engine (`unsloth_zoo/fused_losses/fused_linear.py`) that every loss reading `hidden @ W.T` now goes through: SFT cross entropy, DPO / KTO / ORPO / CPO log-probs and GRPO (including the entropy bonus). It is faster than TRL 1.15's `ChunkedLogProbFunction` on the frozen-head (LoRA) path on every GPU tier tested, uses far less memory than materialised logits, and compiles with 0 graph breaks. This builds on unslothai#1803 (it contains its commits, merged with current main), and the matching Unsloth routing is unslothai/unsloth#14185. ## How it works - **Frozen head (LoRA):** while a chunk's logits are live, the forward also computes `u = d logp / d hidden`, so the backward is `g * u`. That is 2 GEMMs per pass vs TRL's 3. - **Tiled forward gradient:** the frozen-head pass and the no-grad pass walk the vocabulary in [rows, 16384] tiles and accumulate `u` flash-style in fp32, so the transient is one tile instead of `[rows, V]`. On CUDA cards up to 24 GiB (T4, L4, consumer cards) this runs at every batch size, which is both faster and TRL-sized there; larger cards (A100, H100, B200) keep row chunks below 4096 kept rows, where the chunks are faster. Cross entropy keeps the row chunks on Turing. ROCm is unchanged. `UNSLOTH_FUSED_LINEAR_FLASH=0` restores the chunks; `UNSLOTH_FUSED_LINEAR_FLASH_MIN_ROWS` sets the threshold on every card. - **Trainable head or entropy gradient:** recompute backward in TRL-shaped tiles (up to 4096 rows x a vocab tile) with an fp32 head-gradient tile accumulator. - **Entropy that is only logged** (TRL 1.15 DPO / KTO): `fused_linear_logprobs(entropy_requires_grad=None)` keeps the frozen-head forward gradient and recomputes the entropy gradient only if one actually arrives, like TRL's own kernel. - **Precision:** fp32 logits on CUDA through `torch.mm(out_dtype=float32)`, with the half gradient written in place into the same row bytes (no extra buffer). Plain half logits on ROCm and on torch < 2.8. - **Kernels:** Triton row-statistics kernels, plus a vocab-split partial / merge kernel so small chunks still fill the GPU. A Triton fp32 scale kernel applies the incoming gradient. - **Compile:** `torch.library` custom ops with fake and autograd registrations. Masked rows are compacted inside the op, so dynamo never sees a data-dependent shape. - **Call sites:** `unsloth_fused_ce_loss` (both compiler injections), `chunked_logprob`, `preference_loss`, and the GRPO chunked log-probs, including the recompute-with-entropy route. - **Kill switch:** `UNSLOTH_FUSED_LINEAR=0` restores unslothai#1803's paths (main's cross entropy also needs `UNSLOTH_CHUNKED_CE=0`). GRPO then scores the policy pass and its old / reference log-probs with the same (old) function, so the ratio of identical policies starts at exactly 1. - **`UNSLOTH_COMPILE_DISABLE=1`** now only skips `torch.compile`. The fast LoRA forwards, the rewritten modules (fused CE forward, MLP, RMSNorm, gradient accumulation fix), the SDPA mask patch and the gpt-oss grouped bnb4bit path stay on. Before, "1" also turned those off. ## Speed vs TRL 1.15 Exclusive Colab / Kaggle cards, fresh process per arm, ABBA order. Ratio = new / TRL time (below 1 is faster). Frozen head, H 2560, V 151936; the 32k-vocab number is in brackets. | GPU | CE | DPO | GRPO | |---|---|---|---| | RTX PRO 6000 Blackwell | 0.78-0.80 (0.38) | 0.86-0.90 (0.42) | 0.77-0.80 (0.36) | | A100 80GB | 0.57-0.75 (0.30) | 0.78-0.84 (0.32) | 0.60-0.74 (0.27) | | L4 | 0.80-0.85 (0.53) | 0.95-0.97 (0.59) | 0.82-0.86 (0.54) | | T4 (fp16) | 0.72-0.82 (0.41) | 0.86-0.97 (0.47) | 0.81-0.92 (0.44) | - **GRPO with an entropy bonus:** at parity in half mode. The default keeps fp32 logits so a policy pass matches its no-grad reference (bit for bit with a frozen head, and with a trainable head from 4096 kept rows; within fp32 GEMM rounding of at most about 5e-5 below that), at about +4-8% on GDDR and A100 cards. - **Trainable head:** CE is faster than TRL. - The recompute backward re-projects in half and swaps the two largest logits of every 128 columns back to the forward's fp32 values. Its gradient error against fp64 equals the fp32 recompute's (2.3e-3 to 2.5e-3, against TRL's 2.7e-3 to 1.7e-2). Forward log-probs match the no-grad pass within fp32 GEMM rounding (at most 4.4e-5 measured on RTX PRO 6000 / L4, below each pass's own fp64 error; 0 on B200). | GPU | DPO 2k | DPO 8k | GRPO + entropy 2k | GRPO + entropy 8k | |---|---|---|---|---| | RTX PRO 6000 | 0.87 | 1.02 | 0.87 | 0.98 | | A100 | 0.91 | 1.02 | 0.93 | 0.98 | | L4 | 0.97 | 1.06 | 0.96 | 0.99 | - DPO at 8k tokens keeps a 2-6% gap from the fp32 forward. Memory is about half of TRL's (1.1-1.3 vs 2.3-2.6 GiB). - **Tiled forward gradient vs the row-chunk version** (frozen head, 8k / 32k tokens, exclusive Colab cards, 4 ABBA rounds): L4 6-11% faster, T4 DPO / GRPO 9-14%, G4 1-4%, A100 0-2% (one cell +0.8%). V 262144 at 8k tokens peaks at 0.36 GiB (TRL 0.367, before 0.55). The fp64 hidden-gradient error is 11-25% lower. - **AMD gfx1151 vs current main:** CE 0.65x time (0.60 -> 0.17 GiB), DPO 0.44x (6.96 -> 0.17 GiB), GRPO 0.79x, GRPO with entropy 0.97x. - **Logged entropy (TRL 1.15 DPO / KTO through the fused head):** 0.80-0.88x TRL on RTX PRO 6000, A100 and T4 (before the lazy entropy gradient: 1.01-1.11x). - **Small batches (1k-8k tokens, A100 40GB, frozen head, row chunks, every arm timed at the same steady SM clock):** against main, GRPO 0.87-0.93x (1k 0.87-0.88x), CE 0.62-0.73x, DPO 0.23-0.34x; against TRL, GRPO 0.69-0.73x, CE 0.67-0.74x, DPO 0.74-0.83x. Peak memory 0.30-0.53 GiB (main's GRPO scorer 0.43-6.0 GiB). An earlier version of this table reported GRPO 3-8% behind main at 1k / 2k tokens: that bench timed compiled arms at boost clock and this path in the GPU's post-idle low-clock window; with a 2 s steady-state warm-up per arm the gap reverses. On cards up to 24 GiB the tiles take over at these sizes: T4 DPO / GRPO 7-20% faster than the chunks, L4 2-6%, at TRL's memory (2k tokens 0.127 vs 0.123 GiB). ## Accuracy (fp64 oracle) | | new | TRL 1.15 | |---|---|---| | DPO loss error | 1.4e-5 | 7.7e-2 | | CE loss error | 9.5e-8 | 2.2e-4 | | GRPO hidden-grad relative error | 2.9e-3 | 7.2e-3 | The kernel oracle (fwd + bwd, odd N / V, tile edges, softcap / scale / temperature, masks, frozen and trainable heads, fp16 / bf16 / fp32) reports 0 FAIL. Every case is MORE_ACCURATE, WITHIN_TOL or IDENTICAL vs the Inductor-compiled reference. ## Testing - **Unit tests:** `tests/test_fused_linear.py`, `tests/test_fused_linear_routing.py` and `tests/test_compile_disable_keeps_optimizations.py`, plus updates to the existing CE / log-prob / GRPO tests. CPU 339 passed / 56 skipped; GPU 426 passed. The one GPU failure in that set, `test_triton_fp_fusion::test_compiled_kernels_keep_fp_fusion` (mxfp4 / MoE / gdn kernels), fails the same way on the merge base. - **Windows GPU (AMD gfx1151, ROCm 7.14 wheels, no Triton):** the engine runs its torch path. Fused CE matches plain cross entropy exactly, and the GPU unit tests pass (Triton-kernel tests skip there). - **Cross-platform CPU CI:** ubuntu-latest and windows-latest 311 passed / 50 skipped each; macos-15 (torch installed) 309 passed / 52 skipped. - **Version corners:** transformers 4.57.6 / TRL 0.22.2 / PEFT 0.18.0 (floor) 303 passed / 0 failed on CPU. - **Torch versions:** - Kaggle T4 fp16: torch 2.10, 2.11, 2.12, 2.13 and 2.14 all pass, each in a fresh venv. - Colab A100: 2.8 to 2.14 pass; on the final head 2.13.0 and 2.14.1 each pass 370 unit tests and a five-job before / after vs main (SFT, 4-bit SFT, DPO, GRPO, 4-bit inference) with no regression. - 2.6 / 2.7 only had two test assumptions about the fp32-output GEMM, now fixed. - **Final heads, before / after vs main:** 13 of 13 jobs show no regression (Kaggle T4 fp16: Qwen3-0.6B SFT / 4-bit SFT / DPO / 4-bit DPO / KTO / GRPO / 4-bit inference, Qwen3.5-0.8B SFT; A100: gemma-4-E2B SFT and 4-bit inference, Qwen3-0.6B DPO / KTO / GRPO), 0 graph breaks, peaks equal or lower. - **Version corners on GPU:** transformers 4.57.6 / TRL 0.22.2 / PEFT 0.18.0 / torch 2.10, TRL 1.16.0 / PEFT 0.20.0, and TRL main all show no regression (sft, 4-bit sft, dpo, kto, grpo, 4-bit inference); so do vLLM fast_inference GRPO and vision GRPO / 4-bit vision SFT. - **AMD gfx1151 (ROCm 7.13 Linux, 7.14 Windows):** Linux 418 passed / 0 failed on the final head, DPO 17.0 -> 15.5 ms per step (0.226 -> 0.093 GiB), SFT 11.0 -> 8.9 ms (0.130 -> 0.109 GiB); Windows (no Triton) 373 passed / 0 failed. - **Multi-GPU (Kaggle T4x2, model split over both cards by the device-map planner, lm_head on cuda:1):** Qwen3.8-27B and Muse Glimmer 30B GRPO notebooks, before / after vs main, 10 steps, two rounds each. The op runs on cuda:1 through Triton with no fallback. Qwen3.8 generations are identical on all 10 steps (step-1 grad_norm 0.3933 vs 0.3918). Peak on the head's card: 10.92 -> 10.90 GiB (Qwen3.8), 11.15 -> 10.01 GiB (Muse Glimmer). No OOM. - **Vision DPO (TRL 1.15, HuggingFaceH4/rlaif-v_formatted):** tiny Gemma3 / Gemma4 / Qwen2.5-VL / Qwen3-VL and Qwen3-VL-2B (16-bit) show no regression vs main; Qwen3-VL-2B 4-bit is within run-to-run noise, and on one batch its LoRA gradients match TRL's kernel at cosine 0.9998. - **Earlier real checkpoints, before / after vs main:** 21 of 21 jobs show no regression. Peak memory is equal or lower (gemma-4-E2B vision -5%, Qwen3.6-35B-A3B -5%). - T4: Qwen3-0.6B and Qwen3.5-0.8B (SFT, 4-bit SFT, inference, DPO, GRPO); gemma-4-E2B (4-bit SFT, vision). - L4: Qwen3-0.6B, full set. - A100: gemma-4-12B-it, 4-bit SFT. - RTX PRO 6000: gemma-4-26B-A4B-it and Qwen3.6-35B-A3B, 4-bit SFT. - **torch.compile:** a micro census of compiled CE / DPO / GRPO steps goes from 4 / 11 / 5 graph breaks to 0, and `fullgraph=True` passes.
…ed linear kernels (unslothai#15244) ## 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 unslothai#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 unslothai#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`, unslothai/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).
…kwargs (#15267) `tests/test_grpo_truncated_support_policy_gate.py` fails 6 of 9 on main since #14185 (`NameError: name 'os' is not defined` raised from `rl_replacements.py:2`). It shows on the rest shard of every PR based after that merge, for example #15245. ## Cause The test, not the product. It lifts the truncated-support binding block out of `_get_per_token_logps_and_entropies` and runs it on a stub trainer. To find the block it took the first `try` in the body whose source mentions `grpo_truncated_support_kwargs`. #14185 added an earlier `try` in the same body that imports that name too (the `UNSLOTH_GRPO_LOGPROB_RECOMPUTE` scorer pick). The test then lifted that block instead, which reads `os.environ` in a namespace without `os`. The real block is unchanged. ## Fix - The block now starts at the `try` that assigns `_support_kwargs`. - Statements are collected while they read or bind `_support_kwargs` as a name, not while the substring `_support_kwargs` appears (which `grpo_truncated_support_kwargs` also contains). ## Verification - The lifted block on main is identical, byte for byte, to what the old extractor lifted from the source just before #14185. The new extractor also gives the same block on that older source. - `tests/test_grpo_truncated_support_policy_gate.py`: 6 failed on main, 9 passed here. - Sabotage: with `_support_mismatch` forced to `[]` in `rl_replacements.py` (the gate removed), 6 cases fail, so the test still guards the product.
…15269) 16 cases in `tests/test_fused_preference_loss.py` fail in `Repo tests (CPU, rest)` on PRs based on current main, for example #15224 and #15245: every `test_orpo_cpo_match_trl` case plus the DDP / FSDP1 / hook fallback cases. The reference run trips the hidden-states counter (`assert (1 >= 1) == False`) or the dtype check. ## Cause The test, not the product. The test builds its reference from `from trl.experimental.orpo import ORPOTrainer` (and the CPO / DPO equivalents). Unsloth's RL patch rebinds those names, and the defining module's attribute, to the generated `UnslothORPOTrainer` (`unsloth/models/rl.py`, the `trl.{name} = created_module.Unsloth{name}` lines). Since #14185, that generated class's `concatenated_forward` routes through `unsloth_fused_orpo_concatenated_forward`. So once TRL has been patched in the process, the "TRL" side of the comparison is the code under test. The stack of the reference forward shows it: `test_fused_preference_loss.py:437 -> unsloth_compiled_cache/UnslothORPOTrainer.py:1988`. It reproduces locally with unsloth-zoo main on the path (16 failed, 9 passed, run alone). With the older installed zoo 2026.10.7, TRL is not rebound here, which is why it looked like an ordering leak at first. ## Fix - `_trl_trainer(name)` loads TRL's own trainer module from its file under a private module name in the same package, so TRL's relative imports still resolve and nothing Unsloth rebinds is reused. - It asserts that the class it returns is not an `Unsloth*` class. - ORPO, CPO and DPO all take their reference from it. ## Verification - `tests/test_fused_preference_loss.py` against unsloth-zoo main: 16 failed, 9 passed on main; 25 passed here. - Against the installed zoo 2026.10.7: 25 passed on both main and this PR. - Sabotage on the product: scaling the fused ORPO path's `chosen_logps` by 1.001 in `unsloth/models/dpo.py` fails all 10 `test_orpo_cpo_match_trl` cases.
## Summary All 6 tests in `tests/python/test_orpo_processor_text_tokenizer.py` fail on main since #14185 (Backend CI, `Repo tests (CPU, studio)`): ``` E NameError: name '_fused_pass_logps_re' is not defined ``` `_load_orpo_rewriter` rebuilds the ORPO rewriter from `unsloth/models/rl_replacements.py` by exec'ing every private module-level assignment and then the rewriter function. #14185 added private constants built by a module-level helper, for example `_KTO_LOGPS_RE = _fused_pass_logps_re(_KTO_IDS, _KTO_MASK)`, and the loader never defines that helper. Training is unaffected: in `rl_replacements.py` the helper is defined above its callers. ## Change The loader also execs, in source order, the module-level functions those private assignments call. It does not exec every private function: some evaluate module globals such as `DEVICE_TYPE_TORCH` when they are defined, which the loader does not provide. Test-only change. ## Testing - `tests/python/test_orpo_processor_text_tokenizer.py` on main (`231a4aa1fc`): 6 failed. With this change: 6 passed.
…odule hooks The chunked-head guards (unslothai#14185) skip the fused path when the output head carries a hook of its own (_hf_hook, forward / forward-pre / backward tables, a patched forward): the kernel reads head.weight directly and never calls the module. A hook registered through torch.nn.modules.module.register_module_forward_hook / _forward_pre_hook / _full_backward_(pre_)hook applies to every module through the global tables instead, which neither guard reads, so under such a hook (profilers, FLOP counters, user tooling) every module fires it except the head. Add _unsloth_global_module_hooks and consult it from both guards, listed in the ORPO / CPO, DPO and KTO source-copy lists so the generated trainers stay self-contained. unsloth/models/dpo.py already guards the global backward tables for the SFT-style fused head (unslothai#15226 extends it to the forward ones). Tests: a global forward hook makes _unsloth_pref_chunked_head return None and the DPO run record the "output head has hooks" fallback with TRL's loss. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Follow-up to unslothai#14185. Fused-loss engagement counters were updated inside traced scoring helpers, so repeated calls guarded on an ever-changing Python integer and recompiled until `fullgraph=True` reached the limit. Count engagement only outside tracing. Eager calls still update the counters; compiled calls retain the same loss and gradient calculations. This covers the preference, DPO, KTO, online DPO, GKD, PPO and RLOO scoring helpers. The branch is synced with main. The original TRL contract-whitelist half has been removed because unslothai#16220 already fixes its reported compatibility crash. The fused-head adapter and installer are identical to main, including TRL 1.17 score-ID support. Validation completed so far: - Against current main, all three compilation modes reproduce the counter failure before the fix and pass afterward. The ten existing numerical and gradient cases pass on both revisions, with no skips in this differential. - AST comparison confirms the nine changed scoring functions differ from main only by engagement-counter tracing guards. - On torch 2.15.0, Transformers 5.22.1, TRL 1.17.1 and PEFT 0.20.0, the compiled-loss and score-ID suites report 21 passed with no skips. - The final focused suite reports 35 passed with no skips. The full current-base differential reports four FIXED and 31 UNCHANGED checks, no head failures and no skipped cases. - Final-source SFT, DPO and GPT-OSS GRPO on Kaggle T4, plus ordinary GRPO and inference on A100, report NO_REGRESSION. DPO losses and gradient norms match exactly; peak memory is equal. - Remote regression smoke reports SAME: 66 passed, 13 XPASS and 24 skipped on each side, with no changed failures, metric moves or missing cases. - The main switchboard has no functional regression. Two crawler visual differences did not reproduce on confirmation. - Full-size vision GRPO crashes before step one on both base and head with the same pre-existing checkpoint metadata mismatch on torch 2.13 and 2.14.1. The upstream FIFO workaround does not resolve it. The supported tiny-Gemma4 comparison passes on the exact current head: three steps on both arms, all image forwards engaged, identical final loss, zero graph breaks and equal compiled-graph counts. The default full-size checkpoint failure remains a pre-existing limitation. - Final-source scoped staging passed all 35 tests on Linux, Windows and Apple Silicon macOS. The tests use small synthetic tensors and random model initialization. No model checkpoint weights are required for the reproductions.
…odule hooks (#15259) ## Problem The chunked-head guards from #14185 (`_unsloth_pref_chunked_head` for ORPO / CPO, `_unsloth_dpo_chunked_head` for DPO and, through `_unsloth_fused_pass_head`, KTO) keep TRL's logits path when the output head has a hook of its own: `_hf_hook`, the head's forward / forward-pre / backward tables, or a patched `forward`. The fused kernel reads `head.weight` / `head.bias` directly and never calls the module, so a hook on it would be skipped. Hooks registered through `torch.nn.modules.module.register_module_forward_hook`, `register_module_forward_pre_hook`, `register_module_full_backward_hook` and `register_module_full_backward_pre_hook` live in torch's global tables, not on the head, and neither guard reads them. Under such a hook (memory profilers, FLOP counters, user tooling) every module in the model fires it except the head, silently. `unsloth/models/dpo.py` already guards the global backward tables for the SFT-style fused head (`_global_module_backward_hooks`); #15226 extends that to the forward tables. These two guards are the sibling entry points. ## Fix One helper, `_unsloth_global_module_hooks`, consulted by both guards alongside the head's own tables, and listed in the ORPO / CPO, DPO and KTO source-copy lists so the generated trainer sources stay self-contained (`test_generated_items_are_self_contained` now checks for it). ## Verification - `tests/python/test_preference_chunked_logprobs.py::test_declines_without_kernel_or_on_unsupported_setups`: with a global forward hook registered the ORPO guard returns `None`; after `handle.remove()` it returns the head again. - `tests/test_dpo_chunked_logprobs.py::test_global_module_hook_falls_back`: a DPO run under a global forward hook makes zero chunked calls, records the `output head has hooks or a patched forward` fallback and matches TRL's loss. - Locally (CPU, unsloth_zoo without `chunked_logprob`) the fused route cannot fire, so those tests skip; verified instead that the helper flips on each of the four global tables and is clear after removal, that both guards call it, and ruff / duplicate-definition lint are clean. ## Follow-up - Merged current main. - GKD had the same gap. Its chunked JSD reads both heads' weights directly, so neither the heads' own forward / backward hooks nor torch's global module hooks fired. It now falls back to TRL's dense logits in both cases. Accelerate's `_hf_hook` still uses the fused path, because the loss moves to the head's device. - Tests cover all four global hook kinds (`forward`, `forward_pre`, `full_backward`, `full_backward_pre`) for ORPO / CPO, DPO and GKD. Each test first checks that the fused path runs with no hook (call counter above zero), then that removing the hook restores it. Under a hook, ORPO's loss and grads equal TRL's exactly. - The generated GKD trainer source carries the helper. | | main | this branch | |---|---|---| | ORPO / CPO / DPO / GKD under a global module hook | fused path runs, hook never sees the head | falls back to TRL logits | | hook tests (latest venv) | 19 failed | 20 passed | | hook tests (floor, transformers 4.57.6) | 23 failed | 24 passed | | preference, DPO and GKD test files, with TRL tags | | 131 passed / 17 skipped (latest), 143 passed / 5 skipped (floor) | GRPO also reads `lm_head.weight` directly, inside unsloth_zoo's fused loss. It has no plain path to fall back to, so it is left for a separate change. --------- Co-authored-by: Claude Fable 5.1 <[email protected]> Co-authored-by: Daniel Han <[email protected]>
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 vocablogits. Builds on #13934 (contains its commits, merged with current main).logits/*metrics come from the op's mean-logits output. KTO's KL pass runs through the op too._compute_lossand 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._compute_kl_logpsand_compute_losslikewise, covering the four source layouts TRL used in that range.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).ChunkedLogProbFunctionis 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 ownpatch_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'ssupport_ids(truncated support) go to TRL's own kernel, andUNSLOTH_FUSED_LINEAR=0set after the adapter is installed still restores TRL's kernel.grpo_accumulated_loss, so the importance ratio of identical policies starts at 1 (exactly for a LoRA / frozen head).use_weighting, aux loss, vision, FSDP / DeepSpeed, liger,return_outputs, and output heads with forward or backward hooks (incl. pre-hooks), a patchedforwardor an accelerate hook, and square heads (vocab size == hidden size) whose forward gives no hidden-state marker.UNSLOTH_FUSED_LINEAR=0restores TRL's paths everywhere._ChunkedLogProbFunctiontakes nobias, so the adapter is not installed there.UNSLOTH_COMPILE_DISABLE=1: the sentence-transformer fast encoder path stays on; only itstorch.compileis skipped. An 8-bit encoder request keeps the fallback loader, which is the one that forwardsload_in_8bit.Testing
TRL vs rewrite: new tests
tests/python/test_fused_linear_dpo_compute_loss.py,test_fused_linear_kto_compute_loss.pyandtest_fused_linear_trl_routes.pyrun 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:
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.
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 Fused linear + loss kernel for CE, DPO, KTO, ORPO, CPO and GRPO: faster than TRL, 0 graph breaks 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 Fused linear + loss kernel for CE, DPO, KTO, ORPO, CPO and GRPO: faster than TRL, 0 graph breaks 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 Fused linear + loss kernel for CE, DPO, KTO, ORPO, CPO and GRPO: faster than TRL, 0 graph breaks unsloth-zoo#1866.