Repository navigation
DPO / ORPO / CPO / SimPO: run each pair's shared prompt once (prefix-shared preference forward) - #18169
Conversation
…reference forward) Chosen and rejected rows share the prompt. Inside the preference trainers' forward methods (_compute_loss / compute_ref_log_probs on TRL >= 1.0, concatenated_forward before), the decoder backbone runs the longest common prefix of each pair once and both completions attend to it through the PrefixGrouper FlexAttention mask; final hidden states (and every layer's when asked) are gathered back to the padded [2B, L, H] layout, so the head and loss code are unchanged and the shared prefix gets the sum of both rows' gradients. Tokens per pair: 2 (P + C) -> P + 2 C, and padding is dropped. Gating: UNSLOTH_DPO_PREFIX_SHARE=auto (default; CUDA sm80+, text-only dense decoders whose forward applies prefix_seg_info, no softcapping / attention dropout / SSM / MoE, no context parallel or DTensor), 1 (also below sm80), 0 (off). A batch is shared only when rows are right padded, every pair has a common prefix, it saves >= 2048 prompt tokens (_MIN_SAVED) and unshared / shared >= 1.3 (_TOKR). The first shared forward of each backbone is checked against the unshared one (_VERIFY) and a disagreement turns the feature off for that model. Tests: an fp64 CPU oracle (layouts incl. identical rows, one-token prompts / completions, completions sharing a head, T across 128) with fault injection (leaky mask, non-causal prefix, shifted positions, swapped gather), and CUDA tests on a real Unsloth model through TRL's fused head (fp32 logps and LoRA grads vs the unshared forward and its own padding A/A, a leaky mask caught by logps and the verify, and a DPOTrainer run that must see P + 2C decoder tokens).
…ant checkpoints and a flex compile failure The PrefixGrouper first-call check runs a forward and backward on detached copies of q / k / v. Inside a non-reentrant checkpoint (DDP, use_reentrant=False layers) that backward unpacked through the checkpoint's saved-tensor hooks, the checkpoint stopped its recomputation mid-forward, and the check reported the _StopRecomputationError as a compile failure: PrefixGrouper turned off process-wide and the DPO step raised. The copies now use their own identity saved-tensor hooks. A real compile failure raised PrefixGrouperCompileError out of the preference forward, killing training on the first step. The wrapped method now reruns the forward unshared (compile_check_failed() declines every backbone from then on); nothing has backpropagated at that point. Tests: a CPU test that the wrapper reruns on PrefixGrouperCompileError and lets other errors through (fails before this change), and a CUDA test that runs the cold first call inside a non-reentrant checkpoint in a fresh process and compares its grads with the plain call (fails before this change).
… a torch without FlexAttention NEFTune scales its embedding noise by 1 / sqrt(seq_len * hidden). On the flat shared stream that is a smaller noise than the padded rows get, and both rows of a pair would share it on their prompt, so a training forward with neftune_noise_alpha set on the input embeddings now stays unshared. Eval forwards still share. The wrapped preference methods imported PrefixGrouperCompileError from the kernel module on every call. That module imports torch.nn.attention.flex_attention, so on a torch without it (2.4) every DPO / ORPO / CPO step raised ModuleNotFoundError. The except clause now catches nothing when the module cannot import; every backbone is already declined there. Dropout is unchanged: it runs on the shared stream (one mask on the prompt for both rows, each row's own mask distributed as in the unshared forward, so the expected gradient is the same). The module docstring says so. Tests (CPU): NEFTune declines in train mode only (fails before this change); the file skips on a torch without FlexAttention instead of erroring at collection.
…t left by trainer runs), TRL 0.22 to 1.18 The fp32 comparisons failed 32 of 61 on hosts with xformers (B200, torch 2.14.1, xformers 0.0.35), all on the train-mode unshared reference. A training forward drops the padding mask, so Unsloth's attention takes xformers; on sm_100+ xformers only has its bf16 / fp16 flash op and fp32 Q / K / V are downcast to bf16. That reference was bf16-accurate: LoRA grads 2.8% - 6.4% off TRL's own DPOTrainer run in fp64 on CPU, while the shared forward stays within 3e-6 - 7e-6 of it in train and eval mode. fp32 runs now pin dense attention to SDPA (UNSLOTH_DPS_TEST_REAL_ATTENTION=1 keeps the real backend). A trainer run left the model's forward wrapped in accelerate's autocast: Unsloth sets ACCELERATE_MIXED_PRECISION=bf16 for an fp32 model trained with bf16=False and fp16=False, and the Trainer does not unwrap after train(). Every fp32 comparison after a trainer test then ran under bf16 autocast (both forwards 6% - 12% off fp64). The trainer test now unwraps the model after each run, drops the reference adapter TRL >= 1.0 adds and restores the adapter weights. The file no longer needs TRL >= 1.15: batches are built by hand in the preference collators' layout, log-probs go through TRL's fused LM head when present and otherwise through the model's own head one row at a time. The trainer flip test covers DPO everywhere and ORPO / CPO / SimPO where Unsloth patches them (TRL < 1.0), and skips trainers the installed TRL lacks. New: with LoRA dropout 0.3 in train mode the shared forward applies dropout (grads move with the seed, spread 1.05x the unshared one) and its mean gradient over 32 seeds equals the unshared forward's (squared mean distance over its expectation 0.97).
|
@codex review |
Codex Review Summary: ✅ CompletedThis 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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4c757c30a4
ℹ️ 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".
| and not getattr(config, "attn_logit_softcapping", None) | ||
| and not getattr(config, "attention_dropout", 0) | ||
| and not any(getattr(config, a, None) is not None for a in _SSM_MOE_ATTRS) |
There was a problem hiding this comment.
Decline sharing when training dropout is active
When disable_dropout=False and LoRA dropout is nonzero, this gate still permits sharing, which makes the chosen and rejected rows reuse the same prompt dropout realization. Preserving each row's marginal distribution does not preserve the expected preference gradient: DPO applies a nonlinear log-sigmoid to the difference of their log-probabilities, so changing their correlation changes the training objective. The new dropout test only differentiates a linear weighted sum of sequence log-probabilities and therefore cannot detect this regression. The first-forward verification is also insufficient because zero-initialized LoRA B weights can hide dropout's effect until subsequent updates. Decline the shared path while training dropout is active, unless changing the stochastic preference objective is explicitly opt-in.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in bc5fe83: a training forward with any active dropout (p > 0, LoRA dropout included) now stays unshared, since a common prompt mask for the chosen and rejected rows changes the expected gradient through the log-sigmoid. Eval mode and p == 0 still share. The old dropout test is replaced by test_training_dropout_keeps_the_forward_unshared (B200: train mode with LoRA dropout 0.3 does not engage, eval does) plus a CPU unit test.
A shared prompt gives the chosen and rejected rows one dropout mask, and the log-sigmoid of their log-probability difference makes that correlation change the expected DPO gradient (TRL's DPO configs disable dropout by default, but disable_dropout=False with LoRA dropout reached the shared path). Any dropout module in train mode with p > 0 now declines the shared forward; eval mode and p == 0 still share.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bc5fe831db
ℹ️ 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".
| new_kwargs["input_ids"] = layout.flat_ids | ||
| new_kwargs["position_ids"] = layout.position_ids |
There was a problem hiding this comment.
Preserve the LongRoPE regime when flattening paired rows
For a LongRoPE-configured Llama, flattening can make the stream exceed original_max_position_embeddings even though every original row is shorter than that limit. LlamaAttention_fast_forward selects its rotary cache using kv_seq_len, and LongRopeRotaryEmbedding.get_cached switches between short and long frequencies using that length, so supplying the original position IDs does not preserve the unshared computation. If an earlier, smaller batch already passed verification, a later batch crossing this boundary silently uses different rotary frequencies and changes the preference loss and gradients; distributed execution skips verification altogether. Decline sequence-length-dependent RoPE configurations or preserve the original padded forward's rotary-cache selection explicitly.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed. LongRoPE and dynamic NTK choose their frequencies from the sequence length, and the shared stream is longer than either row, so it can cross the switch the unshared rows never reach. The shared forward now declines any model whose rope_scaling / rope_parameters (including the per-layer-type dicts of transformers 5) is longrope, su or dynamic, so those models keep the unshared forward. Covered by test_length_dependent_rope_declines.
…RPO / CPO keep it wrap_preference_trainer replaces concatenated_forward on the Unsloth trainer class. The stock-hook check read that scoping wrapper as a user override and fell back to full logits (ORPO peak 106 -> 236 MiB on a tiny Qwen3 even with the share declined). The GPU test now also finds ORPO / CPO under trl.experimental.
…ollow the sequence length The shared stream is longer than either row, so it could cross original_max_position_embeddings where the unshared rows do not and pick the long factors. [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f59a5d6520
ℹ️ 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".
| def test_training_dropout_is_detected(): | ||
| """Any dropout module in train mode with p > 0 keeps the forward unshared; eval mode or p == 0 shares.""" | ||
| import torch | ||
| from unsloth.models import dpo_prefix_share as dps |
There was a problem hiding this comment.
Reuse the isolated module in the CPU dropout test
On a CPU-only runner or an environment containing only the dependencies needed by these unit tests, this import initializes the full Unsloth package instead of using the isolated module already loaded by _load(). That pulls in the accelerator and optional-dependency initialization and can fail before the dropout assertions run; tests/conftest.py also explicitly disables CPU fallback. Use the existing module-level dps here, as the other tests do, so this CPU test remains independent of the full GPU stack.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed: the CPU test now uses the module-level isolated dps (and the module-level torch), like the rest of the file, so it no longer imports the full Unsloth package.
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! 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]
…ask on their device (unslothai#18273) ## Summary On a model split over GPUs (`device_map`), the first shared DPO / ORPO / CPO / SimPO forward from unslothai#18169 stopped training with ``` RuntimeError: indices should be either on cpu or on the same device as the indexed tensor ``` The first-call verify (on by default) compares the shared hidden states with an unshared forward on every real token. It indexed both with `attention_mask.to(torch.bool)`. In a split model the backbone returns its hidden states on the last block's device, while the mask stays on the input device. `_gather` already moved its index to the hidden states' device, but the verify did not. The wrapper only catches `PrefixGrouperCompileError`, so the error stopped the step. This hits the default `auto` mode (CUDA sm80+, single process, verify on) whenever the decoder spans more than one GPU. The shared forward itself is device-correct: `get_block_mask` builds and caches one block mask per device (`prefix_grouper_kernel.py:254-284`), and `_gather` moves its index. ## Fix `_token_rel_err` moves the mask, and the reference hidden states, to the shared hidden states' device before indexing. Nothing else changes. ## Test `tests/test_dpo_prefix_share.py::test_verify_with_hidden_states_on_another_device` uses a per-token backbone whose hidden states come back on another device (`cuda:1` when there are two GPUs, else the CPU) with the batch and mask on `cuda:0`. It must engage once, verify with zero error and match the unshared forward exactly. | tree | result | |---|---| | main | fails: `RuntimeError: indices should be either on cpu or on the same device as the indexed tensor (cpu)` at `dpo_prefix_share.py:490` | | this branch | passes; the whole file passes, 35 tests | On a CPU-only host the new test skips and the other 34 pass. ## Not covered - An end-to-end run of a real model split across two GPUs. This host leases one GPU per job, so the test puts the hidden states on the CPU instead.
What this does
DPO, ORPO, CPO and SimPO score
[chosen_0 .. chosen_{B-1}, rejected_0 .. rejected_{B-1}], and rowiand rowi + Bstart with the same prompt. Today the decoder runs that prompt twice per pair, plus padding. With this change the decoder backbone runs each pair's longest common prefix once, and both completions attend to it through the PrefixGrouper FlexAttention mask (prefix_seg_info). The final hidden states are then gathered back to the padded[2B, L, H]layout, so TRL's fused LM head, Unsloth's fused preference losses and the full-logits path are all unchanged. The shared prefix receives the sum of both rows' gradients through the gather. Decoder tokens per pair drop from2 (P + C)toP + 2C, and padding is dropped.Scope: the preference forwards only. That is
_compute_loss/compute_ref_log_probson TRL >= 1.0 DPO, andconcatenated_forwardon TRL < 1.0 DPO / ORPO / CPO / SimPO. It is installed by a pre/post hook on the decoder backbone for the duration of those methods, and only for methods whose first argument is the model.Gating
UNSLOTH_DPO_PREFIX_SHARE:auto(default): on for CUDA sm80+, for text-only dense decoders whose forward appliesprefix_seg_info.1: also on below sm80.0: off.The feature declines (and the forward runs unshared as before) in each of these cases:
rope_typelongrope,suordynamic): they pick their frequencies from the sequence length, and the shared stream is longer than either row, so it could cross the switch the unshared rows never reach1 / sqrt(seq_len * hidden), so on the flat stream it would be smaller, and it would be shared between both rows' prompt)A batch is shared only when it saves at least
_MIN_SAVED(2048) prompt tokens andunshared / shared >= _TOKR(1.3). Both thresholds come from A100 measurements, where the shared path has a fixed per-forward host cost.Two safety nets:
_VERIFY). A disagreement turns the feature off for that model and returns the unshared result.PrefixGrouperCompileError) reruns that forward unshared instead of failing the step. Nothing has backpropagated at that point.On a torch without FlexAttention, the wrapper no longer needs the kernel module to import. Every backbone is declined and DPO runs as before. Before this fix, every wrapped forward raised
ModuleNotFoundErroron torch 2.4.1.Train mode: a forward with any active dropout (p > 0, LoRA dropout included) stays unshared. Sharing would give the chosen and rejected rows one dropout mask on their prompt, and the log-sigmoid of their log-probability difference makes that correlation change the expected DPO gradient. TRL's preference configs disable dropout by default (
disable_dropout=True), so the shared path normally runs in training too.Results
Speed, Qwen3-1.7B bf16 LoRA r=16, DPO, P = 1024, C = 300, batch 4, 20 steps (3 warmup + 17 timed). Base is unsloth at the merge base and head is this branch. Each run is a fresh process on the same card, run order base, base, head, head, base.
Every head step engaged (40 shared forwards per run, 0 declined). The first-call verify gave mean / max relative hidden-state error 6.5e-3 / 2.5e-2 in bf16.
Loss: steps 1 and 2 are exactly log 2 in every run. From step 3 on, the base runs do not reproduce each other: bf16 attention backward is not deterministic, and DPO's summed log-probs amplify that. So the yardstick is the base A/A spread. On the A100, mean |loss difference| over steps 3 - 20 was 0.0101 - 0.0110 between base runs and 0.0152 - 0.0171 between base and head. The mean loss was 0.6949 - 0.6958 for base and 0.6925 for head. The two head runs were bitwise identical.
Exactness (fp32, tiny Qwen3, B200, tests below):
DPOTrainerrun in fp64 on CPU with the same LoRA weights, the shared forward's DPO loss is exact and its LoRA grads are within 3.4e-6 - 6.8e-6 relative, in train and eval mode.Tests
tests/test_dpo_prefix_share.py(CPU, fp64):The file skips on a torch without FlexAttention.
tests/test_dpo_prefix_share_gpu.py(CUDA, tiny Qwen3 fp32 through Unsloth):P + 2Cdecoder tokens per pair, and its losses must matchUNSLOTH_DPO_PREFIX_SHARE=0within 3x the padding A/A. On TRL < 1.0 the same test also covers ORPO, CPO and SimPO; it skips trainers that Unsloth does not patch on the installed TRL.The fp32 comparisons pin dense attention to SDPA. In a training forward (no padding mask), Unsloth's attention takes xformers when it is installed. On sm_100+ xformers only has a bf16 / fp16 flash op, so fp32 Q / K / V are downcast to bf16 there. That made the unshared train-mode reference only bf16-accurate: LoRA grads were 2.8% - 6.4% off an fp64 oracle on a B200, while eval mode keeps the padding mask and SDPA. This was the cause of the earlier failures (32 of 61) on hosts with xformers.
UNSLOTH_DPS_TEST_REAL_ATTENTION=1keeps the real backend.The trainer test also unwraps the model after each run. Unsloth trains an fp32 model with
bf16=False, fp16=Falseunder bf16 autocast (ACCELERATE_MIXED_PRECISION=bf16), and accelerate leaves the forward wrapped aftertrain(). Without the unwrap, every fp32 comparison that ran after a trainer test was a bf16 comparison: both forwards were 6% - 12% off fp64.trl.experimental)ImportError: add_fused_lm_head, 1KeyError: 'attention_mask')Not covered
autogate is on there, so correctness rests on the verify and the fallback.ORPO / CPO / SimPO keep the hidden-state log-prob path
Wrapping
concatenated_forwardon the Unsloth trainer class made_unsloth_stock_logps_hookread the scoping wrapper as a user override, so ORPO / CPO / SimPO fell back to full logits even when the share declined. On gfx1151 (Linux and Windows) a tiny Qwen3 ORPO step peaked at 235.7 MiB vs 105.7 MiB at the merge base, with identical losses; restoring the unwrapped method brought it back to 105.7 MiB. The hook check now reads through the marked wrapper, so a real user override is still detected (test_stock_logps_hook_reads_through_the_prefix_share_wrapper: fails before, passes after).