e-means

To sort millions of points into groups, the classic k-means reads every point 25 times. e-means moves each group’s centre a little after every small batch, and reaches the same loss in 1.4 to 2.6 passes, 10 to 45 times faster on GPUs.

Press Race. Both methods start from the same centroids and see the same points. Lloyd moves once per pass over the data; e-means moves after every batch. Watch which one finds its shape first. Then we build e-means piece by piece: the loss, the counts and sums, the shrinking step, the revival of dead clusters and the laws that set every knob.

You need a little algebra (a mean, a square, a sum) and some Python for the code. We build the rest from zero, including k-means itself.

Based on 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 (FAIR at Meta; École Nationale des Ponts et Chaussées), 2026. See the authors’ project page and their playground; the library ships in Faiss as contrib/e_means. Every device here is our own code.

Race Lloyd against e-means

Lloyd epoch 0e-means epoch 0.0

Toy data computed live by our own code: 1,600 points in 2-D (1,000 on a phone), k = 16, a 5-epoch budget. Both start from the same 16 random data points. e-means uses the paper’s batch law divided by 8 (B = 16 on a desktop, 8 on a phone), the paper’s step law (α0 ≈ 0.085 and 0.056), the cosine schedule and, at the end, the last-epoch mean; no revival, as in the authors’ 2-D playground. The dashed line is Lloyd after 25 epochs. The paper’s numbers (1.4 to 2.6 epochs, 10 to 45 times) come from Table 4 on real embeddings, not from this toy.

Chapter 0

Why a Forty-Year-Old Algorithm Needed a Rewrite

See where k-means runs today, what one pass over the data costs, and what e-means claims to save

You have 100 million photos. A vision model has turned each one into an embedding: a list of 96 or 1,024 numbers, a point in a space where similar photos sit close together. You want to split these points into 262,144 groups, so that a search can look in a few groups instead of all 100 million points.

The tool for this job has not changed since the 1980s. It is k-means: pick k points called centroids, give every data point to its nearest centroid, then move each centroid to the middle of its points. Repeat. The group of points that share a centroid is a cluster. Think of the centroids as k post offices, and each house sends its mail to the closest one.

Why does this matter so much? Because k-means hides inside a lot of modern machinery. The paper lists clustering, compression, indexing for retrieval, image segmentation and data curation. It also names newer uses: compressing the attention cache of a language model and making attention sparse. When a vector database builds an index, k-means is often the first step.

One pass costs a lot

The standard way to run k-means is Lloyd’s algorithm. One round of it reads every point once. That round is called an epoch, one full pass over the data. Faiss, a widely used search library, runs Lloyd for 25 epochs by default, and the paper uses that run, Lloyd@25, as its yardstick.

What does one epoch cost? Every point is compared with every centroid. Call the length of each vector d (96 or 1,024 here). Each comparison touches all d numbers of both vectors, about 2d arithmetic operations: a subtract and a multiply-add per coordinate. So one epoch is about 2 × n × k × d operations, where n is the number of points.

2 × (108 points) × (262,144 centroids) × (96 numbers) = 5.0 × 1015 operations per epoch (the paper’s 100M-point setting)

Twenty-five epochs make that 1.3 × 1017. At the paper’s largest scale, 10 billion points and 16.7 million centroids, the Lloyd@25 baseline took 6,784 GPU hours on 64 machines (Table 21). The cost is the number of epochs times the cost of one epoch. You can make each epoch faster with better code. e-means attacks the other factor: it needs far fewer epochs.

Two old ideas, both short of the goal

Lloyd moves each centroid once per epoch. It always moves it to the exact middle of its points, so every move is a good one, and the run is guaranteed to settle. But one move per pass over 100 million points is slow progress.

The other family is mini-batch k-means. It reads a small random batch of points, moves the centroids a little, and repeats. With a batch of 1,000 points, one epoch gives 100,000 moves instead of one. It gets going quickly. The paper sums up the record: where mini-batch k-means was compared with Lloyd, it usually ended at a higher error. It also brings two knobs, the batch size and the size of each move, and nobody had a rule for setting them on a new dataset. So in practice people sweep them, and a sweep costs many runs.

e-means is a mini-batch method that keeps the speed and loses the two weaknesses. It ends at a lower error than Lloyd@25. It sets both knobs from a formula, with no sweep. Feel the claim first, in the paper’s own numbers.

Count the passes each method needs

Each row is one embedding dataset from the VIBE benchmark. Blue is the baseline, warm is e-means, both measured to the same target: the test loss of Lloyd@25. Choose what to count, then tap a row.

All numbers are the paper’s Table 11: the eleven VIBE datasets at full size, k = 16√n rounded to a power of two (8,192 or 16,384), medians over 20 seeds. GPU: Flash-KMeans in FP16 against e-means in BF16 on one H100. CPU: Faiss against e-means, both FP32, 64 cores.

Across all eleven datasets, e-means needs between 1.6 and 2.6 epochs to reach what Lloyd reaches in 25. In seconds, that is 8.0 to 22.8 times faster on a GPU and 9.0 to 15.0 times faster on a CPU. The paper’s headline table (Table 4) shows the same picture at larger scales, from a million to a billion points. There, e-means needs 1.4 to 2.6 epochs. It takes 9.5 to 45.5 times less wall-clock time than Flash-KMeans, the fastest GPU k-means the authors found.

The largest run shows what that means in practice. e-means split 10 billion DINO embeddings into 16.7 million clusters and beat the test loss of Lloyd@25 in 2.5 epochs. With an approximate search for the nearest centroid (Chapter 7), the same quality took 23 GPU hours on one machine.

What this lesson builds

e-means is not a new objective. It solves the exact problem Lloyd solves. What changes is how the centroids move. The method has five parts, and each one gets a chapter. You will be able to write the whole thing yourself by the end.

  1. The k-means objective: the loss, the nearest-centroid rule, and why the mean is the best spot.
  2. Lloyd’s loop: why each step can only lower the loss, and how assignment becomes one matrix multiply.
  3. The EMA bank: keep a count and a sum per cluster, and read the centroid off as their ratio.
  4. Shrink the step, then finish: the cosine schedule, and two ways to end a run.
  5. Revive the dead: find centroids that stopped working and split a busy one in two.
  6. Laws for every knob: two formulas that set the batch size and the step from n, k and T.
  7. Scale it up and read the results: IVF search for the nearest centroid, and the paper’s tables.
  8. The playground: race both methods on six point clouds, train and test.
  9. Field guide: the numbers, a checklist, the core code, and how to cite the paper.
The cost of a k-means run is the number of epochs times the cost of one epoch. Which factor does e-means mainly reduce?

Chapter 1

The k-means Objective

Write down what a good set of centroids means, and prove where each centroid should sit

Six houses stand on one long street, at the 1, 2, 3, 7, 8 and 12 kilometre marks. The town can build two post offices. Each house will walk to the closer one. Where should the offices go?

To answer, we need a score. A natural score is the walking distance, but k-means uses the square of the distance. A house 4 km away costs 16, not 4. Squaring punishes a far house much more than a near one. It also makes the maths clean, as you will see in a moment.

The loss, symbol by symbol

Now leave the street and go to d dimensions. Each data point xi is a list of d numbers. The squared distance between two points is the sum, over all d coordinates, of the squared difference. In 2-D, that is (x1 − c1)2 + (x2 − c2)2, the square of the straight-line distance. The paper writes the whole k-means problem as one line (its Equation 1):

MSE(X, 𝒞)
The mean squared error of the data X = {x1, …, xn} under the centroids 𝒞 = (c1, …, ck). This is the one number k-means tries to make small. It is also called the distortion or the loss.
1/n
Divide by the number of points, so the score is an average per point. Without it, a bigger dataset would always look worse.
∑i=1n
Add up one term for every data point, from the first to the n-th.
‖xi − ca(i)‖2
The squared distance from point i to the centroid it belongs to. The double bars mean the length of a vector.
a(i) = argminj
The assignment of point i: the index j of its nearest centroid. “argmin” returns which j gives the smallest value, not the value itself.

So the loss has two kinds of unknowns: the k centroids, and the n assignments. The assignments are not free. Equation 1 fixes them: every point goes to its nearest centroid. Choose the centroids, and the loss follows.

Two facts that make k-means work

Fact 1: for fixed centroids, the nearest-centroid rule is the best assignment. Each point’s term in the sum depends only on its own assignment. Giving a point to a closer centroid lowers its term and leaves every other term alone. So the nearest centroid is the best choice for each point, one point at a time.

Fact 2: for a fixed group of points, the mean is the best centroid. Take the points Aj assigned to centroid j, and ask where c should sit to make f(c) = ∑ ‖x − c‖2 smallest. The slope of f (its gradient, the same idea you use to train a network) is −2 ∑ (x − c). It is zero when ∑ x = |Aj| c, that is, when c is the average of the points. Since f is a bowl (a sum of squares), that flat spot is its bottom.

There is an even more useful way to see Fact 2. For any spot c, the cost splits into two parts:

∑ ‖x − c‖2
What the cluster costs if its centroid sits at c.
∑ ‖x − x̄‖2
The spread of the points around their own mean x̄. No choice of c can change it.
|Aj| ‖x̄ − c‖2
The penalty for missing the mean: the number of points times the squared miss. It is zero only at c = x̄.

The cross term vanishes because the points’ offsets from their mean add up to zero. Keep this split in mind: Chapter 3 uses it to explain why e-means can be slightly off the mean and still do well.

The street, worked by hand

Put the offices at 2 and 8. Houses 1, 2 and 3 walk to 2; houses 7, 8 and 12 walk to 8. The squared distances are 1, 0, 1 and 1, 0, 16.

MSE = (1 + 0 + 1 + 1 + 0 + 16) / 6 = 19 / 6 = 3.17

Now move each office to the mean of its houses. The first group’s mean is (1 + 2 + 3) / 3 = 2, so that office stays. The second group’s mean is (7 + 8 + 12) / 3 = 9, so that office moves from 8 to 9. The second group now costs 4 + 1 + 9 = 14 instead of 17.

MSE = (2 + 14) / 6 = 2.67 (check with the split: 17 = 14 + 3 × (9 − 8)2)

Does any house now want to switch? House 7 is 2 km from the office at 9 and 5 km from the office at 2. It stays. Nothing changes, so these two offices are a resting point.

Cells: what the nearest-centroid rule looks like

In 2-D, the nearest-centroid rule cuts the plane into regions, one per centroid. Every spot in a region is closer to that region’s centroid than to any other. These regions are Voronoi cells. The border between two cells is the line halfway between their centroids, at right angles to the line that joins them. Drag the centroids below and watch the cells, and the loss, respond.

Drag a centroid, watch the loss

Drag any teal centroid. Each thin line joins a point to its nearest centroid, so the lines show the assignment. Then press Move to the means to do Fact 2 for every cluster at once.

Toy data: 60 points from three made-up groups, seeded so they are the same on every visit, with k = 4. The MSE is computed live with Equation 1 in our own code.

Try this. Start from Reset and press Move to the means a few times. The loss falls and then stops. Now drag two centroids into the same group and move to the means again. The loss stops at a higher value. Each step is the best possible for its own job, yet the answer is worse.

The failure mode: a bad resting point

The symptom is easy to spot in 2-D. Two centroids share one dense group, while another group has no centroid of its own and is served from far away. The measurement is the loss: it stops falling, but at a value above the one you would get with one centroid per group.

Why can neither step fix it? The assignment step only reacts to where the centroids are. The mean step only moves each centroid to the middle of the points it already has. Neither step can carry a centroid across empty space to the group that needs it. This is called a local minimum: no small change helps, but a big change would.

The classic fixes are a careful start, called k-means++, which spreads the first centroids apart, and many restarts. Both cost time. e-means has its own answers: the noise of small batches, and a rule that moves idle centroids to busy places (Chapter 5).

Train loss and test loss

One more idea before we move on. The paper mostly reports the loss on held-out points, ones the algorithm never saw. It uses a dataset’s own held-out vectors when it has them; otherwise it removes 20,000 vectors from the training set. It uses half to fit its laws (the validation set) and half to report results (the test set). Why care? A search index keeps receiving new vectors. Good centroids should fit those too, not only the points they were trained on.

A cluster has 4 points whose mean is x̄. Its centroid sits 0.5 units away from x̄. By how much does the cluster’s summed squared error exceed its best possible value?

Chapter 2

Lloyd’s Loop, and Why It Is Slow

Alternate the two facts, prove the loss never rises, and turn the search for the nearest centroid into one matrix multiply

On the street, you did two things by hand: you sent each house to its nearest office, then you moved each office to the mean of its houses. Do that again and again, and you have Lloyd’s algorithm, the full-batch k-means that every library ships. The paper cites Lloyd’s 1982 article for it.

  1. Start from k centroids. A common start is k data points picked at random.
  2. Assign: give every point to its nearest centroid.
  3. Update: move every centroid to the mean of its points.
  4. Repeat steps 2 and 3, for a fixed number of epochs or until nothing changes.

Why the loss can only go down

Write L(𝒞, a) for the loss with centroids 𝒞 and any assignment a, not only the nearest one. Now follow one round.

The assign step keeps the centroids and picks the nearest centroid for every point. By Fact 1 from Chapter 1, that is the best possible assignment, so L(𝒞, anew) ≤ L(𝒞, aold). The update step keeps the assignment and moves each centroid to its mean. By Fact 2, that is the best spot for every centroid, so L(𝒞new, anew) ≤ L(𝒞, anew).

Chain the two inequalities and the loss after a round is never higher than before it. This trick has a name: coordinate descent. You fix one group of unknowns, solve exactly for the other group, then swap.

Why must it stop? There are only finitely many ways to split n points into k groups. The loss never rises, and if it stays equal the assignment stops changing. So the loop cannot cycle forever: it reaches a resting point in a finite number of rounds. That is the guarantee the paper mentions. In practice the count can be large, so libraries cap it. Faiss caps it at 25.

Step through it yourself. The plot on the right records the loss after every half-step, assign and update separately.

Step Lloyd by hand

The start already gives each point to its nearest centroid, so press Update, then Assign, and repeat (the button changes name). Blue squares are the centroids. The staircase on the right gets one step per half-step. Look for a step that goes up: you will not find one.

Toy data: 400 points in 2-D, k = 8, random data points as the start. Our own code; one full epoch is one Assign plus one Update. The loss after Assign uses the old centroids with the new owners.

Notice the shape of the staircase. The first few rounds cut the loss a lot. Then each round helps less and less. On this toy cloud a round costs nothing. On 100 million points, each round is a full pass over the data, and the last rounds still cost as much as the first.

The trick that makes assignment fast

Almost all of the time in k-means goes to the assign step: n points times k centroids, each a d-number comparison. The paper says it plainly: the flops of e-means, like Lloyd’s, are dominated by this step. So it pays to make it fast, and there is a neat algebra trick. Expand the squared distance:

‖x − c‖2
The squared distance from a point to a centroid. Expand (x − c)·(x − c) like (a − b)2 = a2 − 2ab + b2.
‖x‖2
The point’s own squared length. It is the same for every centroid, so it cannot change which centroid wins. Drop it.
2 x·c
The dot product: multiply matching coordinates and add. This is the only term that mixes the point with the centroid.
‖c‖2
The centroid’s squared length. Compute it once per centroid, not once per pair.

A worked check. Take x = (1, 2), c1 = (0, 0) and c2 = (2, 2). Directly, ‖x − c1‖2 = 1 + 4 = 5 and ‖x − c2‖2 = 1 + 0 = 1. With the expansion, ‖x‖2 = 5, x·c2 = 2 + 4 = 6 and ‖c2‖2 = 8.

5 − 2 × 6 + 8 = 1   and   5 − 0 + 0 = 5 (scores without ‖x‖2: −4 and 0, so c2 wins)

Why is this a big deal? Because all the dot products of a batch with all centroids form one matrix multiply, the operation GPUs are built for. Here is the data flow for one batch:

  1. In: a batch X of shape B × d and the centroids C of shape k × d.
  2. Compute X C⊤, shape B × k: every dot product at once, about 2Bkd operations.
  3. Add the k norms ‖cj‖2 along each row, subtract twice the dot products, and take the smallest score in each row: B integers, the assignments.
  4. Scatter-add: for each cluster, count its points (k numbers) and sum them (k × d).

At the paper’s scale, the B × k matrix is too big to store. With B = 65,536 and k = 262,144 it holds 17 billion numbers. So the paper’s GPU code, like Flash-KMeans, walks through the centroids in blocks and keeps only the best centroid found so far for each point. It compares every point with all k centroids; only the order of the work changes.

One engineering detail shows how fragile this trick is. The paper runs the dot products in low precision: number formats with 16 or 8 bits instead of the usual 32 (BF16, FP8 or INT8). They are faster on a GPU but round every value a little. If the norm ‖c‖2 comes from the full-precision centroid but the dot product from the rounded one, the score gains an extra term, ‖c‖2 − ‖ĉ‖2, that differs for each centroid. It can change the winner. The fix is to compute both terms from the same rounded values (Appendix J, Equation 11). With that fix, FP8 and INT8 stay within 0.13% of BF16 in every setting of Table 16.

The failure mode: one move per pass

The symptom is in your staircase. After the first few rounds, each round barely moves the loss. The measurement is in the paper’s Table 5. Flash-KMeans, a fast Lloyd, is still improving between 10 and 25 iterations: on DEEP with a million points, its test loss goes from 3.8997 to 3.8926 (in units of 0.1). Each of those 15 extra epochs costs a full 2nkd.

Look at it from a centroid’s point of view. During one epoch it waits while the code reads every one of the n points, and then it moves once. Most of those points belong to other clusters. Even the points it owns tell it the same thing again and again. What if each centroid moved as soon as it had seen a few of its points? That is the idea of mini-batch k-means, and the next chapter builds the version e-means uses.

In the expansion ‖x − c‖2 = ‖x‖2 − 2x·c + ‖c‖2, which term can a GPU kernel skip when it only needs the nearest centroid, and why?

Chapter 3

The EMA Bank: Counts and Sums

Keep two running numbers per cluster, let old batches fade, and read each centroid off as their ratio

A café owner wants the average tip. Tips arrive one at a time, all day. She does not keep a list. She keeps a running average and nudges it after each tip: new average = old average + (tip − old average) / (number of tips so far).

That is exactly the classic mini-batch k-means of MacQueen (1967) and Sculley (2010). Each centroid is the running mean of every point ever assigned to it. After its 1,000th point, a centroid moves by only 1/1,000 of the gap. The step shrinks as 1 over the count.

On a fixed dataset, this has a flaw. The first points a centroid received were assigned when the centroids were still bad. They count forever, with the same weight as the latest ones. And as the count grows, the centroid nearly freezes, long before it reaches a good place.

Let old batches fade

An exponential moving average (EMA) fixes the first problem. Instead of dividing by the count, it keeps a fixed fraction of the old value and mixes in a fixed fraction of the new one:

m ← γ m + (1 − γ) x

Here γ (gamma) is the decay, a number just below 1. Each update multiplies every old contribution by γ, so a value seen t updates ago carries a weight proportional to γt. With γ = 0.9, a contribution falls to half its weight after about 6.6 updates, since 0.96.6 ≈ 0.5. That count is the half-life. The paper calls 1 − γ the step α (alpha): the fraction of the way the average moves toward the new value.

VQ-VAE models (van den Oord et al., 2017) use this rule to keep their codebooks up to date, and neural audio codecs use it too. e-means borrows it, with one key choice about what to average.

Average the counts and the sums, not the centroid

For every cluster j, e-means stores two numbers: a count Nj and a sum Sj (a vector of d numbers). After each batch, both take an EMA step (Equation 2), using what the batch gave that cluster (Equation 3):

Nj
The cluster’s running count: a smoothed number of points per batch. It is a real number, not an integer.
γ = 1 − α
The decay. It says how much of the past to keep. Chapter 4 makes it change over the run.
nj
How many points of this batch are nearest to centroid j (Equation 3): an integer from 0 to B.
Sj
The cluster’s running sum: a smoothed vector sum of its points, d numbers.
sj
The vector sum of this batch’s points that are nearest to centroid j (Equation 3).
cj = Sj/Nj
The centroid (Equation 4). The paper never stores it: it reads it off as the ratio whenever it needs it.

Why is the ratio a sensible centroid? Unroll the updates. After t batches, the count is a weighted sum of all past batch counts, and the sum is the same weighted sum of all past batch sums:

Nj = γt Nj(0) + ∑b α γt−b nj,b   and   Sj = γt Sj(0) + ∑b α γt−b sj,b

So Sj/Nj is a weighted mean of every point the cluster ever received. A point from batch b gets weight αγt−b: recent points count most. Two facts follow. First, a weighted mean of points always lies among those points, inside their outline. The authors suggest this explains the stability (Appendix E): plain gradient steps can throw a centroid out of that outline at a large step, and an EMA mean cannot. Second, set α = 1 and use the whole dataset as one batch. Then Nj = nj, Sj = sj, and the ratio is the exact mean. That is Lloyd. Lloyd is the special case of e-means with one batch and a full step.

Why not just average the centroid?

A simpler rule would be: c ← γc + α × (mean of this batch’s points). Here is why that is worse, worked by hand with γ = α = 0.5. A cluster starts at c = 5. Batch 1 gives it one point, at 10. Batch 2 gives it nine points, all at 0. The true mean of those ten points is 1.

Centroid EMA: 0.5 × 5 + 0.5 × 10 = 7.5, then 0.5 × 7.5 + 0.5 × 0 = 3.75

Counts and sums: N = 0.5, S = 5 (c = 10); then N = 0.25 + 4.5 = 4.75, S = 2.5 + 0 = 2.5, so c = 2.5 / 4.75 = 0.53

The centroid EMA treats one point and nine points the same. It also lets the random start keep half its weight after one batch. Counts and sums weight each batch by how many points it brought, so the answer, 0.53, lands much nearer the true mean of 1. And when a batch brings no points at all, Nj and Sj both shrink by γ: the ratio does not change, so the centroid stays exactly where it was.

Step through it below. The centroids sit on a line so you can watch the counts and sums directly.

Feed the EMA bank

Points arrive in batches of 10 from three sources on a line. Each warm centroid is its sum divided by its count, shown in the bars below. Press Next batch, slide γ, and turn on the dashed centroid-EMA to compare.

0.90

Toy stream, our own code: sources at −0.6, 0.1 and 0.7 with 60%, 30% and 10% of the points, spread 0.08. Counts start at 10−10 with sums set so S/N returns the start. The wobble is the standard deviation of each centroid over the last 20 batches.

Try γ = 0. Each centroid jumps to the mean of the latest batch, and the rare cluster flickers. Try γ = 0.99: the centroids barely move. A middle value balances speed against noise. That balance is exactly what Chapter 4 tunes over the course of a run.

The start: N = 10−10

Algorithm 1 begins with k random data points as centroids, cj(0). It sets Nj = 10−10 and Sj = Nj cj(0). Then S/N returns the start exactly, and the start weighs almost nothing. After the first batch that gives cluster j some points, the start’s weight is about 10−10 against αnj.

What breaks with other choices? With N = 0, the ratio is 0/0 and the centroid has no value at all. With N = 1, the random start counts like one real point and pulls the centroid back for many batches. The tiny value gives the best of both.

One batch as data flow

# X_b: (B, d) batch   N: (k,) counts   S: (k, d) sums   alpha: this batch's step
C = S / N[:, None]                                # (k, d) read the centroids off
a = (np.sum(C*C, 1) - 2 * X_b @ C.T).argmin(1)      # (B,) nearest centroid per point
n = np.bincount(a, minlength=k)                        # (k,) batch counts, Eq. 3
s = np.zeros_like(S); np.add.at(s, a, X_b)               # (k, d) batch sums, Eq. 3
N = (1 - alpha) * N + alpha * n                         # Eq. 2
S = (1 - alpha) * S + alpha * s

The memory cost is one sum per cluster: k × d numbers. At the paper’s largest run, 16.7 million clusters of 1,024 numbers, those sums take 64 GiB in 32-bit floats. That is one reason the largest runs spread the work over many GPUs (Appendix M).

The failure mode: a step that never settles

The symptom: with a fixed step, the centroids keep wobbling around the right place and never stop. The measurement: the wobble read-out above stays above zero however long you run. With γ = 0.9, each centroid always gives the latest batch a 10% say, so batch noise keeps pushing it. The fix is to shrink the step as the run goes on, which is the subject of the next chapter.

A batch gives cluster j no points at all. What happens to its centroid under e-means?

Chapter 4

Shrink the Step, Then Finish

Anneal the EMA step on a cosine, count the updates a run makes, and choose how the final centroids are read out

Think of parking a car. Far from the space, you drive at a normal speed. Near it, you creep. If you kept the normal speed to the end, you would overshoot, back up, and overshoot again. If you crept from the start, you would arrive at nightfall.

The EMA step has the same trade. A large step moves the centroids quickly but lets every noisy batch shove them around. A small step is precise but slow. Chapter 3 ended with the symptom of a fixed step: a wobble that never dies. Now we measure it, then fix it.

How much does a fixed step wobble?

Look at one centroid that already sits near its cluster’s mean μ. Each batch brings a few of its points, whose mean mt is μ plus noise with variance σm2. With a fixed step, the centroid moves as ct = γct−1 + αmt (roughly, when the batch counts are steady). Take the variance (the average squared wobble) of both sides. Once the wobble has settled, Var(c) is the same on both sides:

Var(c) = γ2 Var(c) + α2σm2  ⇒  Var(c) = α2σm2 / (1 − γ2) = ασm2 / (2 − α)

The last step uses 1 − γ2 = (1 − γ)(1 + γ) = α(2 − α). For a small step, the wobble’s variance is about ασm2/2: it grows in proportion to the step.

Now recall the split from Chapter 1. A centroid that misses its mean by δ costs |Aj|δ2 extra. So the expected extra loss from the wobble also grows in proportion to α. A fixed step leaves a noise floor: a loss the run cannot get below. Halve the step and the floor roughly halves, but the centroids travel half as fast.

The cosine schedule (Equation 5)

So start with a big step and end with a small one. e-means does this by annealing the step, that is, lowering it on a fixed plan. Raising the decay γ is the same thing, since α = 1 − γ. The plan is a cosine:

α(t)
The step used on batch number t, which runs from 0 to M − 1. The decay for that batch is γ = 1 − α(t).
α0
The peak step, used on the first batch. It is the one knob of the schedule, and Chapter 6 gives a law for it.
ε = 0.1
The floor: the step never goes below 10% of the peak. A step of zero would make the last batches count for nothing.
½(1 + cos(πt/M))
Half a cosine wave, rescaled to run from 1 at t = 0 down to 0 at t = M. It is flat at both ends and steepest in the middle.

The total number of batches M sets the length of the schedule. One epoch holds ⌊n/B⌋ batches (⌊·⌋ rounds down), so a run of T epochs makes

M = T ⌊n / B⌋ updates

A worked example, with the paper’s own ablation setting (Table 1): DEEP, n = 1,000,000 points, k = 16,384 clusters, T = 3 epochs. The laws of Chapter 6 give B = 65,536 and α0 = 0.363. Then ⌊1,000,000 / 65,536⌋ = ⌊15.26⌋ = 15 batches per epoch, and M = 3 × 15 = 45 updates in the whole run.

α(0) = 0.363   ·   α(22) = 0.363 × (0.1 + 0.9 × ½(1 + cos(0.489π))) = 0.205   ·   α(44) = 0.037

Only 45 updates for a million points! Each batch holds 65,536 points, about 4 per cluster on average. So the count Nj of a typical cluster settles near 4. The paper reports that this short run already beats Lloyd’s 25-epoch loss on DEEP (Table 5: 3.8788 against 3.8926, in units of 0.1).

Play with the schedule below. The bottom panel runs one centroid through the EMA bank with your schedule, so you can see the noise floor directly.

Shape the step schedule

Top: the step α(t) over the run, yellow for the cosine and dashed for a fixed step at the peak. Bottom: how far one centroid sits from its true mean, batch by batch, under each schedule. Change the knobs and compare the two endings.

0.40
3
256

Toy: n = 16,384 points, and the watched cluster owns 1/16 of them, drawn from a unit Gaussian around its mean, so each batch brings it about B/16 points. Our own code; the same random batches feed both schedules. The cosine curve is Equation 5 exactly.

With a large peak, the fixed step ends noisy and the cosine ends calm. Both move fast early, so the cosine keeps the speed and loses the noise. The paper’s ablation (Appendix G.3, Table 13) puts numbers on it. Against the best fixed step, retuned on validation data, the cosine lowers the training loss in all 8 settings, by 0.26% to 1.29%. On the test loss it wins in 5 settings, by up to 0.54%, and loses in 3 by at most 0.06%.

Two ways to finish

When the last batch is done, the centroids S/N are a weighted mean of recent batches. The paper adds a cheap last step, and offers two versions, one for each goal.

For the training loss: the last-epoch mean. During the last epoch, record which centroid each point was given. At the end, set each centroid to the plain average of its recorded points. By Fact 2, nothing beats the mean for that assignment, so the training loss of those codes cannot rise. It costs one more pass of adds, with no new distance computations. The paper uses it by default.

For the test loss: a slow EMA. Keep a second set of counts and sums that follow the same updates (and the same splits, Chapter 5), but with a slower, constant step set by a half-life h. They never drive the assignments; they only watch. Averaging over more batches smooths the centroids, which works like a regulariser: it trades a little training loss for a lower test loss. On DEEP with 10 million points (Table 15), it cuts the test loss by 0.018% to 0.082% as k grows, while raising the training loss.

Both finishes cost almost nothing, so one run can even produce both sets of centroids. They matter most when n/k is small, that is, when each cluster has few points.

The failure mode, measured

Symptom: the loss curve of a fixed-step run flattens early, at a plateau. Measurement: Table 1 shows that removing the cosine raises the training loss by 0.26% at T = 3 on DEEP. Fix: anneal the step on the cosine, and finish with the last-epoch mean.

With α0 = 0.4 and ε = 0.1, what is the step exactly halfway through the run, at t = M/2?

Chapter 5

Revive the Dead Clusters

Spot centroids that stopped receiving points, and put them back to work by splitting a busy cluster in two

Back to the post offices. A new office opens nearer to some houses, and one by one they switch. One old office ends up with no houses at all. It still costs money, and it serves nobody. Worse, somewhere else in town one office is buried in mail it cannot handle.

k-means has the same problem. A dead cluster is a centroid that no point picks any more. You asked for k clusters, but you are really using fewer. The loss behaves as if k were smaller, and the dead centroid will never recover on its own: no point is nearest to it, so nothing ever pulls it back toward the data.

How a cluster dies in e-means

Chapter 3 showed what happens when a batch gives cluster j no points: Nj and Sj both shrink by γ. The centroid stays put, but the count fades. After t empty batches, Nj has shrunk by a factor γt. So a falling count is the warning sign, and it costs nothing to watch.

What is a normal count? Each batch hands out exactly B points, so the batch counts always add up to B. The EMA of a sum is the sum of the EMAs, so the counts Nj also settle to a total of about B, and the mean count is about B/k. In the Chapter 4 example, with B = 65,536 and k = 16,384, the mean count is about 4.

The rule (Section 3.1 and Appendix H)

  1. Every five batches, compute the mean count, (1/k) ∑i Ni.
  2. Mark as dead every cluster j whose count is below τ = 0.1 of that mean.
  3. For each dead cluster, draw a donor j′ among all clusters, with probability in proportion to its count Nj′, without replacement. A dead cluster’s tiny count means it is almost never drawn.
  4. Split the donor’s centroid into two children that differ very slightly (Equation 8). One child replaces the donor; the other takes the dead slot.
  5. Give each child half the donor’s count, Nj′/2, and write each sum back as S = c × N, so that S/N still returns the centroid.

In the example above, the threshold is 0.1 × 4 = 0.4. With a step of 0.2, a cluster that stops receiving points falls from 4 to 0.4 in about ln(0.1)/ln(0.8) ≈ 10 batches. So a dying cluster is caught quickly, and checking every five batches keeps the cost tiny.

The split, symbol by symbol

cj
The dead slot’s new centroid: one of the two children.
cj′
The donor’s centroid, the parent of both children. The second child overwrites it.
⊙
Multiply coordinate by coordinate.
[1+δ, 1−δ, …]
A pattern that raises every odd coordinate a hair and lowers every even one. The other child gets the mirror pattern.
δ ≪ 1
A tiny nudge. The paper picks the machine epsilon of BF16, its lowest precision format: 2−7 ≈ 0.0078.

A worked split. The donor sits at c = (0.50, −0.20) with count N = 6, and δ = 0.0078.

child A = (0.50 × 1.0078, −0.20 × 0.9922) = (0.5039, −0.1984)   ·   child B = (0.4961, −0.2016)

NA = NB = 6 / 2 = 3   ·   SA = 3 × (0.5039, −0.1984) = (1.5117, −0.5953)

Look at the midpoint of the two children: ((0.5039 + 0.4961)/2, (−0.1984 − 0.2016)/2) = (0.50, −0.20). It is the donor’s centroid exactly. That is the point of the mirror pattern. On the next batch, each of the donor’s points goes to whichever child is nearer. The border between the two children passes through the donor’s centroid, so it cuts the donor’s points roughly in half. Then the children drift apart, each toward the mean of its own half.

Why these choices

Why choose a busy donor? A cluster with many points usually has a large spread, so splitting it lowers the loss the most. Drawing in proportion to N favours busy clusters but still spreads the splits around.

Why such a tiny δ? The paper sets two conditions. The split must stay local to the donor, and each child must have a chance to catch about half of its points. A tiny mirror nudge satisfies both, and it costs O(d): it never has to look at the donor’s points. Methods that split a cluster by its content must read those points first.

Why not just restart the dead centroid at a random point? That is what many VQ-VAEs do: replace it with a vector from the current batch. The random point often lands in a region that is already well served, so the new centroid starves and dies again. The paper measures this in Table 14, below.

Now watch it happen. To make dead clusters appear at once, this lab starts 8 of its 24 centroids in empty corners. In real runs, clusters die more slowly, as they lose their points to neighbours.

Bring the dead back

Red centroids are dead: their count is below 10% of the mean. The bars below are the counts Nj, with the dashed line at the death threshold. Choose revival on or off, then press Run. A green line flashes from each donor to the slot it fills.

Toy, our own code: 1,500 points, k = 24, B = 32, α0 = 0.3, 6 epochs (276 batches). The check runs every 5 batches with τ = 0.1 and δ = 2−7, as in Appendix H. In this 2-D toy the split nudge is tiny, so each new child first sits on its donor and moves away over the next batches.

With revival off, the corner centroids stay dead for the whole run: no point ever picks them. The loss ends as if k were 16 or 17. With revival on, they are reborn inside busy clusters within the first few checks, and the final loss is lower.

What the paper measured

Dataset (n)PolicyDead clustersImbalanceTest MSE
DEEP (1M)split a donor (e-means)47 (0.3%)1.1940.38762
DEEP (1M)resample from batch2,343 (14.3%)1.4230.39124
DEEP (1M)off4,313 (26.3%)1.6470.39448
DEEP (10M)split a donor (e-means)0 (0.0%)1.1570.34149
DEEP (10M)off9,433 (14.4%)1.3950.34474

These rows come from Table 14. A cluster counts as dead there when fewer than ten points are assigned to it at the end. The imbalance factor is 1.0 when all clusters have equal size and grows as sizes become uneven. Without revival, a quarter of DEEP’s 16,384 centroids die. The ablation in Table 1 calls revival the component with the highest influence: removing it raises the training loss by 2.97% and the test loss by 2.24%. Resampling from the batch recovers only part of that (+2.06% and +1.15%).

The failure mode, in order

Symptom: the run ends with a loss close to what a smaller k would give, and some clusters hold almost no points. Measurement: count clusters with fewer than ten points, or watch for counts below 10% of the mean during training. Fix: every five batches, split a busy donor into each dead slot.

Why does the split use the mirror patterns [1+δ, 1−δ, …] and [1−δ, 1+δ, …] rather than two random nudges?

Chapter 6

Laws for Every Knob

Turn n, k and T into a batch size and a peak step with two fitted power laws, and measure what that shortcut costs

A new dataset lands on your desk: 50 million vectors, 100,000 clusters wanted, and time for three epochs. Lloyd needs nothing more than that. A mini-batch method also asks for a batch size B and a step. Guess wrong, and you lose quality or speed. Sweep them, and you pay for many runs before the real one.

The paper’s answer is to sweep once, very thoroughly, on one dataset, and fit a formula to the winners. Then nobody has to sweep again. This chapter rebuilds those formulas and works them by hand.

Two curves the laws are fitted to

The step valley. Fix k, n, T and B, and plot the validation loss against the peak step α0. The curve is a valley (Figure 2, left). Too small a step under-trains: the centroids never get where they should be. Too large a step is unstable: batch noise throws them around. The bottom of the valley is the best step, and it moves right as B grows. A bigger batch gives a less noisy batch mean, so it can afford a bigger step, and it also gives fewer updates, so it needs one.

The batch knee. Now let every batch size use its best step, and plot the loss against B (Figure 2, right). A wide range of batch sizes do equally well. Past a threshold, the loss climbs quickly, because the run makes too few updates. Bigger batches run faster on a GPU, so you want the largest batch before the climb. The paper defines that knee as the largest B whose loss stays within +0.2% of the curve’s minimum. On DEEP with n = 106 and k = 1,024, the knee sits at 40,464 for T = 2 and rises to 220,202 for T = 25 (Figure 7).

Power laws: straight lines in log space

A power law says y = c × xa. Take logarithms and it becomes a straight line: log y = log c + a log x. With several inputs, it is a plane. So fitting a power law is ordinary least squares on logarithms, the simplest regression there is. The paper fits two such laws (Equations 6 and 7):

α0
The peak step of the cosine schedule (Chapter 4).
ac = 0.824
The constant of the step law: its height when all inputs are 1.
k−0.46
More clusters, smaller step. Each cluster then gets fewer points per batch, so its batch mean is noisier.
B0.90
Bigger batch, bigger step: doubling B multiplies the step by 20.9 = 1.87. This is the step law’s most important input.
n−0.45
More data, smaller step. With B fixed, more data means more updates, so each one can be gentler.
T−0.11
More epochs, a slightly smaller step. A weak effect.
min(…, 1)
A step can never exceed 1. At α = 1, each batch fully replaces the counts and sums.
B = 0.035 k0.13 n0.88 T0.81
The knee batch law. It is rounded to the nearest power of two and capped at n. Above n = 2M, the paper divides it by 8 (bc = 0.0044).

The order matters. First compute B from (k, n, T). Then compute α0 from (k, n, T) and that B. The paper fits them the same way: the step law first, over many batch sizes, then the batch law only on runs that use the fitted step.

Worked by hand: DEEP, 1M points, 16,384 clusters, 3 epochs

  1. Batch law: 0.035 × 16,3840.13 × (106)0.88 × 30.81 = 0.035 × 3.531 × 190,546 × 2.435 = 57,334.
  2. Round to a power of two: log2 57,334 = 15.81, which rounds to 16, so B = 216 = 65,536. It is below n, so the cap does not bite.
  3. n = 106 is not above 2M, so there is no divide by 8.
  4. Step law: 0.824 × 16,384−0.46 × 65,5360.90 × (106)−0.45 × 3−0.11 = 0.824 × 0.01152 × 21,619 × 0.001995 × 0.8862 = 0.363. It is below 1, so the clip does not bite.
  5. Updates: M = 3 × ⌊106 / 65,536⌋ = 3 × 15 = 45.

And one at the billion scale: n = 109, k = 220, T = 2. The batch law gives 30.9 million; n is above 2M, so divide by 8 to get 3.87 million, which rounds to 222 = 4,194,304. The step law then gives α0 = 0.106, and the run makes M = 2 × 238 = 476 updates.

One more thing falls out of the batch law. The number of updates is M ≈ Tn/B = (1/0.035) × T0.19 n0.12 k−0.13. All three exponents are small. So whatever the problem size, the law keeps a run to tens or hundreds of large batches. This is our own reading of the law, not a claim the paper makes, but it explains why e-means fits so well on a GPU.

Compute the knobs from the laws

Set the problem size and the epoch budget, or tap a preset. The curve is the step law for every batch size at your n, k and T; the yellow marker is the batch the batch law picks. The read-out walks through every step.

1M
16,384
3

Coefficients are the paper’s Table 2. The paper fits the step law for 105 ≤ n ≤ 108, k a power of two from 256 to 65,536, and n/k ≥ 8; it then applies the laws to larger runs, up to 10 billion points. We round in log space; the paper says only “the nearest power of two”. The DINO10B preset shows what the law returns; the paper’s own 10B run used a batch of 221 (Appendix M.1), smaller than the law’s value.

What following the law costs: regret

A formula can never beat the best setting found by a full sweep. The question is how much worse it is. The paper measures regret: the relative extra loss from following the law instead of the best setting for that (k, n, T).

regret = (MSElaw − MSE*) / MSE*

For the step law, the median regret is 0.07% on datasets it never saw (SIFT, SPACEV, arXiv and AG-News), and 0.07% when a whole value of n is left out of the fit (Table 2). For the batch law, it is 0.19% and 0.20%, close to the 0.2% the knee allows by design. The divide-by-8 version has 0.07%. Both laws explain most of the variation in their targets (R2 of 0.95 and 0.96).

The fit took about 75,000 runs (74,629). The step law used 62,410 of them: 1,142 settings of n, k, B and T, each with a ladder of 8 to 31 steps and three seeds. The batch law used 12,219. That is the sweep nobody else has to do.

Which inputs matter? Table 7 drops them one at a time, scored with one value of n held out of the fit. Without B, the step law’s regret jumps to 0.57%. Without T, it barely moves (0.074%). Table 8 tries other forms on the same score: a fully linear law, with no logarithms, has 0.79% regret. The plain power law wins.

See the valley yourself

This device runs a small e-means in your browser, for every pair of batch size and peak step, and colours each cell by its validation loss. Stars mark each row’s best step, like the stars of Figure 2.

Map the valley

Press Compute. Rows are batch sizes, columns are peak steps. Darker warm means a lower loss; red means more than 50% above the best cell. Watch the stars drift right as the batch grows.

Illustrative, computed live by our own code: 2,400 training points and 800 validation points in 2-D, k = 24, T = 2, no revival and no finalisation, mean of 2 seeds per cell. The yellow ring marks what the paper’s laws would pick here (B = 64, α0 ≈ 0.22); the laws were fitted on high-dimensional embeddings, so in 2-D they land near the valley, not on its floor.

Two patterns match the paper. Each row is a valley, with a red cliff where the step is too large for the batch. And the best step moves right as the batch grows: on spirals, with this page’s two seeds, it goes from 0.3 at B = 8 to 1 at B = 512. The rows also get worse at the bottom, where big batches leave too few updates. That is the batch knee.

The limitation the authors flag

The laws were fitted on high-dimensional embeddings. The paper states that they are not optimal for very low-dimensional or tiny datasets (Appendix D.2, Figure 11). The real driver is the data’s intrinsic dimension, the number of directions it actually spreads in, and that is usually unknown. The authors tried an exponent for d, found it unstable, and dropped it. So for 2-D toys like this page’s, the authors’ playground and ours use smaller batches than the law suggests.

You keep n, k and T fixed but double the batch size B by hand. By the step law, what should happen to the peak step α0?

Chapter 7

Scale It Up, Then Read the Results

Search only a few buckets of centroids at the billion scale, and check every headline number against the paper’s tables

Picture the largest run in the paper: 10 billion DINO patch embeddings, each with 1,024 numbers, to be split into 224 ≈ 16.7 million clusters. Even with e-means, every point must still find its nearest centroid, once per epoch. Done exactly, 2.5 epochs took 779 GPU hours on 32 machines (Table 21). Most of that time went into comparing each point with all 16.7 million centroids.

Here is the key observation. Finding the nearest centroid is a nearest-neighbour search: the centroids are the database, and each training point is a query. Search libraries have long solved that problem approximately, by looking only where the answer is likely to be. So the paper borrows a search index for the assign step.

IVF: look in a few buckets only

An inverted file index (IVF) works like the shelves of a library. First, a small k-means groups the items into KIVF buckets, each with a meta-centroid, a centroid of centroids. Each centroid goes into the bucket of its nearest meta-centroid. To search, a query first finds its LIVF nearest meta-centroids, then compares itself only with the centroids in those buckets.

How much work does that save? Appendix M.2 counts it. With k centroids split over KIVF buckets, a bucket holds about k/KIVF centroids on average. Each query visits LIVF buckets, so for a batch of B queries:

exact: k × B comparisons   ·   IVF: k × B × LIVF / KIVF comparisons (plus B × KIVF to rank the buckets)

With KIVF = 1,024 and LIVF = 4, that is 256 times fewer comparisons on paper. In practice the buckets are not equal in size, so the gain is smaller. The GPU also needs work in uniform blocks, so the paper pads and splits the matrices and runs many small matrix multiplies at once.

The catch: the answer is approximate. If the true nearest centroid sits in a bucket the query did not visit, the query takes the best centroid it did see. Try it below. Tap the plane to drop a query, or run 500 at once.

Search only a few buckets

Each dot is one of 256 centroids, shaded by its bucket; purple diamonds are the meta-centroids. Tap anywhere to place a teal query. The buckets it visits light up; a green ring means it found the true nearest centroid, a red ring means it missed.

2

Toy, our own code: 256 centroids from an e-means run on the galaxy cloud; meta-centroids from 10 Lloyd epochs on those centroids; queries drawn from the same cloud. The paper’s runs use KIVF from 256 to 16,384 and LIVF of 4 or 16 over millions of centroids.

Visit more buckets and the miss rate falls, but the comparisons rise. Use more buckets and each holds fewer centroids, but you must rank more meta-centroids. The paper found that small KIVF (256 to 1,024) works best on GPUs, because coarse buckets make bigger, more efficient matrix multiplies (Appendix M.3).

The index must keep up with moving centroids

In a normal search engine, the database is fixed and the index is built once. Here the “database” is the set of centroids, and it changes after every batch. So the index must be rebuilt often, and building it must be about as fast as searching it. That rules out slow-to-build graph indexes; the paper tried CAGRA and found its build time prohibitive.

Table 19 tests the options on a small run (224 points, 216 clusters). Retraining the meta-centroids every time helps the training loss a little (17.02 to 16.94, in units of 104). But it is 50 times slower, so the paper trains them once on a sample of the data. Rebuilding the buckets only every 4 or 16 batches is acceptable; every 256 batches is not (training loss 18.37). The main runs rebuild the buckets at every batch.

What the approximation costs

The symptom: with IVF, the per-batch loss and the training loss sit visibly higher than with exact search (Figure 26). The measurement that matters is the test loss, and it is much less sensitive. On the small ablation, the test loss was even lowest with the coarsest search, LIVF = 4. The authors suggest that the noise of approximate assignment may reduce overfitting. The fix, when you need the training loss: run a little longer. Matching Lloyd@25’s training loss on DINO10B takes e-means 4 epochs with a finer IVF (16,384 buckets, 16 visited), and that is still 155 times faster than the Lloyd baseline.

Run (Table 21, DINO10B, k = 224)EpochsTest MSE vs LloydGPU hoursMachines
Lloyd, exact25reference6,78464
e-means, exact2.5−0.014%77932
e-means, IVF4096, L = 43−0.033%23.21
Lloyd, IVF4096, L = 440−0.008%249.12

Read the last row carefully: IVF also speeds up Lloyd, but its error delays Lloyd so much that it needs 40 epochs to match its own exact 25-epoch loss. e-means absorbs the approximation better. Its IVF run beats the Lloyd baseline in 23.2 GPU hours, about 3 hours on one 8-GPU machine. Table 3 summarises the gain from IVF alone: none at 100M points (0.028 against 0.030 GPU hours), 4.3 times at 1B and 34 times at 10B.

Flops, epochs and wall-clock time

Why does the paper count epochs rather than flops? Because one e-means epoch costs about the same as one Lloyd epoch: both are dominated by the assign step, 2nkd operations. The EMA update adds only O(kd) per batch. So fewer epochs means proportionally fewer flops.

Wall-clock time adds two more effects. Large batches keep the GPU busy, which is one reason the batch law aims for the largest batch before the knee. And kernels differ: the paper compares its BF16 kernels with Flash-KMeans in FP16. So a wall-clock speed-up can exceed the epoch ratio. At 1B points on DINO10B, 25/1.6 = 15.6 times fewer epochs became a 45.5 times wall-clock speed-up (Table 4). In Figure 1, above 100M points, the baseline is the authors’ own Lloyd code, because Flash-KMeans runs on one node only. The paper does not split the speed-up into its parts, so treat the epoch count as the clean measure.

The results, in the paper’s own numbers

Read the result tables

Choose a table. Tap a cell or a row to read it as a sentence. Warm is e-means; blue is the Lloyd baseline.

Epochs and Speed-up: Table 4, epochs (in steps of 0.2) for e-means to beat Flash-KMeans at 25 epochs, and the wall-clock speed-up there; medians over 10 seeds up to 100M, one seed at 1B. Fixed budget: Table 5, test MSE relative to Flash-KMeans at 25 iterations from a random start. GPU hours: Table 3, to reach Lloyd’s 25-epoch test loss on DINO10B subsets.

Three findings stand out. First, every cell of Table 4 is between 1.4 and 2.6 epochs, from a million to a billion points. Second, in Table 5, three epochs of e-means beat 25 iterations of Flash-KMeans on all 8 settings. Even against Flash-KMeans with the greedy k-means++ start, five epochs of e-means still win on all 8, though by only 0.06% to 0.33%. Third, the advantage carries over to search: in Appendix L, IVF indexes built with e-means reach the converged recall of Flash-KMeans indexes much sooner, and end equal or better on most of the eleven VIBE datasets.

The paper also checks precision. Its GPU kernels can run the assign step in FP8 or INT8, and the test loss stays within 0.13% of BF16 in every setting of Table 16. Only the search for the nearest centroid uses low precision; the counts, sums and EMA stay in 32-bit floats.

With k = 2,097,152 centroids, KIVF = 1,024 buckets and LIVF = 4, how many centroid comparisons does each query make, on average, if the buckets are equal in size?

Chapter 8

The Playground

Train Lloyd and e-means side by side on six point clouds, and measure train and test loss epoch by epoch

You now know every part of e-means: the loss, the counts and sums, the cosine step, the revival of dead clusters, the laws and the last-epoch mean. This chapter puts them all in one machine you can drive. Pick a cloud of points, pick n, k, the number of epochs and a seed, and press Train.

Both methods start from the same k random data points and see the same data. Lloyd makes one move per epoch. e-means makes ⌊n/B⌋ moves per epoch, with its batch size and peak step set by the paper’s laws. After every quarter epoch, the page measures the training loss on all n points and the test loss on a separate held-out set drawn from the same cloud.

Train both, side by side

Choose a cloud and the knobs, then press Train. Left is Lloyd in blue, right is e-means in warm. Below, solid lines are the training loss and dashed lines the test loss, both per epoch.

6,000
32
5
1

Our own implementation of Algorithm 1, run in your browser in small slices per animation frame so the page never freezes. Phones cap n at 6,000. The paper’s laws were tuned on high-dimensional embeddings and are not optimal on 2-D toy data (Appendix D.2, Figure 11), so by default we follow the authors’ own 2-D playground: the batch law divided by 8, and no revival. Both switches are here so you can test that choice.

What runs when you press Train

  1. Generate n training points and n/4 test points from the chosen cloud, with your seed. Each point is 2 numbers, so the training set is an n × 2 array.
  2. Pick k distinct training points at random as the start for both methods.
  3. Compute B and α0 from the laws of Chapter 6 (divided by 8 unless you switch on the full law), and M = T⌊n/B⌋.
  4. On every animation frame, spend about 10 milliseconds on work. e-means runs as many batches as fit: assign B points, update N and S, every fifth batch check for dead clusters if revival is on. Lloyd runs a full epoch whenever e-means passes a whole epoch, so both stay at the same point on the epoch axis.
  5. Every quarter epoch, measure e-means’s training and test loss; after every Lloyd epoch, measure Lloyd’s.
  6. At the end, if the switch is on, replace e-means’s centroids with the last-epoch mean and measure once more.

A note on cost. One Lloyd epoch at n = 20,000 and k = 64 is 1.28 million point-to-centroid comparisons, a few milliseconds in a browser. One e-means epoch is the same number of comparisons, spread over many batches. That is the paper’s point about flops: per epoch, the two cost about the same, so the race is fairly scored in epochs.

Five experiments to run

  1. The race. Galaxy, n = 6,000, k = 32, T = 5. Read the curves at epoch 1. Lloyd has moved its centroids once; e-means has moved them hundreds of times. Which is closer to its final loss?
  2. The budget. Set T = 1 and train. Then T = 3, then T = 10. The laws change B and α0 each time; watch the info line. Does e-means at T = 3 beat Lloyd at T = 10?
  3. The dead. Spirals, k = 64, n = 2,000. Train with revival off, then on, with the same seed. Compare the final training loss and look for idle centroids in the gaps of the spiral.
  4. Overfitting. Heart, n = 500, k = 64. With only about 8 points per cluster, the training loss falls well below the test loss for both methods. This is the regime of small n/k where the paper finds its finalisation choices matter most.
  5. The law in 2-D. Switch on Full batch law. B grows 8 times, so each epoch makes 8 times fewer updates, and the peak step rises to match. On these toy clouds the smaller batch usually wins, which is why the authors’ 2-D playground divides by 8.

How to read a run honestly

Toy clouds in 2-D are not embeddings. In two dimensions a handful of centroids already capture most of the shape, and Lloyd settles in a few epochs, so the gap between the methods is smaller than in the paper. Some seeds will show Lloyd ahead at the end. That is fine: the paper’s claims are about high-dimensional data, and it reports its own exceptions too, such as the overfitting cells of Figure 10.

What should carry over is the shape of the curves. e-means drops most of its loss in the first epoch, because it makes many small moves where Lloyd makes one. It then settles as the cosine step shrinks. And the dashed test curves tell you whether a lower training loss is real or memorised.

The failure mode, in the playground

Symptom: e-means’s curve flattens high, or jumps around late in the run. Measurement: compare with Lloyd’s final loss on the same seed, and look at the info line for B and α0. Fix: if the batch is so large that M is only a few dozen updates on a tiny cloud, the step law pushes α0 towards 1; switch back to the divided law. If some cells hold no points, switch on revival.

In the playground, why is it fair to compare Lloyd and e-means on an axis of epochs rather than of updates?

Chapter 9

Field Guide

Keep the numbers, the terms, a build checklist and the whole method as code on one page, and cite the paper

The paper in one paragraph. e-means solves the same problem as Lloyd’s k-means, but it moves the centroids after every mini-batch. Each cluster keeps an exponential moving average of its count and its sum, and its centroid is their ratio. The step of that average falls on a cosine from a peak α0 to a tenth of it. Every five batches, clusters whose count drops below a tenth of the mean are revived by splitting a busy donor. A last-epoch mean, or a slow EMA, gives the final centroids. Two power laws, fitted once on about 75,000 runs, set the batch size and the peak step from n, k and T. The result reaches Lloyd’s 25-epoch loss in 1.4 to 2.6 epochs on embedding datasets from a million to 10 billion points, and ends lower.

The numbers

MeasurementValueSource
Epochs to beat Flash-KMeans@25, 1M to 1B points1.4 to 2.6Table 4a
Wall-clock speed-up against Flash-KMeans9.5× to 45.5×Table 4b
Epochs to Lloyd@25, eleven VIBE datasets1.6 to 2.6 (GPU 8.0× to 22.8×, CPU 9.0× to 15.0×)Table 11
DINO10B, k = 224: Lloyd@25 against e-means6,784 GPU h on 64 machines; 2.5 epochs exact in 779 GPU h; IVF in 23.2 GPU h on 1 machineTable 21
Gain from IVF alone at 100M, 1B, 10B pointsnone, 4.3×, 34×Table 3
Ablation, DEEP 1M, k = 16,384, T = 3 (train / test)no revival +2.97% / +2.24%; resample +2.06% / +1.15%; no cosine +0.26% / −0.06%; no finalisation +0.14% / +0.02%Table 1
Dead clusters on DEEP 1M: revival on, resample, off0.3%, 14.3%, 26.3%Table 14
Step law and its median regretα0 = min(0.824 k−0.46 B0.90 n−0.45 T−0.11, 1); 0.07%Eq. 6, Table 2
Batch law and its median regretB = 0.035 k0.13 n0.88 T0.81, power of two, ≤ n; 0.19% (divided by 8 above n = 2M: 0.07%)Eq. 7, Table 2
Fixed constantsN0 = 10−10, ε = 0.1, τ = 0.1 every 5 batches, δ = 2−7§3.1, App. H
FP8 and INT8 assignment against BF16within 0.13% test MSETable 16
k-means++ start: cost against the e-means run itself2,852 to 6,080 s against 22 to 72 s, for changes of 0.19% or less, in either directionTable 12

The terms

TermMeaning
Centroid, clusterA representative point; the set of data points nearest to it.
MSE, distortionThe mean squared distance from each point to its nearest centroid (Equation 1).
Epoch, batchOne pass over all n points; a random group of B points read together.
Lloyd@25Lloyd’s k-means after 25 epochs, the Faiss default and the paper’s yardstick.
Nj, SjA cluster’s EMA count and EMA sum; the centroid is Sj/Nj.
Decay γ, step αHow much of the past an EMA keeps, and its complement α = 1 − γ.
Peak step α0, MThe first and largest step of the cosine schedule; the number of updates, T⌊n/B⌋.
Dead cluster, donorA cluster whose count fell below τ of the mean; the busy cluster split to replace it.
Knee, regretThe largest batch within +0.2% of the best loss; the relative extra loss from following a law.
IVF, meta-centroidAn index that groups centroids into buckets; the centre of a bucket.
Last-epoch mean, slow EMAThe two finishes: best for the training loss, and best for the test loss.

Checklist: building e-means yourself

  1. Hold out a test set before you train. Report the test loss, not only the training loss.
  2. Compute B from the batch law, round to a power of two, cap at n, and divide by 8 above n = 2M. Then compute α0 from that B.
  3. Start from k random data points. Set N = 10−10 and S = N × c, never N = 0.
  4. For each batch: compute α(t) from Equation 5, read C = S/N, assign with ‖c‖2 − 2x·c, then update N and S with the batch counts and sums.
  5. If you use low precision for the dot products, compute the norms from the same rounded centroids. Keep N and S in 32-bit floats.
  6. Every five batches, revive clusters below 0.1 of the mean count by splitting a donor drawn in proportion to N. Halve its count and write S = c × N for both children.
  7. Record each point’s cluster in the last epoch, and finish with the last-epoch mean (or keep a slow EMA if the test loss is what you need).
  8. For low-dimensional data, expect the laws to be off; try a smaller batch, as the authors do in 2-D.

The whole method as code

import numpy as np

def law(n, k, T):                                   # Eq. 7 then Eq. 6, Table 2
    B = 0.035 * k**0.13 * n**0.88 * T**0.81
    if n > 2_000_000: B /= 8
    B = int(min(2 ** round(np.log2(B)), n))
    a0 = min(0.824 * k**-0.46 * B**0.90 * n**-0.45 * T**-0.11, 1.0)
    return B, a0

def assign(X, C):                                 # ||x||^2 is the same for every centroid: drop it
    return (np.sum(C * C, 1)[None] - 2 * X @ C.T).argmin(1)

def revive(N, S, rng, tau=0.1, delta=2.0**-7):  # Appendix H
    dead = np.flatnonzero(N < tau * N.mean())
    live = np.setdiff1d(np.arange(len(N)), dead)
    if len(dead) == 0 or len(live) == 0: return
    donors = rng.choice(live, min(len(dead), len(live)), replace=False, p=N[live] / N[live].sum())
    sign = np.where(np.arange(S.shape[1]) % 2 == 0, 1.0, -1.0)
    for j, dj in zip(dead, donors):
        c, h = S[dj] / N[dj], N[dj] / 2
        N[j] = N[dj] = h
        S[j] = c * (1 + delta * sign) * h              # child in the dead slot
        S[dj] = c * (1 - delta * sign) * h             # child in the donor's slot

def emeans(X, k, T, eps=0.1, seed=0):
    rng = np.random.default_rng(seed)
    n, d = X.shape
    B, a0 = law(n, k, T)
    per = n // B; M = T * per; t = 0
    C = X[rng.choice(n, k, replace=False)].astype(np.float64)
    N = np.full(k, 1e-10); S = N[:, None] * C          # S/N returns the start exactly
    last = np.full(n, -1)
    for _ in range(T):
        order = rng.permutation(n)
        for b in range(per):
            idx = order[b * B:(b + 1) * B]
            alpha = a0 * (eps + (1 - eps) * 0.5 * (1 + np.cos(np.pi * t / M)))   # Eq. 5
            lab = assign(X[idx], S / N[:, None]); last[idx] = lab
            nj = np.bincount(lab, minlength=k)                                    # Eq. 3
            sj = np.zeros_like(S); np.add.at(sj, lab, X[idx])
            N = (1 - alpha) * N + alpha * nj                                          # Eq. 2
            S = (1 - alpha) * S + alpha * sj
            t += 1
            if t % 5 == 0: revive(N, S, rng)
    C = S / N[:, None]                                   # Eq. 4, then the last-epoch mean
    cnt = np.bincount(last[last >= 0], minlength=k)
    sums = np.zeros_like(C); np.add.at(sums, last[last >= 0], X[last >= 0])
    C[cnt > 0] = sums[cnt > 0] / cnt[cnt > 0, None]
    return C

This is our own compact rewrite for reading, not the authors’ code. It keeps every mechanism of Algorithm 1 but none of the engineering: no blocked GPU kernels, no low precision, no sharding, no IVF. The production version ships in Faiss as contrib/e_means. One simplification to know: points left over when n is not a multiple of B keep their label from an earlier epoch.

Where e-means sits

e-means joins three lines of work. From quantisation, it inherits the k-means problem itself, the same one the Lloyd-Max quantiser solves for signals. From VQ-VAEs and neural audio codecs, it borrows the EMA codebook update and the habit of reviving dead codes. The paper notes that this update is a hard-assignment form of EM with decayed statistics, the cousin of the soft EM used for Gaussian mixtures. And from vector search, it borrows the IVF index, which in turn is built with k-means. Its new parts are the cosine schedule, the donor split, the two finishes and, above all, the laws that remove the sweep.

Keep going

Cite this paper

If you use e-means or its scaling laws, cite the authors’ paper. The reference, in plain text:

Swann Bessa, Pierre-Emmanuel Mazaré, Gergely Szilvasy, Hugo Touvron, David Picard, Matthijs Douze and Hervé Jégou. “e-means: Outperforming k-means (in One-Tenth the Epochs).” arXiv:2611.09501 [cs.LG], 2026. arxiv.org/abs/2611.09501

@misc{bessa2026emeans,
  title         = {e-means: Outperforming k-means (in One-Tenth the Epochs)},
  author        = {Bessa, Swann and Mazar{\'e}, Pierre-Emmanuel and Szilvasy, Gergely and Touvron, Hugo and Picard, David and Douze, Matthijs and J{\'e}gou, Herv{\'e}},
  year          = {2026},
  eprint        = {2611.09501},
  archivePrefix = {arXiv},
  primaryClass  = {cs.LG},
  url           = {https://arxiv.org/abs/2611.09501}
}

Credit: the method, the experiments and every number on this page come from Swann Bessa, Pierre-Emmanuel Mazaré, Gergely Szilvasy, Hugo Touvron, David Picard, Matthijs Douze and Hervé Jégou at FAIR at Meta and École Nationale des Ponts et Chaussées. Read the paper on arXiv, the project page, and try the authors’ playground. The words, devices and code here are our own.

The takeaway. Lloyd waits a full pass to make one perfect move. e-means makes many small, count-weighted moves, shrinks them on a schedule, recycles idle centroids, and lets two fitted laws choose its knobs. Same objective, a tenth of the epochs.
Now teach it back: open Teach and derive S/N and the cosine step on the whiteboard. Then go back to the race at the top and run it on the galaxy. You should now be able to say, at every epoch, why the warm cells move while the blue ones wait.
e-means: Outperforming k-means (in One-Tenth the Epochs)
Read the paper · Project page · Back to Veanors