Skip to content

Cross entropy: 16384 / 8 warp chunked forward on T4 and A100 - #14498

Merged
danielhanchen merged 4 commits into
mainfrom
ce-chunk-config-per-arch
Oct 21, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
ce-chunk-config-per-arch

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

For vocabs above 65536 (Llama-3, Qwen3, Gemma), Fast_CrossEntropyLoss runs the chunked forward kernel with 65536-wide chunks and 32 warps on every GPU. On T4 and A100 a 16384-wide chunk with 8 warps is faster.

Change

  • New _CHUNKED_FORWARD_CONFIGS in unsloth/kernels/cross_entropy_loss.py: (BLOCK_SIZE, num_warps, max vocab) per NVIDIA capability, cached per device and vocab like the existing eviction-hint lookup.
    • T4 (sm75): 16384 / 8 for every vocab.
    • A100 (sm80): 16384 / 8 up to vocab 163840. At Gemma's 262144 the new config is slower on torch 2.10 (0.976 to 0.998x) and faster on 2.14 (1.02 to 1.04x), so it keeps the default there.
  • Unchanged:
    • every other arch, plus ROCm and XPU: 65536 / 32 warps (16 on CDNA), bit-identical output;
    • vocabs up to 65536: still the single-block kernel;
    • the backward kernel: its alternatives were within about 1.5%.

Validation

Kaggle T4, Colab A100 and Colab L4, torch 2.10 and 2.14. Each arm ran in a fresh process, three repeats with the order rotated, plus an identical copy of the old config as an A/A arm. Old time / new time, so above 1 is faster:

GPU / torch forward kernel whole loss, fwd + bwd A/A
T4 2.10, fp16 1.12 to 1.38x 1.05 to 1.10x 3% or less
T4 2.14, fp16 1.76 to 2.42x 1.35 to 1.44x 0.4% or less
A100 2.10, vocab 128256 / 151936, bf16 1.05 to 1.27x 1.01 to 1.09x 0.3% or less
A100 2.14, vocab 128256 / 151936, bf16 1.08 to 1.26x 1.03 to 1.09x 0.3% or less
L4 2.10 / 2.14, bf16 (not changed) 1.004 to 1.027x 1.000 to 1.007x 0.2% or less
  • Shapes: vocab 128256, 151936 and 262144 at 2K to 16K tokens.
  • On T4 torch 2.10 at vocab 262144, the 8K and 16K token forward rows are inside noise (both T4s were benchmarked at once on one Kaggle machine), but the whole loss still wins there.
  • L4 gains were too small to change it.

Accuracy, on T4 fp16, A100 bf16 and L4 bf16, both torch versions:

  • cases: vocab 128256, 151936 and 262144; 256000 with softcapping or logit scaling; a mostly masked batch;
  • every case passes the existing tolerances and is within about 2e-6 of an fp64 reference;
  • per-row losses move by at most 3.8e-6, from summing the chunks in a different order.

New tests/test_cross_entropy_chunk_config.py: the routing per capability and vocab, ROCm / CDNA, and accuracy on the real device. Locally on B200: main 44 failed / 10 passed (the routing tests), this PR 54 passed. On T4, A100 and L4 with both torch versions, the first revision: main 23 failed / 10 passed, this PR 33 passed.

End to end, Llama-3.2-1B-Instruct SFT, 20 steps, batch 4, sequence up to 2048. These runs set UNSLOTH_RETURN_LOGITS=1, since by default Llama computes the loss through unsloth_fused_ce_loss and does not reach this kernel. A counter confirmed 20 calls per run, with the expected config on each side. Runs went main, PR, PR, main:

GPU / torch 16-bit, PR vs main 4-bit, PR vs main main vs main
T4 2.10 +0.97% -0.47% 3.4% / 1.1%
T4 2.14 -2.56% +0.00% 6.0% / 0.3%
A100 2.10 -1.19% +0.91% 1.3% / 0.8%
A100 2.14 -0.01% -0.07% 0.2% / 0.3%
  • Every arm passes the loss comparison.
  • Step time is inside noise: the loss is a small share of a 1B model step.
  • The gain shows on models that take this kernel: those whose logits are materialised (through the patched ForCausalLMLoss) and large-vocab models with long sequences.

Not covered:

  • arches not measured, so unchanged: sm86, H100, B200, sm120 and ROCm;
  • end to end on L4, and on any model with a vocab above 163840;
  • the A100 cap of 163840 is a judgement call: nothing was measured between 151936 and 262144;
  • Windows and WSL.

The chunked forward (vocab > 65536) launched 65536-wide blocks with 32 warps on every NVIDIA arch.
On sm_75 and sm_80 16384-wide blocks with 8 warps are faster for Llama-3, Qwen3 and Gemma vocabs.
Route (BLOCK_SIZE, num_warps) by compute capability; every other arch keeps the previous config.
…vocab

At Gemma's 262144 vocab 16384 / 8 is 1 to 2.4% slower than 65536 / 32 on A100 with torch 2.10
and 2 to 3.5% faster with torch 2.14, so only Llama-3 / Qwen3 sized vocabs route there. T4 keeps
16384 / 8 at every vocab.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 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-21T12:13:20.408259Z
We couldn’t complete this review. Comment @codex review to try again.
b72e796 New commits
🔒 Security Review ⚠️ Failed 2026-10-21T11:55:33.320931Z
We couldn’t complete this review. Comment @codex security review to try again.
5ad40f1 PR opened
ℹ️ 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 5ad40f15d6

ℹ️ 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 0a20d7b into main Oct 21, 2026
1 check passed
@danielhanchen
danielhanchen deleted the ce-chunk-config-per-arch branch October 21, 2026 12:39
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 25, 2026
… 65536 (unslothai#14712)

## What

`Fast_CrossEntropyLoss.forward` finished the chunked path (vocab >
65536) with two in-place ops on the tensor it returns: `losses +=
logsumexp` and `losses.masked_fill_(...)`. Under `torch.compile`
(default or `fullgraph=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)

| vocab | eager | compiled | fullgraph | dynamic=True |
|---|---|---|---|---|
| 32768 (single block) | ok | ok | ok | ok |
| 65537, 151936, 262144 before | ok | grad rel err 1.0 (all zero) | grad
rel err 1.0 | ok (graph breaks) |
| 65537, 151936, 262144 after | ok | 2e-4 (fp16) / 2e-3 (bf16) | same |
ok |

The same zero gradients show up at the parent of unslothai#14498, so this
predates it. Graph break counts are unchanged (0 static, 8 under
`dynamic=True`). The compiled `LOSS_MAPPING` loss Unsloth installs uses
`dynamic=True`, which graph-breaks around the function and was already
correct; the broken case is a user or Trainer `torch.compile` over a
forward that computes the loss (default `dynamic=None` compiles
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.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 25, 2026
…NaN (unslothai#14713)

## 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

unslothai#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 unslothai#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.
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