Repository navigation
Cross entropy: keep the loss and label gradient of confident tokens - #15140
Conversation
42a2241 to
d191645
Compare
Once the label logit leads the logsumexp of the other logits by more than ~16.6 nats, its exp(0) = 1 swamps the other terms in fp32. logsumexp - x then rounds to exactly 0, and so does the label gradient softmax - 1, while every other class keeps its positive gradient. The loss reads 0 and the row gradient no longer sums to zero. Below the cliff the error is already visible: at a 10 nat margin the loss is 0.8% too high. Sum the non-label terms alone (reusing the exp already computed) and take loss = softplus(logsumexp(others) - x), which stays accurate down to exp underflow. The backward uses exp(-loss) - 1 for the label. log1p / expm1 are written with tl.log / tl.exp (Kahan's trick), so no libdevice is needed. The chunked path stores a second per-chunk logsumexp that skips the label. See "A Fix for Softmax and Cross-Entropy", arXiv:2610.31642.
The other chunks store their plain logsumexp. On an L4 this brings the chunked forward overhead from +6-11% to +4.5% (fwd + bwd +1.4%).
d191645 to
210020a
Compare
# Conflicts: # unsloth/kernels/cross_entropy_loss.py [skip ci]
|
@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: Something went wrong. Try again later by commenting “@codex review”. ℹ️ 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: Something went wrong. Try again later by commenting “@codex review”. ℹ️ 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". |
…mexp, adding the label back as a scalar [skip ci]
…-loss) cannot push the label gradient past -1 [skip ci]
Once the label logit leads the logsumexp of the other logits by more than ~16.6 nats, the label's
exp(0) = 1swamps the other terms in fp32.loss = logsumexp - xand the label gradientexp(x - logsumexp) - 1then 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.main, fp32, the label leadingV - 1zero logits bymargin:bf16 inputs are affected the same way, since the kernels upcast to fp32.
Change
unsloth/kernels/cross_entropy_loss.py:exp(logits - c), sum the non-label terms alone, and takeloss = softplus(logsumexp(others) - x). Nothing is added to 1, so the loss stays accurate down to exp underflow.exp(-loss) - 1, evaluated asexpm1(-loss)from the accurate forward loss. The backward kernel now getslosses, which is also saved for backward.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.log1p/expm1are written withtl.log/tl.exponly (Kahan's trick), so CUDA, ROCm and XPU all take the same code.Results
NVIDIA L4 (SageMaker ml.g6.2xlarge), torch 2.8.0+cu129, triton 3.4.0. Base is
mainat 065955d; head is d191645. The branch has since been rebased (now 210020a), with no changes underunsloth/kernels/or to the test files above. bf16 logits, every 7th label-100. Each number is the median oftriton.testing.do_bench, in ms.maintimed in 3 separate jobs varies by at most 0.1% at every size.Tests
tests/test_cross_entropy_confident_labels.py, new and GPU-gated like the other CE tests:softplus(logsumexp(others) - x)reference, with the row gradient sum checked too;tests/test_cross_entropy_eviction_hints.py: the newlogsumexp_others_ptris added to the compile signature.Results on L4, using
-m "not server and not native_mxc"(overrides the defaultnot gpu) overtest_cross_entropy_*.py,test_fused_ce_logit_scale.py,test_fused_ce_not_return_dict_logits.pyandtest_triton_fp_fusion.py:mainwith the new test file: 254 passed, 19 failed (every confident-label case; the 6 random-logit cases pass on both).Not covered
unsloth_fused_ce_lossunless logits are returned, and that callstorch.nn.functional.cross_entropy, which collapses the same way. This PR coversfast_cross_entropy_loss, which serves theUNSLOTH_RETURN_LOGITS=1branch and the patched transformersForCausalLMLoss.Maintainer update
main(Cross entropy: correct gradients under torch.compile for vocabs above 65536 #14712, Cross entropy: an all -inf vocab chunk no longer turns the loss into NaN #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 undertorch.compileon torch 2.11, which Cross entropy: correct gradients under torch.compile for vocabs above 65536 #14712 fixed and this branch would otherwise have brought back. Cross entropy: an all -inf vocab chunk no longer turns the loss into NaN #14713's all -inf chunk guard is kept ahead of the label-free sum.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);mainmisses 28 of 60 (every margin of 17 and up). CE test files: 282 passed here,main263 passed and 19 failed (the confident-label tests).mainKernel time on A100 80GB, torch 2.11, bf16,
do_benchmedian over 4 rounds per arm in rotation (base spread under 1% except vocab 32000 at 18%):