Skip to content

Fix NaN cross entropy loss when a 16K vocab chunk is fully masked - #14772

Closed
danielhanchen wants to merge 2 commits into
mainfrom
fix-ce-masked-chunk-nan
Closed

danielhanchen wants to merge 2 commits into
mainfrom
fix-ce-masked-chunk-nan

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

The chunked cross entropy forward computes a logsumexp per vocab chunk as
c + log(sum(exp(logits - c))) with c = max(chunk). When the caller masks every logit
in a chunk to -inf (constrained or partially masked vocabulary, no softcapping), c is
-inf and logits - c is -inf - -inf = NaN. The NaN reaches the per row logsumexp, so the
loss and every gradient in that row become NaN. Rows with an ignored label but a masked
chunk also get NaN gradients, since 0 * NaN is NaN.

Reach: #14498 picked 16K chunks on T4 and A100 for vocabularies up to 163840 (for
example Llama 3 at 128256). With 64K chunks a mask had to cover 64K contiguous logits
to trigger this; with 16K chunks a masked block of 16K aligned logits is enough. The
path is used when fast_cross_entropy_loss runs on the chunked kernel, for example with
UNSLOTH_RETURN_LOGITS=1.

Fix: if a chunk's max is -inf, use 0 instead. The empty chunk then contributes
log(0) = -inf to the final torch.logsumexp over chunks, which is zero probability mass,
exactly what a fully masked chunk should contribute. Finite chunks are unchanged.

Tests: tests/test_cross_entropy_masked_vocab_chunk.py runs the real forward and
backward kernels from the source file under TRITON_INTERPRET=1 on CPU at both chunk
widths, with a fully masked first chunk, a fully masked middle chunk and an ignored row
with a masked chunk, and compares loss and gradients against an fp64 reference. The
16K case fails on main (loss is nan) and passes with this change. A CUDA variant of the
same check through fast_cross_entropy_loss runs on GPU runners.

Not covered: a row whose logits are all -inf and whose label is ignored still gets NaN
gradients at both chunk widths. That is older behaviour and separate from this change.

GPU check (B200): with this change all tests/test_cross_entropy_*.py pass (191, including the CUDA variant); on main the new file fails 3 of 5 (the 16K interpreter case, the CUDA case and the masked chunk guard). Regression smoke suite on main plus this change: no regressions against main.

The chunked forward subtracts the chunk max before the logsumexp. When the caller masks an
entire chunk to -inf the max is -inf and -inf - -inf is NaN, so the loss and every gradient
in the row become NaN. 16K chunks on T4 and A100 for a 128256 vocab reach this where 64K
chunks did not. Reset an all -inf max to 0 so the empty chunk contributes -inf, zero mass,
to the final logsumexp.
@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-22T19:37:28.060661Z 4618f65 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. Bravo.

Reviewed commit: 4618f65721

ℹ️ 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 added a commit that referenced this pull request Oct 22, 2026
pre-commit.ci fails `ruff-format-with-kwargs` on every open PR (#14806,
#14805, #14803, #14790, #14785, #14781, #14780, #14777, #14776, #14775,
#14774, #14773, #14772, #14770, #14769, #14768, and others): "files were
modified by this hook". pre-commit.ci runs the hooks on all files, and
20 files on main (26 by the time this lands) are not in the formatter's
output, so every PR is reformatted outside its own diff. Where
pre-commit.ci can push, its autofix commit drags those unrelated files
into the PR (for example #14790's touches `tests/test_block_compile.py`,
`tests/test_bnb_integration_compile.py` and `unsloth/models/_utils.py`).

The drift came in with PRs merged today, among them #14702, #14751,
#14759, #14784, #14786, #14787, #14788, #14791 and the FP8 block decode,
GRPO routing replay, 4-bit decode, compiled blocks and MoE LoRA target
changes.

### Change

`python scripts/run_ruff_format.py` (the hook's own entry point,
`ruff==0.6.9` as pinned in `.pre-commit-config.yaml`) applied to those
20 files, plus 6 more from #14739, #14779 and #14806, which merged while
this was open. Formatting only.

### Verification

- Every changed file parses to an identical AST before and after.
- A second run of the hook over the same files changes nothing (fixed
point), and over all tracked Python files on this branch it changes
nothing.
- `ruff check` passes on the changed files;
`tests/test_formatter_fixed_point.py` passes (16).

Open PRs pick this up on their next pre-commit.ci run after merging
main.
@danielhanchen

Copy link
Copy Markdown
Member Author

Closing as a duplicate of #14713, which makes the same one-line change in unsloth/kernels/cross_entropy_loss.py (shift by 0 when a chunk's max is -inf) and was opened first.

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