Fused Warp Kernels for Apax Molecular Dynamics

This blog post has been written by Claude under weak supervision of a human who’s on vacation and doing this more as a labour of love and plans to review it more closely later on, please give them some grace.

This is a long technical record of a few sessions spent making MD with apax faster on NVIDIA GPUs, mostly by moving the hot parts of the gaussian-moment (the original basis functions were gaussians, which is why the name, but strangely enough this entire blog post relies on Bessel functions and in general, any smooth enough radial basis is probably fine) (GMNN) descriptor out of XLA and into Claude-coded NVIDIA Warp kernels that are probably being reviewed currently, and by borrowing the neighbour list from NVIDIA ALCHEMI Toolkit-Ops. It is written as a document of record: what we changed, why, how we checked it, what the profiler said, and what did not work. Everything lives on the branch warp-model-and-perf-improvements of my apax fork. A longer per-change review document, SPEEDUPS.md, sits at the root of that branch.

Edit, 2026-12-03: cost at each stage

Cost in microseconds per atom per MD step (µs/atom-step). Lower is better, and bold marks the fastest result for each system size (per GPU). A dash means we did not measure it. Repeats vary by about 1-4 %, so small steps between rows are within noise.

L40S, 6 Å model with a 128-128 readout, scrambled atom order:

stage (each row adds to the one above) 3.9k atoms 17.9k 104k
original apax (TF32 matmuls) 0.534 0.639 -
Warp moments, pull gradient, fused NLH, ALCHEMI list (through E13)* 0.185 0.155 0.239
+ Warp contractions (E15) 0.152 0.099 0.141
+ Morton sorting at each rebuild (E14) 0.148 0.087 0.125
+ cached reverse-pair map (E16) 0.140 0.081 0.123
+ whole pair array passed to Warp (E19) 0.139 0.078 0.120
+ fused pair vectors (E21) 0.132 0.074 0.098
+ thermostat inverse masses (E23) 0.128 0.074 0.098
+ refitted thread split (E24) 0.123 0.074 -
+ split backward contractions (E25) 0.120 0.073 0.097

* The 3.9k number in this row used the ordered starting structure; the other two used scrambled order.

L40S, later changes, ordered atoms (copies of the 3.9k box). Do not subtract these from the table above: the atom order is different, and E30 is already included.

stage 3.9k atoms 15.4k 30.9k 104k
6 Å, 128-128: peeled loop, no unrolling (E31) 0.115 0.073 - 0.096
6 Å, 128-128: + loop unrolled 2× (E31) 0.112 0.073 0.075 0.093
6 Å, 128-128: + L2 blocking (E32; switches itself on only at large N) 0.112 0.073 0.075 0.085
6 Å, 64-64 readout, retrained, no blocking 0.106 0.068 0.070 0.085
5 Å, smaller descriptor, 64-64 readout, retrained, no blocking 0.084 0.045 0.041 0.051
same 5 Å model + L2 blocking (automatic size) 0.084 0.045 0.041 0.049

The last three rows are different trained models, so their gains are not pure code speedups. The 5 Å model uses 16 Bessel functions, 8 radial and 4 tensor channels. Validation errors (48 structures):

model energy MAE force MAE (eV/Å)
6 Å, 128-128 0.189 0.0605
6 Å, 64-64 0.196 0.0535
5 Å, 64-64 0.196 0.0582

These say nothing yet about liquid structure or diffusion, which a shorter cutoff could affect.

Other GPUs, 6 Å 128-128 model, scrambled atom order:

GPU and stage 3.9k atoms 17.9k 104k
RTX PRO 6000: original apax 0.359 0.325 0.345
RTX PRO 6000: all-JAX path, fp32 0.350 0.288 0.307
RTX PRO 6000: Warp path (through E25) 0.105 0.054 0.052
RTX PRO 6000: + pair-centric list, loop peel, unroll (E30, E31) 0.100 0.050 0.050
H200: original apax 0.452 0.295 0.273
H200: all-JAX path, fp32 0.440 0.298 0.284
H200: Warp path (through E31) 0.130 0.084 0.071

L40S, 5 Å model, several MD runs sharing one GPU through MPS (cost over all runs together):

atoms per process 1 process 2 4
3,861 0.085 0.058 0.045
7,722 0.060 0.046 0.042
15,444 0.046 0.040 0.042

The lowest cost so far is about 0.040 µs/atom-step (two 15.4k-atom runs on one L40S, 5 Å model). One run alone reaches 0.041 at 30.9k atoms.

The rest of this post covers changes up to E25.

The short version

Steps per second for NVT MD with one model (details below), with atom indices scrambled the way they end up after a long run. Original is our starting point where a few TF32 matmuls existed, which we replace with fp32 (and call branch). And then we have a Warp path.

RTX PRO 6000 Blackwell (96 GB):

atoms original apax branch, all-JAX path branch, Warp path Warp, 2 processes on one GPU (CUDA MPS)
3,861 722 739 2,470 3,609 (total)
17,875 172 194 1,045 1,244 (total)
104,247 27.8 31.2 185 170 (total)

In microseconds per atom per step that is 0.36 / 0.33 / 0.35 for the original code, and 0.105 / 0.054 / 0.052 for a single Warp process. With two processes sharing the GPU through MPS, the 17.9k case comes out at 0.045 µs, i.e. 45 ns per atom-step of aggregate throughput.

L40S (48 GB): 485 → 2,160 steps/s at 3.9k atoms (4.5×) and 87.6 → 763 steps/s at 17.9k atoms (8.7×). A 1.14 million atom box now fits on the card (34.7 GB peak) and runs at 7.2 steps/s.

Accuracy: forces in MD stay within 0.15-0.19 meV/Å (max) and 0.021 meV/Å (rms) of a model evaluated entirely in fp64, which is the same as the plain XLA fp32 path.

Model specifics, test systems, etc.

Model. An apax GMNN student, g20_r6t5_l1e3, from the EC:EMC volume-scan experiments: 12 Bessel radial functions, r_max 6 Å, 12 radial and 5 tensor channels, a 128-128 readout, and the NLH empirical repulsion. It was trained on a LiPF6 / EC:EMC electrolyte dataset generated by distilling PET-MAD-1.6 (that experiment was motivated by the open dataset and protocol of Magdău et al., npj Comput. Mater. 2023). With a 0.5 Å neighbour-list skin, each atom has about 103 neighbours.

Systems. One validation frame (1 LiPF6 per 11 solvent molecules, 1.2 g/cm³), replicated 3×3×3 (3,861 atoms), 5×5×5 (17,875 atoms), and 3×3×3 of the 3.9k box (104,247 atoms). Hydrogen mass 4 amu, NVT at 330 K, dt 1 fs, Nose-Hoover chain.

Benchmark protocol. apax runs MD as a loop over jitted blocks of 500 steps (“chunks”). We log the wall time of each chunk, drop the first one (it includes compilation) and report the median of the rest. Spread between repeats is about ±1-4 %. Unless stated otherwise, atom indices are randomly permuted before the run; the reason for that is in the section on spatial sorting.

We try to keep energies/forces as close to the fp32 reference as possible using high precision internally as required (the atomic energies need fp64 accumulations). TF32 and so on are rejected because the goal isn’t to trade off accuracy for inference speed (although that can be an idea for the future).

Profiling specifics

We use Nsight Systems with 1,000 steady-state steps, and dump the optimized HLO so each kernel can be traced back to the line of apax that produced it. At the start of this round (after an earlier round that had already introduced Warp kernels for the moments), a 17.9k-atom step on the L40S looks like this:

total kernel time 2430.1 us/step
  225.0 us  1.0x  _kernels__locals__gm_forward
  153.8 us  1.0x  _kernels__locals__gm_backward
  109.9 us  1.0x  _reverse_kernel__locals__reverse_pairs
   78.4 us  2.0x  gemm_fusion_dot_213    f32[17875,5,9]   .../_contract/arij, asik, atjk -> arst/dot_general
   66.3 us  1.0x  loop_add_fusion_10     f32[17875,107]   .../_warp_moments/add_any
   59.4 us  1.0x  input_concatenate_fusion_14  f32[17875,35,15]  .../_contract/arijk, asijl, atkl -> arst/transpose
   ...

Grouping by region:

region (17.9k, L40S) µs/step share
moment contraction, forward 325 13 %
moment contraction, backward 793 33 %
unpacking packed moments 196 8 %
Warp moment kernels 556 23 %
readout MLP 164 7 %
everything else ~400 16 %

So more than half of the step is XLA evaluating the Gaussian-moment contractions (the step that turns per-atom moment tensors into rotation-invariant features) and their gradient.

An approximately impact-size-ordered list of code changes

Contraction kernels (contract_kernel: warp)

The GMNN descriptor contracts per-atom moment tensors b (rank 1), C (rank 2, symmetric) and D (rank 3, symmetric) over radial channels. Per atom that is about 107 input numbers and 355 output features, every one of them a small multilinear form belonging to one of seven families:

1  b0 . b1                        (ari, asi -> ars)
2  <C0, C1>                       (arij, asij -> ars)
3  sum_i <D0[i], D1[i]>           (arijk, asijk -> ars)
4  <C0, C1 C2^T>                  (arij, asik, atjk -> arst)
5  b0^T C2 b1                     (ari, asj, atij -> arst)
6  sum_i <D0[i] C2, D1[i]>        (arijk, asijl, atkl -> arst)
7  sum_i row_i(C1) . (D0[i] b2)   (arijk, asij, atk -> arst)

In base JAX, these were coded up as einsums and then using indexing to get the unique numbers from the contractions. This leads to a large amount of memory traffic since we’re writing down temporaries and doing relatively small amounts of arithmetic for it (it’s actually pretty bad in terms of arithmetic intensity, but let’s not focus on the negatives too hard…).

The feature table. The trained readout expects feature 0 in column 0, feature 1 in column 1, and so on, so the kernel has to produce all 355 features in exactly the order the original JAX code did. Rather than trusting ourselves to get that order right by hand, we build it once in Python from the same index helpers the original code uses (tril_2d_indices, tril_3d_indices). Each row of the table names one feature: its family (1-7) and the up-to-three radial channels it combines. A GPU thread just reads its row and computes that one number. If someone changes the order in the original code, the table follows automatically, and the tests compare the two outputs directly:

def feature_table(C, n_contr=8, drop_contractions=()):
    """(n_features, 4) int32 rows (family, c0, c1, c2) for contr_1..7 in `_contract` order."""
    ...
    blocks = {
        1: [(1, i, j, 0) for i, j in t2],
        2: [(2, i, j, 0) for i, j in t2],
        3: [(3, i, j, 0) for i, j in t2],
        4: [(4, i, j, k) for i, j, k in t3],
        5: [(5, i, j, t) for i, j in t2 for t in range(C)],
        6: [(6, i, j, t) for i, j in t2 for t in range(C)],
        7: [(7, r, s, t) for r in range(C) for s in range(C) for t in range(C)],
    }

The full forward kernel, with its helpers:

B1 = K           # where the rank-1 moments (b) start in an atom's packed row
B2 = K + 3 * C   # where the rank-2 moments (C, 6 unique numbers each) start
B3 = K + 9 * C   # where the rank-3 moments (D, 10 unique numbers each) start

@wp.func
def vec_b(m: wp.array2d(dtype=wp.float32), a: int, c: int):
    o = B1 + 3 * c
    return wp.vec3(m[a, o], m[a, o + 1], m[a, o + 2])

@wp.func
def mat_c(m: wp.array2d(dtype=wp.float32), a: int, c: int):
    # unique order (xx, xy, xz, yy, yz, zz)
    o = B2 + 6 * c
    xx = m[a, o]
    xy = m[a, o + 1]
    xz = m[a, o + 2]
    yy = m[a, o + 3]
    yz = m[a, o + 4]
    zz = m[a, o + 5]
    return wp.mat33(xx, xy, xz, xy, yy, yz, xz, yz, zz)

@wp.func
def mats_d(m: wp.array2d(dtype=wp.float32), a: int, c: int):
    # unique order (xxx, xxy, xxz, xyy, xyz, xzz, yyy, yyz, yzz, zzz); D[i]_jk = d_ijk
    o = B3 + 10 * c
    q0 = m[a, o]
    q1 = m[a, o + 1]
    q2 = m[a, o + 2]
    q3 = m[a, o + 3]
    q4 = m[a, o + 4]
    q5 = m[a, o + 5]
    q6 = m[a, o + 6]
    q7 = m[a, o + 7]
    q8 = m[a, o + 8]
    q9 = m[a, o + 9]
    d0 = wp.mat33(q0, q1, q2, q1, q3, q4, q2, q4, q5)
    d1 = wp.mat33(q1, q3, q4, q3, q6, q7, q4, q7, q8)
    d2 = wp.mat33(q2, q4, q5, q4, q7, q8, q5, q8, q9)
    return d0, d1, d2

@wp.func
def row(A: wp.mat33, i: int):
    return wp.vec3(A[i, 0], A[i, 1], A[i, 2])

@wp.kernel(module="unique")
def gm_contract_fwd(
    m: wp.array2d(dtype=wp.float32),      # packed moments, one row per atom
    table: wp.array2d(dtype=wp.int32),    # feature table: (family, c0, c1, c2) per feature
    feats: wp.array2d(dtype=wp.float32),  # output features, one row per atom
):
    a, f = wp.tid()
    fam = table[f, 0]
    c0 = table[f, 1]
    c1 = table[f, 2]
    c2 = table[f, 3]
    v = wp.float32(0.0)
    if fam == 1:
        v = wp.dot(vec_b(m, a, c0), vec_b(m, a, c1))
    elif fam == 2:
        v = wp.ddot(mat_c(m, a, c0), mat_c(m, a, c1))
    elif fam == 3:
        x0, x1, x2 = mats_d(m, a, c0)
        y0, y1, y2 = mats_d(m, a, c1)
        v = wp.ddot(x0, y0) + wp.ddot(x1, y1) + wp.ddot(x2, y2)
    elif fam == 4:
        v = wp.ddot(mat_c(m, a, c0), mat_c(m, a, c1) @ wp.transpose(mat_c(m, a, c2)))
    elif fam == 5:
        v = wp.dot(vec_b(m, a, c0), mat_c(m, a, c2) @ vec_b(m, a, c1))
    elif fam == 6:
        x0, x1, x2 = mats_d(m, a, c0)
        y0, y1, y2 = mats_d(m, a, c1)
        C2 = mat_c(m, a, c2)
        v = wp.ddot(x0 @ C2, y0) + wp.ddot(x1 @ C2, y1) + wp.ddot(x2 @ C2, y2)
    elif fam == 7:
        x0, x1, x2 = mats_d(m, a, c0)
        C1 = mat_c(m, a, c1)
        b2 = vec_b(m, a, c2)
        v = (
            wp.dot(row(C1, 0), x0 @ b2)
            + wp.dot(row(C1, 1), x1 @ b2)
            + wp.dot(row(C1, 2), x2 @ b2)
        )
    feats[a, f] = v

The helper functions rebuild full 3×3 matrices from the unique numbers we store. A symmetric matrix has only 6 different entries and a symmetric rank-3 tensor only 10, so the packed row stores just those. The kernel itself is one thread per (atom, feature): it reads its feature’s row of the table, rebuilds the tensors it needs and computes one number.

The backward pass (a hand-derived VJP, since every form is multilinear) took four tries, and the progression is probably the most useful part of this post:

version idea backward time at 17.9k Claude inference from profiler trace*
v1 one thread per (atom, channel), loop over all 355 features 6.9 ms lanes in a warp take different branches, only N×5 threads
v2 static work list grouped by (channel, family, slot), one thread per (chunk, atom) 5.2 ms ncu: 255 registers/thread, 12.4 GB of local-memory loads and 9.4 GB of stores per launch, 16 % occupancy
v3 one kernel per family, branches removed at code generation with wp.static 0.80 ms registers back to normal
v4 moments, cotangents and gradients stored component-major (transposed) 0.25 ms every warp access is one coalesced cache line

* I’d like to review these inferences closely, but I’m only just learning Warp so chances are Claude is probably more competent than me here.

The work list for v2-v4 is built once in Python. Some background first. Each feature is a product of two or three tensors (“slots”). By the product rule, the gradient with respect to one slot is the feature’s incoming gradient times the product of the other slots. So every (feature, slot) pair adds one term to the gradient of one tensor: the b, C or D tensor of the channel in that slot. The work list decides which GPU thread adds up which of those terms.

def backward_chunks(table, chunk=32):
    groups = {}
    for f, (fam, *cs) in enumerate(table):
        for p in range(_N_SLOTS[fam]):
            groups.setdefault((cs[p], fam, p), []).append(f)
    chunks, entries = [], []
    for (c, fam, p), fs in sorted(groups.items()):
        for k in range(0, len(fs), chunk):
            part = fs[k : k + chunk]
            chunks.append((c, fam, p, len(entries), len(part), _KIND[(fam, p)]))
            entries += part
    return np.asarray(chunks, np.int32), np.asarray(entries, np.int32)

Line by line:

  • for f, (fam, *cs) in enumerate(table): walk over every feature f. fam is its family and cs its channels.
  • for p in range(_N_SLOTS[fam]): walk over every slot of that feature: 2 for families 1-3, 3 for families 4-7.
  • groups.setdefault((cs[p], fam, p), []).append(f): file the feature under the key (channel being differentiated, family, slot). Why: every feature in one group adds to the same tensor (same channel, same kind) using the same formula. So one thread can add up a whole group in its registers and write the result once, and every thread working on that group runs exactly the same code.
  • sorted(groups.items()): a fixed, reproducible order.
  • for k in range(0, len(fs), chunk): split big groups into chunks of at most chunk features. Why: this is a trade-off. A long chunk means fewer final writes (one per chunk), but fewer threads in total, and small systems need many threads to keep the GPU busy. The chunk length therefore grows with system size: 4 features at 3.9k atoms, 16 at 17.9k, 32 above ~64k.
  • chunks.append((c, fam, p, len(entries), len(part), _KIND[(fam, p)])): one row per chunk, saying which channel it differentiates, which family and slot, where its list of features starts, how many there are, and which kind of tensor (b, C or D) it writes into.
  • entries += part: one flat list of feature ids, so each chunk’s features are one contiguous slice of it.
  • The result depends only on the model’s shape and the chunk length, so it is computed once and handed to the GPU as constant arrays.

Why this layout avoids “divergence”. A GPU runs threads in groups of 32 called warps (a hardware term, unrelated to the NVIDIA Warp library). All 32 threads of a warp execute the same instruction at the same moment. If an if sends some threads one way and the rest the other way, the warp has to run both paths one after the other, with half its threads idle each time. That is called divergence, and v1 suffered from it: its threads walked through different features with different formulas.

Each backward thread here is numbered (chunk, atom), with the atom number counting fastest. So 32 neighbouring threads, which form one warp, are the same chunk for 32 consecutive atoms. Same chunk means same family, same slot, same list of features and the same number of loop steps; only the atom, i.e. the data, differs. Every thread of the warp therefore takes the same branch every time, and nothing diverges.

The same numbering is why v4 stores everything transposed (component-major). Then the same number for 32 consecutive atoms sits side by side in memory, and one memory transaction serves the whole warp (a “coalesced” access) instead of 32 separate ones.

Inside the loop, each thread adds up its chunk’s terms for its atom, in registers: a 3-vector for b, a 3×3 matrix for C, or three 3×3 matrices for D. At the end it folds this full gradient onto the unique numbers we actually store. For example, the stored xy entry of a symmetric C appears twice in the full matrix (xy and yx), so its gradient is the sum of both. It then adds the 3, 6 or 10 results into the atom’s gradient with atomic adds. Atomics are needed because other chunks (other features that use the same tensor) add into the same numbers, possibly at the same moment, and an atomic add makes sure no update gets lost. Thanks to the chunking, that happens once per chunk instead of once per feature.

A later refinement (E25) split families 6 and 7 further, one kernel per slot position, after ncu showed those two still using 126-166 registers. Doing that made small systems slower, because each kernel’s grid became tiny, so the chunk length now scales with system size (4 features per thread at 3.9k atoms, 16 at 17.9k, 32 above ~64k).

Result: the contraction went from 1.31 ms to about 0.36 ms per step at 17.9k atoms, +68 % overall at that size and +30 % at 3.9k.

Fused periodic pair vectors

The pair vectors were computed in XLA from two gathers, a minimum-image wrap and a box product, and differentiated by XLA. That is about 150 µs per step at 17.9k atoms of almost pure memory traffic: data read and written with hardly any arithmetic. Whether that traffic reaches DRAM or stays in the 96 MB L2 cache is up to the hardware, not us. Each pair-sized array is about 22-27 MB at this size (2.2 million pair slots × 3 floats), and several of them are alive between kernels. So part of it can stay in L2, but whatever stays there pushes other data out, and the rest goes to DRAM. We did not measure the split for this particular step. A custom VJP with one Warp kernel each way replaces it (abridged):

@wp.kernel(module="unique")
def pair_vectors(R: wp.array(dtype=wp.vec3), pairs: wp.array2d(dtype=wp.int32),
                 box: wp.array(dtype=wp.mat33), n_atoms: wp.int32, dr: wp.array(dtype=wp.vec3)):
    p = wp.tid()
    c = wp.min(pairs[1, p], n_atoms - 1)
    n = wp.min(pairs[0, p], n_atoms - 1)
    s = R[c] - R[n]
    h = wp.float32(0.5)
    s = wp.vec3(s[0] - wp.floor(s[0] + h), s[1] - wp.floor(s[1] + h), s[2] - wp.floor(s[2] + h))
    dr[p] = box[0] @ s

The backward kernel uses the symmetry of the neighbour list. A small example shows how. Take three atoms A, B and C, where A neighbours both B and C, but B and C are too far apart. The list is sorted by centre atom and holds every pair in both directions:

slot q centre neighbour pair vector reverse slot rev[q]
0 A B R_A − R_B 2
1 A C R_A − R_C 3
2 B A R_B − R_A 0
3 C A R_C − R_A 1

In the backward pass, each pair vector q arrives with a gradient ct[q]. A pair vector is centre minus neighbour, so ct[q] counts with a plus sign for its centre atom and a minus sign for its neighbour atom. For atom A:

dR_A = ct[0] + ct[1] (A is the centre) − ct[2] − ct[3] (A is the neighbour)

The obvious way to compute this is a scatter: one thread per pair adds +ct into its centre atom and −ct into its neighbour atom. But then many threads write into the same atom at unpredictable times (A gets writes from 4 different threads here, a real atom from about 200), and every write must be an atomic add to a random place in memory. That is slow.

The symmetry gives a better way. Whenever A is the neighbour in some pair (slot 2: B→A), the reverse pair (slot 0: A→B) sits in A’s own part of the list, and rev points from one to the other. So the pairs where A is the neighbour are exactly the reverses of the pairs where A is the centre, and

dR_A = (ct[0] − ct[rev[0]]) + (ct[1] − ct[rev[1]]) = ct[0] − ct[2] + ct[1] − ct[3]

which is the same number. Now the thread(s) for atom A only read A’s own contiguous slice of the list plus the reverse slots, and only write A’s own result. No thread writes into another atom, so no scatter is needed. (In practice 4 threads share an atom and combine their partial sums; that is the only remaining atomic, and it never collides with other atoms.)

Little JAX tracer gotcha (or so it appears): the first version decided whether to use the fused path by checking that the box was not a JAX tracer. Inside the integrator the box is always traced, even in NVT, so the fused path silently never ran and the “+1 %” we measured was noise. Profiling caught it (the kernel was missing from the trace). The decision is now made once at setup from the ensemble type.

Result: +5 % at 3.9k and 17.9k, +22 % at 104k atoms.

Neighbour list from ALCHEMI (neighbor_builder: alchemi)

jax-md builds its cell list by materialising every candidate pair: 31 million candidates for 17.9k atoms (about 1,750 per atom, for about 100 real neighbours), followed by large scatters. A rebuild cost ~2.4 ms, roughly 300 µs per step amortised. We first wrote our own Warp cell list (+12 % at 17.9k), then deleted it in favour of NVIDIA’s maintained implementation, keeping only a ~100-line adapter that returns a jax-md compatible NeighborList (same layout, padding, capacity rule and overflow flag). Pair sets are checked to be identical to jax-md’s on cubic and sheared triclinic boxes.

Along the way we found that jax-md’s fractional-coordinate cell list uses one scalar cell size for all three axes, derived from the shortest axis. In elongated boxes every cell is too long on the other two axes, and memory blows up:

atoms ALCHEMI builder jax-md builder
71.5k (116.6 × 116.6 × 58.3 Å) 2.55 GB 19.1 GB
143k (cubic) 4.99 GB 9.97 GB
322k (174.9 × 174.9 × 116.6 Å) 9.35 GB 34.6 GB

Spatial sorting at every rebuild

Atom ordering controls cache locality of the scatters/gathers/the neighbour list in general. Same structure, random versus spatially ordered atom indices:

order 17.9k steps/s 104k steps/s
original (replicated boxes, already local) 396 43.4
Morton (Z-order) 394 43.3
random 360 (−9 %) 40.2 (−7 %)

Diffusion scrambles any initial order within about a nanosecond, so a production run drifts toward the random row. The adapter now renumbers atoms in Morton order at every rebuild and builds the list in that order:

def _spread_bits(v):
    v = v & jnp.uint32(0x3FF)
    v = (v | (v << 16)) & jnp.uint32(0x030000FF)
    v = (v | (v << 8)) & jnp.uint32(0x0300F00F)
    v = (v | (v << 4)) & jnp.uint32(0x030C30C3)
    v = (v | (v << 2)) & jnp.uint32(0x09249249)
    return v

What this bit trickery does: each atom’s fractional coordinates are cut into 1024 bins per axis, so each axis gives a 10-bit integer. A Morton code interleaves the bits of the three integers: x’s lowest bit, then y’s, then z’s, then x’s second bit, and so on, into one 30-bit number. _spread_bits does the first half of that. It inserts two zero bits after every bit of a 10-bit number (binary abc becomes a00b00c). Each line shifts copies of the bits apart (by 16, 8, 4, then 2 places) and the mask clears the copies that landed in the wrong place. The three spread numbers are then combined as spread(x) | spread(y) << 1 | spread(z) << 2. For example, x = 3 (binary 011), y = 5 (101) and z = 0 give, read in (z, y, x) groups from the top, 010 001 011. Sorting atoms by this number walks through the box along a Z-shaped curve, so atoms that are close in space mostly end up with close indices.

The permutation keeps the species pattern (each element is sorted into its own index slots), so the model keeps its compile-time constant atomic numbers. A small wrapper evaluates the model on R[perm] and maps per-atom outputs back, so the integrator, trajectory and constraints never see the renumbering.

The first measurement of this was confusing: sorting helped at 104k atoms but made 17.9k atoms 13 % slower, and an identity permutation was just as slow. The profile showed XLA’s own readout and contraction kernels slowing down, for example one fusion going from 36 to 89 µs with identical HLO and identical launch configuration. Under ncu, which flushes caches before each kernel, both versions took 102 µs and read 84 MB from DRAM. The difference was the order XLA chose to run kernels in: in the slow schedule, other work ran between the GEMMs that produced 64 MB of data and the fusion that consumed it, and the data fell out of the 96 MB L2. Once the contractions moved to Warp that region was gone, and sorting became a clean win: +13 % at 17.9k and 104k atoms on scrambled input, about −3 % on input that is already ordered.

Human’s note: “This is what Claude thinks. I will try to review and verify this, but I’m not sure I’m even qualified to (for now…).”

Smaller items

id change effect (3.9k / 17.9k)
E16 reverse-pair map computed once per rebuild, stored as a third row of the index array +6 % / +7 %
E19 Warp kernels read the whole (rows, P) index array instead of row slices (XLA materialised every slice as a ~9 MB copy) +1 % / +4 %, +3 % at 104k
E23 Nose-Hoover chain: precompute 1/Q (the chain is ~60 serial fp64 exp and ~70 divisions per step, ~38 µs regardless of size) +3 % / 0 %
E24 thread split of the moment kernel refitted (the optimal thread count grows like the square root of N) +4 % at 3.9k
E25 backward contraction per (family, position) with size-dependent chunks +3 % / +1 %

The memcpy accounting behind E19 is worth showing, because none of it appears in a kernel summary:

 36.1 us/step  1.1x  memcpy128
 32.1 us/step  4.0x  [CUDA memcpy Device-to-Device] 8.911 MB    <- row slices as custom-call operands
 19.1 us/step  2.0x  [CUDA memcpy Device-to-Device] 26.733 MB   <- index array around the update lax.cond

The second kind is still there: XLA does not let a conditional’s output alias its input, so the branch that leaves the neighbour list unchanged copies it every step (~14 µs, about 1 %).

Things that did not work

attempt what happened
per-family forward contraction kernels kernels got faster (105 → 83 µs) but the zero-initialised output costs 27 µs
feature-major forward contraction slower (106 → 116 µs): lanes of one warp no longer share an atom’s 428-byte row
CSR segment starts cached as a fourth index row −1.7 %: the larger index array costs more in the per-step copies than it saves
vector-packed radial coefficients in the moment kernel 217 → 469 µs; Warp’s generic-length vector type did not compile to vector loads
optimization_barrier to remove the index copies no change
BF16x3 matmuls for the readout 1.4× faster GEMMs, 7× the fp32 error; rejected
TF32x3 / BF16x6 (fp32-accurate emulation) slower than plain fp32 on these GPUs
latency-hiding scheduler on/off no effect on the schedule problem above
larger neighbour skin flat within ±2 % from 0.3 to 0.7 Å

Accuracy

check_fp64.py evaluates each configuration against a model with fp64 descriptor and readout, the exact (untabulated) radial function and fp64 geometry. On the 3.9k box and on a strongly sheared triclinic copy of it:

path MD forces max / rms (meV/Å), cubic triclinic energy error per atom
XLA fp32 0.163 / 0.024 0.191 / 0.023 1-3 × 10⁻⁵ meV
Warp, jax-md list 0.153 / 0.021 0.192 / 0.021 1.5-1.8 × 10⁻⁴ meV
Warp, full stack 0.153 / 0.021 0.191 / 0.021 1.4-1.7 × 10⁻⁴ meV

The remaining force error comes from fp32 rounding of positions and displacements and is shared by every path. The numbers are identical on the L40S and the RTX PRO 6000.

A correction from along the way: at one point I reported that all fp32 paths sat at about 1.6 meV/Å. The test script had bypassed apax’s matmul_precision: highest setting, so XLA was using TF32. With the setting applied, the numbers are the ones above.

Blackwell and MPS

The same code, unchanged, on an RTX PRO 6000 Blackwell gives the numbers at the top of this post. A single Warp process is 14 % faster than on the L40S at 3.9k atoms, 37 % at 17.9k and 86 % at 104k.

The cluster runs these GPUs in Exclusive_Process mode, so the only way to put two MD runs on one card is CUDA MPS. Starting the MPS daemon failed silently (exit code 1, empty log) until we noticed that the control socket path was about 170 characters long. Unix sockets are limited to 108. With a short directory it started immediately. Throughput with two processes:

run 1 process 2 processes, total gain
Warp, 3.9k 2,283 3,609 1.58×
all-JAX, 3.9k 690 901 1.31×
Warp, 17.9k 1,026 1,244 1.21×
all-JAX, 17.9k 192 193 1.00×
Warp, 104k 185 170 0.92×

Small Warp systems leave the GPU idle for part of each step, and a second process fills that time. The all-JAX path at 17.9k is already limited by memory bandwidth (nvitop showed about 82 % memory-bandwidth use during these runs), so two processes just split it.

How close to the hardware limit?

A rough count for 17.9k atoms gives about 13 GFLOP of essential work per step (3.7 for the pair kernels, 2.5 for the contractions, 6.7 for the readout, forward and backward). At the L40S’s 91.6 TFLOPS fp32 peak that is about 0.14 ms, against a measured 1.31 ms, so roughly 10 % of peak. The readout GEMMs run at about half of peak already; the pair and contraction kernels are at 8-11 %, limited by instruction count and occupancy; and about 450 µs per step goes to work that does very little arithmetic for the time it takes: neighbour-list rebuilds (mostly searching and sorting through memory), the thermostat (a short chain of fp64 maths where each step waits for the previous one), memory copies and gaps between kernel launches. A further 2× looks possible with a lot more work; beyond that would need relaxing the fp32 requirement.

Tests

The validation scripts used during development were turned into 31 self-contained pytest tests (synthetic rattled NaCl crystals and random radial tables, so no trained model is needed). The GPU tests skip cleanly without CUDA or the optional packages.

test file what it checks
test_warp_contract.py contraction kernels and VJP against the original _contract in fp64, including n_contr and drop_contractions; the backward work list covers every slot exactly once
test_warp_moments.py moment kernels and VJP against an fp64 XLA reference, for several thread splits
test_neighbor_grad.py CSR segment starts (padding, empty atoms, jax-md’s stray last slot), reverse pairs, the gather VJP, fused pair vectors on cubic and triclinic boxes
test_alchemi_neighbor_list.py ALCHEMI lists against jax-md (pairs, capacity, ordering, padding, reverse row), the rebuild criterion, sorted lists; Morton permutation and the model wrapper on CPU
test_nhc_fused.py the fused Nose-Hoover chain against jax-md’s implementation
$ pytest tests/unit_tests/layers/descriptor/test_warp_contract.py \
         tests/unit_tests/layers/descriptor/test_warp_moments.py \
         tests/unit_tests/layers/test_neighbor_grad.py \
         tests/unit_tests/md/test_alchemi_neighbor_list.py \
         tests/unit_tests/md/test_nhc_fused.py
31 passed, 22 warnings in 52.92s

The first run of these tests on the Blackwell node failed 7 times. Four were bugs in the tests themselves: three from a NaN gradient in the fp64 reference at padded pairs, and one from a locality check that counted each atom as its own neighbour (on fixtures that built the 2-atom primitive NaCl cell where a cubic one was intended). The other three caught a real precision regression: jax-md stores the thermostat masses Q in fp32, so the precomputed 1/Q of E23 was formed in fp32 and differed from the original by 4 × 10⁻¹⁰ relative. It is now formed in fp64 and matches to 10⁻¹⁰.

Using it

# MD config
moment_kernel: warp          # fused Warp moment kernels
contract_kernel: warp        # fused Warp contractions
neighbor_grad: pull          # scatter-free pair gradient (+ fused pair vectors)
fuse_nlh: true               # NLH repulsion inside the moment kernels
neighbor_builder: alchemi    # pip install nvalchemi-toolkit-ops; NVT / NVE only
capacity_multiplier: 1.05    # tighter neighbour-list capacity (constant volume)
# sort_atoms: true           # default with the ALCHEMI builder
# matmul_precision: highest  # default: no TF32

pip install 'apax[alchemi]' pulls in warp-lang and nvalchemi-toolkit-ops. The ALCHEMI [jax] extra pins jax<0.10.2; the base package works with jax 0.10.2.

Code footprint and caveats

The fast path is about 1,540 lines across five modules: warp_moments.py (498), warp_contract.py (435), neighbor_grad.py (295), alchemi_neighbor_list.py (223) and the fused thermostat. The two kernel files are the real maintenance cost: they hard-code the Bessel basis, the cosine cutoff and the packed moment layout, so a change to the descriptor needs a matching kernel change. The tests above compare them against fp64 references, so a mismatch should fail loudly.

Things that are not covered: NPT with the Warp-specific neighbour list and pair vectors (NPT falls back to the general path), hessians, and GPUs other than the L40S and RTX PRO 6000. The thread-split and chunk-length heuristics were fitted on the L40S at three sizes and held up on Blackwell, but a runtime autotuner would be the robust option elsewhere.

The code in these sessions was written by Claude, with the direction, precision requirements and choices about what to keep coming from me. Every number in this post comes from a run recorded in SPEEDUPS.md on the branch or in the lab notebook kept next to it; I plan to go through them again properly when I’m back.