Repository navigation
DPO, ORPO, CPO: opt-in fused preference loss (UNSLOTH_FUSED_PREFERENCE_LOSS=1) - #13870
Conversation
|
@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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ab60c2fcc4
ℹ️ 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".
| out = fused_linear_token_logps( | ||
| hidden_or_logits, | ||
| head[0], | ||
| head[1], |
There was a problem hiding this comment.
Fall back before scoring outside a DDP forward
When model is wrapped in DDP with find_unused_parameters=True and the output head is untied and trainable, DDP finishes traversing the hidden-state output at the end of model(...) and marks the head parameter unused; invoking the fused kernel on the unwrapped head afterward then makes its autograd hook mark that parameter ready a second time, causing backward to fail with DDP's “Expected to mark a variable ready only once” error. This configuration is used by Transformers for non-checkpointed distributed training unless overridden, so the fused path should decline it or perform the head operation inside the wrapped forward.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in ac660ac: reproduced with gloo (one and two ranks). Under DistributedDataParallel(find_unused_parameters=True), a trainable untied head applied after model(...) returns fails backward with "Expected to mark a variable ready only once". The fused path now returns None, so TRL's concatenated_forward runs, when the model is DDP-wrapped with find_unused_parameters set and the head weight or bias requires grad; find_unused_parameters=False and frozen heads keep the fused path. Added test_orpo_under_ddp_find_unused_falls_back, checking both settings against TRL's loss, metrics and gradients.
| from .rl_replacements import _unsloth_grpo_returns_hidden_states | ||
|
|
||
| is_hidden = _unsloth_grpo_returns_hidden_states(unwrapped, tensor, head_weight) | ||
| except Exception: | ||
| is_hidden = tensor.shape[-1] == head_weight.shape[1] != head_weight.shape[0] |
There was a problem hiding this comment.
Reject ambiguous square output heads
When an otherwise supported model ignores UNSLOTH_RETURN_HIDDEN_STATES and has vocab_size == hidden_size, its real logits have the same trailing width as hidden states. In that ambiguous case _unsloth_grpo_returns_hidden_states returns true when the unpatched model has no explicit signal, so this call classifies the logits as hidden states and the fused path applies the output head a second time, silently changing every loss and gradient. Require an explicit positive hidden-state signal for square heads or fall back to TRL; the fallback test currently avoids this case by using unequal dimensions.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in ac660ac: when the output head is square (vocab_size == hidden_size) the fused path now requires an explicit positive signal from _unsloth_grpo_hidden_states_signal (the compiler marker or the hidden states wrapper) before running the forward, and otherwise returns None so TRL's own concatenated_forward runs. Added test_square_head_needs_explicit_hidden_states_signal with a square 64 x 64 head, covering a forward that ignores the flag (falls back, matches TRL) and a marked forward (fused, matches TRL).
… for unmarked square heads [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: ac660acb90
ℹ️ 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".
| if isinstance(model, torch.nn.parallel.DistributedDataParallel) and getattr( | ||
| model, "find_unused_parameters", False |
There was a problem hiding this comment.
Detect DDP beneath torch.compile
When Accelerate's Dynamo integration wraps DDP(find_unused_parameters=True) in torch.compile, model is an OptimizedModule, so this direct isinstance check is false even though _orig_mod is DDP. A trainable untied head is then scored outside the wrapped forward and backward can again fail with DDP's “mark a variable ready only once” error. The fresh evidence beyond the resolved direct-DDP thread is this _orig_mod wrapper case; the repository's _unsloth_find_ddp already traverses that chain, so use equivalent detection before enabling the fused path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 10886a2: the find_unused_parameters check now walks the _orig_mod chain (as _unsloth_find_ddp does), so DDP under torch.compile is detected and a trainable untied head falls back to TRL's forward. Added test_orpo_under_compiled_ddp_find_unused_falls_back, which raised "marked as ready twice" before.
| try: | ||
| unwrapped = trainer.accelerator.unwrap_model(model) | ||
| except Exception: | ||
| unwrapped = model |
There was a problem hiding this comment.
Fall back before unwrapping FSDP models
When model is an FSDP1 wrapper, accelerator.unwrap_model removes the wrapper and this helper can accept the output head's 2-D parameter view. The fused kernel then reads that saved view after the FSDP forward has resharded or freed the full parameter, outside FSDP's managed module call, which can produce invalid storage/shape errors or bypass correct gradient synchronization; the DTensor check only covers FSDP2-style parameters. Detect FSDP before unwrapping and fall back to TRL's forward.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 10886a2: _output_head now returns no head when the model contains any FSDP1 FullyShardedDataParallel module (checked before unwrap_model, cached per model), so FSDP1 runs use TRL's forward. Added test_orpo_under_fsdp1_falls_back.
…ch.compile [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: 10886a2a8f
ℹ️ 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".
| if head is None or hasattr(head, "base_layer") or hasattr(head, "modules_to_save"): | ||
| return None, None | ||
| weight = getattr(head, "weight", None) | ||
| if not isinstance(weight, torch.Tensor) or weight.dim() != 2: |
There was a problem hiding this comment.
Require an unhooked plain linear output head
When get_output_embeddings() returns a custom nn.Linear subclass or a linear carrying an Accelerate _hf_hook/forward hook, these checks still accept it based only on its 2-D weight. The normal model forward invokes that custom behavior (and offload hooks may materialize the weight only during head.forward), whereas the fused kernel later reads the saved weight and bias directly, causing incorrect log-probabilities or meta/wrong-device failures. Restrict this path to a plain, unhooked linear projection, as the existing is_plain_linear validation in unsloth/models/diffusion_loss.py does, and otherwise fall back to TRL.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 8a83cbd: _output_head now accepts only type(head) is torch.nn.Linear with no _hf_hook, no instance-level forward, and no forward or forward-pre hooks, the same rule as is_plain_linear in diffusion_loss.py. Anything else falls back to TRL. test_hooked_or_custom_head_falls_back covers a forward hook, a pre hook, _hf_hook and a Linear subclass, and checks the fused path does not engage and the loss equals TRL's.
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 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 |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
|
pre-commit.ci run |
…hai#1782) Preference trainers only need one log probability per completion token, but they build batch x seq_len x vocab logits for the chosen and rejected rows and again for the reference. At long context with a large vocabulary that tensor and its gradient dominate peak memory. This adds `unsloth_zoo/fused_losses/preference_loss.py`: - `fused_linear_token_logps` takes the final hidden states plus the output head weight and bias. It projects only the scored positions, a chunk of rows at a time, and recomputes each chunk in backward, so peak memory holds one rows x vocab chunk. - It supports logit scaling, division and final soft capping, and a head bias. It also returns the vocab mean of the logits and log sum p^2 without gradient, for trainer metrics and WPO weights. - On fp16 and bf16 heads it asks the GEMM for float32 output where torch supports it (2.8+), so the softmax no longer sees half-precision-rounded logits. An out-of-memory error there is raised as usual rather than turning the float32 path off for the rest of the process. - `linear_mean_logits` gives the vocab mean of the logits for the trainer metrics without building full logits. The losses themselves stay TRL's own code: the companion unslothai/unsloth#13870 feeds these log probabilities into TRL's `dpo_loss`, `odds_ratio_loss` and `cpo_loss`, and only when `UNSLOTH_FUSED_PREFERENCE_LOSS=1` is set. Nothing calls the new module otherwise. Measured at 8192 tokens, 152k vocab, bf16, forward and backward: extra peak 4.67 GiB with full logits, 1.33 GiB with the chunked path. Tests compare against a float64 full-logits oracle (values and gradients to 1e-12, gradcheck, empty mask, large logits, out-of-memory handling).
…nslothai#13979) ## Summary With `UNSLOTH_OFFLOAD_OPTIMIZER_STATE=1` and more than one chunk, Q-GaLore with `weight_quant=True` crashed on the first step: ``` RuntimeError: attempting to assign a gradient of size '[256, 256]' to a tensor of size '[1]' ``` The chunked step hides gradients between chunks and restores them afterwards, but Q-GaLore weight quantization swaps `p.data` for a one element placeholder inside `step`, so the original gradient can no longer be assigned back. ## Change - `_chunk_safe` now returns False when any param group sets `weight_quant`. Such optimizers use the existing unchunked route: state is restored, one normal step runs, and state is offloaded again. Offloading between steps still applies. - Nothing changes when the env var is unset, and other optimizers are unaffected. ## Tests - `test_weight_quant_q_galore_steps_unchunked` (CPU) checks the gate. - `test_q_galore_multi_chunk_offload[False|True]` (CUDA, bitsandbytes) runs the real `QGaLoreAdamW8bit` with a 256 KiB chunk budget for two steps and checks INT8 weights, scales and gradients match a run without offload bitwise, with state left on CPU. It failed with the error above before the change. - `tests/test_optimizer_state_offload.py`, `tests/test_formatter_fixed_point.py`, `tests/test_source_read_encoding.py`: 64 passed, 2 skipped on GPU. # unslothai#13870: opt-in fused preference loss, trainable head, short-sequence peak VRAM Verdict: the regression is real, but it comes from the zoo kernel and zoo PR unslothai#1824 already fixes it. With unslothai#1824 applied, the leftover short-sequence overhead is a small, bounded trade-off on the unsloth side. That overhead is set by the 256 MiB fp32 chunk budget, does not grow with vocab x hidden, and also exists for frozen heads. I made no change to the unsloth gate and created no branch. I made a throwaway worktree `wt_pm_fused_pref_gate`, then removed it and deleted its branch without committing anything.
Needs unslothai/unsloth-zoo#1782 (the chunked kernel).
With
UNSLOTH_FUSED_PREFERENCE_LOSS=1, the generated DPO (TRL 0.22 to 0.28), ORPO and CPO trainers score completions from the model's final hidden states through the new unsloth_zoo chunked kernel, instead of materialising full logits for the policy and reference passes.What is reproduced from TRL's concatenated_forward:
Fallbacks: any input the reimplementation does not cover returns None and TRL's original forward runs:
With the flag unset, the generated trainer files are byte-identical to before.
Results:
TRL 1.15 already fuses the DPO head upstream, and 0.29 to 1.14 DPO has no concatenated_forward, so the flag does not touch DPO on those versions.
Training curves: step 1 is identical (exactly log 2), after that DPO losses depart from the unfused run because the fused path no longer rounds logits to bf16 and Adam's early steps amplify small gradient differences (unfused repeats already differ by up to 0.016 on a T4). There is no long-run final-quality comparison yet, which is one reason this is opt-in.
Not covered: DDP / multi-GPU, softcap and logit-scaling models on GPU (CPU tests only), torch below 2.8 (falls back to half-precision logits with an fp32 softmax), KTO.