Kernel gallery¶
Parakeet compiles ordinary NumPy code, plain Python loops, and explicit
data-parallel operators (par.map, par.allpairs, par.fold, par.imap,
par.ireduce, par.scatter_add) through the same @par.jit decorator and
the same algebraic IR.
How this page is organized: the examples progress from straightforward pairwise NumPy fusion and histograms to custom semiring reductions, parallel recurrences, and modern attention and loss kernels — introducing Parakeet's capabilities one layer at a time. Where a section has tabs, those tabs show alternative ways to write the exact same computation (idiomatic NumPy vs. plain loops vs. explicit Parakeet operators) that all compile to the same fused, tiled schedule.
For a complete end-to-end training walkthrough, see nanoGPT. For genomics, cheminformatics, and 3D protein kernels, see Bioinformatics & structural biology. For the underlying identities behind these rewrites, see Algebraic laws.
Every snippet below is included directly from
examples/algebraic_gallery.py
and verified by python -m examples.algebraic_gallery.
1. Pairwise fusion and automatic tiling¶
Exact nearest neighbor¶
Exact nearest-neighbor search finds, for each of Q query vectors in
$\mathbb{R}^D$, the index of the closest vector among R reference vectors
under Euclidean distance. Writing this with broadcasting NumPy is two lines,
but executing it eagerly allocates a full Q × R distance matrix — 64 MiB
at Q = 1,024, R = 16,384 — that thrashes cache and GPU memory.
Parakeet fuses the distance calculation directly into an ordered tiled
reduction across R, keeping only a small score tile in L1 cache or GPU shared
memory (16 KiB per block) and preserving NumPy's exact first-index rule on
equal-distance ties and NaNs.
For each query row, map the squared distance over all reference rows and
take np.argmin. The outer par.map runs that search in parallel across
queries.
def squared_distance(query, reference):
return np.sum((query - reference) ** np.float32(2))
@par.jit
def exact_1nn(x_query, x_ref):
"""Exact nearest-neighbor index per query row."""
return par.map(
lambda query: np.argmin(par.map(lambda reference: squared_distance(query, reference), x_ref)),
x_query,
)
Define the logical Q × R domain with par.allpairs, pack each
(distance, index) pair into a NamedTuple, and reduce with an explicit
associative merge rule (first_minimum).
def squared_distance(query, reference):
return np.sum((query - reference) ** np.float32(2))
class Winner(NamedTuple):
distance: np.float32
index: np.int64
def first_minimum(left, right):
# Keep the first NaN. Among finite values, replace only on strict improvement.
right_wins = np.isnan(right.distance) or right.distance < left.distance
return right if right_wins and not np.isnan(left.distance) else left
@par.jit
def nearest_fold(queries, references):
scores = par.allpairs(squared_distance, queries, references)
return par.fold(Winner, first_minimum, scores, axis=1, indexed=True, emit=lambda winner: winner.index)
All three spellings compile to the same tiled pairwise schedule on CPU, Metal,
and CUDA without allocating the Q × R distance matrix.
Compare timings, scaling, and scratch memory.
Inverse-distance smoothing¶
Swap the fold state from (min_distance, index) to (weight_sum, weighted_sum)
and the same squared distances predict a smoothed scalar observation at each
query with weight $w_{ij} = 1 / (1 + |q_i - r_j|^2)$. Parakeet computes each
distance once, sums both fields inside each tile, and divides the totals after
the final merge.
@par.jit
def smooth_numpy(queries, references, observations):
observations = observations.reshape(references.shape[0])
delta = queries[:, None, :] - references[None, :, :]
weights = 1 / (1 + np.sum(delta ** np.float32(2), axis=2))
return np.sum(weights * observations, axis=1) / np.sum(weights, axis=1)
def squared_distance(query, reference):
return np.sum((query - reference) ** np.float32(2))
class WeightedSum(NamedTuple):
weight: np.float32
weighted_value: np.float32
def add_sums(left, right):
return WeightedSum(left.weight + right.weight, left.weighted_value + right.weighted_value)
@par.jit
def smooth_fold(queries, references, observations):
values = observations.reshape(references.shape[0])
scores = par.allpairs(squared_distance, queries, references)
def contribution(distance_squared, ref_index):
weight = 1 / (1 + distance_squared)
return WeightedSum(weight, weight * values[ref_index])
def weighted_mean(total):
return total.weighted_value / total.weight
return par.fold(contribution, add_sums, scores, axis=1, indexed=True, emit=weighted_mean)
Gaussian kernel regression¶
Nadaraya-Watson kernel regression predicts each query's target vector by
weighting reference observations with a Gaussian kernel
$\exp(-\gamma |q_i - x_j|^2)$. Because the running maximum, weight sum, and
weighted output form an associative
rescaled monoid, Parakeet streams
references in tiles instead of allocating an N × M weight matrix — the exact
same online monoidal pass that powers tiled attention below.
@par.jit
def rbf_kernel_regression(x_query, x_train, y_train, neg_gamma):
d2 = np.sum((x_query[:, None, :] - x_train[None, :, :]) ** np.float32(2.0), axis=-1)
s = d2 * neg_gamma
e = np.exp(s - np.max(s, axis=-1, keepdims=True))
return (e / np.sum(e, axis=-1, keepdims=True)) @ y_train
2. Histograms and scatter-add fusion¶
Histograms and tree splits¶
Histogram-based gradient boosted trees accumulate gradients and Hessians into
feature bins, scan cumulative left/right sums, and pick the split bin with the
highest gain. You can write the bin accumulations as a declarative NumPy
comprehension, with np.add.at, as a plain Python for loop, or with explicit
par.scatter_add (including keyed generator expressions) — all four lower to
Parakeet's $O(N)$ IndexScatter operator. Because both accumulations share the
same bin_ids array, Parakeet fuses them into a single
thread-privatized traversal
over the observations.
A pull-style comprehension [np.sum(grads[bin_ids == b]) for b in range(nbins)]
(or [sum(grads[i] for i in range(len(bin_ids)) if bin_ids[i] == b) for b in range(nbins)])
would cost $O(\text{nbins} \cdot N)$ naively. Parakeet inverts it
automatically to an $O(N)$ IndexScatter and fuses both histograms into
one pass.
@par.jit
def gbdt_best_split_comprehension(bin_ids, grads, hess, nbins, reg_lambda):
"""Declarative pull-style comprehension inverted to one fused O(N) scatter."""
g_hist = np.array([np.sum(grads[bin_ids == b]) for b in range(nbins)])
h_hist = np.array([np.sum(hess[bin_ids == b]) for b in range(nbins)])
g_left = np.cumsum(g_hist)
h_left = np.cumsum(h_hist)
g_right = g_left[nbins - 1] - g_left
h_right = h_left[nbins - 1] - h_left
gain = (g_left * g_left) / (h_left + reg_lambda) + (g_right * g_right) / (h_right + reg_lambda)
best_bin = np.argmax(gain)
return best_bin, gain[best_bin]
@par.jit
def gbdt_best_split_numpy(bin_ids, grads, hess, nbins, reg_lambda):
"""Return the split bin with the highest gain and the gain at that bin."""
g_hist = np.zeros(nbins, dtype=np.float32)
h_hist = np.zeros(nbins, dtype=np.float32)
np.add.at(g_hist, bin_ids, grads)
np.add.at(h_hist, bin_ids, hess)
g_left = np.cumsum(g_hist)
h_left = np.cumsum(h_hist)
g_right = g_left[nbins - 1] - g_left
h_right = h_left[nbins - 1] - h_left
gain = (g_left * g_left) / (h_left + reg_lambda) + (g_right * g_right) / (h_right + reg_lambda)
best_bin = np.argmax(gain)
return best_bin, gain[best_bin]
When an indexed += loop writes only into fresh buffers that are never
read inside the loop, Parakeet proves independence, lifts each update to
IndexScatter, and fuses sibling histograms sharing b = bin_ids[i] into
one parallel traversal automatically.
@par.jit
def gbdt_best_split_loop(bin_ids, grads, hess, nbins, reg_lambda):
"""Same histogram split written with a plain Python accumulation loop."""
g_hist = np.zeros(nbins, dtype=np.float32)
h_hist = np.zeros(nbins, dtype=np.float32)
for i in range(len(bin_ids)):
b = bin_ids[i]
g_hist[b] += grads[i]
h_hist[b] += hess[i]
g_left = np.cumsum(g_hist)
h_left = np.cumsum(h_hist)
g_right = g_left[nbins - 1] - g_left
h_right = h_left[nbins - 1] - h_left
gain = (g_left * g_left) / (h_left + reg_lambda) + (g_right * g_right) / (h_right + reg_lambda)
best_bin = np.argmax(gain)
return best_bin, gain[best_bin]
@par.jit
def gbdt_best_split(bin_ids, grads, hess, nbins, reg_lambda):
"""Return the split bin with the highest gain and the gain at that bin."""
g_hist = par.scatter_add(nbins, bin_ids, grads)
h_hist = par.scatter_add(nbins, bin_ids, hess)
g_left = np.cumsum(g_hist)
h_left = np.cumsum(h_hist)
g_tot = g_left[nbins - 1]
h_tot = h_left[nbins - 1]
g_right = g_tot - g_left
h_right = h_tot - h_left
gain = (g_left * g_left) / (h_left + reg_lambda) + (g_right * g_right) / (h_right + reg_lambda)
best_bin = np.argmax(gain)
return best_bin, gain[best_bin]
3. Custom semirings with index operators¶
Min-plus matrix product¶
In shortest-path and tropical algebra, matrix multiplication replaces (*, +)
with (+, min): $C_{ij} = \min_r (A_{ir} + B_{rj})$. Writing the index space
explicitly with par.imap and par.ireduce(..., combine=np.minimum) avoids an
m × n × k broadcast tensor and triggers the same cache and register tiling as
standard matrix multiplication.
@par.jit
def tropical_min_plus(a, b):
"""One min-plus matrix product: C[i, j] = min_r (A[i, r] + B[r, j])."""
m, k = a.shape
_, n = b.shape
return par.imap(
lambda i, j: par.ireduce(lambda r: a[i, r] + b[r, j], k, combine=np.minimum),
(m, n),
)
4. Sequential recurrences to parallel scans¶
Exponential IIR filter¶
A plain Python for t in range(T): affine recurrence s = a[t] * s + b[t]
has O(T) serial depth. Because affine maps compose associatively, Parakeet's
chunkwise scan pass rewrites
the loop into a parallel prefix scan (TileScan) across CPU cores or GPU
threadblocks with no O(T) scratch arrays.
@par.jit
def iir_exponential_filter(a, b):
T = a.shape[0]
out = np.empty_like(b)
s = np.float32(0.0)
for t in range(T):
s = a[t] * s + b[t]
out[t] = s
return out
Mamba-2 state-space recurrence¶
The same chunkwise state-space duality generalizes to bilinear matrix-state
recurrences: a 6-line Python loop over time rewrites into division-free
chunkwise batched GEMMs that automatically lower to CPU register tiling, Metal
simdgroup_matrix, and CUDA TF32 WMMA.
@par.jit
def mamba2_ssd(q, k, v, a):
T = q.shape[0]
out = np.empty((T, v.shape[1]), dtype=np.float32)
S = np.zeros((k.shape[1], v.shape[1]), dtype=np.float32)
for t in range(T):
S = a[t] * S + k[t][:, None] * v[t][None, :]
out[t] = q[t] @ S
return out
5. Attention and large-vocabulary losses¶
Causal attention¶
Write scaled dot-product attention with a causal mask in six lines of NumPy. Three general passes compose automatically:
- Online monoidal tiling fuses the softmax-weighted contraction into a
single streaming pass with no
T × Tscore matrix (details). - Tile-interval mask pruning proves upper-triangular tiles are completely masked and skips loading their keys and values (details).
- Rematerialized differentiation recomputes score tiles on the fly during
par.grad,par.jvp, andpar.hvpinstead of storingT × Ttensors (details).
@par.jit
def causal_flash_attention(q, k, v):
T = q.shape[-2]
idx = np.arange(T)
mask = idx[:, None] >= idx[None, :]
scale = np.float32(1.0 / np.sqrt(np.float32(q.shape[-1])))
s = np.where(mask, np.matmul(q, np.swapaxes(k, -1, -2)) * scale, np.float32(-1e9))
e = np.exp(s - np.max(s, axis=-1, keepdims=True))
return np.matmul(e / np.sum(e, axis=-1, keepdims=True), v)
For a sliding window, intersect the mask with (idx[:, None] - idx[None, :]) <= window;
interval analysis skips tiles outside the window automatically.
Linear cross-entropy¶
Computing cross-entropy over a large vocabulary V from hidden states
h @ w normally materializes an M × V logit matrix. Online monoidal tiling
chunks the contraction and logsumexp over the vocabulary while gathering the
target logit on the fly, and algebraic rematerialization differentiates the
loss with zero M × V memory.
def cut_cross_entropy(h, w, targets):
logits = h @ w
m = np.max(logits, axis=-1, keepdims=True)
z = logits - m
lse = np.log(np.sum(np.exp(z), axis=-1))
picked = z[np.arange(h.shape[0]), targets]
return -np.mean(picked - lse)
Multi-head latent attention¶
Multi-head latent attention (MLA) projects keys and values from a shared
low-rank latent c_kv. When the query length is small (such as autoregressive
decoding), bilinear contraction reassociation
absorbs w_uk into q and defers w_uv until after attention — running
tiled attention directly over the compressed latent c_kv.
@par.jit
def deepseek_mla(q, c_kv, w_uk, w_uv):
k = c_kv @ w_uk
v = c_kv @ w_uv
scale = np.float32(1.0 / np.sqrt(np.float32(q.shape[-1])))
s = (q @ k.T) * scale
e = np.exp(s - np.max(s, axis=-1, keepdims=True))
return (e / np.sum(e, axis=-1, keepdims=True)) @ v
Grouped-query attention¶
When a head-group axis G in q broadcasts against a single shared KV head
(1 in k and v), shared-KV head-group tiling folds G into the query tile
so all G query heads reuse one shared-memory load of k and v.
@par.jit
def gqa_attention(q, k, v):
# q: (B, H_kv, G, T_q, D), k, v: (B, H_kv, 1, T_kv, D)
scale = np.float32(1.0 / np.sqrt(np.float32(q.shape[-1])))
s = np.matmul(q, np.swapaxes(k, -1, -2)) * scale
e = np.exp(s - np.max(s, axis=-1, keepdims=True))
return np.matmul(e / np.sum(e, axis=-1, keepdims=True), v)
6. End-to-end training and inspecting rewrites¶
nanoGPT end-to-end training¶
Train a two-layer character-level transformer from scratch in pure NumPy +
Parakeet. The complete nanoGPT walkthrough follows the
entire runnable script in order, using par.map and par.value_and_grad to
compile the forward pass, backward pass, and Adam optimizer into one native
step.
Inspecting algebraic rewrites¶
Call par.show_rewrite(fn, *example_args) on any compiled or plain Python
function to inspect which compiler optimizations fired and compare the operator
IR before and after optimization: