Chapter 11: Mini-Batch EMA Clustering: e-means
"Outperform k-means in one-tenth the epochs."
— Bessa et al. (Meta FAIR, arXiv 2611.09501, 2026)
11.1 The Mini-Batch Regime: Why Epochs Beat Iterations
Classical Lloyd's algorithm alternates a full assignment pass with a full mean recomputation until convergence. Every iteration reads the entire dataset, and convergence is declared on centroid stagnation — a stopping rule that can take dozens of passes on 8-million-pixel image palettes and embedding indices. The practical alternative is mini-batch k-means: process \(B \ll n\) rows per update, and stop after a fixed budget of \(T\) passes.
The plain mini-batch recipe (sculpty, Weissberger et al. 2019) replaces the exact mean with an exponential moving average (EMA):
where \(n_j\) is the batch count assigned to cluster \(j\) and \(s_j\) the batch sum. Fixed-\(\alpha\) EMA has two failure modes: early updates with large \(\alpha\) hammer the centroid around, late updates with the same \(\alpha\) keep it jittering forever. e-means (Bessa et al. 2026) fixes both with a cosine-annealed step schedule and adds a third mechanism — dead-cluster revival — that removes the worst failure mode of random initialization at large \(k\).
The headline result, and the design goal of this chapter: at equal or smaller epoch budgets, e-means matches or beats full-data k-means in the regime where clustering actually matters in production — \(n \ge 10^5\), \(k \ge 10^3\) — while costing \(T\) data passes by construction:
On the benchmarks of Chapter 11.6, \(T = 5\) e-means is 8.8× faster in wall clock than 25-iteration Lloyd on 100K × 128-d embeddings with \(k = 4096\) — and 43% better in final MSE.
11.2 The e-means State Machine
The model state per cluster is a mass \(N_j\) and a centroid \(c_j\), both FP32. Every row of data carries unit mass. The state machine has exactly four verbs:
1. Initialization
Centroids are drawn as \(k\) random data rows without replacement (partial Fisher–Yates on a scratch index array); masses start at \(N_j(0) = 2^{-16}\) — positive but negligible, so the first real batch dominates every centroid.
2. The EMA Update (per batch)
With cosine-annealed step \(\alpha(t)\):
The corner case \(\alpha = 1\) is exact: the centroid becomes the batch mean (\(c_j = s_j / n_j\)) and the mass becomes the batch count. The schedule (Eq. 5 of the paper) is computed in FP64 and cast to FP32 once at use:
peaking at \(\alpha_0\) on the first update and annealing to a 10% floor — never to zero, so late epochs still track the data.
3. The Scaling Laws (auto-recipe)
The batch size and peak step are not hyperparameters; they are power laws of the problem shape, fit on the reference's benchmark suite (constants from the shipped faiss code, which this chapter's implementation follows over the paper's wording where they differ):
| Quantity | Law |
|---|---|
| Batch (throughput) | \(B = 0.035134 \; k^{0.134749}\, n^{0.876473}\, T^{0.813344}\) |
| Batch (quality) | \(B = 0.00439175 \; k^{0.134749}\, n^{0.876473}\, T^{0.813344}\) |
| Peak step | \(\alpha_0 = \text{clamp}\big(0.8244 \; k^{-0.4617}\, B^{0.9003}\, n^{-0.4498}\, T^{-0.1057},\; 10^{-4},\; 1\big)\) |
B is rounded to the nearest power of two; the quality law auto-selects
for \(d \le 16\) (low-dimensional data tolerates — and prefers — smaller
statistical batches). For an 8.3M-pixel palette problem (\(d=3, k=256,
T=5\)) the laws resolve to \(B = 32{,}768\), \(\alpha_0 = 0.4826\): 254 updates
per pass, 1270 total.
4. Finalization
After the last epoch, each non-empty cluster is replaced by the mean of its last-epoch members, accumulated in FP64 and divided in FP32 — no new assignment pass is spent.
In RCRE the state machine is src/ml/e_means.c (≈900 lines, fully
commented), with the public API as a sibling of the k-means family:
RCRE_EMMeansParams p = rcre_ml_emeans_params_default(); // T=5, auto laws
float inertia; int n_splits;
rcre_ml_emeans_fit_ex(&X, /*k=*/256, &p, &C, &L,
&inertia, &n_splits, arena, pool);
/* exact nearest-centroid assignment + exact MSE: */
rcre_ml_emeans_assign(&X, &C, &L, &inertia, arena);
rcre_ml_emeans_recipe(&X, k, &p, &rec) exposes the resolved plan
(batch, \(\alpha_0\), epoch rows, total updates) for observability — the
auto-tuning is a formula, and you can see exactly what it produced for
your \((n, k, T)\).
11.3 Dead-Cluster Revival: Gumbel-Max Donor Selection
At \(k = 4096\) on 100K rows, random-row initialization leaves most centroids dead: with mass \(2^{-16}\), a centroid that never wins an argmin never moves, never gets mass, and stays dead forever. Lloyd's answer is a smarter initialization (k-means++); e-means' answer is a runtime repair — every 5 updates:
masses N_j (log-scale key: log N_j - log(-log U_j), U_j ~ U(0,1))
donor j* = argmax_j key_j <- Gumbel-max over log-masses
child j = smallest-mass cluster below threshold
split: for each dimension dd (index order):
child[dd] += (dd even ? +1e-4 : -1e-4)
donor[dd] -= (dd even ? +1e-4 : -1e-4)
Three details matter and are pinned by the test suite:
- Gumbel-max over the logs of the masses. The threshold is \(\text{mass} < \tau \cdot \sum_j N_j / k\) (auto \(\tau = 0.1\), off for \(d \le 2\)), but the donor is chosen by drawing a Gumbel variate per cluster and taking the max — i.e. the revival donates mass in proportion to existing mass, in a single O(k) pass with no sorting.
- The U stream is consumed for all \(k\) clusters per check, whether or not any split actually happens. Skipping the draws when no split occurs desynchronizes every subsequent Gumbel draw — the strict-parity test of §11.6 exists precisely to catch that class of bug.
- The split is per-dimension alternating \(\pm 10^{-4}\), child written
first (it reads the original donor), and if donor and child
collapse to identical bits (a 1-ULP coordinate), the child's first
coordinate is pushed by
nextafter. On the sift100k workload of §11.6, revival performs 10,947 splits — the mechanism that keeps the 4096-cluster model dense while Lloyd strands hundreds of centroids.
11.4 The Assignment Kernel: Exact Dots vs. GEMM
Every e-means update begins by assigning each row to its nearest centroid. The cost is \(B \cdot k \cdot d\) per update, so the kernel is dual — selected by the product \(k \cdot d\):
Exact kernel (\(k \cdot d \le 16384\) — every palette and small
embedding problem, including the 8.3M-pixel case where \(k \cdot d = 768\)):
per row, per dimension, the true squared distance is accumulated
sequentially in FP32 without FMA contraction (the translation unit is
compiled with -ffp-contract=off), and ties break to the first index:
for (size_t j = 0; j < k; j++) {
float dv = 0.0f;
for (size_t dd = 0; dd < d; dd++) {
float df = x[dd] - c[j * d + dd];
dv += df * df; // no FMA: the parity contract depends on it
}
if (dv < best) { best = dv; best_j = j; } // first index on ties
}
GEMM kernel (\(k \cdot d > 16384\)): the batch is chunked so
\(\text{chunk} \cdot k \le 16\text{ MB}\), rows are gathered into a
contiguous slab, and the score matrix is the HAL-dispatched
rcre_hal.gemm_f32 (NEON / AVX2 / scalar) of \(x \cdot c^\top\); the argmin
runs on \(cc_j - 2\, x \cdot c_j\) (the row-constant \(\|x\|^2\) removed).
One subtle trap the GEMM path sidesteps: \(cc_j - 2\, x \cdot c_j\) is only monotone in the true distance, not equal to it — for data far from the origin, cancellation makes the expanded form negative (on sift100k the expanded objective is ≈ \(1.6 \times 10^{10}\) while the true MSE is ≈ \(1.8 \times 10^4\)). The argmin is unaffected (row-constant removal is exact), but the reported objective is therefore always the true distance to the winning centroid, accumulated in FP64.
11.5 Determinism by Construction: The Slab Contract
e-means is pool-parallel, and the parallelism is structured so that determinism is a theorem, not a hope. Each batch chunk is split into contiguous slabs of \(\ge 64\) rows — at most 16 partial-statistics buffers, one per slab — and every slab writes its own buffer; no cache, no mutex, no shared pixel state in the data path:
The partition depends only on the batch size — never on the pool size, never on the core count. The threadpool decides which worker runs which slab; the slab boundaries, the within-slab row order, and the slab-merge order are all fixed by \(B\). Therefore:
- pooled runs are bit-identical across pool sizes and machines (verified: 45,059-assertion bit-identity between 1-worker and 18-worker pools, centroids and labels);
- the serial run (single slab, pure sequential FP32 accumulation) is a separately guaranteed configuration. Its batch sums differ from the pooled two-level grouping at the ULP level, and that difference feeds back chaotically through the EMA system — one flipped early argmin cascades. The honest serial-vs-pooled contract is therefore quality equivalence (final MSE within 0.5%, training-label agreement ≥ 99%), not 1 ULP. Same guarantee class as any order-sensitive F32 accumulator.
11.6 The Numerical Contract: Three Tiers of Parity
Floating-point code is only as honest as its test contract. e-means splits the state into tiers, each with a different proof:
| Quantity | Type | Contract |
|---|---|---|
| centroids \(c_j\), masses \(N_j\) | FP32 | bit-exact port of the reference's operation order |
| batch sums \(s_j\), counts \(n_j\) | FP32 | unbuffered, row order (slab partials merged in row order) |
| scheduled \(\alpha(t)\) | FP64 → FP32 | Eq. 5 in double, cast once at use |
| objective (inertia) | FP64 | true distance to the winner (reference: FP32 — documented improvement) |
| finalization pass sums | FP64 | last-epoch means (reference: FP32 — documented improvement) |
Tier 1 — strict parity (0 ULP). An independent Python oracle
(projects/rcre_emeans/ref/) runs the documented FP32 operation order
and serializes its own streams — labels, batch sums, counts, and Gumbel
draws. The C state machine replays the oracle's streams and must
reproduce every post-update centroid and mass to the last bit:
205,790 assertions, 0 ULP, including the 15-split revival case. This
proves the transliteration; it does not prove quality.
Tier 2 — statistical parity. Full runs on both sides with native PRNGs (C: splitmix64 streams; oracle: MT19937 — bit-parity of full runs is impossible by design) at the same seed: the C run's final MSE must be within +0.5% of the oracle's. Measured: C at 0.589× the oracle's MSE (0.2565 vs 0.4354 per dimension) — the gate is a ceiling, not a target.
Tier 3 — quality floors. The paper's two-blob local-minimum trap (one 200-point blob, one 3000-point blob, \(k=8\)): e-means puts 7/8 centroids on the large blob and ties Lloyd-25. Full-run non-degeneracy: e-means(5) beats the single-cluster baseline by 136×.
Measured Performance (M5 Max, 18 cores)
| Workload | e-means (T=5) | Pooled | Lloyd-25 | Final-MSE ratio |
|---|---|---|---|---|
| 4krgb (n=8.3M, d=3, k=256) | 13.5 s | 1.11 s (12.3×) | 35.9 s | 1.019 (tie) |
| sift100k (n=100K, d=128, k=4096) | 8.9 s | 1.16 s (7.6×) | 78.1 s | 0.566 (43% better) |
The honest boundary, measured and documented: at small scale
(n=20K, k=256) k-means++ + 25 Lloyd iterations keeps a ~2.4× MSE
advantage from its initialization — the paper's "≥ k-means at equal
epochs" is a large-scale statement, and make bench above is the regime
where both wall clock and quality hold.
11.7 Chapter Project: The 8-Million-Pixel Palette
Project Objective
Implement a -palette:k operator for an 8,294,400-pixel RGB image
(\(d = 3\), \(k = 256\)): train e-means on the pixel matrix, then quantize
every pixel to its assigned centroid color with the exact assignment
kernel — the first production consumer of rcre_ml_emeans_*.
Applied Tasks
- Pack the image's SoA bands (R, G, B planes) into the \((n, 3)\) F32 training matrix with one arena allocation.
- Resolve the recipe for \((n, k, T=5)\) and verify \(B = 32{,}768\), \(\alpha_0 \approx 0.4826\) against the laws of §11.2.
- Train pooled, then run
rcre_ml_emeans_assignfor the exact nearest-color map (exact kernel: \(k \cdot d = 768 \le 16384\)). - Verify determinism: two pooled runs with different pool sizes produce
bit-identical centroids (compare with
memcmp).
Grading Test: The full pipeline (train + assign) completes under AddressSanitizer with zero leaks in under 3 seconds on an 18-core pool, the 256 palette colors have zero duplicates (revival never produced a bit-identical pair), and the pooled 1-worker/18-worker centroid comparison reports 0 bytes differing.