Skip to main content

Triton-Optimized Cross-Entropy Kernel

A high-performance, memory-efficient cross-entropy loss implementation using Triton for CUDA GPUs. Significantly faster than PyTorch's native cross-entropy, especially for large vocabulary sizes in large language models.

Attribution:
This implementation is adapted from Unsloth's cross-entropy kernel.


Features

  • Memory Efficient: Fused kernel reduces memory footprint.
  • High Performance: Optimized for large vocabulary sizes with Triton JIT.
  • Causal LM Compatible: Handles shifted logits/labels for autoregressive language modeling.
  • Ignore Index Support: Configurable ignore index for masking tokens (default: -100).
  • CUDA Accelerated: Fully utilizes CUDA GPUs for maximum throughput.
  • Autograd Compatible: Exposes a PyTorch-compatible autograd.Function and nn.Module.

Requirements

  • PyTorch (CUDA-enabled)
  • Triton
  • CUDA-compatible GPU

Installation

Install from PyPI:

pip install crossentropy-triton

Or install with specific PyTorch/Triton versions:

pip install crossentropy-triton torch triton

Usage

Basic Usage (Autograd Function)

import torch
from crossentropy_triton import CrossEntropyFunction

device = torch.device('cuda')

# Create sample data [batch, seq, vocab_size]
logits = torch.randn(2, 10, 32000, device=device, requires_grad=True)
labels = torch.randint(0, 32000, (2, 10), device=device)

# Forward pass with ignore_index=-100 (default for masked tokens)
loss = CrossEntropyFunction.apply(logits, labels, -100)
print(f"Loss: {loss.item():.4f}")

# Backward pass
loss.backward()
print(f"Gradients computed - shape: {logits.grad.shape}")

Using the Causal LM Loss Module

import torch
from crossentropy_triton import TritonCausalLMLoss

device = torch.device('cuda')
vocab_size = 32000

# Initialize the loss function
loss_fn = TritonCausalLMLoss(vocab_size)

# Create sample data
logits = torch.randn(2, 10, vocab_size, device=device, requires_grad=True)
labels = torch.randint(0, vocab_size, (2, 10), device=device)

# Forward and backward pass
loss = loss_fn(logits, labels)
print(f"Causal LM loss: {loss.item():.4f}")

loss.backward()
print(f"Backward pass completed")

Performance Characteristics

  • Optimized Block Size: Chooses optimal kernel block sizes up to 32,768.
  • Memory Fusion: Fuses softmax and gradient computation in a single kernel.
  • Efficient Masking: Ignore index is handled directly in the kernel.
  • Gradient Scaling: Proper normalization by non-ignored tokens.

Technical Details

Kernel Implementation

  • cross_entropy_kernel: Computes the forward pass (loss) and gradients in the logits tensor.
  • element_mul_kernel: Scales in-place gradients by gradient outputs during backward.

Memory and Numerical Stability

  • Supports both contiguous and non-contiguous tensors.
  • In-place gradient computation for minimal overhead.
  • Log-sum-exp trick for stable softmax.

Shifted Sequence Handling

  • Causal/auto-regressive shifts are built in for next-token prediction.

License

MIT License

Metadata

Release files for crossentropy-triton 0.1.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for crossentropy-triton 0.1.2
File Size Uploaded Provenance
crossentropy_triton-0.1.2.tar.gz 7.4 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for crossentropy-triton 0.1.2
File Interpreter ABI Platform
crossentropy_triton-0.1.2-py3-none-any.whl Python 3 none any Details

Total release size: 13.9 kB

Release files / crossentropy_triton-0.1.2.tar.gz

Download URL crossentropy_triton-0.1.2.tar.gz
Size 7.4 kB
Tags Source
SHA-256 checksum
How to use checksums
7bbd4592b7d9b2add38906607ac54ca396b15f9f1d64d835783e8aea0000ce50
BLAKE2b-256 checksum
How to use checksums
b772e236e9eccfbddbec04e1a1f9ded7241b9f915dea955785b872876d9f75b5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.10.6

Release files / crossentropy_triton-0.1.2-py3-none-any.whl

Download URL crossentropy_triton-0.1.2-py3-none-any.whl
Size 6.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
58631daa6ad30d6d37b19afc71e40c0debe3967c87d429a4f4a9a3418dd5bccc
BLAKE2b-256 checksum
How to use checksums
5079adaaa7b32ababaa689d8056bdcade41748ae99cf35e88d4010f8214bf3ea
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.10.6

Security for crossentropy-triton 0.1.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page