emeans-rocm 0.2.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
emeans_rocm/README.md ADDED
@@ -0,0 +1,632 @@
1
+ <p align="center">
2
+ <img src="figure/emeans-wordmark-framed.png" alt="e-means" width="70%">
3
+ </p>
4
+
5
+ # e-means: outperforming k-means in one-tenth the epochs
6
+
7
+ [arXiv](https://arxiv.org/abs/2611.09501) · Blog post link (soon) · [Browser demo](https://e-means.github.io/playground.html) · Reproduction scripts ([`benchs/e_means`](https://github.com/facebookresearch/faiss/tree/main/benchs/e_means))
8
+
9
+ Code contributors: Gergely Szilvasy, Swann Bessa, Matthijs Douze
10
+
11
+
12
+ ## What e-means is
13
+
14
+ A modern, robust replacement for k-means developed at Meta FAIR. e-means delivers a **~10× speedup in epochs and wall-clock** while achieving **lower loss** compared to Lloyd's k-means, with no additional hyperparameters. e-means uses a mini-batch update rule specialized for the k-means problem, based on exponential moving averages.
15
+
16
+ ## When to use it
17
+
18
+ e-means exhibits robustness to a large array of scales, datasets and dimensions (see [paper](https://arxiv.org/abs/2611.09501)). On most k-means applications, e-means can achieve the same loss in about 10 times fewer epochs.
19
+
20
+ ![e-means against Lloyd's k-means, in epochs, CPU time and GPU time](figure/readme_figure_v6.png)
21
+
22
+ ## Citing e-means
23
+
24
+ If you use e-means, please cite our paper using the following BibTeX entry:
25
+
26
+ ```bibtex
27
+ @misc{bessa2026emeans,
28
+ title = {{e-means}: outperforming {k-means} (in one-tenth the epochs)},
29
+ author = {Bessa, Swann and Mazar{\'e}, Pierre-Emmanuel and Szilvasy, Gergely and
30
+ Touvron, Hugo and Picard, David and Douze, Matthijs and J{\'e}gou, Herv{\'e}},
31
+ year = {2026},
32
+ note = {Preprint},
33
+ url = {https://arxiv.org/abs/2611.09501}
34
+ }
35
+ ```
36
+
37
+ ## Installation
38
+
39
+
40
+ e-means ships inside faiss, and with faiss alone you can run e-means on CPU. On GPU, e-means runs through PyTorch with Triton/CuTe kernels and never calls faiss, so the CPU build of faiss is enough on a GPU machine too. For GPU runs, install CUDA-enabled PyTorch using the [official instructions](https://pytorch.org/get-started/locally/): its Linux CUDA builds also install Triton. For the CuTe kernels on Hopper GPUs (SM90: H100 and H200), install CUTLASS DSL 4.7.1 or later and QuACK 0.6.5 or later. `cuda-cccl[cu13]` is optional but recommended for grouping performance. If you install only the Triton packages, select `assignment_backend="triton"` explicitly.
41
+
42
+ ```bash
43
+ pip install faiss-cpu # enough on a CPU, and also for GPU runs
44
+ # GPU runs: CUDA-enabled PyTorch from https://pytorch.org/get-started/locally/ (it brings Triton)
45
+ python -m pip install "nvidia-cutlass-dsl[cu13]>=4.7.1" "quack-kernels[cu13]>=0.6.5" "cuda-python>=13,<14" # CuTe, SM90
46
+ python -m pip install "cuda-cccl[cu13]" # optional, recommended for grouping performance
47
+ ```
48
+
49
+ **AMD GPUs (ROCm).** Install a ROCm build of PyTorch and a Triton build for the same ROCm
50
+ release (AMD's gfx1200 PyTorch wheel installs a matching Triton build itself). Use a separate
51
+ virtual environment. For example, for an RX 9000 card (gfx1200) on ROCm 10.1:
52
+
53
+ ```bash
54
+ python3 -m venv ~/venvs/emeans-rocm && source ~/venvs/emeans-rocm/bin/activate
55
+ python -m pip install --index-url https://stable.repo.amd.com/rocm/whl-next/ \
56
+ "torch[device-gfx1200]==2.14.0+rocm10.1.0" # brings triton 3.8.0+rocm10.1.0
57
+ pip install faiss-cpu numpy
58
+ python -c "import torch, triton; print(torch.__version__, torch.version.hip, triton.__version__)"
59
+ ```
60
+
61
+ The `faiss-cpu` wheel bundles the upstream copy of this package, which has no AMD support:
62
+ replace it with this repository's `contrib/e_means` as shown in the
63
+ [e-means-rocm Quick start](../../README.md#quick-start), or the AMD paths below are not used.
64
+
65
+ ROCm PyTorch reports AMD GPUs as device type `"cuda"`, so the usual `device="cuda"` code runs
66
+ unchanged. See the AMD notes under Kernels for what is supported.
67
+
68
+ ```python
69
+ from faiss.contrib.e_means import NumpyEmeans
70
+ ```
71
+
72
+ | Package | What it adds |
73
+ |---|---|
74
+ | faiss-cpu and NumPy | NumPy arrays on CPUs |
75
+ | PyTorch | data held as PyTorch tensors, on a CPU or a GPU |
76
+ | The three CuTe packages above | the fastest kernels, H100 and H200 only (`assignment_backend="cute"`) |
77
+ | `cuda-cccl` (optional) | faster grouping inside the CuTe kernels. Without it, e-means warns once and uses a PyTorch fallback |
78
+ | Triton | fast kernels on other recent NVIDIA GPUs, A100 or newer, and on AMD MI300, MI350, RX 7000 and RX 9000 GPUs (`assignment_backend="triton"`) |
79
+
80
+ GPU kernels compile the first time they run, which takes a few seconds.
81
+
82
+ ## Quick start
83
+
84
+ Instantiate the `Emeans` class with the dimension `d` and the number of clusters `k`. Using the `train` method, train it on your vectors, and read the centroids and dataset labels returned. To assign additional vectors, use the `assign` method. On GPU, we provide Triton, CuTe, and PyTorch backends for training and assignment to the nearest centroid. On CPU, we rely on the faiss primitive `faiss.knn` with `k=1` for NumPy arrays, and Pytorch for CPU tensors. We highlight that the Triton and CuTe backends are much faster than the PyTorch backend, which is a fallback for GPUs not supporting Triton and CuTe.
85
+
86
+ On a CPU:
87
+
88
+ ```python
89
+ import numpy as np
90
+ from faiss.contrib.e_means import NumpyEmeans
91
+
92
+ x = np.random.rand(200_000, 64).astype("float32") # 200,000 vectors of dimension 64
93
+
94
+ em = NumpyEmeans(64, 500) # 500 clusters, 5 passes over the data by default
95
+ centroids, labels = em.train(x) # (500, 64) float32, and each vector's cluster
96
+ x_new = np.random.rand(100_000, 64).astype("float32")
97
+ distances, new_labels = em.assign(x_new) # the nearest centroid of new vectors
98
+ ```
99
+
100
+ The labels come from the last training epoch, at no extra cost. They are not always each vector's nearest final centroid, because the centroids still moved during that last epoch. For exact nearest-centroid labels, call `assign` on the training vectors too. In practice, for a fixed FLOP budget T, it is better to run e-means on T epochs and use the returned labels, rather than running e-means on T-1 epochs and calling `assign` on the training vectors (which costs as many FLOPs as one epoch).
101
+
102
+ On a GPU, pass a PyTorch tensor that is already on the GPU: e-means never moves data from CPU to GPU for you.
103
+ e-means picks the fastest kernels that can run your input: CuTe on an H100 and H200 for BF16 data, Triton on other recent NVIDIA GPUs, PyTorch otherwise.
104
+
105
+ ```python
106
+ import torch
107
+ from faiss.contrib.e_means import Emeans
108
+
109
+ xg = torch.from_numpy(x).cuda().to(torch.bfloat16) # on the GPU, in 16-bit (BF16)
110
+ em = Emeans(64, 1024)
111
+ centroids, labels = em.train(xg)
112
+ print(em.recipe["assignment_backend"]) # the kernels it picked, "cute" on an H100
113
+ ```
114
+
115
+ To choose a backend explicitly, pass `assignment_backend="cute"`, `"triton"` or `"native"` (PyTorch). Both automatic and explicit selection raise an error if the selected backend cannot run or its required software is missing, broken or incompatible. Read `em.recipe["assignment_backend"]` to see which backend was selected.
116
+
117
+ ## Parameters
118
+
119
+ By default, you only need to configure the number of training passes (`nepochs`). Hyperparameters such as batch size and initial step size are derived automatically using empirical scaling laws.
120
+
121
+ ### Core configuration
122
+
123
+ - **`nepochs`** (`float`, default: `5`): Number of training passes. Fractional values (such as 2.5) are supported. A value of 5 is typically sufficient to beat Lloyd's loss at convergence.
124
+ - **`batch_law`** (`str`, default: `"auto"`): Determines how batch size is calculated:
125
+ - `"auto"`: Picks `"quality"` at low dimension and `"throughput"` otherwise (see the note below).
126
+ - `"throughput"`: Optimized for training speed.
127
+ - `"quality"`: Uses batches roughly $8\times$ smaller than `"throughput"`. This yields lower final MSE, though training may be slower on small datasets.
128
+
129
+ > **Note on low dimension.** For $d \le 16$, e-means uses the quality batch by default, and for $d \le 2$ it also turns cluster revival off. We found that the quality batch has a bigger advantage at low dimension, and that cluster revival is detrimental at $d = 2$. With several processes (`DistributedEmeans`, `EmeansShardedCentroids`), the batch must still divide by the number of processes, and on small low-dimension problems the quality batch may not: `begin` then raises, naming the law and the batch. Pass `batch_law="throughput"`, or a `batch_size` divisible by the number of processes.
130
+
131
+ ### Manual overrides
132
+
133
+ - **`batch_size`** (`int`, optional): Overrides the scaling law. Setting this manually automatically adjusts `alpha0` via equation (3).
134
+ - **`alpha0`** (`float`, optional): Overrides the calculated initial step size.
135
+ - **`max_points_per_centroid`** (`int`, optional): Caps the training set, as in `faiss.Kmeans`. When `train` gets more than `max_points_per_centroid * k` vectors, it trains on a random subset of that many (drawn from `seed`) and returns label -1 for the others. The scaling laws then use the subset size.
136
+
137
+ ### Scaling laws
138
+
139
+ | Index | Law | Formula |
140
+ |---|---|---|
141
+ | (1) | Batch size (`"throughput"`) | $B = 0.035134 \cdot k^{0.134749} \cdot n^{0.876473} \cdot T^{0.813344}$ |
142
+ | (2) | Batch size (`"quality"`) | $B = 0.00439175 \cdot k^{0.134749} \cdot n^{0.876473} \cdot T^{0.813344}$ |
143
+ | (3) | Starting step size ($\alpha_0$) | $\alpha_0 = 0.8244 \cdot k^{-0.4617} \cdot B^{0.9003} \cdot n^{-0.4498} \cdot T^{-0.1057}$ |
144
+
145
+ Variables: $n$ is the total number of vectors, $k$ is the cluster count, $T$ is the number of passes
146
+ (`nepochs`), and $B$ is the batch size.
147
+
148
+ Constraints:
149
+
150
+ - The computed batch size $B$ from (1) or (2) is rounded to the nearest power of two and capped at
151
+ $\approx n/2$.
152
+ - The step size $\alpha_0$ from (3) is clamped to the range $[0.0001, 1.0]$.
153
+
154
+ ### Examples
155
+
156
+ These examples use the tensor `xg` from the GPU quickstart.
157
+
158
+ ```python
159
+ # 1. Custom pass count (default scaling laws applied)
160
+ em = Emeans(64, 1024, nepochs=3)
161
+ em.train(xg)
162
+ print(em.recipe["batch_size"], em.recipe["alpha0"], em.recipe["steps_per_pass"])
163
+
164
+ # 2. Fractional passes
165
+ em = Emeans(64, 1024, nepochs=2.5)
166
+
167
+ # 3. Quality mode (uses Eq. 2; yields ~8x smaller batch size)
168
+ em = Emeans(64, 1024, batch_law="quality")
169
+
170
+ # 4. Manual batch size (alpha0 adjusts automatically via Eq. 3)
171
+ em = Emeans(64, 1024, batch_size=8192)
172
+
173
+ # 5. Full manual override
174
+ em = Emeans(64, 1024, batch_size=8192, alpha0=0.05)
175
+ ```
176
+
177
+ ## Settings and results in the `Emeans` class
178
+
179
+ Settings are the arguments you pass to `Emeans` when you create the model. Only `d` and `k` are
180
+ required. `help(Emeans)` describes every argument and method in full.
181
+
182
+ For conversion, use `QuantizedEmeans(d, k, quantizer=q)`; see "Data precision".
183
+
184
+ ```python
185
+ em = Emeans(64, 1024, nepochs=5, seed=0) # d and k, then any of the settings below
186
+ ```
187
+
188
+ | Setting | Default | What it does |
189
+ |---|---|---|
190
+ | `d` | required | Dimension of the vectors |
191
+ | `k` | required | Number of clusters |
192
+ | `nepochs` | `5` | Passes over the data, can be fractional |
193
+ | `assignment_backend` | `"auto"` | Kernels that find the nearest centroids. Auto picks CuTe in H100/H200 BF16, else Triton, else PyTorch |
194
+ | `batch_law` | `"auto"` | Law that picks the batch size: `"throughput"` (equation 1), `"quality"` (equation 2), or `"auto"`, which picks between them (see the note on low dimension above) |
195
+ | `batch_size` | chosen by the batch law | Batch size. If omitted, chosen by equation (1) or (2) |
196
+ | `alpha0` | equation (3) | Starting step size. If omitted, computed from the batch size by equation (3) |
197
+ | `unused_threshold` | `None` | Revives clusters whose running count falls below this fraction of the mean. `None` means 0.1, or 0 (no revival) for $d \le 2$ (see the note on low dimension above) |
198
+ | `max_points_per_centroid` | `None` | Trains on a random subset of `max_points_per_centroid * k` vectors when there are more; the others get label -1. `None` trains on all of them |
199
+ | `seed` | `1234` | Seeds the starting centroids, the shuffling and the revivals |
200
+ | `verbose` | `False` | Prints one line of statistics per pass |
201
+ | `assignment_chunk_size` | depends on the input | Rows searched at once. Memory and speed impact only |
202
+ | `centroid_chunk_size` | `4096` | Centroids searched at once, PyTorch kernels only |
203
+ | `capture_assignments` | `True` | Keeps each vector's label from the last pass (8 bytes per vector) |
204
+ | `spherical` | `False` | Keeps the centroids on the unit sphere, for cosine similarity |
205
+ | `check_finite` | `False` | Makes `train` and `accumulate` raise `ValueError` on NaN or infinite input (one pass over the data and one GPU synchronization per call) |
206
+
207
+ Results are what you read from the model once it is trained.
208
+
209
+ ```python
210
+ centroids, labels = em.train(xg)
211
+ print(em.centroids.shape, em.recipe["batch_size"]) # two of the results below
212
+ ```
213
+
214
+ | Result | What it is |
215
+ |---|---|
216
+ | `em.train(x)` | Returns the centroids and each training vector's last-pass label |
217
+ | `em.centroids` | The centroids, as 32-bit floats, on the same device as the input |
218
+ | `em.assignments` | The same last-pass labels, kept on the model |
219
+ | `em.assign(x)` | Each vector's nearest centroid and its squared distance (in spherical mode, its similarity, where higher is closer) |
220
+ | `em.obj` | The error of each pass, measured while the centroids move (not the final error) |
221
+ | `em.iteration_stats` | Per pass: error, time, imbalance and number of splits |
222
+ | `em.recipe` | The batch size, step size, steps per pass, rows per pass and kernels actually used |
223
+ | `em.n_splits` | How many dead clusters were revived |
224
+
225
+ ## On the CPU
226
+
227
+ e-means runs on the CPU whenever your data is a NumPy array or a PyTorch tensor on the CPU. It is convenient for small problems and for trying things out. GPUs are much faster, so we recommend using them for configurations where $n \times k > 10^{10}$, where $n$ is the dataset size and $k$ is the number of clusters. There are two paths depending on the input's type:
228
+
229
+ - **NumPy arrays:** each vector's nearest centroid is found with `faiss.knn`, in 32-bit floats. Other float types, such as `float64`, are converted first, which makes a 32-bit copy.
230
+ - **PyTorch tensors on the CPU:** also computed in 32-bit floats with a dedicated PyTorch CPU path. 16-bit tensors (FP16, BF16) are accepted, but converted to 32-bit.
231
+
232
+ Note that on CPU the `quantizer` parameter must remain `None`. Also, faiss and PyTorch use all available cores by default. To use fewer, call `faiss.omp_set_num_threads(n)` and `torch.set_num_threads(n)`.
233
+
234
+ ## On GPU: four cases
235
+
236
+ What to do on GPU depends on what fits in its memory: the data, the centroids, or neither. If you want more speed, you can also use more GPUs.
237
+
238
+ | Your situation | What to use |
239
+ |---|---|
240
+ | The data and the centroids both fit on 1 GPU | `train(x)`, with `x` on 1 GPU, see "Data and centroids fit on 1 GPU" |
241
+ | The data does not fit on 1 GPU, the centroids do | the batch loop, see "Data too big for GPU memory" |
242
+ | The two previous cases, but you want faster training | several GPUs with replicated centroids, see `DistributedEmeans` in "Several GPUs"|
243
+ | The centroids do not fit on 1 GPU | several GPUs with sharded centroids, see `EmeansShardedCentroids` in "Several GPUs" |
244
+
245
+ ### Data and centroids fit on 1 GPU
246
+ Put the data on the GPU and call `train`. The last pass keeps every vector's label (8 bytes per vector, turned off by `capture_assignments=False`), and training ends with the exact closing mean. The GPU must hold the
247
+ data, the centroids with their running sums, the labels and a small working buffer.
248
+
249
+ ```python
250
+ import numpy as np, torch
251
+ from faiss.contrib.e_means import Emeans
252
+
253
+ xg = torch.from_numpy(x).cuda() # your float32 NumPy array, copied to the GPU once
254
+ em = Emeans(64, 1024, nepochs=5, check_finite=True) # raise on NaN or infinity
255
+ centroids, labels = em.train(xg) # both come back on the GPU
256
+ print(em.recipe["assignment_backend"], em.recipe["batch_size"]) # kernels used, batch size
257
+ ```
258
+
259
+ Two things to know:
260
+
261
+ - **The data must already be on the GPU.** A NumPy array or a CPU tensor trains on the CPU instead.
262
+ - **GPU data is checked for NaN or infinity only with `check_finite=True`.** Without it, one bad
263
+ value does not stop training and can go unnoticed. In our tests, one infinite coordinate left a
264
+ few broken centroids while the reported loss looked normal.
265
+
266
+ **Before training: will it run, and will it fit?** `supported` returns the kernels training
267
+ would use for a data type on a device (`"native"`, `"triton"` or `"cute"`), or `None` when
268
+ training would be refused, without running anything. `memory_estimate` returns an upper bound in
269
+ bytes on the GPU memory `train` needs for an untrained model, so you can pick `train` or the batch
270
+ loop below up front.
271
+
272
+ ```python
273
+ from faiss.contrib.e_means import supported, memory_estimate
274
+
275
+ supported("cuda", torch.bfloat16) # "triton" on an RX 9000 or A100
276
+ supported("cuda", torch.float8_e4m3fn, spherical=True) # None: spherical needs FP32/FP16/BF16
277
+ em = Emeans(64, 1024)
278
+ if memory_estimate(em, len(x), torch.float32, "cuda") < torch.cuda.mem_get_info()[0]:
279
+ centroids, labels = em.train(torch.from_numpy(x).cuda())
280
+ ```
281
+
282
+ - `supported` takes the data type the search sees: for `Emeans`, FP32 on a GPU is converted to
283
+ BF16 by default, so ask for `torch.bfloat16`; raw INT8/UINT8 codes are trained with
284
+ `QuantizedEmeans`. It checks the GPU and the installed software as training does, but does not
285
+ compile a kernel.
286
+ - `memory_estimate` covers `Emeans` and `QuantizedEmeans(quantizer=None)` on one GPU, includes the
287
+ data itself (`include_input=False` leaves it out) and BLAS workspaces measured on ROCm, and adds
288
+ a 25% margin. On an RX 9060 XT it was 1.07× to 1.33× the measured peak (20,000 × 32 to
289
+ 1M × 128 vectors, 64 to 16,384 centroids). Quantizers and `max_points_per_centroid` are not
290
+ covered.
291
+
292
+
293
+ ### Data too big for memory
294
+
295
+ This applies when your data does not fit in the memory of the device you train on (the GPU, or the RAM on a CPU), but the centroids do. `train` needs all the data as one array or tensor on that device. When your data does not fit on the device, you feed the batches yourself, and the model runs the same algorithm: `train` runs exactly this loop internally.
296
+
297
+ Training runs on the device of the starting centroids you pass to `begin`, and every batch must be on that
298
+ same device. Copy each batch there yourself, using the following training loop:
299
+
300
+ ```python
301
+ import numpy as np, torch
302
+ from faiss.contrib.e_means import Emeans
303
+
304
+ em = Emeans(d, k) # d: dimension, k: number of clusters
305
+ rng = np.random.default_rng(0)
306
+ start = torch.from_numpy(x[rng.choice(len(x), k, replace=False)]).cuda() # starting centroids
307
+ em.begin(len(x), start) # total rows: the model now lives on the GPU
308
+ B = em.recipe["batch_size"]
309
+ for rows in em.recipe["epoch_rows"]: # one entry per pass
310
+ order = rng.permutation(len(x))[:rows] # a fresh random order every pass
311
+ for i in range(0, rows, B):
312
+ batch = torch.from_numpy(x[order[i:i + B]]).cuda() # in practice: read from disk
313
+ em.update(em.accumulate(batch))
314
+ em.end_epoch()
315
+ centroids = em.finalize()
316
+ ```
317
+
318
+ Follow these rules:
319
+
320
+ - Don't forget to call `begin` and `finalize`.
321
+ - Every batch must be exactly the recipe's batch size, except the last one of each pass, which is
322
+ whatever is left.
323
+ - If you have to do batch accumulation because your batch size is too large, call `accumulate` on each piece, then `update` once with what the last `accumulate` returned.
324
+ - Every vector must appear exactly once per pass. The code checks the counts, not which vectors you
325
+ send.
326
+
327
+ As written, each copy waits for the GPU. To overlap loading and computing, use pinned host buffers
328
+ and a separate CUDA stream. The DINO demo's reader (`benchs/e_means/ssd_streaming.py`) does this for
329
+ data read from SSD.
330
+
331
+ If the data does not fit on one GPU but fits across several, sharded centroids do the batching for
332
+ you, see the next section.
333
+
334
+ ## Several GPUs
335
+
336
+ Multi-GPU training runs one copy of your program per GPU, launched with `torchrun`:
337
+
338
+ ```bash
339
+ torchrun --standalone --nproc-per-node=8 my_script.py
340
+ ```
341
+
342
+ Each copy owns one GPU, joins a group (`torch.distributed`), and loads only its own share of the
343
+ data onto its GPU. e-means never splits or moves your dataset: you decide which rows each copy loads,
344
+ usually by its rank. The copies synchronize inside e-means at every batch, so they must all make the
345
+ same calls with the same settings.
346
+
347
+ There are two classes, depending on whether the centroids fit on one GPU:
348
+
349
+ | | Copied centroids (`DistributedEmeans`) | Sharded centroids (`EmeansShardedCentroids`) |
350
+ |---|---|---|
351
+ | Centroids on each GPU | all of them | a slice, 1/n_gpus of them |
352
+ | Use it when | the centroids fit on one GPU | the centroids do not fit on one GPU |
353
+ | At each batch | each GPU processes its share of the batch against all centroids, then the per-cluster sums are added across GPUs | the whole batch is sent to every GPU, each scores it against its slice, and the GPUs agree on each vector's nearest centroid |
354
+ | Training | your own batch loop: there is no `train` | `train(x_local)` does the batching |
355
+ | Also on CPUs | yes | no, GPUs only |
356
+ | Requirements | the batch and the rows of every pass divide by the number of GPUs | the same, plus `k` divides by the number of GPUs, every GPU holds the same number of rows (the IVF variant also needs `quantizer=None`) |
357
+
358
+ The batch size is a power of two, so use 2, 4 or 8 GPUs: with 3 or 6, the batch does not divide.
359
+
360
+ With sharded centroids, every GPU holds the whole batch at once, gathered from all the GPUs.
361
+ Budget `batch_size * d * bytes per value` on each GPU for it, on top of your data and the centroids.
362
+
363
+ For sharded centroids, you have to run the following script on each GPU:
364
+
365
+ ```python
366
+ import os, numpy as np, torch, torch.distributed as dist
367
+ from faiss.contrib.e_means import EmeansShardedCentroids
368
+
369
+ local_rank = int(os.environ["LOCAL_RANK"])
370
+ torch.cuda.set_device(local_rank)
371
+ dist.init_process_group("nccl")
372
+ rank, world = dist.get_rank(), dist.get_world_size()
373
+
374
+ data = np.load("vectors.npy", mmap_mode="r") # nothing read yet
375
+ d, k = data.shape[1], 1024 # dimension, number of clusters
376
+ assert len(data) % world == 0, "data rows must divide evenly across ranks"
377
+ share = len(data) // world # equal shares
378
+ x_local = torch.from_numpy(np.array(data[rank * share:(rank + 1) * share])).cuda()
379
+
380
+ em = EmeansShardedCentroids(d, k, nepochs=5, group=dist.group.WORLD)
381
+ my_centroids, my_labels = em.train(x_local) # this GPU's slice, labels of its rows (global ids)
382
+
383
+ slices = [torch.empty_like(my_centroids) for _ in range(world)]
384
+ dist.all_gather(slices, my_centroids.contiguous()) # all k centroids, in order
385
+ dist.destroy_process_group()
386
+ ```
387
+
388
+ For copied centroids, the training loop each copy runs (with `d`, `k`, `x_local`, `rank` and `world` as above):
389
+
390
+ ```python
391
+ from faiss.contrib.e_means import DistributedEmeans
392
+
393
+ em = DistributedEmeans(d, k, nepochs=5, group=dist.group.WORLD)
394
+ dev = x_local.device
395
+ init = x_local[torch.randperm(len(x_local), device=dev)[:k]] # rank 0's starting centroids are used
396
+ em.begin(len(x_local) * world, init)
397
+ B = em.recipe["batch_size"] # the batch summed over all GPUs
398
+ for rows in em.recipe["epoch_rows"]: # rows per pass, over all GPUs
399
+ order = torch.randperm(len(x_local), device=dev)
400
+ for start in range(0, rows, B):
401
+ a, b = start // world, min(rows, start + B) // world # this GPU's share of the batch
402
+ em.update(em.accumulate(x_local[order[a:b]])) # sums are added across GPUs
403
+ em.end_epoch()
404
+ centroids = em.finalize() # the same on every GPU
405
+ ```
406
+
407
+ With sharded centroids, if you write your own loop over the data instead of calling `train` (as the
408
+ SSD demo does), the final means can come from the labels saved during the last pass, without searching again:
409
+ `em.final_closing_mean(batches, assignments=codes)`, called after the last pass and before `finalize`.
410
+ `codes` holds those labels on the CPU (int32 or int64, `-1` for rows the last pass skipped), and `batches`
411
+ must go over the rows in the same order. Without `assignments`, it assigns every row once more against
412
+ the final centroids.
413
+
414
+ `EmeansShardedCentroidsIVF` finds the nearest centroids with an IVF index, which is approximate and
415
+ pays off with very many centroids, typically above $10^6$. The 10-billion-vector DINO demos, resident on two GPUs and
416
+ streamed from SSD, are in `benchs/e_means/`, with their own README.
417
+
418
+ ## Kernels and data precision on GPU
419
+ ### Kernels
420
+ Most of e-means' runtime goes into assigning each training vector to its nearest centroid. We made optimized kernels in CuTe and Triton to make this computation as fast as possible. Note that we also provide a fallback to a plain PyTorch path, but it's much slower than the Triton and CuTe kernels, because it does not fuse the distance computation with the selection of the nearest centroid.
421
+
422
+ Which implementation your run will use (CuTe, Triton, PyTorch) is automatically selected from your GPU type and your data's precision.
423
+
424
+ | Your data | H100/H200 | B200 | B300 | A100 | Other recent GPUs (RTX 30/40, L40S, A10) | Older GPUs (V100, T4) | AMD MI300, MI350 (gfx942, gfx950)⁴ | AMD RX 7000, RX 9000 (gfx11xx, gfx120x)⁴ |
425
+ |---|---|---|---|---|---|---|---|---|
426
+ | FP32, default BF16 conversion | **CuTe**¹ | Triton¹ | Triton¹ | Triton¹ | Triton¹ | no | Triton¹ | Triton¹ |
427
+ | Native FP32 (`quantizer=None`) | Triton | Triton | Triton | Triton | Triton | PyTorch | Triton | Triton³ |
428
+ | BF16 | **CuTe** | Triton | Triton | Triton | Triton | no | Triton | Triton |
429
+ | FP16 | Triton | Triton | Triton | Triton | Triton | no | Triton | Triton |
430
+ | FP8 (`float8_e4m3fn`) | Triton² | Triton | Triton | no | no | no | MI350: Triton⁵; MI300: no | RX 9000: Triton⁵; RX 7000: no |
431
+ | INT8, UINT8 | Triton² | Triton | no | Triton | no | no | Triton⁶ | Triton⁶ |
432
+ | float64 | no | no | no | no | no | no | no | no |
433
+
434
+ - ¹ CUDA FP32 input uses BF16 operands by default. To retain native FP32 input, use
435
+ `QuantizedEmeans(d, k, quantizer=None)`. These are automatic choices for supported extents;
436
+ the selected backend is recorded in `em.recipe["assignment_backend"]`.
437
+ - ² CuTe if you pass `assignment_backend="cute"`.
438
+ - "no" means training is refused with an error at the start.
439
+ - Install the packages required by the selected backend. Missing, broken or incompatible required software
440
+ raises an error; e-means does not switch to another assignment backend. (One exception on AMD:
441
+ without Triton, the automatic choice on the four AMD families is PyTorch; see ⁴.)
442
+ - FP8 and INT8 data are used as raw codes in their own units, unless you pass the matching converter.
443
+ INT8 also needs a dimension of 43,919 or less.
444
+ - ³ RX 7000 and RX 9000 GPUs have no FP32 matrix instruction, so native FP32 is much slower than
445
+ BF16 there: 1.4× to 5.8× on an RX 9060 XT (200k × 64 to 4M × 128 vectors). Keep the default BF16
446
+ conversion on these cards. Triton is still faster than PyTorch for native FP32 (1.6×
447
+ measured), so it stays the automatic choice.
448
+ - ⁴ AMD support in this fork (v0.1; INT8 and FP8 in v0.2) is validated on RX 9000. On an RX
449
+ 9060 XT (gfx1200, ROCm 10.1) every precision above trains, the e-means tests pass, and Triton
450
+ is 2.1× to 9.3× faster than PyTorch for BF16 and 2.0× to 8.9× for FP16 (200k × 64 to
451
+ 4M × 128 vectors, more as the problem grows). RX 9000 GPUs use tile settings tuned for them,
452
+ which make the BF16/FP16 assignment kernel up to 3.5× faster and BF16 training up to 1.8×
453
+ faster than the NVIDIA-fitted defaults (INT8 and FP8: see ⁵ and ⁶). MI300 validation and
454
+ tuning are planned for v0.3; MI350 and RX 7000 are compile-checked only and use the
455
+ NVIDIA-fitted tile settings.
456
+ Other AMD GPUs (for example MI200, gfx90a) run native FP32 through PyTorch only; there, FP32 data stays FP32 instead of being converted to BF16.
457
+ On the four families without Triton, the automatic choice uses the slower PyTorch path (BF16 by
458
+ default, or your data's FP16/BF16/FP32) instead of raising an error as on NVIDIA.
459
+ - ⁵ FP8 on AMD (v0.2) needs a native E4M3 matrix instruction: MI350 (gfx950) and RX 9000
460
+ (gfx120x). MI300 and RX 7000 would only emulate it through FP16 (saving memory, not time) and
461
+ refuse FP8 with an error. On an RX 9060 XT the FP8 tests pass, the encode gives exactly
462
+ PyTorch's codes for every FP32 value up to 448 in magnitude, and training ends within 0.1% of
463
+ BF16's loss. With the FP8 settings tuned for RX 9000, FP8 training is 1.13× to 1.37× faster
464
+ than BF16 (200k × 64 to 4M × 128 vectors, 1,024 to 16,384 centroids). MI350 is compile-checked
465
+ only and uses the NVIDIA-fitted settings.
466
+ - ⁶ INT8 on AMD (v0.2) runs on the integer matrix instructions of all four families. On an RX
467
+ 9060 XT it trains, the INT8 tests pass and distances are exact. With the INT8 settings tuned for
468
+ RX 9000, the INT8 assignment kernel is 2.6× to 10× faster than with the NVIDIA-fitted
469
+ settings, and INT8 training is 1.02× to 1.37× faster than BF16 (200k × 64 to 4M × 128 vectors,
470
+ 1,024 to 16,384 centroids, final loss within 0.06% of BF16). Elsewhere the pipeline depth is set per
471
+ family so the kernel fits in 64 KiB of shared memory (upstream's setting needs up to 112 KiB
472
+ outside MI300). MI300 is to be checked in the v0.3 cloud session; MI350 and RX 7000 are
473
+ compile-checked only.
474
+ - On the CPU, computation remains FP32 (see On the CPU).
475
+
476
+ **More on AMD GPUs.**
477
+ - The CuTe kernels are NVIDIA H100/H200 only; `assignment_backend="cute"` raises an error on AMD.
478
+ - Training uses the plain (eager) loop on AMD, not CUDA-graph replay. Results are the same, only
479
+ speed differs. Replay works on the RX 9060 XT but gave no measurable speed-up there, so it is
480
+ opt-in: set `EMEANS_ROCM_GRAPH_REPLAY=1`.
481
+ - As on NVIDIA, training is not bit-reproducible by default: batch statistics are summed with
482
+ atomic additions, so repeated FP32 runs can end in different clusterings. For identical runs,
483
+ call `torch.use_deterministic_algorithms(True)` (verified on ROCm, eager and replay).
484
+ - `assignment_backend="native"` (PyTorch) handles FP32, FP16 and BF16 on the four families, as on
485
+ NVIDIA SM80+; it is verified on gfx1200 and 2.0× to 9.3× slower than Triton for FP16/BF16,
486
+ more as the problem grows.
487
+ - Several GPUs (`DistributedEmeans`, sharded centroids) are expected to work on AMD but are untested.
488
+
489
+ ### Data precision
490
+ The precision used in your e-means run has an important influence on training speed. On a GPU, e-means iterations can run in smaller number formats, which recent GPUs process faster: 16-bit floats (FP16, BF16), 8-bit floats
491
+ (FP8) or 8-bit integers (INT8). The centroids, the running sums and the returned distances always
492
+ stay in 32-bit floats (FP32): only the nearest-centroid search uses the smaller format because it is the main bottleneck. On the CPU, everything is FP32.
493
+ By default, FP32 data on a GPU is converted to BF16 for that search, by a `CastQuantizer(d, torch.bfloat16)`.
494
+ To keep the search in real FP32 instead, use `QuantizedEmeans(d, k, quantizer=None)`.
495
+
496
+ **How the format is chosen:** by your data's type, or by a converter you pass. Apart from that BF16
497
+ default for FP32 data, e-means never converts on its own. The kernels used for each format and GPU
498
+ are in the table under Kernels, above.
499
+
500
+ | Input numbers | CuTe kernels (H100) | Triton kernels | PyTorch kernels |
501
+ |---|---|---|---|
502
+ | Native FP32 (`quantizer=None`) | not supported | A100 or newer, AMD MI300/MI350/RX 7000/RX 9000 | CPU and any CUDA or ROCm GPU |
503
+ | FP16, BF16 | BF16 only | A100 or newer, AMD MI300/MI350/RX 7000/RX 9000 | A100 or newer, AMD MI300/MI350/RX 7000/RX 9000 |
504
+ | FP8 (E4M3) | yes | H100, B200, B300, AMD MI350/RX 9000 | not supported |
505
+ | INT8, UINT8 | yes | A100, H100, B200, AMD MI300/MI350/RX 7000/RX 9000; dimension up to 43,919 | not supported |
506
+
507
+ **How to convert data to lower precision.** You can either convert once yourself before training, which also saves memory, or keep the original precision in memory and pass a **converter** (`quantizer=`), which converts each chunk on the fly for faster distance computation:
508
+
509
+ | Target | Convert once yourself | Keep FP32, convert on the fly |
510
+ |---|---|---|
511
+ | BF16 | `x.to(torch.bfloat16)` | Pass quantizer `CastQuantizer(d, torch.bfloat16)` when instantiating `QuantizedEmeans` |
512
+ | FP16 | `x.to(torch.float16)` | `CastQuantizer(d, torch.float16)` |
513
+ | FP8 | `q.compute_codes(x)` with a calibrated `Fp8Quantizer` | the calibrated `Fp8Quantizer` |
514
+ | INT8 | `q.compute_codes(x)` with a calibrated `Int8Quantizer` | not available: INT8 only takes codes made up front |
515
+
516
+ ```python
517
+ from faiss.contrib.e_means import QuantizedEmeans
518
+ from faiss.contrib.e_means.quantizer import CastQuantizer
519
+ from faiss.contrib.e_means.quantizer_fp8 import Fp8Quantizer
520
+ from faiss.contrib.e_means.quantizer_int8 import Int8Quantizer
521
+
522
+ xg32 = torch.from_numpy(x).cuda()
523
+
524
+ # Native FP32, without the default BF16 conversion
525
+ centroids, labels = QuantizedEmeans(64, 1024, quantizer=None).train(xg32)
526
+
527
+ # BF16, converted on the fly
528
+ centroids, labels = QuantizedEmeans(64, 1024, quantizer=CastQuantizer(64, torch.bfloat16)).train(xg32)
529
+
530
+ # FP8: calibrate on a sample, then train on FP32 data (encoded per chunk)
531
+ q = Fp8Quantizer(64)
532
+ q.train(xg32[:50_000])
533
+ q.to(xg32.device)
534
+ centroids, labels = QuantizedEmeans(64, 1024, quantizer=q).train(xg32)
535
+
536
+ # INT8: calibrate, encode everything once, train on the codes
537
+ q = Int8Quantizer(64)
538
+ q.train(xg32[:50_000])
539
+ q.to(xg32.device)
540
+ centroids, labels = QuantizedEmeans(64, 1024, quantizer=q).train(q.compute_codes(xg32))
541
+ ```
542
+
543
+ With a converter, the centroids and distances come back in your original FP32 units.
544
+
545
+ **Values that do not fit the format:**
546
+
547
+ | Format | Values outside its range |
548
+ |---|---|
549
+ | BF16 | never in practice: it has FP32's range. It only rounds, keeping about 3 significant digits |
550
+ | FP16 | values of 65,520 and above become infinity, silently: no clipping and no warning |
551
+ | FP8, INT8 | the converter is calibrated on your sample: a shift per dimension and one power-of-two scale. Values beyond the sample's range are clamped to the edge (448 for FP8) |
552
+
553
+ So with FP16, check the data once with `CastQuantizer(d, torch.float16).validate(x)`, which raises if
554
+ anything is out of range, or use BF16. With FP8 and INT8, calibrate on a sample that includes your
555
+ extremes. `validate` reports out-of-range values for FP8. For INT8, clamping outliers is accepted by
556
+ design.
557
+
558
+ **Centering.** `CastQuantizer(d, dtype, center=True)` subtracts your data's mean before rounding to 16
559
+ bits. Call `train(sample)` to fit the mean and `to(device)` before use. It helps when the vectors sit
560
+ far from the origin, where rounding would otherwise spend the few available digits on the shared
561
+ offset. It is not available in spherical mode. With centering, pass FP32 data or
562
+ `q.compute_codes(x)`, not data you converted with `.to(...)` yourself.
563
+
564
+ **Low dimension.** In very low dimensions (2 or 3), 16-bit formats are more likely to hurt the result, so FP32 is the safer choice: on a GPU, use `QuantizedEmeans(d, k, quantizer=None)` to keep FP32.
565
+
566
+ ## How the centroid updates work
567
+
568
+ e-means is based on exponential moving average updates: each centroid is the ratio of two running averages: one counts the number of points the cluster receives, the other sums the embeddings of these points. At each mini-batch, these averages are updated as follows:
569
+
570
+ ```
571
+ N_j <- (1 - alpha) * N_j + alpha * n_j # running count of the points cluster j receives
572
+ S_j <- (1 - alpha) * S_j + alpha * s_j # running sum of those points
573
+ c_j = S_j / N_j # the centroid
574
+ ```
575
+
576
+ Here `n_j` and `s_j` are the count and the sum of the batch's points assigned to cluster j, and `alpha` is the step size. With the whole dataset as one batch and a step of 1, this is exactly one Lloyd iteration. The components added by e-means are:
577
+
578
+ - The batch size and the starting step size come from two scaling laws, setting them automatically for any problem size.
579
+ - The step size shrinks during training along a cosine curve, down to a tenth of its starting value.
580
+ - A cluster that receives too few points is revived by splitting a busy cluster in two, as faiss does. By default this is off for $d \le 2$ (see the note on low dimension under Parameters).
581
+ - At the end of the last pass, each centroid is set to the exact mean of the points that pass assigned to it. This costs nothing extra, because those assignments were already made.
582
+
583
+ ## Spherical e-means
584
+
585
+ **What it does.** Spherical e-means clusters vectors by direction instead of position. It maximizes the cosine similarity between each vector and its centroid. On vectors of norm 1, this is the same as minimizing the squared distance on the unit sphere, which equals 2 − 2 × cosine.
586
+
587
+ **How it works.** It is the e-means update of the previous section, with three changes:
588
+
589
+ - Before every use, each centroid is its running average rescaled to norm 1. A zero centroid stays
590
+ zero.
591
+ - Each vector goes to the centroid with the highest dot product, which for vectors of norm 1 is the
592
+ highest cosine similarity.
593
+ - The closing step takes each cluster's exact mean, then rescales it to norm 1.
594
+
595
+ The reported error is the sum of 2 − 2 × similarity over the vectors.
596
+
597
+ **How to use it.** Normalize your vectors to norm 1 yourself, then pass `spherical=True`:
598
+
599
+ ```python
600
+ xs = torch.nn.functional.normalize(xg32, dim=1) # every vector now has norm 1
601
+ em = Emeans(64, 1024, spherical=True)
602
+ centroids, labels = em.train(xs)
603
+ similarity, labels = em.assign(xs) # similarity: higher is closer
604
+ ```
605
+
606
+ - `assign` returns each vector's dot product with its nearest centroid, where higher is closer, so make sure your vectors are normalized to obtain cosine similarity.
607
+ - It works with 32-bit and 16-bit floats, not with FP8 or INT8, and not with a centered `CastQuantizer`.
608
+ - The model does not check the norm of your vectors. Vectors that are not of norm 1 are accepted silently. Their labels still follow cosine similarity, but long vectors pull their centroid harder than short ones, and the reported error and similarities are no longer cosine quantities.
609
+
610
+ ## Demos and tests
611
+
612
+ ```bash
613
+ python demos/demo_e_means.py --data-dir /path/to/data # DEEP1M, one GPU, 3 passes, 10 seeds
614
+ torchrun --standalone --nproc-per-node=2 demos/demo_e_means_distributed.py
615
+ torchrun --standalone --nproc-per-node=2 demos/demo_e_means_sharded.py
616
+ python -m unittest discover -s tests -p 'test_e_means.py'
617
+ python -m unittest discover -s tests -p 'torch_test_e_means*.py'
618
+ ```
619
+
620
+ The tests need two commands, because Python's default test discovery skips the PyTorch test files.
621
+
622
+ On AMD GPUs, the same commands run the Triton tests on the four supported families; tests of
623
+ CuTe, several GPUs, and FP8 on MI300 and RX 7000 are skipped. Add `EMEANS_ROCM_GRAPH_REPLAY=1`
624
+ to also run the CUDA-graph replay tests. Some tests need no GPU at all: they compile the Triton
625
+ kernels for gfx942, gfx950, gfx1100 and gfx1200 and check the generated code
626
+ (`torch_test_e_means_ptx_free.py`, `torch_test_e_means_amd_fences.py`,
627
+ `torch_test_e_means_int8_compile.py`), and others mock the device
628
+ (`torch_test_e_means_backend_selection.py`, `torch_test_e_means_device_profile.py`). To run
629
+ tests without
630
+ touching an AMD GPU, hide it with `ROCR_VISIBLE_DEVICES=` (empty); `HIP_VISIBLE_DEVICES=-1`
631
+ aborts on ROCm 10.1.
632
+ The 10-billion-vector demos (DINO10B, resident and from SSD) are in `benchs/e_means/`, with their own README.