o-means clustering
Reduce nearest centroid search with coarse cells, understand approximate training and compare final clustering quality.
ImplementedAner 0.1.0 or newerSearch nearby groups of centroids
The centroids belong to coarse cells. A point first chooses nearby cell centers, then searches only the centroids in those cells. More probes cover more candidates.
The query lies near a cell boundary. Its closest centroid belongs to the second nearest coarse cell. Try two probes.
Why large codebooks can benefit
With balanced cells, a point compares against G coarse centers and about p × k/G fine centroids. Explore the reference defaults.
The cells must stay current as centroids move. Refreshing, rebuilding, sorting and uneven cell sizes all consume time. The native benchmark must measure those costs too.
Read the native execution guide to compare all four methods, understand Tensor placement and CPU worker budgets, and connect the native mechanisms to measured results.
The separate dev.7 optimization study measures bounded final evaluation tiles and optional native phase profiles, with exact numerical checks. Its recorded qualification is distinct from the historical results below; these controls add no Aner language arguments.
The dev.6 three host study now retains actual M2 Metal, V100 CUDA and L40 CUDA measurements, CPU worker curves and separate strict Lloyd CPU supplements. It preserves the earlier dev.3/dev.4 observations as distinct historical studies.
ml.fit_omeans extends the e-means moving mass update with a two level centroid index. Each centroid belongs to one coarse cell. Each training point probes several cells, searches their centroids, and checks the winning donor's child and grandchild after revival. This reduces assignment work at large k, but can miss the true nearest center during training.
The full API on this page requires Aner 0.0.10 or newer. It uses aner.tensor storage and bounded aner.parallel CPU execution; no FAISS or Python runtime is loaded. Portable release profiles provide CPU execution and Metal on compatible Apple builds. CUDA requires a separate CUDA enabled profile; the supplementary stable Linux CUDA package and its hardware qualification are independent of the retained development benchmarks. Read e-means parameters and shared readouts and the complete data science workflow first.
Quick start
import aner.ml
import aner.tensor
import aner.parallel
let x = [[0.0, 0.0], [0.0, 2.0], [10.0, 10.0], [10.0, 12.0]]
let execution = parallel.local(workers: 4)
let model = ml.fit_omeans(features: x, clusters: 2,
epochs: 3.0, seed: 42, execution: execution)
print(model.summary())
print(model.coarse_cells())
print(model.probes())
let labels = model.predict(input: x, execution: execution)
print(tensor.value(labels, 0, 0))This small example explains the API; it does not demonstrate a speedup. With small k, the recipe probes every cell and index maintenance may add overhead. Run omeans_native.aner or the shared Metal example. O-means accepts the e-means fitting controls plus the index overrides below.
| Optional parameter | Meaning and constraints |
|---|---|
coarse_cells: Int64 = 0 | Zero selects the recipe. An override must be between 1 and clusters; it sets the number of disjoint centroid cells, not the requested output clusters. |
probes: Int64 = 0 | Zero selects the recipe. An override must be between 1 and min(coarse_cells, 24) after resolving the cell count. More probes examine more candidate cells at each update. |
The shared unused_threshold override also applies. These controls can be omitted independently and named arguments can be reordered. coarse_cells() and probes() report the actual settings; query prediction, score and per row squared distances remain exhaustive regardless of these training controls.
import aner.ml
let x = [[0.0], [2.0], [10.0], [12.0]]
let model = ml.fit_omeans(x, 2, 3.0, 42,
coarse_cells: 2, probes: 1, unused_threshold: 0.0)
print(model.coarse_cells())
print(model.probes())
print(model.unused_threshold())How the two levels work
A shared update, a smaller search
- 01
Build coarse cells
Group the current centroids. Every centroid belongs to one cell; the index is refreshed as centers move.
- 02
Probe and assign
Search selected cells, then check the winning donor’s child and grandchild after revival.
- 03
Update and revive
Accumulate counts and sums, update the moving mass, and revive weak centers at scheduled checks.
- 04
Close and evaluate
Form final means and exhaustively assign the fitting rows against the centers returned to the caller.
Rebuilds clear child links and refresh centroid membership. The schedule below records the initial policy and the policies used during the first pass and later passes.
Multiple probes matter near cell boundaries: the closest coarse center need not own the closest fine centroid. Probing more cells improves candidate coverage but costs more comparisons. Coarse cells are disjoint centroid memberships; the overlap is in each point's search across multiple cells. This is not a persistent point bound algorithm or a centroid neighbor graph.
The reference defaults are:
G = min(k, max(16, 16 * ceil(floor(k/128)/16)))
p = min(G, 24 if k > 16384 else (12 if D >= 512 else 16))With balanced cells, assignment considers approximately G + p*k/G + 2 candidates per point, rather than k. This is an operation count estimate, not a time prediction. Cell imbalance, index refresh, memory access and reductions affect actual performance.
Schedule and differences from e-means
| Component | Native o-means recipe |
|---|---|
| Initial index | Four coarse Lloyd updates, followed by assignment into cells. |
| First training pass | Rebuild every five batches, with zero coarse Lloyd updates. |
| Later passes | Rebuild every max(5, ceil(ceil(N/B)/2)) batches, with two coarse Lloyd updates. |
| Batch law default | Throughput law for N ≤ 2,000,000, quality law above that; e-means instead selects by dimension. |
| Less than one epoch | Derive batch and step recipes at one epoch, then process the requested fractional row budget. |
| Less than two epochs | Accumulate closing statistics with weight exp(-(total_rows - rows_processed)/N). Revival divides donor closing sums and mass between donor and child. |
| Two or more epochs | Ordinary closing statistics over the final full pass. |
| Rebuild and IDs | Clear child links at rebuild. Aner retains stable external centroid IDs through indirection instead of exposing index sorting as a change of cluster identity. |
| Returned labels and loss | Additional exhaustive assignment against returned centers, even though training used approximate search. |
The stable ID implementation and native Float32/Float64 arithmetic are recorded port choices. The reference uses CUDA kernels with different precision and accumulation policies. Identical seeds do not imply bitwise equality across implementations. Automatic settings are inspectable with recipe(), coarse_cells(), probes(), batch_size() and alpha0().
M2 execution and practical choice
import aner.ml
import aner.nn
import aner.tensor
let x = [[0.0, 0.0], [0.0, 2.0], [10.0, 10.0], [10.0, 12.0]]
let device_x = nn.to(x.astype("Float32"), "mps")
let model = ml.fit_omeans(device_x, 2, 3.0, 42)
print(model.summary())Tensor placement selects CPU, Metal or native CUDA Float32; the optional local context bounds CPU work. Reusable device buffers retain batch state. A prepared centroid layout groups neighboring cell members for contiguous CPU vector and GPU memory access, while labels retain external IDs; GPU coarse probing uses one SIMD group or CUDA warp per row. Coarse index construction and donor revival have checked host synchronization boundaries, so this native port is not an entirely asynchronous GPU pipeline. Workspace admission includes index and scratch estimates without retaining a full data by centroid matrix. Native CUDA passed correctness and memory/race/synchronization qualification on V100; the separate dev.6 L40 campaign passed actual CPU/CUDA correctness and measurements, without rerunning those sanitizer checks. Distributed clustering remains separate work. See NVIDIA execution and the dev.6 CUDA e/o/p example.
Use e-means as the exhaustive assignment baseline. Evaluate o-means when k is large enough that multiple cell search reduces candidate work. Compare final distortion as well as elapsed time. If all cells are probed, the assignment savings disappear. If cells become imbalanced or the index becomes stale, throughput or quality can deteriorate.
Evidence and references
The authors report 4.49× geometric mean equal error speedup over their e-means baseline using interpolated crossings on RTX 5090, and 4.08× using measured points only. The published ablation attributes part of the gain to shared kernel/numerical changes. These figures cannot be multiplied by e-means' H100 speedup claims or applied to M2.
The paper also reports missed nearest centers, sensitivity to cell imbalance, and cases where longer e-means runs reach lower error. Thus o-means does not universally produce better models. Matched dev.4 M2/V100 measurements report actual native timing and final objective. Historical dev.3 M2 measurements retain their original identity. L40 was pending at those retained studies' cutoffs; the separate dev.6 three host study now records its execution.
- Owlgebra announcement, November 12, 2026.
- Full paper: Two Level Assignment for Mini Batch
k-Meansat Large k, Rahul Bajaj, Jaya Nupur and Anuj Garg, November 2026. - Pinned implementation and README.
- Pinned schedule and public benchmark.
The code reference is MIT licensed; see clustering attribution. Public author benchmarks are evidence for those particular protocols, not independent validation of this native port.
See the Machine learning module reference for the shared API.
Time and quality, side by side
These observations come from the retained native run on Apple M2 Max with Aner 0.0.10-dev.3. Select a workload to compare the same dimensions, cluster count, epoch budget and seed.
2,048 rows · 16 dimensions · 32 clusters · 3 epochs · seed 42 · Float32 input
| Configuration | MSE | Inertia | Timing runs |
|---|---|---|---|
| e-means · 1 CPU worker · Float32 | 6.72130 | 13765.2 | 5 |
| e-means · 4 CPU workers · Float32 | 6.72130 | 13765.2 | 5 |
| e-means · 8 CPU workers · Float32 | 6.72130 | 13765.2 | 5 |
| e-means · 12 CPU workers · Float32 | 6.72130 | 13765.2 | 5 |
| e-means · Metal + 4 CPU workers · Float32 | 6.72130 | 13765.2 | 5 |
| o-means · 1 CPU worker · Float32 | 11.1275 | 22789.0 | 5 |
| o-means · 4 CPU workers · Float32 | 11.1275 | 22789.0 | 5 |
| o-means · 8 CPU workers · Float32 | 11.1275 | 22789.0 | 5 |
| o-means · 12 CPU workers · Float32 | 11.1275 | 22789.0 | 5 |
| o-means · Metal + 4 CPU workers · Float32 | 11.1275 | 22789.0 | 5 |
| Lloyd k-means · 1 CPU worker · Float64 | 10.9832 | 22493.5 | 5 |
| Lloyd k-means · 4 CPU workers · Float64 | 10.9832 | 22493.5 | 5 |
MSE: inertia / n; sum of backend precision squared coordinate distances per observation. Read distortion alongside elapsed time. A faster run with a larger error is a different tradeoff; this chart does not establish a speedup at equal quality. Lloyd uses the existing strict CPU engine with Float64 and exact centroid accumulation; see the measurement protocol.
Inspect the raw benchmark evidence