Skip to content

Cross entropy: keep the loss and label gradient of confident tokens - #15140

Merged
danielhanchen merged 8 commits into
unslothai:mainfrom
mlzoo:fix-ce-softmax-collapse
Oct 25, 2026
Merged

danielhanchen merged 8 commits into
unslothai:mainfrom
mlzoo:fix-ce-softmax-collapse

Conversation

@mlzoo

@mlzoo mlzoo commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

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.

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

Maintainer update

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%

@mlzoo
mlzoo requested a review from danielhanchen as a code owner October 24, 2026 16:10
@mlzoo
mlzoo force-pushed the fix-ce-softmax-collapse branch from 42a2241 to d191645 Compare October 24, 2026 17:03
mlzoo added 2 commits October 24, 2026 17:42
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%).
@mlzoo
mlzoo force-pushed the fix-ce-softmax-collapse branch from d191645 to 210020a Compare October 24, 2026 17:42
@danielhanchen danielhanchen self-assigned this Oct 25, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-25T08:40:56.022411Z
We couldn’t complete this review. Comment @codex review to try again.
70eb131 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants