Repository navigation
Cross entropy: correct gradients under torch.compile for vocabs above 65536 - #14712
Conversation
…le keeps the gradients
|
@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: Didn't find any major issues. Nice work! 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. Swish! 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". |
… guard for in-place edits of returned tensors (unslothai#15231) ## What `_GatherSequence.forward` (context parallel, DPO / GRPO sequence gather) finished its batch > 1 path with `out.copy_(buffer.movedim(0, 1))` on a tensor it had just allocated and then returned. Under `torch.compile` on torch 2.11 that pattern gives the traced backward a wrong gradient for the output, the same failure unslothai#14712 fixed in the cross entropy kernel. This PR returns `buffer.movedim(0, 1).contiguous()` instead: same values, same one fresh allocation, nothing mutated in place. It also adds `tests/test_autograd_inplace_outputs.py`, a CPU-only AST check that fails when any `torch.autograd.Function.forward` under `unsloth/` mutates a freshly allocated tensor it returns (`+=`, `x.op_(...)`). Writes by a kernel into the buffer and in-place edits of inputs stay allowed: both were measured correct under compile. ## Evidence Two gloo ranks on CPU, eager vs `torch.compile` gradient of `(gather(x) * w).square().sum()`, relative error: | torch | arm | batch 1 | batch 2 | |---|---|---|---| | 2.11 | main | 0.0 | 1.0 (both ranks) | | 2.11 | this PR | 0.0 | 0.0 | | 2.13 | main | 0.0 | 0.0 | | 2.13 | this PR | 0.0 | 0.0 | Minimal autograd.Function patterns on GPU (L4 / A100), compiled vs eager grad, relative error: | forward ends with | 2.10 | 2.11 | 2.12 | |---|---|---|---| | kernel write into `empty`, returned | 0 | 0 | 0 | | kernel write, then out-of-place op | 0 | 0 | 0 | | kernel write, then `+=` / `masked_fill_` | 0 | 1.0 | 0 | | `empty_like` then `copy_` | 0 | 1.0 | 0 | | `new_empty` then `return out.copy_(...)` | 0 | 1.0 | 0 | | input mutated in place | 0 | 0 | 0 | The guard test fails on `main` (flags `context_parallel.py:1046`) and on the cross entropy kernel from before unslothai#14712 (flags `losses += logsumexp` and `losses.masked_fill_`), and passes here. `tests/test_context_parallel_rl.py`: 22 passed. Scan of the rest: `UnslothFusedLoss` in unsloth-zoo has the same shape but is already wrapped in `torch.compiler.disable` (unsloth-zoo#1482); the MoE grouped GEMM only writes its output through the Triton kernel.
…nslothai#15140) Once the label logit leads the logsumexp of the other logits by more than ~16.6 nats, the label's `exp(0) = 1` swamps the other terms in fp32. `loss = logsumexp - x` and the label gradient `exp(x - logsumexp) - 1` then both round to exactly 0, while every other class keeps its positive gradient. The loss reads 0 and the row gradient sums to `+exp(-margin)` instead of 0. Below the cliff the error is already visible: at a 10 nat margin the loss is 0.8% too high. This is the "softmax collapse" from [A Fix for Softmax and Cross-Entropy](https://arxiv.org/abs/2610.31642). `main`, fp32, the label leading `V - 1` zero logits by `margin`: | margin | loss (main) | loss (fp64) | label grad (main) | label grad (fp64) | row grad sum (main) | |---|---|---|---|---|---| | 10 | 4.5776e-05 | 4.5399e-05 | -4.5717e-05 | -4.5398e-05 | -3.2e-07 | | 17 | 0 | 4.1399e-08 | 0 | -4.1399e-08 | 4.1e-08 | | 20 | 0 | 2.0612e-09 | 0 | -2.0612e-09 | 2.1e-09 | | 40 | 0 | 4.2484e-18 | 0 | -4.2484e-18 | 4.2e-18 | bf16 inputs are affected the same way, since the kernels upcast to fp32. ### Change `unsloth/kernels/cross_entropy_loss.py`: - **Forward:** reuse `exp(logits - c)`, sum the non-label terms alone, and take `loss = softplus(logsumexp(others) - x)`. Nothing is added to 1, so the loss stays accurate down to exp underflow. - **Backward:** the label gradient is `exp(-loss) - 1`, evaluated as `expm1(-loss)` from the accurate forward loss. The backward kernel now gets `losses`, which is also saved for backward. - **Chunked path (vocab > 65536):** each chunk also stores a logsumexp that skips the label, and the loss becomes `softplus(logsumexp(chunk_lse_others) - x)`. Only the chunk holding the label does the extra masked sum (second commit); the others store their plain logsumexp. - **No libdevice:** `log1p` / `expm1` are written with `tl.log` / `tl.exp` only (Kahan's trick), so CUDA, ROCm and XPU all take the same code. - **Same results elsewhere:** random logits match fp64 to the same tolerance before and after, with and without softcapping or logit scaling. ### Results NVIDIA L4 (SageMaker ml.g6.2xlarge), torch 2.8.0+cu129, triton 3.4.0. Base is `main` at 065955d; head is d191645. The branch has since been rebased (now 210020a), with no changes under `unsloth/kernels/` or to the test files above. bf16 logits, every 7th label `-100`. Each number is the median of `triton.testing.do_bench`, in ms. | vocab (tokens) | fwd main | fwd PR | Δ | fwd+bwd main | fwd+bwd PR | Δ | |---|---|---|---|---|---|---| | 32000 (8192) | 2.147 | 2.148 | +0.0% | 6.649 | 6.646 | -0.0% | | 128256 (8192) | 8.155 | 8.540 | +4.7% | 26.543 | 26.918 | +1.4% | | 151936 (8192) | 9.624 | 10.084 | +4.8% | 31.411 | 31.873 | +1.5% | | 262144 (4096) | 8.318 | 8.685 | +4.4% | 27.222 | 27.648 | +1.6% | - **A/A spread:** `main` timed in 3 separate jobs varies by at most 0.1% at every size. - **Single-block path (vocab ≤ 65536):** no measurable cost. - **Chunked path:** about 4.5% of the forward, and 1.5% of forward + backward. Doing the masked sum in every chunk instead cost 6% to 11% of the forward. ### Tests - `tests/test_cross_entropy_confident_labels.py`, new and GPU-gated like the other CE tests: - margins 5 to 80 for vocab sizes 32000, 65537 and 262144, so both the single-block and chunked paths, checked against an fp64 `softplus(logsumexp(others) - x)` reference, with the row gradient sum checked too; - a bf16 confident label; - random logits with and without softcapping. - `tests/test_cross_entropy_eviction_hints.py`: the new `logsumexp_others_ptr` is added to the compile signature. Results on L4, using `-m "not server and not native_mxc"` (overrides the default `not gpu`) over `test_cross_entropy_*.py`, `test_fused_ce_logit_scale.py`, `test_fused_ce_not_return_dict_logits.py` and `test_triton_fp_fusion.py`: - this PR: 273 passed; - `main` with the new test file: 254 passed, 19 failed (every confident-label case; the 6 random-logit cases pass on both). ### Not covered - **Other GPUs:** only L4 was measured. A100, H100 and B200 (which takes the 8192-wide chunks from unslothai#15141) were not. - **End to end:** no training step timing, only the kernel. - **The fused loss path:** the Llama-style forward computes the loss with unsloth_zoo's `unsloth_fused_ce_loss` unless logits are returned, and that calls `torch.nn.functional.cross_entropy`, which collapses the same way. This PR covers `fast_cross_entropy_loss`, which serves the `UNSLOTH_RETURN_LOGITS=1` branch and the patched transformers `ForCausalLMLoss`. - **Overlap:** unslothai#14712 and unslothai#14713 also edit the chunked forward, so whichever lands second needs a small rebase. ### Maintainer update - **Merged `main`** (unslothai#14712, unslothai#14713 landed in the same chunked forward). The chunked path now finishes out of place (`losses = losses.masked_fill(...)`): an in-place op on the returned tensor gives wrong gradients under `torch.compile` on torch 2.11, which unslothai#14712 fixed and this branch would otherwise have brought back. unslothai#14713's all -inf chunk guard is kept ahead of the label-free sum. - **One reduction instead of two.** Both kernels now sum the non-label terms once and add the label back as a scalar for the plain logsumexp (`c + log(sum_others + exp(x - c))`), instead of a full sum plus a masked sum. Torch 2.11, fp64 reference, vocab 32000 / 151936 / 262144, margins 5 to 40, eager / compiled / `fullgraph=True` / `dynamic=True`: 0 of 60 cells off on T4 (fp16) and L4 (bf16); `main` misses 28 of 60 (every margin of 17 and up). CE test files: 282 passed here, `main` 263 passed and 19 failed (the confident-label tests). | vocab, 151936 compiled | loss rel err `main` | loss rel err here | |---|---|---| | margin 17 | 4.4e-4 | 3.3e-7 | | margin 25 | 9.6e-2 | 4.5e-7 | | margin 40 | 1.0 (loss 0) | 6.7e-4 | Kernel time on A100 80GB, torch 2.11, bf16, `do_bench` median over 4 rounds per arm in rotation (base spread under 1% except vocab 32000 at 18%): | vocab (tokens) | fwd, first revision | fwd, now | fwd+bwd, first revision | fwd+bwd, now | |---|---|---|---|---| | 32000 (8192) | +27.7% | +10.6% | +12.6% | +4.0% | | 128256 (8192) | +7.4% | +6.2% | +2.9% | +2.5% | | 151936 (8192) | +7.2% | +6.7% | +2.8% | +2.5% | | 262144 (4096) | +13.2% | +9.2% | +5.0% | +3.5% | --------- Co-authored-by: Daniel Han <[email protected]>
Follow-up to #14712. ## Problem `Fast_CrossEntropyLoss` computes its chunk and block counts with `divmod` on the vocab size. With `dynamic=True` the size is symbolic and Dynamo cannot trace `divmod` on it: `fullgraph=True` raises Unsupported, and `fullgraph=False` fails in the Triton launch for vocabs above 65536. The default loader path passes `torch_compile=False`, so this is only reached through a direct `patch_loss_functions(torch_compile=True)` or a user compile. ## Change Use ceil division instead of `divmod`. Eager computes the same integers. ## Tests `tests/test_cross_entropy_compiled_grads.py` now also runs `dynamic=True` (torch 2.10+). Single GPU, torch 2.13: - main: 3 failed, 9 passed. Failing: `test_compiled_grads_match_the_fp64_reference[True-True-32768]`, `[True-True-65537]`, `[True-True-151936]`. - this branch: 12 passed. ## Not covered GPU run on torch 2.13 only. An earlier L4 run on torch 2.12 also failed 5 of the 6 dynamic cases on main and passed all 12 here. torch 2.14 and later were not run on GPU.
## Summary `Repo tests (CPU, rest)` is red on `main` (seen on #18650, reproduced on current `main`): ``` FAILED tests/test_autograd_inplace_outputs.py::test_no_inplace_mutation_of_returned_fresh_tensors AssertionError: unsloth/kernels/fast_lora.py:686 LoRA_MLP: i.fill_(_SKIPPED_FILL) ``` ## Cause #18607 (skip the LoRA MLP down projection in gradient checkpoint replays) builds the skipped output as `i = X.new_empty(X.shape)`. When the test-only `_SKIPPED_FILL` sentinel is set, it then calls `i.fill_(_SKIPPED_FILL)`. `i` is returned from `LoRA_MLP.forward`. The guard exists because torch 2.11 compiles a wrong gradient for an ATen in-place op on a fresh tensor a `torch.autograd.Function` forward returns (#14712), and the block-compile path (#18641) traces this forward. The guard is right, and the skip itself is right: only the mutation needs to go. ## Change - `unsloth/kernels/fast_lora.py`: allocate the skipped output already filled, `X.new_full(X.shape, _SKIPPED_FILL)`, when the sentinel is set. Otherwise it stays `X.new_empty(X.shape)`. The values are identical (`new_empty` + `fill_` and `new_full` both give a tensor of that shape full of that value), and production never sets the sentinel. There is no in-place op left on the returned tensor. ## Testing - `tests/test_autograd_inplace_outputs.py` fails on `main` with the line above and passes with this change. - `tests/test_gc_skip_replay_mlp_down.py` and `tests/test_autograd_inplace_outputs.py` on CPU: 20 passed, 6 skipped. The skipped six need CUDA. - Not run here: those six CUDA tests, which fill the skipped output with NaN to prove nothing reads it, and `test_gc_skip_replay_mlp_down_block_compile.py` (torch >= 2.11 with CUDA). This host has no local GPU for this session, and the remote attempt failed in dependency setup before any test ran. CI's GPU jobs will exercise them.
What
Fast_CrossEntropyLoss.forwardfinished the chunked path (vocab > 65536) with two in-place ops on the tensor it returns:losses += logsumexpandlosses.masked_fill_(...). Undertorch.compile(default orfullgraph=True) the traced backward then received a zero gradient for that output, so every logit gradient came back as exactly zero while the loss value stayed correct. This PR computes the result out of place:losses = (losses + logsumexp).masked_fill(labels == -100, 0).Evidence (B200, torch 2.11, fp16 and bf16, fp64 reference)
The same zero gradients show up at the parent of #14498, so this predates it. Graph break counts are unchanged (0 static, 8 under
dynamic=True). The compiledLOSS_MAPPINGloss Unsloth installs usesdynamic=True, which graph-breaks around the function and was already correct; the broken case is a user or Trainertorch.compileover a forward that computes the loss (defaultdynamic=Nonecompiles statically first).Tests
tests/test_cross_entropy_compiled_grads.py: compiled and fullgraph gradients vs an fp64 reference for vocab 32768, 65537 and 151936. The chunked cases fail on main and pass here. Existing cross entropy tests pass.