KEOClustering benchmark

← Back to KEO

Rethinking K-Means: How e-Means and o-Means Reduce Clustering Computation

· 42 min read

How incremental centroid updates and approximate nearest-centroid search can reduce the computational cost of clustering, tested on 1.18 million GloVe embeddings, three more embedding datasets and one physics dataset.

Contents

We set out to answer one question: Can we obtain the clustering quality of 25 iterations of Lloyd’s k-means algorithm using only around two passes over the dataset?

Our preliminary results suggest that this is possible on all four datasets we tested (GloVe-100, NYTimes-256, Fashion-MNIST and GIST-960), though the number of passes needed varies from about 1.4 to 3.2. More interestingly, on GloVe-100 our reconstruction of o-means achieves comparable clustering quality with substantially fewer distance computations than e-means at larger cluster counts. That saving did not carry over to the other embedding datasets (section 11). On a fifth, very different dataset (HIGGS, 11 million collision events described by 28 physics features) e-means also matched Lloyd’s quality in well under 25 passes, but across seeds it needed anywhere from 1.3 to 3.1 (section 11.4).

There are, however, important distinctions between reducing the number of passes, reducing computational work, and reducing actual wall-clock time. These are three different performance objectives, and our results provide evidence for each to varying degrees.

In this post we explain the two algorithms, derive the computational costs, describe how we ran the benchmark (in detail on GloVe-100, then repeated on three more datasets), and separate what our data supports from what still needs validation.

1. Why conventional k-means becomes expensive

Before examining e-means and o-means, it is useful to understand why the conventional k-means algorithm becomes computationally expensive when the number of clusters grows.

1.1 The clustering problem

Suppose we have a dataset containing \(n\) vectors, each represented in a \(d\)-dimensional feature space:

$$ X = \{x_1,x_2,\ldots,x_n\}, \quad x_i\in\mathbb{R}^d $$

Our objective is to partition these vectors into \(k\) clusters.

Each cluster is represented by a centroid:

$$ C = \{c_1,c_2,\ldots,c_k\} $$

The centroid is the representative point of its cluster.

For standard Euclidean k-means, the objective is to minimize the average squared distance between every observation and its nearest centroid:

$$ J(C)=\frac{1}{n}\sum_{i=1}^{n} \min_{1\leq j\leq k} \|x_i-c_j\|_2^2 $$

Here:

This is the objective we measure throughout.

The computational challenge is that every observation must be compared against all \(k\) centroids to determine its cluster assignment.

1.2 Lloyd’s algorithm: two alternating operations

The conventional implementation of k-means generally uses Lloyd’s algorithm, which repeatedly performs two operations.

Operation 1: Assignment step

For each vector, identify its nearest centroid:

$$ a(i)=\underset{j\in\{1,\ldots,k\}}{\arg\min} \|x_i-c_j\|_2^2 $$

This assigns each observation to one cluster.

Operation 2: Centroid update step

Once assignments are calculated, recompute each centroid as the arithmetic mean of the observations assigned to it:

$$ c_j = \frac{1}{|A_j|} \sum_{x_i\in A_j}x_i $$

Where \(A_j\) represents the observations assigned to cluster \(j\).

These two operations repeat until convergence or until a predefined iteration budget is exhausted.

Diagram of Lloyd’s k-means: an assignment step (assign each point to its nearest centroid) and an update step (move each centroid to the mean of its points), repeated until convergence or the iteration budget is used.

Figure 1. Lloyd’s k-means: an assignment step and an update step, repeated.

1.3 Why does the assignment step dominate?

The assignment operation requires comparing every vector against every centroid.

The number of vector-centroid comparisons per full pass is:

$$ W_{\text{Lloyd}}=n\times k $$

Each comparison also requires computing a distance across \(d\) dimensions.

Consequently, the assignment complexity is:

$$ O(nkd) $$

In our experiment at k = 16,384:

ParameterValue
Number of vectors (\(n\))1,183,514
Dimensions (\(d\))100
Clusters (\(k\))16,384
Vector-centroid comparisons19,390,693,376

That is approximately 19.39 billion distance evaluations per full assignment pass.

An important distinction: 19.39 billion is the number of vector-centroid comparisons, not the number of individual floating-point operations. Each distance evaluation itself processes 100 dimensions.

For 25 iterations, the algorithm performs approximately:

$$ 25\times n\times k $$$$ \approx 484.77\text{ billion distance evaluations} $$

This explains why even a relatively modest dataset can become computationally expensive when the number of clusters reaches tens of thousands.

The problem becomes particularly relevant in:

The e-means paper also names retrieval, compression, image segmentation, and data curation as important applications of k-means.

2. Understanding e-means: replacing full-pass updates with exponential moving averages

The first major algorithm examined in this experiment is e-means.

The underlying research paper is:

e-means: outperforming k-means (in one-tenth the epochs) by Swann Bessa, Pierre-Emmanuel Mazaré, Gergely Szilvasy, Hugo Touvron, David Picard, Matthijs Douze, and Hervé Jégou, published as an arXiv preprint in November 2026.

The central idea is to improve the optimization process rather than repeatedly recomputing every centroid using the entire dataset.

2.1 The limitation of full-batch centroid updates

In Lloyd’s algorithm, a centroid is updated only after processing the complete dataset.

Imagine processing 1.18 million vectors:

  1. Assign all vectors to their nearest centroids.
  2. Accumulate the sums and counts.
  3. Recalculate all centroids.
  4. Begin the next iteration.

This means that centroid positions remain unchanged throughout the entire assignment pass.

However, there is no fundamental requirement that centroid updates must wait until every observation has been processed.

This is where mini-batch optimization becomes useful.

2.2 Mini-batch processing

Instead of processing the entire dataset as one unit, divide it into smaller batches.

Let:

$$ \mathcal{B}_t=\{x_1,x_2,\ldots,x_B\} $$

where \(B\) is the mini-batch size.

For every batch, the algorithm:

  1. Assigns vectors to their nearest centroids.
  2. Calculates the number of observations assigned to each centroid.
  3. Calculates the sum of vectors assigned to each centroid.
  4. Updates centroid statistics.
  5. Continues with the next batch using the updated centroids.

Unlike Lloyd’s algorithm, centroid statistics are updated multiple times during one pass through the dataset.

This produces substantially more frequent optimization updates.

2.3 Exponential moving average (EMA)

The important mathematical component of e-means is its use of exponential moving averages.

Rather than directly storing only the latest centroid, maintain two quantities for every cluster:

For a new batch, define:

$$ n_j^{(t)} = |\{x_i\in\mathcal{B}_t:a(i)=j\}| $$

And:

$$ s_j^{(t)} = \sum_{x_i\in\mathcal{B}_t:a(i)=j}x_i $$

The running statistics are updated using:

$$ N_j^{(t)} = (1-\alpha_t)N_j^{(t-1)} +\alpha_t n_j^{(t)} $$$$ S_j^{(t)} = (1-\alpha_t)S_j^{(t-1)} +\alpha_t s_j^{(t)} $$

The resulting centroid is:

$$ c_j^{(t)}=\frac{S_j^{(t)}}{N_j^{(t)}} $$

Here, \(\alpha_t\) is the update coefficient.

A larger value makes the latest batch more influential. A smaller value gives greater weight to historical statistics.

The e-means paper expresses this using a decay parameter \(\gamma_t\):

$$ \gamma_t=1-\alpha_t $$

The two formulations are equivalent.

2.4 Why maintain both sums and counts?

Consider a cluster that receives 100 observations in one batch.

Suppose the sum of those observations is:

$$ s_j=[200,400] $$

The batch mean is:

$$ \mu_j=[2,4] $$

Now suppose another batch contains only 10 observations, with a sum of:

$$ s_j=[50,20] $$

Its mean is:

$$ \mu_j=[5,2] $$

If we simply average the two batch means, both batches receive equal importance, despite containing different numbers of observations.

Maintaining the sum and count statistics allows the algorithm to preserve the relative contribution of cluster assignments through its EMA state.

This is an important implementation detail: the centroid is derived from the ratio of two moving statistics, not simply from an EMA of batch means.

2.5 Connection to vector quantization and VQ-VAE

EMA-based centroid updates are not an entirely new concept.

A related approach appears in Vector Quantized Variational Autoencoders (VQ-VAE), where codebook embeddings are updated using moving averages of assigned latent vectors.

The important distinction is the optimization objective.

VQ-VAE uses EMA to track a changing latent representation distribution. The e-means research adapts this mechanism to optimize the canonical k-means objective on a fixed dataset.

The paper explicitly builds on this connection and modifies the update procedure for the clustering problem.

2.6 Why does e-means need a learning-rate schedule?

A mini-batch algorithm introduces a trade-off.

If the update coefficient is too large:

If the update coefficient is too small:

The e-means paper uses a decaying update schedule based on a cosine curve.

The initial update coefficient is derived from the problem configuration, including:

The authors derive empirical scaling laws to select these parameters rather than requiring a separate manual hyperparameter search for every dataset.

A simplified conceptual representation is:

$$ \alpha_t = \alpha_0 f(t,T) $$

where \(f(t,T)\) decreases over the training schedule.

The actual implementation uses a cosine-based schedule and additional algorithm-specific mechanisms.

2.7 Dead-cluster revival

Another important issue in clustering is the possibility of empty or nearly empty clusters.

A centroid may receive very few observations, making its position unreliable.

The e-means implementation includes a cluster-revival mechanism that can split a populated cluster to revive an underused centroid.

This helps prevent the algorithm from wasting cluster capacity.

The paper also includes a finalization step that recomputes centroids using the assignments from the final training pass. This improves the final training objective without requiring another complete assignment pass.

2.8 Why can e-means converge in fewer passes?

The key distinction is the frequency of updates.

Lloyd’s k-meanse-means
Updates centroids after a full passUpdates statistics after each mini-batch
Uses full-dataset assignment iterationsUses mini-batch assignment
Centroids remain fixed within a passCentroids change within a pass
Conventional mean-based updatesEMA-based running statistics
Standard iterative optimizationScheduled mini-batch optimization

A pass through the dataset is therefore not equivalent to one optimization step.

This distinction is essential when interpreting our results.

Two passes of e-means do not mean that the algorithm performed only two centroid updates. It may have performed many hundreds or thousands of mini-batch updates within those passes.

3. Understanding o-means: reducing the cost of nearest-centroid assignment

e-means reduces the number of full dataset passes needed to achieve a target clustering quality.

However, it still performs exhaustive nearest-centroid searches.

This means every vector must be compared against all \(k\) centroids.

At large values of \(k\), this remains expensive.

The second method we tested is o-means.

Its central objective is different:

Instead of making every nearest-centroid search exhaustive, reduce the number of candidate centroids that must be evaluated.

3.1 The nearest-centroid search bottleneck

For a vector \(x_i\), conventional k-means calculates:

$$ d_j=\|x_i-c_j\|_2^2 $$

for every centroid \(j\).

The selected cluster is:

$$ a(i)=\arg\min_j d_j $$

When \(k=32,768\), every observation potentially requires 32,768 distance evaluations.

Doing this for more than one million vectors creates a substantial computational workload.

However, most centroids may be relatively far away from a given observation.

This creates an opportunity for approximate search.

Our reconstruction of o-means uses a small index to narrow down the candidate centroids.

A useful conceptual way to understand this design is through a coarse-to-fine search structure.

First, organize the centroids into groups or coarse regions.

Then, for each input vector:

  1. Search for nearby coarse regions.
  2. Select a subset of candidate groups.
  3. Retrieve the centroids belonging to those groups.
  4. Calculate exact distances within the selected candidates.
  5. Assign the vector to the closest candidate centroid.

Diagram of an IVF index search: a query vector is compared with five cluster centroids, the two nearest clusters are selected, and the nearest neighbour is searched for only inside those two clusters.

Figure 2. Coarse-to-fine search in an inverted-file (IVF) index. Image: Zilliz/Milvus, from “A Brief Introduction to the ScaNN Index and How It Improves IVFPQ”.

This resembles the general principle used in inverted-file (IVF) indexing for approximate nearest-neighbor search.

An important qualification: the authors’ o-means needs CUDA and could not run on our machine, so we reconstructed it from the project page. The index structure, probing policy and candidate-selection procedure of the original may differ from ours, and we cannot verify that they match.

Treat this description as the general search principle, not as a verified account of the original implementation’s internals.

3.3 The trade-off: search recall versus computational cost

Approximate search introduces an important risk.

The nearest centroid in the complete centroid set may not be present in the candidate subset.

Define:

$$ a_{\text{exact}}(x) = \arg\min_{j\in\{1,\ldots,k\}} \|x-c_j\|^2 $$

And:

$$ a_{\text{approx}}(x) = \arg\min_{j\in S(x)} \|x-c_j\|^2 $$

where \(S(x)\) is the subset of centroids selected by the search index.

If:

$$ a_{\text{approx}}(x)\neq a_{\text{exact}}(x) $$

the approximate assignment differs from the exhaustive assignment.

We measured the following mismatch rates at \(k=16,384\):

Training passesAssignment mismatch
14.6%
32.6%

These numbers indicate that the approximate search becomes more consistent with exhaustive assignment as training progresses.

However, an assignment mismatch does not necessarily mean that the final clustering is worse.

Two different centroids may be almost equally close to a vector. Choosing the second-best centroid can change the assignment without substantially changing the objective.

Conversely, a small number of missed assignments can still have a meaningful effect if those assignments involve vectors near important cluster boundaries.

Therefore, two metrics should be evaluated independently:

This is particularly important when approximate search is integrated into an iterative optimization algorithm.

3.4 Why the approximation can become more attractive as k increases

Suppose the index allows us to inspect only a fraction \(p\) of the centroids.

The approximate assignment workload becomes:

$$ W_{\text{approx}}\approx pnk $$

instead of:

$$ W_{\text{exact}}=nk $$

Ignoring index maintenance and other overhead, the reduction in distance evaluations is approximately:

$$ 1-p $$

For example, if the algorithm evaluates 13.3% of the centroids, it avoids approximately 86.7% of the exhaustive distance calculations.

The actual savings will be lower because maintaining the index also requires computation.

These fractions are not a property of k itself. They come from the default index settings we used for each k (32/16, 128/16 and 256/24 groups / groups probed), which give nominal search fractions of 50.8 %, 13.3 % and 10.2 %. A different probe count at k = 4,096 would change the picture, and we did not tune it.

This is why we measure total work rather than simply reporting the nominal candidate fraction.

4. Our experiment: 1.18 million GloVe vectors on an Apple M4

Our dataset is GloVe-100 as packaged by ann-benchmarks (glove-100-angular): 1,183,514 training vectors with 100 dimensions each, plus 10,000 query vectors that we split evenly into validation and test sets (seed 0) after removing exact duplicates of training vectors. All vectors are L2-normalised, so every distance in this post is between unit vectors.

4.1 What are GloVe embeddings?

GloVe stands for Global Vectors for Word Representation.

It is an unsupervised word representation method developed by Jeffrey Pennington, Richard Socher, and Christopher Manning.

Unlike a simple one-hot representation, a GloVe embedding represents a word as a dense numerical vector.

Words with related distributional properties can occupy nearby regions of the embedding space.

The original GloVe method learns representations from global word-word co-occurrence statistics.

Its objective is based on weighted least-squares reconstruction of word co-occurrence information.

For this experiment, the important point is that each word is represented by a vector in:

$$ \mathbb{R}^{100} $$

We then cluster these vectors.

4.2 Experimental configuration

ParameterConfiguration
DatasetGloVe-100
Observations1,183,514
Dimensions100
Sourceann-benchmarks glove-100-angular
PreprocessingL2-normalised
Held-out data10,000 ann-benchmarks queries split into validation and test (seed 0); one fixed test set for every method
Initialisationk randomly chosen training rows (seeded)
e-means batch sizeset by the paper’s scaling law: 16,384 to 262,144 rows, depending on k and passes
o-means search (our reconstruction)coarse groups / groups probed: 32/16 (k = 4,096), 128/16 (k = 16,384), 256/24 (k = 32,768); library defaults, not tuned
CPU threadstorch threads recorded: 4 (of 10 logical CPUs)
Cluster counts4,096; 16,384; 32,768
Random seeds0, 1, 2
HardwareApple M4
Memory24 GB
ExecutionCPU only
Python3.12.9
PyTorch2.15.0
FAISSfaiss-cpu 1.16.0
Experiment packagekeo 0.1.4
Experiment cells252
Failed runs0

We compare four implementations:

  1. Conventional Lloyd k-means.
  2. e-means reimplementation.
  3. Official FAISS e-means implementation.
  4. Reconstructed o-means implementation.

In the o-means row, the first number is how many coarse groups the centroids are split into and the second is how many groups are searched for each vector. They give nominal search fractions of 50.8 %, 13.3 % and 10.2 % of an exact search.

The distinction between the last two implementations matters. The authors’ o-means needs CUDA and was not available for our CPU experiment, so every o-means result in this post comes from our own reconstruction, not from the original implementation.

4.3 Why test different cluster counts?

We use three cluster counts:

$$ k\in\{4096,16384,32768\} $$

This is important because the performance characteristics of the algorithms may change with the number of clusters.

For example:

Testing different values of \(k\) helps reveal whether the algorithm’s efficiency improvements are dependent on the clustering configuration.

4.4 Why use three random seeds?

K-means is sensitive to initialization.

Different initial centroid configurations can produce different local minima and final objective values.

Using three seeds provides an initial indication of variability.

However, three seeds are insufficient to establish strong statistical confidence.

The median and range are useful descriptive statistics, but they do not establish statistical significance.

This limitation becomes important when interpreting small improvements such as 0.1% or 0.2%.

5. Understanding the evaluation metrics

Before comparing the results, it is important to understand what we actually measure.

5.1 Mean squared error

The primary quality metric is the mean squared distance to the nearest centroid:

$$ MSE = \frac{1}{n} \sum_{i=1}^{n} \min_j\|x_i-c_j\|_2^2 $$

Lower MSE indicates a better solution under the chosen Euclidean k-means objective.

We use Lloyd k-means after 25 iterations as our reference point.

Let:

$$ MSE_{25} $$

represent the reference error.

The relative quality gap is:

$$ G = \frac{MSE_{\text{method}}-MSE_{25}} {MSE_{25}}\times100 $$

Interpretation:

GapMeaning
NegativeBetter than Lloyd@25
ZeroEqual to Lloyd@25
PositiveWorse than Lloyd@25
Between -0.5% and +0.5%Within our tolerance band

The 0.5% tolerance is our own convention, not a universal standard for clustering quality.

5.2 Why use held-out vectors?

A clustering algorithm can perform well on the vectors used during training but generalize differently to unseen observations.

A held-out evaluation helps determine whether the learned centroids represent the broader embedding distribution.

We report test MSE on held-out vectors. The test set is half of the 10,000 query vectors that ship with the dataset (the other half is validation), after removing exact duplicates of training vectors. The split uses a fixed seed, so every method is scored on the same test set.

5.3 Passes versus distance computations

This is arguably the most important distinction in this post.

A pass measures how much of the dataset an algorithm processes.

A full-scan equivalent measures the number of distance evaluations relative to exhaustive Lloyd assignment.

Define:

$$ W_{\text{scan}} = \frac{\text{Total distance evaluations}} {n\times k} $$

One full scan corresponds to \(n\times k\) distance evaluations.

For exhaustive e-means, one pass is approximately one full scan.

For approximate o-means, one pass can be substantially cheaper.

Therefore:

An algorithm can require more passes but still perform less total computational work.

This explains why reporting convergence in passes alone would be insufficient to establish the computational advantage of o-means.

6. Results: How many passes are actually needed?

The first major result concerns the number of passes required to reach the quality of Lloyd k-means after 25 iterations.

For each method we interpolate between budgets to find the number of passes at which its relative test MSE crosses 0, that is, where it matches Lloyd@25. This is stricter than entering the ±0.5% band.

6.1 Convergence comparison

Gap to k-means after 25 iterations against passes over the data, in three panels for k = 4,096, 16,384 and 32,768.

Figure 3. Relative test MSE against Lloyd@25 as a function of dataset passes. Blue represents Lloyd k-means, orange represents e-means, and green represents reconstructed o-means. Hollow markers indicate the authors’ FAISS implementation; filled markers indicate our implementation. The title baked into the image says both methods need 1.5 passes; that does not hold for our e-means at k = 32,768 (+0.58 % at 1.5 passes).

The reported median results are:

Algorithmk = 4,096k = 16,384k = 32,768
e-means (ours)1.931.911.78
e-means (authors)2.111.711.47
o-means (reconstruction)1.961.821.44

Values are the interpolated passes at which relative test MSE crosses 0 (matches Lloyd@25), median over 3 seeds.

The first observation is that both e-means and the reconstructed o-means achieve the reference quality with substantially fewer passes than Lloyd’s algorithm.

At \(k=16,384\):

At \(k=32,768\), reconstructed o-means reaches the target in approximately 1.44 passes.

These results support the hypothesis that mini-batch EMA optimization can substantially reduce the number of dataset passes required for this particular clustering workload.

6.2 Why does Lloyd k-means remain behind?

The reported quality gaps for conventional Lloyd k-means are:

Lloyd iterationsk = 4,096k = 16,384k = 32,768
5+1.15%+0.73%+0.44%
10+0.41%+0.27%+0.11%

The gap becomes smaller as Lloyd performs more iterations.

This is expected: repeated assignment and centroid-update operations progressively optimize the objective.

However, the important observation is that even after ten iterations, Lloyd has not reached the reference quality defined by its own 25-iteration result within our tolerance at the tested cluster counts.

The mini-batch algorithms achieve that target in considerably fewer dataset passes.

6.3 An important implementation discrepancy

The convergence table should not be interpreted as showing that every implementation behaves identically.

At \(k=32,768\), our e-means implementation is still approximately +0.58% worse than Lloyd@25 at 1.5 passes.

The authors’ e-means implementation is approximately -0.05% at the same budget.

This is outside our parity threshold and is an important qualification.

We think differences in fractional-pass scheduling are the likely explanation, and we examine them later.

7. Computational efficiency: Why o-means is particularly interesting

The convergence results show that both methods reduce the number of passes.

But convergence alone does not explain the computational advantage.

The next question is:

How much actual distance-computation work does each algorithm perform to achieve the same clustering quality?

7.1 Full-scan equivalents

Recall that:

$$ W_{\text{scan}}= \frac{D_{\text{total}}}{n\times k} $$

where \(D_{\text{total}}\) is the total number of vector-centroid distance evaluations.

For conventional exhaustive search, one pass corresponds approximately to one full scan.

For approximate search, the number of comparisons can be significantly lower.

7.2 Work required to reach Lloyd@25

Gap to k-means after 25 iterations against work in full scans of the data, in three panels.

Figure 4. Relative test MSE against computational work, measured in equivalent exhaustive distance-computation scans. The image title (“o-means 0.2, e-means 1.5, k-means 10 full scans”) holds near k = 16,384 only; at k = 4,096 o-means (our reconstruction) needs about 1.1 scans and at k = 32,768 about 0.14.

The reported results are:

Algorithmk = 4,096k = 16,384k = 32,768
e-means (ours)1.921.901.77
o-means (reconstruction)1.100.260.14
o-means / e-means57%14%8%

The results reveal a significant difference between the two methods.

At \(k=16,384\), reconstructed o-means requires approximately 0.26 full-scan equivalents, compared with 1.90 for e-means.

The relative computational work is:

$$ R=\frac{0.26}{1.90} $$$$ R\approx0.137 $$

This corresponds to approximately 86.3% fewer distance evaluations.

At \(k=32,768\):

$$ R=\frac{0.14}{1.77} $$$$ R\approx0.079 $$

This corresponds to approximately 92.1% fewer distance evaluations.

Key finding: At the larger cluster counts, reconstructed o-means reaches comparable clustering quality with approximately 8–14% of the distance-computation work of e-means.

This is a particularly interesting result because the improvement comes from reducing the search space, rather than merely optimizing the arithmetic performed during exhaustive search.

7.3 Why does o-means perform differently at different k values?

The relative savings are not constant.

At \(k=4,096\), reconstructed o-means uses approximately 57% of e-means’ distance-computation work.

At \(k=16,384\), this falls to approximately 14%.

At \(k=32,768\), it falls further to approximately 8%.

There are two important factors:

First: Search-space size.

As the number of centroids increases, exhaustive nearest-centroid search becomes more expensive.

A coarse search structure can become increasingly valuable because it avoids examining large portions of the centroid set. In our runs this is confounded with the default settings, which probe a smaller share of centroids at larger k, so we cannot separate the effect of k from the effect of those settings.

Second: Convergence budget.

The reconstructed o-means implementation also reaches the target quality in fewer passes at the larger cluster counts.

Thus, its total work advantage combines two improvements:

  1. Fewer centroid comparisons per observation.
  2. Fewer passes needed to achieve the target quality.

It would be incorrect to attribute the entire improvement to approximate nearest-centroid search alone.

7.4 The hidden cost of maintaining an index

An approximate search structure is not free.

When centroids move during training, their index may need to be updated.

We therefore include index-maintenance work in the o-means cost.

Share of e-means’ work that o-means (our reconstruction) performs at the same number of passes, in three panels.

Figure 5. Reconstructed o-means computational work as a fraction of e-means, including index maintenance, compared with the fraction of exhaustive centroid comparisons. The image title (“about 16 %”) describes the middle panel only; the share is 54–62 % at k = 4,096 and 10–14 % at k = 32,768.

The reported cost ratios are:

Cluster countTotal o-means work / e-means
4,09654–62%
16,38413–18%
32,76810–14%

An interesting observation appears at \(k=4,096\).

The nominal candidate-search fraction is approximately 50.8%, but the measured total work is approximately 53–62%.

The difference is attributable to additional overhead, including index maintenance.

At larger cluster counts, the relative overhead becomes much less significant.

This is a common systems-engineering trade-off: an optimization that introduces fixed or auxiliary costs becomes more attractive as the primary workload grows.

8. Wall-clock performance on the Apple M4

Distance-computation counts provide a hardware-independent way to compare the algorithms’ workloads.

However, most engineers ultimately care about elapsed time.

We therefore also record wall-clock training time.

8.1 Benchmark results

Gap to k-means after 25 iterations against seconds to train; top row our code, bottom row the authors’ faiss code.

Figure 6. Relative test MSE against elapsed training time. The upper row represents our implementations, while the lower row represents the authors’ FAISS implementations. The image title’s 6.1 s, 13.3 s and 106.2 s are k = 16,384 numbers from our code only; never compare the two rows.

At \(k=16,384\), our implementation measures:

MethodTraining budgetTime
e-means1.5 passes13.3 seconds
o-means reconstruction1.5 passes6.1 seconds
Lloyd k-means10 iterations106.2 seconds
Lloyd k-means25 iterations~266 seconds

These rows are not at equal quality. At 1.5 passes our e-means is +0.49 % and our reconstruction of o-means +0.24 % relative to Lloyd@25, and the 1.5-pass points are also affected by the fractional-pass scheduling discrepancy. We therefore do not turn them into a speedup ratio.

For an equal-quality comparison within our code at k = 16,384: e-means beats Lloyd@25 at 2 passes (−0.12 %), which takes 17.8 seconds, while Lloyd@25 takes about 266 seconds. The 6.1 seconds for our reconstruction of o-means reflects fewer distance computations on a CPU, not the GPU design it targets.

8.2 Why wall-clock results require caution

We ran the experiment on an Apple M4 laptop CPU with some background applications open at low load and uncontrolled thermal conditions.

This introduces several sources of measurement variability:

Additionally, the authors’ FAISS code and our implementation must be treated as separate benchmark groups.

For the same reason, we never compare numbers across the two software rows.

8.3 Does this establish that o-means is faster on GPUs?

No.

We tested our reconstruction of o-means on a CPU only.

The authors’ o-means implementation needs CUDA, so we could not run it.

This matters because GPU performance depends on more than the number of arithmetic operations.

Relevant considerations include:

An algorithm that performs fewer distance evaluations may still have an unfavorable GPU execution profile if its index introduces irregular memory access or synchronization overhead.

The strongest conclusion supported by this experiment is that reconstructed o-means performs fewer distance evaluations on the tested workload.

Its GPU speed advantage remains unverified.

9. Generalization: Does training quality transfer to unseen vectors?

A clustering method should not simply optimize its training subset.

It should also produce centroids that represent the broader data distribution.

We investigate this with training-versus-test quality comparisons.

9.1 Understanding the train-versus-test plot

Gap on new data against gap on training data for each setting, with a diagonal marking equality.

Figure 7. Relative clustering error on the training subset versus held-out observations. The diagonal represents equal training and test gaps.

The interpretation is straightforward:

We find that, at \(k=16,384\) and \(k=32,768\), the low-pass e-means and o-means results appear below the diagonal.

At \(k=4,096\), the results are closer to the diagonal.

This is an interesting observation, but it should not be interpreted as proof that approximate clustering improves generalization.

There are several possible explanations:

  1. The training subset may not perfectly represent the complete dataset.
  2. The training and evaluation measurements may have different sampling variability.
  3. The clustering algorithms may respond differently to the sampled subset.
  4. The approximate search may introduce an optimization trajectory that produces different centroids.

Our data does not establish which explanation is responsible.

More importantly, the training diagnostic uses a fixed 200,000-row subset. The resulting gap should therefore be treated as qualitative evidence rather than a precise generalization measurement.

10. Reproducibility: Does the e-means reimplementation match the authors’ implementation?

A research reproduction is only useful when its implementation matches the algorithm it claims to reproduce.

This is particularly important for e-means because we ran both the authors’ FAISS implementation and our own reimplementation.

10.1 Why implementation parity matters

Even if two implementations use the same underlying mathematical update rule, they may produce different results because of:

We set a parity tolerance of ±0.5% relative to the authors’ implementation.

10.2 Reported parity results

Difference in test error between our e-means and the authors’ e-means for each pass setting.

Figure 8. Relative difference between our e-means implementation and the authors’ FAISS implementation. The grey region represents the accepted ±0.5% tolerance. The image title (“up to 1 %”) is true only at fractional pass counts (1.5 and 12.8) and k = 32,768.

Settingk = 4,096k = 16,384k = 32,768
1.5 passesWithin 0.12%+0.26%+0.63%
12.8 passesWithin 0.12%+0.40%+0.94%

The implementation agrees reasonably well for integer pass counts.

Integer settings of 1, 2, 3, 5 and 8 passes agree within 0.26% for every seed.

However, fractional settings produce larger discrepancies.

At \(k=32,768\), the difference reaches +0.94% at 12.8 passes.

This is outside the predefined parity threshold.

10.3 The fractional-pass scheduling issue

We found two implementation differences. Both come from reading the two codebases; we have not isolated either with an experiment.

First: final-pass scheduling.

The authors’ implementation always ends fractional-pass schedules with a complete pass, whereas our reimplementation does not.

This changes the amount of data processed and the sequence of updates.

Second: incomplete batches.

Our implementation drops leftover rows that do not fill a batch.

As a result, a nominal 12.8-pass configuration at \(k=16,384\) processes only approximately 11.3 passes’ worth of rows.

This is a significant issue because a nominal pass budget is not necessarily the same as the actual number of observations processed.

It also helps explain why our convergence curves are not monotonic in some configurations.

10.4 Why non-monotonic convergence matters

For an iterative optimization algorithm, we often expect the objective to improve as more computation is performed.

However, mini-batch optimization is not guaranteed to exhibit monotonic improvement at every intermediate point.

The reason is that centroid updates are influenced by changing batches, update schedules, and approximate assignments.

A larger nominal training budget can sometimes produce a worse final result when the schedule or finalization procedure differs.

In the reported experiment, e-means at \(k=32,768\) achieves a gap of approximately -1.36% at eight passes but -0.58% at 12.8 passes.

This should not be presented as evidence that more training inherently hurts e-means.

The implementation mismatch must first be resolved.

Reproducibility lesson: A mathematically similar implementation is not necessarily an experimentally equivalent implementation.

11. Do the results hold on other datasets?

Everything above uses GloVe-100. A result on one dataset says little about the next one, so after the GloVe run we repeated the same protocol on three more datasets. A fifth dataset, HIGGS, is a different kind of data and is covered separately in section 11.4. None of the four is in the evaluation lists of the e-means or o-means papers.

11.1 What we ran

DatasetVectors (after cleaning)dkn/kEvaluation vectors (val / test)Preprocessingo-means setting (nlist / nprobe, nominal share of exact search)
GloVe-1001,183,5141004,096; 16,384; 32,768289; 72; 365,000 / 5,000L2-normalised32/16, 51%; 128/16, 13%; 256/24, 10%
NYTimes-256289,7612564,096; 16,38471; 183,794 / 3,794L2-normalised32/16, 51%; 128/16, 13%
Fashion-MNIST60,0007842,048295,000 / 5,000none (Euclidean)64/12, 22% (cell_size 32)
GIST-9601,000,0009604,096244492 / 491none (Euclidean)32/12, 38%

All four come from ann-benchmarks and use the same budgets (1 to 12.8 passes for e-means and o-means, up to 25 iterations for Lloyd), three seeds and the same two e-means backends as the GloVe run. The runs finished with no failed cells.

Some choices need stating:

11.2 Cost to match Lloyd@25

The same quantity as in sections 6 and 7: the number of passes, and of full-scan equivalents, at which the median relative test MSE crosses 0 against Lloyd@25. Median over 3 seeds.

Datasetke-means (ours), passese-means (authors), passeso-means, passese-means (ours), scanso-means, scans
GloVe-1004,0961.932.111.961.921.10
GloVe-10016,3841.911.711.821.900.26
GloVe-10032,7681.781.471.441.770.14
NYTimes-2564,0961.981.912.271.911.54
NYTimes-25616,3843.193.104.693.042.24
Fashion-MNIST2,0481.741.361.62†1.720.41†
GIST-9604,0962.542.461.902.491.05

† In one of the three seeds, o-means was already below Lloyd@25 at the smallest budget (1 pass). That seed counts as 1 pass, an upper bound, which pulls the median down.

11.3 What carries over and what does not

e-means reaches Lloyd@25 quality in far fewer than 25 passes on every dataset. The range is 1.4 to 3.2 passes. This is the part of the GloVe result that held up.

How many passes it needs depends on the dataset. GloVe needed 1.5 to 2.1, GIST-960 about 2.5, and NYTimes-256 at k = 16,384 needed 3.1 to 3.2, the highest of any run. We do not know why. NYTimes-256 is the smallest of the large-k cases (n/k = 18) and has many duplicate rows, but we have not tested either as the cause.

Our implementation tracks the authors’ closely. The two differ by 0.07 to 0.38 passes on the new datasets (0.18 to 0.31 on GloVe), and neither is consistently better.

The o-means saving does not generalise. The large saving was specific to GloVe at k ≥ 16,384, where o-means needed 0.26 and 0.14 full scans against 1.90 and 1.77 for e-means. Elsewhere the ratio of o-means to e-means scans was:

Dataset, ko-means scans ÷ e-means scans
GloVe-100, 32,7680.08
GloVe-100, 16,3840.14
Fashion-MNIST, 2,0480.24
GIST-960, 4,0960.42
GloVe-100, 4,0960.57
NYTimes-256, 16,3840.74
NYTimes-256, 4,0960.81

NYTimes-256 at k = 16,384 is the instructive case. It has the same nominal setting as GloVe at k = 16,384 (128 cells, 16 probed, 13% of an exact search), yet o-means needed 4.69 passes against 3.19 for e-means, and the work it actually did was much higher than nominal. At 2 passes it compared against about 30% of the centroids, against 15% on GloVe, and it missed the true nearest centroid for about 8% of points against about 3% on GloVe. So on this dataset the index is both less selective and less accurate. We have not isolated the reason; uneven cell sizes on clumpy data is a hypothesis, not a finding.

The parity gate fails again. Our e-means and the authors’ agree within 0.70% at integer pass counts (worst case NYTimes-256, k = 16,384, 5 passes), which is looser than the 0.26% on GloVe, and differ by up to 1.95% at the fractional budgets 1.5 and 12.8 (Fashion-MNIST). The target was 0.5%. At the median over seeds, the fractional budgets exceed it on Fashion-MNIST (1.1% and 1.8%) and NYTimes-256 at k = 16,384 (1.2% and 1.8%), as on GloVe-100 at k = 32,768, but not on GIST-960 or NYTimes-256 at k = 4,096. The pattern matches the fractional-pass schedule difference described in section 10.3, which we still have not isolated by experiment. On GIST-960 the two agree within 0.64% at every budget.

11.4 A different kind of data: HIGGS

The four datasets above are all embeddings, which is what the e-means paper describes its method for. HIGGS is not. It holds 11 million simulated particle collisions, each described by 28 numbers: 21 low-level measurements (momenta, angles, b-tags) and 7 quantities derived from them. Neither paper evaluates it, so this tests the method outside its stated scope. We report it on its own and never pool it with the embedding datasets.

How 4,096 clusters form on HIGGS (66 s, with sound effects). Every frame is drawn from the benchmark run itself (seed 0): we re-fitted that seed and checked all 20 snapshots against the stored results, which match exactly. The 2-D picture is a squash of the 28 features that keeps 21.6% of the spread, so distances in it are not distances in the data, and the dots are interpolated between measured passes. Dots are deliberately not coloured by cluster, because membership lives in all 28 dimensions.

What we ran. The same budgets and protocol as before, at one k (4,096; n/k is about 2,700), with 3 seeds. Features are z-scored using training statistics only. We held out 22,000 events; after removing 1,139 that also occur in the training set, that leaves 10,430 validation and 10,431 test events. The training set (10,978,000 events) contains 277,559 exact duplicate rows (2.5%), which we kept. o-means used the library defaults (32 cells, 16 probed, about 51% of an exact search on paper). One pass over HIGGS at this k costs about 2.6 times a GloVe-100 pass.

One provenance caveat: the UCI server could not resume an interrupted download of the 2.6 GB file, so we used the OpenML copy of the same 11,000,000 rows. We compared its first rows with the UCI file, not every value.

Datasetke-means (ours), passese-means (authors), passeso-means, passese-means (ours), scanso-means, scans
HIGGS4,0961.731.471.801.690.96

Median over 3 seeds. Across the seeds, e-means (ours) crossed Lloyd@25 at 1.30 to 3.10 passes and o-means at 1.69 to 2.59.

Gap to k-means after 25 iterations against passes over the data on HIGGS at k = 4,096.

Gap to k-means after 25 iterations against work in full scans of the data on HIGGS at k = 4,096.

A note on the first figure: its headline says e-means and o-means “need 1 pass”. That uses a looser rule than the table (within 0.5% of Lloyd@25, instead of crossing 0). On HIGGS the whole e-means and o-means curve sits within about plus or minus 0.5%, so that rule cannot tell the methods apart, and we quote the table instead.

What the data shows:

Are the features used sensibly? We used all 28 as published, z-scored. That is consistent but not what a physicist would necessarily choose. Six of the 28 are azimuth angles, which are uniformly spread and carry no signal on their own, so they add noise dimensions to every distance. Four are b-tags with only three distinct values. The momentum and mass features are heavy-tailed (the largest z-score is about 30), so a few events dominate some distances. None of this invalidates the comparison, which asks how each method compresses this data compared with Lloyd on the same data, but it ties the result to this feature choice. Running without the angle columns, or with a log transform of the momenta, is an obvious next experiment that we have not run.

11.5 What this still does not show

12. What our experiment establishes — and what it does not

The most valuable part of this benchmark is not simply the reported speedup.

It is that we can state its limitations explicitly.

A rigorous technical interpretation should separate demonstrated results from open questions.

12.1 What our experiment supports

Our measurements support the following observations:

  1. e-means can achieve the Lloyd@25 reference quality in approximately 1.4–3.2 passes across the four embedding datasets. On HIGGS (a physics dataset, section 11.4) the median was 1.7 passes, with 1.3 to 3.1 across seeds. On GloVe-100 it took about 1.5–2.1 (about 1.5 for the authors’ implementation at k = 32,768, and about 1.8–1.9 for ours); on NYTimes-256 at k = 16,384 it took about 3.1–3.2.
  2. The reconstructed o-means implementation achieves similar quality in approximately 1.4–2.0 passes on GloVe-100, and in 1.4–4.7 passes across all four datasets.
  3. Reconstructed o-means substantially reduces distance-computation work on GloVe-100 at \(k=16,384\) and \(k=32,768\), and moderately on Fashion-MNIST and GIST-960. On NYTimes-256 the reduction is small (0.74–0.81 of e-means’ work).
  4. Index maintenance introduces measurable overhead, particularly at smaller cluster counts.
  5. Our e-means implementation agrees reasonably well with the authors’ implementation at integer pass counts (within 0.26% on GloVe-100 and within 0.70% on the other datasets).
  6. Within our own code, e-means reaches Lloyd@25 quality far sooner than Lloyd does (about 17.8 seconds at 2 passes against about 266 seconds at k = 16,384). Our CPU timings for o-means are not representative of its intended GPU design, so we draw no speed conclusion from them.

12.2 What remains unverified

LimitationWhy it matters
Only three seedsInsufficient for strong statistical conclusions
Four ann-benchmarks datasets plus HIGGSThe four are image or text-derived; HIGGS is one k on one tabular dataset
Dataset and k vary togetherA difference between datasets cannot be put down to the data alone
CPU-only o-means reconstructionDoes not establish GPU performance
No official o-means runReconstruction may differ from the intended algorithm
Fractional-pass mismatchWeakens some convergence comparisons
No ablation studiesCannot isolate the contribution of individual components
Uncontrolled thermalsReduces confidence in precise timing comparisons
No smaller dataset tiersCannot establish scaling behavior with dataset size (GloVe-100 ran at full size only)
No statistical significance testingSmall differences may reflect random variation

12.3 An important question about the baseline

The reference is Lloyd k-means after 25 iterations, not necessarily the globally optimal clustering solution.

It is also not a converged solution: we did not run Lloyd to convergence. Lloyd itself still improves between iterations 10 and 25 (from +0.41 % to 0 % at k = 4,096, +0.27 % to 0 % at k = 16,384, and +0.11 % to 0 % at k = 32,768), and e-means with more passes ends about 0.6 to 1.5 % below Lloyd@25. Matching Lloyd@25 is therefore a soft bar, chosen for comparability with the 25-iteration convention, not a claim about the best achievable objective.

K-means is a non-convex optimization problem.

Different initializations can lead to different local minima.

Consequently, beating Lloyd@25 does not establish that an algorithm has found the global optimum.

It establishes only that it achieved a lower measured objective than the chosen 25-iteration reference under the specified evaluation protocol.

This distinction is important when presenting the results to a research audience.

13. Further experiments that would strengthen the findings

There are several experiments that would substantially improve the scientific strength of this work.

13.1 Increase the number of random seeds

The immediate next step should be increasing the seed count from three to at least ten.

For every configuration, report:

This would help establish whether the observed improvements are robust to initialization.

13.2 Resolve fractional-pass scheduling

The next priority is to ensure that our and the authors’ e-means implementations process equivalent numbers of observations.

Specifically:

Until this is resolved, fractional-pass parity results should remain provisional.

13.3 Run smaller dataset tiers

The current experiment uses the full 1.18-million-vector dataset.

Smaller dataset sizes should be evaluated to understand how the algorithms scale with \(n\).

This is particularly important because index maintenance may have different relative costs at different dataset sizes.

13.4 Perform o-means ablations

The current o-means results use library-default settings.

A proper ablation study should investigate:

This would reveal which design choices contribute most to the observed improvement.

13.5 Benchmark on GPUs

The most important systems-level follow-up is a GPU comparison.

Ideally, evaluate:

Use the same dataset, initialization, objective, precision, and quality target.

Report both:

$$ \text{Time to target quality} $$

and:

$$ \text{Distance computations to target quality} $$

The distinction matters because algorithmic efficiency and hardware execution efficiency are not interchangeable.

13.6 Evaluate on more kinds of data

Section 11 added NYTimes-256, Fashion-MNIST, GIST-960 and HIGGS. Still untested:

A particularly useful experiment would use an image dataset where the resulting clusters can be inspected visually.

14. Reproduce it

From the repository root:

uv run keo download glove100                 # fetches the dataset and checks its pinned SHA-256
uv run keo run main_glove_tierA              # k = 16,384
uv run keo run main_glove_tierB              # k = 4,096 and 32,768
uv run keo figures main_glove --theme both   # figures and the CSV behind each one

The three extra datasets of section 11 run the same way:

uv run keo download nytimes256
uv run keo download fashionmnist784
uv run keo download gist960
scripts/run_benchmarks.sh                    # runs all three, resumable
python scripts/cross_dataset_table.py        # the table of section 11.2

HIGGS (section 11.4) is converted first from the OpenML copy of the UCI file:

curl -LO https://data.openml.org/datasets/0004/45570/dataset_45570.pq
python scripts/convert_physics_dataset.py dataset_45570.pq \
  --out data/higgs28/higgs28.hdf5 --exclude Target --test-fraction 0.002 --seed 0
uv run keo run bench_higgs28

The converted file’s SHA-256 is pinned in configs/datasets/higgs28.yaml, and two builds from different folders give identical bytes.

Seeds 0, 1 and 2 are set in the experiment config files, and uv.lock pins the Python dependencies.

We ran everything on an Apple M4 (10 logical CPUs, 24 GB), CPU only, with Python 3.12.9, torch 2.15.0, faiss-cpu 1.16.0 and keo 0.1.4. Timings were taken with some background applications open, so treat them as indicative.

15. Conclusion: Two different optimization strategies, one clustering problem

Our experiment looks at two complementary ways to improve large-scale k-means clustering.

e-means changes how centroids are optimized.

By using mini-batch processing and exponential moving averages, it updates centroid statistics more frequently instead of waiting for a complete dataset pass.

o-means, as reconstructed in this experiment, changes how centroid assignments are calculated.

By using an approximate search structure, it avoids evaluating every centroid for every observation.

The two approaches therefore attack different parts of the computational problem.

e-meanso-means (our reconstruction)
What changesHow centroids are updated (mini-batch EMA)How the nearest centroid is found (index search)
Cost it reducesPasses neededDistance computations per pass

Shared objective: achieve a competitive clustering solution with less computational work.

On GloVe-100 at \(k=16,384\), the reconstructed o-means implementation matches Lloyd@25 with approximately 0.26 full-scan equivalents, compared with approximately 1.90 for e-means. That is a substantial reduction in distance-computation work.

The three further datasets tell us how far that result travels. e-means keeps its advantage everywhere: 1.4 to 3.2 passes against Lloyd’s 25. The o-means saving does not: it is large on GloVe-100 at larger k, moderate on Fashion-MNIST and GIST-960, and small on NYTimes-256 (2.24 scans against 3.04 at k = 16,384), where the index was both less selective and less accurate. The GloVe-100 figure is therefore the best case we measured, not a typical one.

The results should remain preliminary.

We have not run the authors’ o-means, we used only three seeds, the parity gate between our e-means and the authors’ fails at fractional pass counts on three of the four embedding datasets (GloVe-100, NYTimes-256 at k = 16,384 and Fashion-MNIST) although it held on HIGGS, and dataset and k vary together. We also have not explained the NYTimes-256 behaviour.

Our next step is not a broader speedup claim; it is to resolve these implementation differences, understand where the o-means index stops helping, increase the statistical coverage, and test other kinds of data and GPU hardware.

The broader engineering lesson is that large-scale clustering performance is not determined by the distance calculation alone.

How frequently you update centroids and how intelligently you search for them can be just as important as optimizing the underlying computation.

References and further reading

These are the most relevant primary and technical resources for understanding this experiment.

1. e-means: outperforming k-means (in one-tenth the epochs) — Swann Bessa et al. (2026). The foundational paper explaining EMA optimization, mini-batch updates, scaling laws, and experimental results.

Read the original e-means research paper (arXiv).

2. FAISS e-means implementation — Official implementation documentation, including centroid updates, configuration, CPU/GPU execution, and distributed training.

FAISS e-means documentation and implementation.

3. GloVe: Global Vectors for Word Representation — Jeffrey Pennington, Richard Socher, and Christopher D. Manning (2014).

Stanford GloVe research and dataset.

4. FAISS: A Library for Efficient Similarity Search and Clustering of Dense Vectors — Relevant background for large-scale vector search and clustering.

FAISS GitHub repository.

5. K-means++: The Advantages of Careful Seeding — David Arthur and Sergei Vassilvitskii (2007). Foundational work on centroid initialization.

Read the k-means++ paper.

6. Web-Scale K-Means Clustering — David Sculley (2010). Foundational work on scalable mini-batch k-means.

Read the mini-batch k-means paper.

7. Neural Discrete Representation Learning — Aaron van den Oord, Oriol Vinyals, and Koray Kavukcuoglu (2017). Introduces VQ-VAE and provides relevant background on EMA-based codebook updates.

Read the VQ-VAE paper.

8. o-means implementation details: The authors’ o-means needs CUDA, so we could not run it, and we found no public paper or repository for it. Our reconstruction is based on the project page; the exact algorithm and its relationship to existing approximate-search methods remain unverified.