Technical note, November 2026

h-means: mini-batch k-means with a hierarchical warm start and Hartigan assignment

At equal distance computations, h-means reaches 1.6% to 6.7% lower k-means loss than e-means for 20 or fewer points per cluster, and matches or slightly improves on it for larger clusters.

e-means (Bessa et al., Meta FAIR, 2026) trains k-means on mini-batches with an exponential moving average of cluster statistics and reaches a lower loss than Lloyd's algorithm in a tenth of the passes. h-means keeps the e-means update, laws and schedule, and changes the initialisation and the assignment rule: a hierarchical warm start with loss-proportional allocation of centroids, and Hartigan's exact move rule in place of nearest-centroid assignment. This page is the full account; every number on it comes from the logged runs of one repository.

Three Gaussians plus uniform noise, the first distribution of the e-means playground. All three draw the same points and the same number of centroids (k is printed under each panel) and spend the same number of distance computations per pass. Lloyd and e-means start from the same random rows; since 70% of the points lie in the largest Gaussian, about 70% of their centroids start inside it and stay there, packed so tightly that they read as one disk. h-means allocates centroids in proportion to the loss, so the sparse noise region, where every point is far from its centroid, receives many more of them. The h-means panel looks fuller only because its centroids are spread out where each one is visible. The simulation runs in this tab.

Two dimensions exaggerate the gap (the e-means laws were not fitted there, and faiss switches dead-cluster revival off at d ≤ 2); the measurements below on 96- to 784-dimensional data are the fair comparison.

With fewer centroids the same thing can be seen cell by cell. Each centroid owns the region of the plane closest to it, its Voronoi cell, and the k-means loss is the sum over cells of the squared distances to the centroid. The cells are tinted by their area. Lloyd and e-means keep most of their centroids inside the big Gaussian, where the cells are tiny, and leave a handful of huge cells over the noise, where every point is far from its centroid. h-means hands the noise many more centroids, so its cells are of more even size and the loss is lower. At this small k the hierarchical warm start costs about one extra pass, which the stat line shows. The checkbox turns the cells on in every simulation on this page and in the playground.

The gain, as a function of points per cluster

−6.7%
train loss vs the best e-means at 5 passes, NYTimes k = 32,768 (7 points per cluster), 5 seeds
16 / 16
configurations (six datasets, Deep-10M included) where h-means is below the better of e-means's two batch laws at equal passes; every seed on each
3 of 5
passes: at 15 points per cluster or fewer, h-means after 3 passes is already below e-means after 5
±0.03%
train loss vs e-means (quality law) at 240 to 480 points per cluster on SIFT: a tie, the regime where h-means has nothing to add

SIFT-128, 980,000 vectors, k from 2,048 to 262,144, three seeds, five passes each. The gain is a function of n/k: a tie above about two hundred points per cluster, increasing below sixty.

h-means train loss relative to the best e-means, SIFT-128, 5 passes

Negative is h-means better. Bars show ± one seed standard deviation. Hover for the numbers.

At k = 262,144 (four points per cluster) the difference is −14.7%. At that scale Lloyd's algorithm is itself competitive with e-means. The summary is that h-means is a better optimiser of the k-means objective when clusters are small, and equivalent to e-means when they are not. Both changes address the same weakness: with few points per cluster, the mini-batch estimate of a cluster's size and position is noisy, and nearest-centroid assignment makes moves that increase the objective.

EMA statistics (e-means)

Mass and centroid of every cluster are exponential moving averages over mini-batches. Kept unchanged.

No tuning (e-means)

Batch size and step size follow fitted laws of n, k and the pass budget. The user sets k and the budget.

Hierarchical warm start (h-means)

k/16 coarse centroids first; each coarse cluster then receives children in proportion to its share of the loss.

Hartigan's move rule (h-means)

A point moves only if the exact change of the objective, with the N/(N±1) size factors, is negative.

×=

One matrix product (h-means)

The rule for all k centroids is a dot product in d + 2 dimensions, so it costs the same as nearest-centroid search.

EMAexact Hartigan

Pass schedule (h-means)

The budget is split between EMA passes and exact passes by a rule on n/k; above 64 points per cluster there are no exact passes.

The k-means problem

k-means looks for k centroids that minimise the mean squared distance from every point to its nearest centroid:

L(c1,…,ck)  =  1n∑i=1n  min⁡j ∥xi−cj∥2\mathcal{L}(c_1,\dots,c_k) \;=\; \frac{1}{n}\sum_{i=1}^{n}\;\min_{j}\,\lVert x_i - c_j\rVert^2

Every method on this site maintains a sum SjS_j and a count NjN_j per cluster and takes cj=Sj/Njc_j = S_j / N_j. Lloyd's algorithm recomputes both from the full data at every iteration. Each iteration costs n·k distance computations, one "pass", and 25 iterations are a common budget. All comparisons here are at equal passes, which makes them independent of hardware.

The e-means algorithm

e-means (Bessa, Jégou, Touvron and others, Meta FAIR, 2026) processes mini-batches of B points. With njn_j the number of batch points assigned to cluster j and mjm_j their mean, the update is an exponential moving average of the mass and a mass-weighted pull of the centroid:

Nj←(1−α) Nj+α nj,cj←cj+α njNj (mj−cj)N_j \leftarrow (1-\alpha)\,N_j + \alpha\, n_j, \qquad c_j \leftarrow c_j + \frac{\alpha\, n_j}{N_j}\,(m_j - c_j)

The step follows a cosine schedule from a peak α0\alpha_0 down to a tenth of it. Batch size and peak step are not tuned by hand but set by two fitted laws of k, n and the number of passes T:

B  =  CB k0.135 n0.876 T0.813,α0  =  0.824 k−0.462 B0.900 n−0.450 T−0.106B \;=\; C_B\, k^{0.135}\, n^{0.876}\, T^{0.813}, \qquad \alpha_0 \;=\; 0.824\, k^{-0.462}\, B^{0.900}\, n^{-0.450}\, T^{-0.106}

with CB=0.0351C_B = 0.0351 for the throughput setting and eight times smaller for the quality setting. After the last pass the centroids are replaced by the exact means of the points seen during that pass.

Dead-cluster revival

Every five updates, clusters whose mass has fallen below a tenth of the mean are revived by splitting a donor sampled in proportion to mass. h-means inherits this unchanged; the e-means paper's ablation shows its value on DEEP and SIFT. In two dimensions dead clusters are rare, which is why faiss switches revival off at d ≤ 2, and a 2-D simulation of it shows nothing, so none is given here.

What reproducing e-means showed

Hierarchical warm start with loss-proportional allocation

Run e-means for half a pass with kc=k/16k_c = k/16 coarse centroids. Assign every point to its coarse centroid (one pass of n⋅kcn \cdot k_c, a sixteenth of a full pass) and accumulate each coarse cluster's count ∣Cj∣|C_j| and sum of squared errors SSEj\mathrm{SSE}_j. Apportion the k fine centroids to the coarse clusters by largest remainder:

kj  =  apportion⁡ ⁣(k⋅SSEj∑iSSEi),1≤kj≤∣Cj∣k_j \;=\; \operatorname{apportion}\!\Big(k \cdot \frac{\mathrm{SSE}_j}{\sum_i \mathrm{SSE}_i}\Big), \qquad 1 \le k_j \le |C_j|

Children start at random members of their coarse cluster and take two Lloyd iterations in which a point only sees the kjk_j children of its own coarse cluster (cost 2 n k/kc2\,n\,k/k_c, an eighth of a pass). The EMA mass of each child is initialised to its count scaled to one batch, Nj=∣Cjchild∣⋅B/nN_j = |C_j^{\text{child}}| \cdot B / n, so the first EMA updates neither ignore nor over-trust the warm start. The whole warm start costs about a tenth of a pass.

The simulation isolates the initialisation: all three panels run plain e-means passes with nearest-centroid assignment, from random rows, from a warm start that gives every coarse cluster the same number of children, and from the loss-proportional warm start. The mixture has Zipf-distributed component sizes, where uniform allocation starves the large components. On the 96-dimensional Zipf mixture of the benchmark, uniform allocation is 9% worse.

Hartigan's move rule

Moving one point x from cluster a (size NaN_a) to cluster b (size NbN_b) changes the k-means objective by exactly

Δa→b(x)  =  NbNb+1 ∥x−cb∥2  −  NaNa−1 ∥x−ca∥2\Delta_{a\to b}(x) \;=\; \frac{N_b}{N_b+1}\,\lVert x - c_b\rVert^2 \;-\; \frac{N_a}{N_a-1}\,\lVert x - c_a\rVert^2

so the point moves to the b that minimises NbNb+1∥x−cb∥2\tfrac{N_b}{N_b+1}\lVert x-c_b\rVert^2 if that is below its stay cost NaNa−1∥x−ca∥2\tfrac{N_a}{N_a-1}\lVert x-c_a\rVert^2. Lloyd's rule is the limit of both factors going to one. With ten points per cluster the factors are 0.91 and 1.11: a twenty percent asymmetry that nearest-centroid assignment ignores.

Matrix formulation

With gj=Nj/(Nj+1)g_j = N_j/(N_j+1), the join cost of every centroid is a dot product of augmented vectors:

gj ∥x−cj∥2  =  [ ∥x∥2,  x,  1 ]⋅[ gj,  −2 gj cj,  gj∥cj∥2 ]g_j\,\lVert x - c_j\rVert^2 \;=\; \big[\,\lVert x\rVert^2,\; x,\; 1\,\big]\cdot\big[\,g_j,\; -2\,g_j\,c_j,\; g_j\lVert c_j\rVert^2\,\big]

A batch of points against all k centroids is therefore one matmul in d + 2 dimensions instead of d, followed by scattering the stay cost into each point's current column and an argmin. A Hartigan pass costs the same as an exact Lloyd pass. Empty clusters cannot be joined through the rule (their join cost is set to infinity; a first version without this guard collapsed); they are re-seeded at the farthest point of a mass-sampled donor every five updates. Inside the EMA passes the rule uses the scaled EMA mass N^j=Nj⋅n/B\hat N_j = N_j \cdot n / B as the size estimate.

The simulation runs at ten points per cluster, the regime where the factors matter. The first and third panels share the warm start and the passes and differ only in the rule: the first keeps nearest-centroid assignment (Lloyd's rule) throughout and finishes with exact passes that move points by that rule with the same incremental bookkeeping; the third uses Hartigan's rule in the EMA passes and in the exact passes, which is h-means. The middle panel is e-means. In the benchmark ablation the Lloyd-rule tail gains nothing over no tail, so it is the N/(N±1) factors and not the exact bookkeeping that carry the gain.

Pass schedule

With T total passes, the first max⁡(1,round⁡(f T))\max(1, \operatorname{round}(f\,T)) are e-means EMA passes with the Hartigan-corrected assignment. The remaining passes are exact: the per-cluster sums and counts of all points, available for free from the last EMA pass, are updated incrementally as points move. The EMA fraction f depends on the points per cluster: 0.4 below 24, 0.8 below 64, 1.0 above. Exact passes only make local moves, which is what small clusters need; with many points per cluster the warm start carries the gain and further EMA passes preserve it better than exact passes do (on a separable mixture at 234 points per cluster, EMA-only after the warm start scored 41.0 against 43.0 with exact passes and 50.9 for e-means). Everything else, laws, schedule, revival, finalisation, is e-means's. For the user the method has the same two inputs as e-means, k and the pass budget.

Escaping local minima

The e-means site shows that mini-batch noise lets e-means escape the local minima of Lloyd's algorithm on well separated Gaussians of unequal size with more centroids than blobs: Lloyd crowds centroids on a small blob and leaves a large one short, e-means starts in the same trap and leaves it. h-means keeps this behaviour, since its EMA passes are e-means passes. The toys below follow the e-means site (same data for every start, 20 passes, Lloyd 25 iterations). With 5 to 10 clusters the hierarchy of the warm start is degenerate (one coarse centroid) and its local Lloyd iterations would cost two full passes, so h-means runs here without it: random rows, then Hartigan-corrected EMA passes. Press "Run 100 random starts" to count how often each method ends more than 1% above the best loss reached. Measured with this code (starts 1000 to 1099): on the two-blob toy Lloyd is stuck on 55 of 100 starts and e-means and h-means on 12; on the grid and the square the port shows only a small difference (90 against 86 and 65 against 58), less than the e-means site reports for its fixed batches of 256, so the escape depends on the batch and step sizes the laws choose for n = 2,000.

Design exploration

The ideas tried, in chronological order, with their measured outcome. "Negative" means the idea did not improve on exact assignment at equal wall-clock time or equal distance computations on this hardware.

  1. negative

    Approximate assignment with a cached candidate list (each point only re-scored against its last few nearest centroids, refreshed periodically). Near-ties on real embeddings are missed and the loss stalls above exact assignment.

  2. negative

    Graph-based assignment (centroid k-NN graph, local search from the previous label). Same failure mode, more bookkeeping.

  3. negative

    Bounded exact assignment (triangle-inequality bounds to skip centroids). Certifies 0.1% of the distance computations on 128-d embeddings; the bounds are too loose in high dimension.

  4. negative

    PCA filter-and-refine (score in 32 dimensions, refine the top candidates exactly). Twice the multiply-adds at best and slower than one dense matmul on an accelerator.

  5. negative

    Inverted-file first pass, growing batches, Lloyd-rule incremental tail. None moved the loss at equal passes.

  6. kept

    Hierarchical warm start with loss-proportional allocation. A coarse e-means run with k/16 centroids, children apportioned by SSE, two local Lloyd iterations. About 0.1 pass of cost, worth 0.3% at n/k = 60 and more below. A uniform split instead of loss-proportional is 9% worse on a Zipf mixture.

  7. result

    The Hartigan correction is the main source of the gain at small n/k. Replacing the Lloyd rule with Hartigan's exact move rule in the final passes: 2.1% better at k = 65,536 and 5.4% at k = 131,072 on SIFT at equal passes. A Lloyd-rule tail with the same exact bookkeeping gains nothing, so it is the N/(N±1) factors, not the exact means, that matter.

  8. kept

    Hartigan's rule inside the EMA passes too, with the EMA mass scaled by n/B as the cluster size estimate. The only change that also helps at n/k ≈ 60 (0.25% on SIFT k = 16,384).

  9. negative

    Loss-proportional revival donors. Sampling the split donor by SSE instead of mass: free, but within noise everywhere. Kept as an option, not part of the claim.

  10. result

    Split of the pass budget. Three fixed recipes ran on the full grid: v1 (no Hartigan in the EMA passes), v2 (80% EMA, 20% exact), v3 (40% EMA, 60% exact). v3 won below 20 points per cluster, v2 between 30 and 60, and both lost a quarter percent above 120. A synthetic check at 234 points per cluster showed the exact tail itself losing the warm start's gain. The final recipe sets the EMA fraction from n/k (0.4 below 24, 0.8 below 64, 1.0 above). The thresholds were chosen on the grid we report; see the limitations.

Experimental validation

Six datasets (SIFT-128, GloVe-100, NYTimes-256, Fashion-MNIST-784, two synthetic 96-dimensional Gaussian mixtures, Deep-96 at 10M rows), k from n/k ≈ 150 down to n/k ≈ 7, five seeds for the mini-batch methods, one machine (Apple M3 Ultra, PyTorch on the GPU). Loss is the exact train MSE on all training rows. "Best e-means" is the better of e-means's two batch laws for that configuration. The results page has every table with error bars, held-out loss, wall-clock time on GPU and CPU, the Deep-10M run and the ablations.

h-means train loss relative to the best e-means at 5 passes, every configuration

Negative is h-means better. Bars show ± one standard deviation over seeds. Hover for the numbers.

Library and code

The repository ships a scikit-learn style estimator with a NumPy backend (the only dependency) and an optional PyTorch backend for CPU, Apple MPS and CUDA. EMeans is the faithful e-means with the same interface.

pip install "git+https://github.com/heldernoid/hmeans.git"                      # NumPy backend
pip install "hmeans[torch] @ git+https://github.com/heldernoid/hmeans.git"     # + PyTorch backend
import numpy as np
from hmeans import HMeans, EMeans

X = np.random.rand(200_000, 64).astype("float32")
km = HMeans(n_clusters=4096, n_passes=5, random_state=0).fit(X)
km.cluster_centers_, km.labels_, km.inertia_
EMeans(n_clusters=4096, n_passes=5).fit(X)

The reproduction page lists the repository layout and the commands that regenerate every table and figure from the logged runs.

Limitations

Citation

@techreport{monteiro2026hmeans,
  title  = {h-means: mini-batch k-means with a hierarchical warm start and Hartigan assignment},
  author = {Monteiro, H\'elder},
  year   = {2026},
  note   = {Technical note. Code, logs and playground: https://github.com/heldernoid/hmeans}
}

References

  1. L. Bessa et al. e-means: outperforming k-means in one-tenth the epochs. arXiv:2611.09501, 2026. Code in faiss, contrib/e_means. Site: e-means.github.io.
  2. J. A. Hartigan and M. A. Wong. Algorithm AS 136: A k-means clustering algorithm. Applied Statistics 28(1), 1979.
  3. S. P. Lloyd. Least squares quantization in PCM. IEEE Transactions on Information Theory, 1982.
  4. J. MacQueen. Some methods for classification and analysis of multivariate observations. Berkeley Symposium, 1967.
  5. D. Sculley. Web-scale k-means clustering. WWW 2010.
  6. D. Arthur and S. Vassilvitskii. k-means++: the advantages of careful seeding. SODA 2007.