libsdca is an accurate and fast implementation of classification losses: cross-entropy, multiclass and multilabel SVM hinges, top-k losses and knowledge distillation. The losses are available as PyTorch modules and JAX functions on CPU and CUDA, and as NumPy, Rust, C++ and C functions. A stochastic dual coordinate ascent (SDCA) solver trains linear and kernel classifiers with the multiclass and multilabel training objectives.
- Accurate: Losses and gradients are checked against high-precision references
(technical report), and the remaining
limits are documented (known limits).
- For confident predictions, the cross-entropy kernels avoid softmax collapse [6] and can retain losses and gradient entries down to the subnormal range of the output dtype.
- Distillation gradients are exactly zero at equal student and teacher logits [5].
- Fast: Fused CPU and CUDA kernels implement the losses. In our benchmarks they match
or outperform
torch.compileandjax.jitin most comparisons (technical report). - Multiclass, top-k and multilabel losses: In addition to cross-entropy, the library implements the multiclass hinge (Crammer–Singer SVM [1]), the top-k hinge and the top-k cross-entropy [3, 4], the multilabel hinge [2] and cross-entropy, and logit distillation. Each hinge has a nonsmooth and a smoothed form, and cross-entropy and distillation have proximal variants (loss definitions).
- PyTorch, JAX and native interfaces: PyTorch modules and functions (with
torch.compilesupport), JAX functions forjit,gradandvmap, NumPy, a scikit-learn estimator, Rust, header-only C++ and C share the loss definitions, and each keeps the calling conventions of its language (documentation). - SDCA solver with a duality-gap guarantee: SDCA trains linear and kernel classifiers
(multiclass, top-k and multilabel SVMs, softmax regression). When
status == "solved", the duality gap bounds the suboptimality of the returned model (solver results).
Create a fresh environment with uv and install libsdca with
PyTorch support:
uv venv --seed --managed-python --python 3.12 .venv
source .venv/bin/activate
pip install 'libsdca[torch]'Try a confident two-class prediction on CPU. Class 0 leads by 20. Its cross-entropy
gradient is approximately −2.061 × 10⁻⁹, small enough that subtracting 1 from its
rounded float32 probability gives zero.
import torch
from libsdca.torch import CrossEntropyLoss
target = torch.tensor([0])
losses = {"PyTorch": torch.nn.CrossEntropyLoss(), "libsdca": CrossEntropyLoss()}
for name, loss in losses.items():
logits = torch.tensor([[0., -20.]], dtype=torch.float32, requires_grad=True)
loss(logits, target).backward()
print(f"{name}: {logits.grad[0, 0].item():.4g}")Expected gradients of the label on CPU in float32:
PyTorch: 0 # lost: the float32 probability rounds to 1, so p - 1 = 0
libsdca: -2.061e-09 # correct
Explore the margin in Google Colab or run the example as a script.
Each notebook runs on a Colab CPU. Together they use every loss of libsdca.torch
(details):
| Notebook | Shows |
|---|---|
| The gradient of a confident prediction | Where the standard cross-entropy gradient rounds to zero |
| Six losses on MNIST | Cross-entropy, top-k cross-entropy, the multiclass and top-k hinges and proximal cross-entropy |
| Multilabel classification | The multilabel cross-entropy and hinge on a tagging dataset, and the SDCA solver |
| Distillation on MNIST | Distillation and proximal distillation from a teacher's logits |
| A language-model head without the logits | linear_cross_entropy on next-word prediction |
| Distillation at equality | The gradient of a student that already equals its teacher |
Loss scaling in float16 |
Which small gradients loss scaling recovers |
| Grokking on addition modulo 31 | Accuracy and margin of cross-entropy and the smoothed hinge on modular addition |
Every interface installs with one command or CMake target, and its guide documents all options:
| Interface | Install | Guide |
|---|---|---|
| Python (NumPy) | pip install libsdca |
docs/PYTHON.md |
| scikit-learn estimator | pip install 'libsdca[sklearn]' |
docs/PYTHON.md |
| PyTorch losses | pip install 'libsdca[torch]' |
docs/TORCH.md |
| JAX losses (CPU) | pip install 'libsdca[jax]' |
docs/JAX.md |
| JAX losses (Linux NVIDIA GPU) | pip install 'libsdca[jax-cuda]' |
docs/JAX.md |
| Rust | cargo add libsdca |
docs/RUST.md |
| C++ (header-only) | CMake target libsdca::libsdca |
docs/CPP.md |
| C | CMake target libsdca::sdca_c (-DSDCA_BUILD_C_API=ON) |
docs/C.md |
conda environment
conda create --yes --override-channels --channel conda-forge --prefix .venv python=3.12 pip
conda activate ./.venv
pip install 'libsdca[torch]'C++ and C from source
git clone https://github.com/mlapin/libsdca && cd libsdca
cmake -S . -B build -DCMAKE_INSTALL_PREFIX=/usr/local # add -DSDCA_BUILD_C_API=ON for C
cmake --build build --target installCMake and BLAS options are in DEPENDENCIES.md.
Wheels, GPU and compiler requirements
- Wheels: Prebuilt for Linux
x86_64(manylinux_2_28, OpenBLAS from thescipy-openblas32package, whichpipinstalls with it) and macOS 11+arm64(Accelerate); other platforms build from the sdist with a C++11 compiler and link a system CBLAS when one is found (BLAS). The build usesCCandCXXwhen set, else the compiler of the Python installation, elsec++,g++orclang++onPATH. - GPU: CUDA needs Linux, an NVIDIA GPU and a compatible driver. The PyTorch training examples
use CUDA when available;
jax-cudainstalls the CUDA 13 runtime (Python 3.11+, driver 580+) and Triton. The fused kernels launch through jax-triton 0.5 on Python 3.12+, or a C++17 XLA FFI handler built on first use. NumPy, scikit-learn, Rust, C and C++ run on CPU. - Compilers: PyTorch and JAX compile their CPU kernels on first use, which needs a C++17
compiler and, for PyTorch, Python headers (
build-essential python3-devon Debian/Ubuntu,xcode-select --installon macOS); without them PyTorch and JAX CPU calls run the same kernels in the prebuilt native library and PyTorch CUDA calls launch them through Python, with a one-time warning (build tools). uv-managed and conda Pythons include headers.
Each example uses cross-entropy and the top-2 hinge (top-2 SVM) loss with the default options. The documentation covers every parameter and option.
Use the loss modules with autograd on CPU or CUDA:
import torch
from libsdca.torch import CrossEntropyLoss, TopKHingeLoss
device = "cuda" if torch.cuda.is_available() else "cpu"
logits = torch.randn(32, 5, device=device, requires_grad=True)
targets = torch.randint(5, (32,), device=device)
ce = CrossEntropyLoss()(logits, targets) # same arguments as torch.nn.CrossEntropyLoss()
hinge = TopKHingeLoss(k=2)(logits, targets) # top-2 SVM loss
(ce + hinge).backward()The losses are plain functions that compose with jax.grad, jit and vmap:
import jax
import jax.numpy as jnp
from libsdca.jax import cross_entropy, topk_hinge_loss
logits = jnp.array([[1.0, 2.0, 0.5], [0.0, 1.0, 3.0]])
targets = jnp.array([0, 2])
value, gradient = jax.value_and_grad(cross_entropy)(logits, targets)
value, gradient = jax.value_and_grad(topk_hinge_loss)(logits, targets, k=2)fit trains a linear classifier with the SDCA solver and returns the model with its
convergence status:
import numpy as np
import libsdca
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 10))
y = (X @ rng.normal(size=(10, 3))).argmax(axis=1)
model = libsdca.fit(X, y) # cross-entropy (softmax regression)
print(model.status, model.score(X, y))
model = libsdca.fit(X, y, libsdca.TopKHinge(k=2)) # top-2 SVM
print(model.status, model.score(X, y))SDCAClassifier wraps the solver as a scikit-learn estimator:
import numpy as np
from libsdca.sklearn import SDCAClassifier
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 10))
y = (X @ rng.normal(size=(10, 3))).argmax(axis=1)
clf = SDCAClassifier().fit(X, y) # cross-entropy
print(clf.status_, clf.score(X, y))
clf = SDCAClassifier("topk_hinge", k=2).fit(X, y) # top-2 SVM
print(clf.status_, clf.score(X, y))The Rust, C++ and C guides start with the same two losses. More examples are in examples/ and rust/examples.
libsdca.torch.check_cross_entropy_gradient compares the gradient of your cross-entropy
loss on a batch of your logits with an accurate reference. It counts the entries that the
loss rounds to zero. check_loss checks properties that the gradient of any loss must have,
including a loss that you wrote by hand or compiled:
from libsdca.torch import check_cross_entropy_gradient, check_loss
report = check_cross_entropy_gradient(logits, labels, criterion) # your logits and loss
print(report) # lost entries by margin, errors in ulps
check_loss(my_loss, strict=True) # AssertionError listing the failuresGradient checks explains both functions and how to read
their reports, and examples/python/gradient_checks/
uses them in a training loop. The script
examples/python/accuracy_inputs.py prints more
inputs where a standard formula loses the value, in PyTorch and JAX.
The index of all pages is in docs/.
- Interface guides: PyTorch, JAX, Python, Rust, C++, C
- Shared reference: loss definitions, solver options and results, precision, masked classes and known limits
- Benchmarks and numerical validation (summary; the technical report has the details)
- Dependencies, contributing, guide for AI coding assistants and changelog
- Project page
If libsdca is useful in your research, please cite the TPAMI paper; the NeurIPS paper
introduces the top-k SVM, and the technical report describes the library:
@article{lapin2018analysis,
title = {Analysis and Optimization of Loss Functions for Multiclass, Top-k, and Multilabel Classification},
author = {Lapin, Maksim and Hein, Matthias and Schiele, Bernt},
journal = {IEEE Transactions on Pattern Analysis and Machine Intelligence (TPAMI)},
volume = {40},
number = {7},
pages = {1533--1554},
year = {2018}
}
@inproceedings{lapin2015topk,
title = {Top-k Multiclass {SVM}},
author = {Lapin, Maksim and Hein, Matthias and Schiele, Bernt},
booktitle = {Advances in Neural Information Processing Systems (NeurIPS)},
year = {2015}
}
@misc{lapin2026libsdca,
title = {libsdca: Accurate and Fast Classification Losses for {SDCA} and Neural Networks},
author = {Lapin, Maksim},
year = {2026},
howpublished = {Technical report, \url{https://mlapin.github.io/libsdca/report/}}
}GitHub's Cite this repository button uses CITATION.cff.
The numbered citations above refer to:
- K. Crammer and Y. Singer. On the algorithmic implementation of multiclass kernel-based vector machines. JMLR, 2001.
- K. Crammer and Y. Singer. A family of additive online algorithms for category ranking. JMLR, 2003.
- M. Lapin, M. Hein and B. Schiele. Top-k multiclass SVM. NeurIPS, 2015.
- M. Lapin, M. Hein and B. Schiele. Loss functions for top-k error: analysis and insights. CVPR, 2016.
- J. T. Barron, D. Gnanapragasam and M. Tschannen. A fix for softmax and cross-entropy. arXiv:2610.31642, 2026.
- L. Prieto, M. Barsbey, P. A. M. Mediano and T. Birdal. Grokking at the edge of numerical stability. ICLR, 2025.
libsdca was implemented with the help of AI coding agents. The losses and gradients are
checked against high-precision references
(technical report), and
CONTRIBUTING.md describes the tests.
libsdca is released under the MIT License.