Skip to content

Cross entropy: an all -inf vocab chunk no longer turns the loss into NaN - #14713

Merged
danielhanchen merged 6 commits into
mainfrom
ce-masked-chunk-nan
Oct 25, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
ce-masked-chunk-nan

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

What

The chunked forward computes a per-chunk logsumexp as c + log(sum(exp(x - c))) with c the chunk max. When a whole chunk is -inf (a masked or banned token range), c is -inf and x - c is -inf - -inf = NaN, so the final logsumexp, the loss and every gradient in the row become NaN. This PR shifts by 0 when the chunk max is -inf, which makes that chunk's partial logsumexp -inf and drops it out of the final reduction, the same way PyTorch's logsumexp handles infinite maxima. Finite chunks are unchanged bit for bit.

Why now

#14498 moved T4 and A100 to 16384-wide chunks, so a masked range of 16384 aligned columns now fills a whole chunk where it used to share a 65536 chunk with finite logits. A fully masked 65536 range already hit this before #14498.

Evidence (B200, real kernels, fp64 reference, 131073 vocab, target 0)

masked columns 65536 / 32 (before) 16384 / 8 (T4, A100 now) after this PR
16384..32768 11.6499796 ok NaN, non-finite grads matches reference
65536..131072 NaN NaN matches reference

Tests

test_an_all_masked_chunk_matches_the_fp64_reference in tests/test_cross_entropy_chunk_config.py for both chunk widths and both masked ranges: fails on main, passes here. The rest of the cross entropy tests pass.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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 ✅ Completed 2026-10-25T05:33:06.428989Z b603d9d 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: Didn't find any major issues. Delightful!

Reviewed commit: 14ebf8436d

ℹ️ 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 Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: b603d9dede

ℹ️ 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
danielhanchen merged commit c1df811 into main Oct 25, 2026
29 of 37 checks passed
@danielhanchen
danielhanchen deleted the ce-masked-chunk-nan branch October 25, 2026 07:55
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 25, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant