Metadata-Version: 2.4
Name: xgemm
Version: 0.1.0
Summary: Fused NVIDIA GPU kernel primitives for JAX: exponential GEMM and Gaussian RBF products
Author: SparseTrace AI
License-Expression: MIT
Project-URL: Homepage, https://sparsetrace.ai
Project-URL: Repository, https://github.com/sparsetrace/xgemm
Keywords: jax,gpu,cuda,xgemm,exp-gemm,rbf,kernels
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: POSIX :: Linux
Classifier: Topic :: Scientific/Engineering :: Mathematics
Requires-Python: <3.14,>=3.11
Description-Content-Type: text/markdown
Requires-Dist: numpy<3,>=1.26
Requires-Dist: jax[cuda12]<0.11,>=0.9
Provides-Extra: test
Requires-Dist: pytest<10,>=8; extra == "test"
Provides-Extra: release
Requires-Dist: build>=1.2; extra == "release"
Requires-Dist: twine>=5; extra == "release"
Requires-Dist: auditwheel>=6; extra == "release"


# XGEMM: Fused Implicit Gaussian Kernel Operations

**XGEMM** provides matrix-free exponential dot-product and Gaussian RBF kernel products for JAX, with fused distance moments, analytical bandwidth derivatives, and radix-2 weighted-delay products (*Fung's trick*). Kernel entries are evaluated on demand; the full pairwise kernel matrix is never stored. Developed by [SparseTrace AI](https://sparsetrace.ai).

## Install

```bash
pip install xgemm
```

Requires **Linux x86-64**, **Python 3.11–3.13**, and an NVIDIA driver compatible with CUDA-enabled JAX (installed as a dependency). Precompiled native FP32 CUDA kernels target **A100 (SM80)** and **RTX PRO 6000 Blackwell (SM120)**. H100/H200 (SM90) and B200 (SM100) use a deliberately selected tiled JAX GPU implementation for the standard operators; Fung's trick currently requires SM80 or SM120. No automatic CPU fallback.

## Kernel primitives

All products are implicit: for a kernel $A$, XGEMM evaluates $(Av)_i=\sum_j A_{ij}v_j$ or $(AV)_{ib}=\sum_j A_{ij}V_{jb}$ without constructing $A$.

| Primitives | Kernel or result |
|---|---|
| `matvec`, `matmat` | Exponential dot-product, $A_{ij}=\exp(q_i^\top k_j)$ |
| `matvec_tilt`, `matmat_tilt` | Additive potentials, $A_{ij}=\exp(q_i^\top k_j+u_i+w_j)$ |
| `matvec_rbf_from_x`, `matmat_rbf_from_x` | Gaussian RBF from coordinates, $K_{ij}=\exp(-\beta\lVert x_i-y_j\rVert^2)$ |
| `matvec_rbf`, `matmat_rbf` | Same RBF product with preprocessed features and squared norms |
| `rbf_moments` | Fused distance moments $M_p(i)=\sum_j K_{ij}\lVert x_i-x_j\rVert^{2p}v_j$, $p=0,\ldots,3$ |
| `matvec_grad_hess` | RBF matvec, first derivative, and second derivative with respect to $\beta$ or $\log\beta$ |
| `fung_matvec`, `fung_matmat` | Radix-2 weighted delay-coordinate Gaussian products |
| `prepare_rbf_query`, `prepare_rbf_key` | Helpers for reusable RBF inputs |
| `backend_info` | Device and backend diagnostics |

### Bandwidth derivatives

Let $d_{ij}^2=\lVert x_i-x_j\rVert^2$, $K_{ij}=e^{-\beta d_{ij}^2}$, and $M_p(i)=\sum_j K_{ij}(d_{ij}^2)^p v_j$. The `matvec_grad_hess` result is `(value, gradient, hessian)`:

$$
\begin{aligned}
Kv&=M_0,\\
\frac{\partial(Kv)}{\partial\beta}&=-M_1,
&\frac{\partial^2(Kv)}{\partial\beta^2}&=M_2,\\
\frac{\partial(Kv)}{\partial\log\beta}&=-\beta M_1,
&\frac{\partial^2(Kv)}{\partial(\log\beta)^2}&=\beta^2M_2-\beta M_1.
\end{aligned}
$$

Use `wrt="log_beta"` (default) or `wrt="beta"`. `rbf_moments(..., order=p)` returns columns $M_0,\ldots,M_p$, with $0\le p\le3$.

### Fung's trick: weighted delay kernels

For a time series $X\in\mathbb{R}^{N\times D}$, a power-of-two window $L=2^m$, and $K=N-L+1$ delay vectors, Fung's trick computes

$$
A_{ij}=\exp\!\left[-\beta\sum_{a=0}^{L-1}w_a\lVert X_{i+a}-X_{j+a}\rVert^2\right],
\quad 0\le i,j<K.
$$

The lag weights are specified **implicitly** by $m$ radix-2 stages:

$$
H(z)=\prod_{r=0}^{m-1}(h_{0,r}+h_{1,r}z^{-2^r}),
\qquad w_a=[z^{-(L-1-a)}]H(z).
$$

The CUDA kernel streams along diagonals, preserving $O(L)$ filter state **per active diagonal** in shared memory. For $K\gg L$, its work is $O(K^2(D+\log L))$, versus $O(K^2LD)$ for naive delay-vector distances. It never stores the $K\times K$ kernel; input `X[N,D]` must currently be resident on the GPU (not an out-of-core streaming API). Native support: **SM80/SM120, FP32, $1\le D\le32$, $2\le L\le1024$**, nonnegative stage factors with positive sums, and FP64 output-accumulation scratch.

## Quick start

```python
import jax.numpy as jnp
from xgemm import (
    matvec, matmat, matvec_tilt,
    matvec_rbf_from_x, matmat_rbf_from_x,
    matvec_rbf, prepare_rbf_query, prepare_rbf_key,
    matvec_grad_hess, rbf_moments,
    fung_matvec, fung_matmat, backend_info,
)

X = jnp.array([[0., 0.], [.5, .2], [.2, .8]], dtype=jnp.float32)
v = jnp.ones(3, dtype=jnp.float32)
V = jnp.ones((3, 4), dtype=jnp.float32)
beta = 0.8

# Exponential dot product and additive one-body potentials.
y_exp = matvec(X, X, v)
Y_exp = matmat(X, X, V)
y_tilt = matvec_tilt(X, X, v, q_query=jnp.zeros(3), q_key=jnp.zeros(3))

# RBF products; the from_x helpers center coordinates to reduce cancellation.
y_rbf = matvec_rbf_from_x(X, X, v, beta=beta)
Y_rbf = matmat_rbf_from_x(X, X, V, beta=beta)

# Reusable, preprocessed RBF inputs (center X first if necessary).
Qq, norm_q = prepare_rbf_query(X, beta)
Qk, norm_k = prepare_rbf_key(X)
y_prepared = matvec_rbf(Qq, Qk, v, norm_q, norm_k, beta=beta)

# Fused Gaussian moments and analytical bandwidth derivatives.
M = rbf_moments(X, v, beta=beta, order=3)  # [N, 4]
jet = matvec_grad_hess(X, v, beta=beta, wrt="log_beta")
y, dy, d2y = jet.value, jet.gradient, jet.hessian

# Fung's trick: radix-2 window L=4, hence K=12-4+1=9.
X_series = jnp.arange(24, dtype=jnp.float32).reshape(12, 2) * 0.1
h0 = jnp.array([0.5, 0.5], dtype=jnp.float32)
h1 = jnp.array([0.5, 0.5], dtype=jnp.float32)
y_delay = fung_matvec(X_series, jnp.ones(9), h0, h1, beta=beta)
Y_delay = fung_matmat(X_series, jnp.ones((9, 3)), h0, h1, beta=beta)

print(backend_info())
```

## Backend options and limits

- **`backend="auto"`** (default): native CUDA on SM80/SM120; tiled GPU JAX for standard operators on SM90/SM100. Other devices raise an error. Fung's trick requires native SM80/SM120.
- **`backend="jax"`**: explicit portable JAX reference (including CPU); never selected automatically. **`backend="jax_gpu"`**: explicitly require tiled JAX on GPU for supported standard operators.
- **`tile=128`**: JAX tile size for standard products and moments; native kernels manage their own tiling. Fung's trick does not take a `tile` argument.
- **`beta`**: native RBF and Fung kernels require a static Python scalar; `rbf_moments`/derivatives require $\beta>0$. **`order`**: 0–3 for moments; **`wrt`**: `"log_beta"` or `"beta"` for derivatives.
- **Precision:** native FP32 uses fast exponentials. Correctness tests use tolerances around `5e-3`, **not** universal error bounds. Common coordinate-centering reduces RBF cancellation but cannot recover precision already lost in FP32 data. Dot-product and tilted exponentials can overflow for large positive logits; scale inputs accordingly.
- **Dimensions and packaging:** native dot-product/tilt support $D\le32$; native coordinate-based RBF supports larger feature dimensions. Installation requires a compatible precompiled Linux wheel; older glibc-based clusters may need a separately built wheel.
