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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
fast_cross_entropy_loss: all-masked labels give loss 0 instead of NaN (#13325)
Daniel Han464d3693870b
diff --git a/tests/test_cross_entropy_all_masked_labels.py b/tests/test_cross_entropy_all_masked_labels.pynew file mode 100644index 00000000000..12ad3d29afb--- /dev/null+++ b/tests/test_cross_entropy_all_masked_labels.py@@ -0,0 +1,39 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++import pytest+from real_accelerator import (+ has_real_cuda,+) # tests/_shared, on sys.path via tests/conftest.py+import torch++pytestmark = pytest.mark.gpu+++# A batch whose labels are all -100 (truncation cut every response away) used to return 0 / 0 = NaN.[email protected](not has_real_cuda(), reason = "CUDA Triton kernels required")[email protected]("n_items", [None, 0, "tensor"])+def test_fast_cross_entropy_all_masked_labels(n_items):+ from unsloth.kernels.cross_entropy_loss import fast_cross_entropy_loss++ logits = torch.randn(2, 5, 256, device = "cuda", dtype = torch.bfloat16, requires_grad = True)+ labels = torch.full((2, 5), -100, device = "cuda")+ if n_items == "tensor":+ n_items = torch.tensor(0, device = "cuda")+ loss = fast_cross_entropy_loss(logits, labels, n_items = n_items)+ loss.backward()+ assert loss.item() == 0.0+ assert torch.isfinite(logits.grad).all() and not logits.grad.any()++[email protected](not has_real_cuda(), reason = "CUDA Triton kernels required")+def test_fast_cross_entropy_partly_masked_keeps_the_mean():+ from unsloth.kernels.cross_entropy_loss import fast_cross_entropy_loss++ torch.manual_seed(0)+ logits = torch.randn(1, 4, 256, device = "cuda")+ labels = torch.tensor([[3, -100, 7, -100]], device = "cuda")+ expected = torch.nn.functional.cross_entropy(logits.flatten(0, 1), labels.flatten())+ torch.testing.assert_close(+ fast_cross_entropy_loss(logits, labels), expected, rtol = 1e-5, atol = 1e-5+ )diff --git a/unsloth/kernels/cross_entropy_loss.py b/unsloth/kernels/cross_entropy_loss.pyindex 8d35ce6cf35..038109083ca 100644--- a/unsloth/kernels/cross_entropy_loss.py+++ b/unsloth/kernels/cross_entropy_loss.py@@ -451,6 +451,10 @@ def fast_cross_entropy_loss(n_items = torch.count_nonzero(labels != -100)if torch.is_tensor(n_items):n_items = n_items.to(device)+ # No labelled tokens (all -100): loss 0 and zero grads, not 0 / 0 = NaN.+ n_items = torch.where(n_items == 0, torch.ones_like(n_items), n_items)+ elif n_items == 0:+ n_items = 1return loss.sum() / n_items