Skip to content

Cross entropy: 8192-wide chunks at 4 warps for the chunked forward on B200 - #15141

Merged
danielhanchen merged 1 commit into
mainfrom
ce-b200-chunked-config
Oct 24, 2026
Merged

danielhanchen merged 1 commit into
mainfrom
ce-b200-chunked-config

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

On B200 the chunked cross entropy forward, used for vocabularies above 65536, still runs one 65536-wide chunk per program at 32 warps. That config is capped at 64 registers per thread with 16 spills, and only one block fits per SM. 8192-wide chunks at 4 warps compile to 78 registers with no spills and make the forward 1.5x to 1.9x faster. The comparison against NVIDIA TileGym's cross entropy kernel is what pointed at this.

Change

_CHUNKED_FORWARD_CONFIGS in unsloth/kernels/cross_entropy_loss.py gets a (10, 0): (8192, 4, None) entry, next to the existing T4 and A100 ones.

  • Scope: B200 (sm_100) only, for every vocabulary that takes the chunked path. sm_103 and every other GPU keep their current configs.
  • Same math: only the chunk width and warp count change, and the per-chunk logsumexp is combined the same way. The backward is untouched.

Results

B200, torch 2.14.1, bf16 logits, forward only. Base and head alternated in fresh processes with CUDA graphs, 6 repeats each.

vocab (tokens) main this PR speedup A/A spread (main)
Llama 3, 128256 (8192) 0.634 ms 0.414 ms 1.53x 0.2%
Qwen3, 151936 (8192) 0.915 ms 0.487 ms 1.88x 0.2%
Gemma 3, 262144 (4096) 0.631 ms 0.415 ms 1.52x 0.2%
  • Backward: 1.00x at all three sizes, as expected.
  • RTX PRO 6000 (sm_120, Colab G4): a sweep of chunk configs there showed every config at about 91% of memory bandwidth, so chunk size makes no difference and that GPU keeps its current config.

Tests

tests/test_cross_entropy_chunk_config.py:

  • new test_b200_uses_8k_blocks_with_4_warps (5 vocab sizes);
  • sm_100 is removed from the "other archs keep the previous config" list;
  • test_loss_and_grads_match_across_chunk_widths now checks the 8192 / 4 config too: loss and gradients match the 65536-wide chunk, with softcapping and logit scaling.

Results on B200:

  • with the other cross entropy test files: 62 passed with torch 2.14.1;
  • test_cross_entropy_chunk_config.py alone: 52 passed with torch 2.10.0.

On Kaggle T4, which does not take the new entry, the selected kernel tests had 0 failures on main and on a branch carrying this change, and fp16 CE losses were identical to 9 digits. T4 does not take the new entry.

Not covered

  • Other Blackwell GPUs: B300 / sm_103 was not available, so it keeps the old config.
  • End to end: no full training step timing, only the kernel.

… B200

One 65536-wide chunk at 32 warps per program leaves the B200 forward
register bound. 8192-wide chunks at 4 warps run 1.5-1.9x faster at
8192 tokens for 128256 / 151936 / 262144 vocabularies (bf16). Other
architectures keep their configs.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 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-24T16:32:50.256715Z 169493d 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. Keep it up!

Reviewed commit: 169493d848

ℹ️ 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 6eb93c8 into main Oct 24, 2026
4 of 30 checks passed
@danielhanchen
danielhanchen deleted the ce-b200-chunked-config branch October 24, 2026 16:38
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]>
danielhanchen added a commit that referenced this pull request Oct 28, 2026
… sm120 (#15744)

## Summary

Adds an sm120 (RTX PRO 6000, RTX 5090) entry to
`_CHUNKED_FORWARD_CONFIGS` in `unsloth/kernels/cross_entropy_loss.py`.
sm120 now uses 8192-wide chunks at 4 warps for the chunked cross entropy
forward, the same entry B200 got in #15141. Before this change, sm120
used the default single 65536-wide chunk at 32 warps.

```python
_CHUNKED_FORWARD_CONFIGS = {
    (7, 5): (16384, 8, None),
    (8, 0): (16384, 8, 163840),
    (10, 0): (8192, 4, None),
    (12, 0): (8192, 4, None),
}
```

Only the `(12, 0)` key is new. Every other compute capability, including
sm121, routes exactly as before. The backward kernel is unchanged.

## Where this kernel runs

This kernel only runs when logits are materialised: with
`UNSLOTH_RETURN_LOGITS=1`, with an NVFP4 / MX fake-quant `lm_head`, and
through the patched HF `ForCausalLMLoss`. Default text SFT goes through
the fused linear CE in unsloth-zoo and GRPO uses its own logprob path,
so neither is affected.

## Kernel results (RTX PRO 6000, sm120)

Setup: 6 arms, 3 interleaved rounds, a fresh process per arm, `do_bench`
median with L2 flushed. The matrix was vocab 128256 / 151936 / 262144 x
rows 2048 / 4096 / 8192 / 16384, bf16 and fp16, on torch 2.10.0 (Triton
3.6) and torch 2.14.1 (Triton 3.8). Main vs a repeat of main (A/A)
stayed within 0.3% in every cell.

| | torch 2.10 | torch 2.14 |
|---|---|---|
| chunked forward kernel, bf16 | 1.09x to 1.18x | 1.13x to 1.39x |
| chunked forward kernel, fp16 | 1.11x to 1.26x | 1.15x to 1.41x |
| loss forward + backward, bf16 | 1.03x to 1.06x | 1.04x to 1.13x |
| loss forward + backward, fp16 | 1.03x to 1.08x | 1.05x to 1.14x |

The 16384 / 8, 32768 / 8 and 32768 / 16 configs all landed within 0.5%
of 8192 / 4. No cell got slower. A 32000 vocab uses the single-block
kernel and does not change (1.000x). I also swept the backward block
size and warps: the best alternative was 1.6% faster on geomean, so I
left the backward as is.

## Accuracy

The result matches an fp64 reference (`F.cross_entropy` in float64) as
closely as before. Loss error is 2e-7 to 1.7e-6 for both configs. The
max grad error is the same for both: 6e-6 in bf16, 3e-7 to 9e-7 in fp16.
The output is not bitwise identical, because the per-chunk logsumexp
values combine in a different order. The difference is well inside the
tolerance `test_loss_and_grads_match_across_chunk_widths` already uses
for `(8192, 4)`.

## End to end (RTX PRO 6000, torch 2.14.1, `UNSLOTH_RETURN_LOGITS=1`, 30
LoRA steps)

Arms ran in the order base, head, head, base. All 30 steps in every run
went through the chunked kernel, with base at (65536, 32) and head at
(8192, 4).

| model | base ms / step | head ms / step | A/A spread |
|---|---|---|---|
| Qwen3-0.6B | 81.19 / 78.36 | 79.63 / 79.76 | 3.5% / 0.2% |
| Llama-3.2-1B-Instruct | 86.46 / 85.46 | 86.08 / 85.45 | 1.2% / 0.7% |

The end-to-end change is within noise. At about 3K tokens per step, the
loss is about 1.5 ms of an 80 ms step, so most of the gain shows up on
large token counts with logits returned. Per-step loss matches base
within the same spread as two base runs.

## Tests

- `tests/test_cross_entropy_sm120_chunk_config.py` is new and runs on
CPU with a mocked capability. It pins (8192, 4) for sm120 across vocabs
and checks that sm121, sm110, sm90 and sm89 keep the previous config. On
main it fails 7 of 11.
- `tests/test_cross_entropy_chunk_config.py` gets the sm120 route, and
its "other archs" case now uses `(12, 1)`.
- CE tests on an RTX PRO 6000 (10 files): 249 passed with this change.
On main, 12 fail, and all 12 are the new sm120 pins.
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.

1 participant