Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

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

Daniel Han0a20d7bf1c78
diff --git a/tests/test_cross_entropy_chunk_config.py b/tests/test_cross_entropy_chunk_config.py
new file mode 100644
index 00000000000..ff805ee3824
--- /dev/null
+++ b/tests/test_cross_entropy_chunk_config.py
@@ -0,0 +1,140 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+
+"""Chunked CE forward must launch the per-arch (BLOCK_SIZE, num_warps); loss/grads independent of chunk width."""
+
+import pytest
+import torch
+
+if not torch.cuda.is_available() or torch.version.hip is not None:
+ pytest.skip("needs an NVIDIA CUDA device", allow_module_level = True)
+
+from unsloth.kernels import cross_entropy_loss as ce_mod
+from unsloth.kernels.utils import MAX_FUSED_SIZE
+
+
+def _route(
+ capability,
+ monkeypatch,
+ vocab = 128256,
+):
+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda index = None: capability)
+ ce_mod._chunked_forward_config_at.cache_clear()
+ try:
+ return ce_mod._chunked_forward_config(torch.device("cuda", 0), vocab)
+ finally:
+ ce_mod._chunked_forward_config_at.cache_clear()
+
+
[email protected]("vocab", [65537, 128256, 151936, 256000, 262144])
+def test_t4_uses_16k_blocks_with_8_warps(vocab, monkeypatch):
+ assert _route((7, 5), monkeypatch, vocab) == (16384, 8)
+
+
[email protected]("vocab", [65537, 128256, 151936, 152064, 163840])
+def test_a100_uses_16k_blocks_with_8_warps_up_to_163840(vocab, monkeypatch):
+ assert _route((8, 0), monkeypatch, vocab) == (16384, 8)
+
+
[email protected]("vocab", [163841, 256000, 262144])
+def test_a100_keeps_the_previous_config_for_larger_vocabs(vocab, monkeypatch):
+ assert _route((8, 0), monkeypatch, vocab) == (MAX_FUSED_SIZE, 32)
+
+
+ "capability",
+ [(6, 1), (7, 0), (7, 2), (8, 6), (8, 7), (8, 9), (9, 0), (10, 0), (10, 3), (12, 0)],
+)
[email protected]("vocab", [128256, 262144])
+def test_other_archs_keep_the_previous_config(capability, vocab, monkeypatch):
+ assert _route(capability, monkeypatch, vocab) == (MAX_FUSED_SIZE, 32)
+
+
+def test_device_without_index_uses_the_current_device(monkeypatch):
+ seen = []
+
+ def capability(index = None):
+ seen.append(index)
+ return (7, 5)
+
+ monkeypatch.setattr(torch.cuda, "get_device_capability", capability)
+ ce_mod._chunked_forward_config_at.cache_clear()
+ try:
+ assert ce_mod._chunked_forward_config(torch.device("cuda"), 128256) == (16384, 8)
+ finally:
+ ce_mod._chunked_forward_config_at.cache_clear()
+ assert seen == [torch.cuda.current_device()]
+
+
+def test_non_cuda_devices_keep_the_previous_config():
+ assert ce_mod._chunked_forward_config_at("xpu", 0, 128256) == (MAX_FUSED_SIZE, 32)
+
+
+def _launch(
+ vocab,
+ config,
+ monkeypatch,
+ rows = 64,
+ softcap = 0.0,
+ scale = 0.0,
+):
+ launches = []
+ kernel = ce_mod._chunked_cross_entropy_forward
+
+ class Spy:
+ def __getitem__(self, grid):
+ def run(*args, **kwargs):
+ launches.append(
+ (tuple(grid), kwargs["BLOCK_SIZE"], kwargs["N_CHUNKS"], kwargs["num_warps"])
+ )
+ return kernel[grid](*args, **kwargs)
+
+ return run
+
+ monkeypatch.setattr(ce_mod, "_chunked_cross_entropy_forward", Spy())
+ monkeypatch.setattr(ce_mod, "_chunked_forward_config", lambda device, vocab_size: config)
+ generator = torch.Generator(device = "cuda").manual_seed(vocab)
+ logits = (torch.randn(rows, vocab, device = "cuda", generator = generator) * 3).to(torch.bfloat16)
+ labels = torch.randint(0, vocab, (rows,), device = "cuda", generator = generator)
+ labels[::5] = -100
+ labels[1:4] = torch.tensor([0, vocab - 1, 16383], device = "cuda")
+ logits.requires_grad_(True)
+ loss = ce_mod.fast_cross_entropy_loss(
+ logits.view(1, rows, vocab),
+ labels.view(1, rows),
+ logit_softcapping = softcap,
+ logit_scaling = scale,
+ )
+ loss.backward()
+ return launches, loss.detach(), logits.grad.detach()
+
+
[email protected]("vocab", [128256, 151936, 262144])
+def test_launch_uses_the_routed_config(vocab, monkeypatch):
+ launches, _, _ = _launch(vocab, (16384, 8), monkeypatch)
+ n_chunks = -(-vocab // 16384)
+ assert launches == [((64, n_chunks), 16384, n_chunks, 8)]
+
+
+ "vocab, softcap, scale",
+ [
+ (128256, 0.0, 0.0),
+ (151936, 0.0, 0.0),
+ (262144, 0.0, 0.0),
+ (256000, 30.0, 0.0),
+ (256000, 0.0, 0.0625),
+ ],
+)
+def test_loss_and_grads_match_across_chunk_widths(vocab, softcap, scale, monkeypatch):
+ _, loss_old, grad_old = _launch(
+ vocab, (MAX_FUSED_SIZE, 32), monkeypatch, softcap = softcap, scale = scale
+ )
+ _, loss_new, grad_new = _launch(vocab, (16384, 8), monkeypatch, softcap = softcap, scale = scale)
+ torch.testing.assert_close(loss_new, loss_old, rtol = 1e-5, atol = 1e-5)
+ torch.testing.assert_close(grad_new, grad_old, rtol = 2e-2, atol = 2e-3)
+
+
+def test_vocab_at_most_65536_stays_on_the_single_block_kernel(monkeypatch):
+ launches, _, _ = _launch(32768, (16384, 8), monkeypatch)
+ assert launches == []
diff --git a/unsloth/kernels/cross_entropy_loss.py b/unsloth/kernels/cross_entropy_loss.py
index b1a18eb79d8..e2a381320ea 100644
--- a/unsloth/kernels/cross_entropy_loss.py
+++ b/unsloth/kernels/cross_entropy_loss.py
@@ -128,6 +128,31 @@ def _chunked_evict_policy(device):
return _chunked_evict_at(device.type, index)
+# (BLOCK_SIZE, num_warps, max vocab) for the chunked forward, measured faster on T4 / A100.
+# A100 at Gemma 262144 was mixed across torch versions, so larger vocabs keep the default.
+_CHUNKED_FORWARD_CONFIGS = {
+ (7, 5): (16384, 8, None),
+ (8, 0): (16384, 8, 163840),
+}
+
+
[email protected]_cache(maxsize = None)
+def _chunked_forward_config_at(device_type, index, vocab_size):
+ if device_type == "cuda" and torch.version.hip is None:
+ capability = tuple(torch.cuda.get_device_capability(index))
+ config = _CHUNKED_FORWARD_CONFIGS.get(capability)
+ if config is not None and (config[2] is None or vocab_size <= config[2]):
+ return config[0], config[1]
+ return MAX_FUSED_SIZE, (16 if is_cdna() else 32)
+
+
+def _chunked_forward_config(device, vocab_size):
+ index = device.index
+ if index is None and device.type == "cuda":
+ index = torch.cuda.current_device()
+ return _chunked_forward_config_at(device.type, index, vocab_size)
+
+
def _chunked_cross_entropy_forward(
logits_ptr,
logits_row_stride: tl.constexpr,
@@ -357,6 +382,9 @@ class Fast_CrossEntropyLoss(torch.autograd.Function):
)
else:
# For large vocabs > 65336 like Gemma 256K
+ BLOCK_SIZE, num_warps = _chunked_forward_config(device, vocab_size)
+ div, mod = divmod(vocab_size, BLOCK_SIZE)
+ n_chunks = div + (mod != 0)
logsumexp = torch.empty(
(
n_rows,
@@ -380,13 +408,13 @@ class Fast_CrossEntropyLoss(torch.autograd.Function):
labels,
VOCAB_SIZE = vocab_size,
N_CHUNKS = n_chunks,
- BLOCK_SIZE = MAX_FUSED_SIZE,
+ BLOCK_SIZE = BLOCK_SIZE,
DO_SOFTCAPPING = DO_SOFTCAPPING,
SOFTCAP = logit_softcapping,
DO_LOGIT_SCALING = DO_LOGIT_SCALING,
LOGIT_SCALE = logit_scaling,
EVICT = _chunked_evict_policy(device),
- num_warps = 32 if not is_cdna() else 16,
+ num_warps = num_warps,
enable_fp_fusion = True,
)
# logsumexp(chunked_logsumexp) - x, with the -x done separately.