e-means clustering
Fit native mini batch clustering with exponential moving statistics, inspect final labels and select CPU, Apple Metal or NVIDIA CUDA execution.
ImplementedAner 0.1.0 or newerA moving mean with a memory
Each centroid carries a position and an EMA mass. A new batch contributes both a sum and a count. Its influence depends on how many points reached this cluster.
For the same 0 < α < 1, a cluster receiving more points moves farther toward its batch mean. Applying α directly to the centroid would lose this count adjustment.
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. Earlier dev.3/dev.4 studies keep their original source identities and qualification cutoffs.
ml.fit_emeans fits an immutable CentroidModel using occupancy weighted exponential moving averages (EMA), shuffled mini batches, a cosine step schedule, low mass cluster revival and a closing mean. This is the November 2026 e-means technique, unrelated to the older evolutionary E-Means algorithm.
The full API on this page requires Aner 0.0.10 or newer. It is native C++ with Aner Tensor storage, bounded aner.parallel workers and native Metal and CUDA Float32 kernels. The portable release profiles provide CPU execution and Metal on compatible Apple builds; CUDA requires a separately built CUDA enabled profile and compatible NVIDIA hardware. A version number alone does not establish that optional backend. FAISS, Python, PyTorch and Triton are references, not runtime dependencies. The existing Lloyd K-means and contextual mini batch K-means keep their own contracts. Follow the complete data science workflow for training only preprocessing, multiple seeds and held out evaluation.
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_emeans(features: x, clusters: 2,
epochs: 3.0, seed: 42, execution: execution)
print(model.summary())
print(model.inertia())
let predicted = model.predict(input: [[0.0, 1.0], [10.0, 11.0]],
execution: execution)
print(tensor.value(predicted, 0, 0))Cluster IDs are arbitrary center indices. A lower squared distance objective does not prove more meaningful groups, better classification or a global optimum. Fit any standardizer using training rows, and apply that same transform to queries. See the runnable CPU example and Metal example.
Every fitting parameter
ml.fit_emeans(features: Tensor, clusters: Int64, epochs: Float64, seed: Int64,
batch_size: Int64 = 0, alpha0: Float64 = 0.0,
max_workspace_bytes: Int64 = 268435456,
unused_threshold: Float64 = -1.0) -> CentroidModel
// The context overload inserts execution after seed.
ml.fit_emeans(features: Tensor, clusters: Int64, epochs: Float64, seed: Int64,
execution: ParallelContext, batch_size: Int64 = 0,
alpha0: Float64 = 0.0,
max_workspace_bytes: Int64 = 268435456,
unused_threshold: Float64 = -1.0) -> CentroidModel| Parameter | Meaning and effect |
|---|---|
features | Finite N × D Tensor, with positive dimensions. CPU Float32/Float64, Metal Float32 and native CUDA Float32 are supported. Device placement selects the engine. |
clusters | Required Int64 from 1 through N. More centers change both the objective and computational cost; occupied clusters are not guaranteed. |
epochs | Required finite positive Float64 pass budget, at most 1000. 3.0 means three training passes; it is not a stopping tolerance. Fractional passes retain their remainder batch. |
seed | Required signed Int64 seed for initial rows and shuffling. Record it with data order, dtype, backend, binary and recipe. |
execution | Optional local CPU context. parallel.local(workers: 4) admits bounded workers; it does not reserve physical cores or choose the GPU. Omission selects a bounded native worker count for substantial work and serial execution for small phases. |
batch_size | Zero selects the empirical recipe. A positive override selects logical statistical batch rows, capped at N. Physical kernel tiles do not create additional EMA updates. |
alpha0 | Zero selects the empirical step law. An explicit value must be in (0, 1]; occupancy and cosine decay determine actual center movement. |
max_workspace_bytes | Positive charged workspace admission limit; default 256 MiB. Input storage, allocator and driver overhead are outside this estimate; it is not a process RSS limit. Insufficient admission fails. |
unused_threshold | Default -1.0 selects the dimension dependent revival recipe. Zero disables revival; a finite nonnegative value overrides the relative moving mass threshold. This controls weak center revival, not a convergence tolerance. |
The engine also admits at most 256 million input elements, one million statistical updates and a checked coordinate work ceiling. Existing Tensor construction budgets still apply before fitting. Distance or reduction overflow fails explicitly; the GPU engines reject any evaluated nonfinite candidate distance, including one that would not win the assignment. These are finite range floating point engines, not the legacy exact sum K-means policy.
Named arguments may be reordered and optional controls omitted independently. The examples write epochs: 3.0 to make the Float64 pass budget explicit. Input and output tensors are detached from automatic differentiation. Unsupported devices or remote execution contexts fail explicitly.
What the update computes
For one logical batch, let n[j] be cluster occupancy and s[j] its coordinate sum. M[j] is the moving mass and c[j] is its center:
M_new[j] = (1 - alpha) * M[j] + alpha * n[j]
weight = alpha * n[j] / M_new[j]
c_new[j] = c[j] + weight * (s[j] / n[j] - c[j])An empty batch cluster retains its position while its mass decays for alpha < 1. At exactly alpha = 1, the reference compatible branch retains an empty cluster's previous mass; occupied clusters take their batch mean and count. The weight depends on occupancy: with old mass 8, batch count 2 and alpha 0.5, new mass is 5 and center weight is 0.2. Moving a center from 0 toward a batch mean of 10 therefore gives 2. A plain EMA of centroid positions would give a different result.
The training loop, in four steps
- 01
Assign a batch
Compare rows against the current centroid snapshot. Keep one winning cluster per row.
- 02
Collect statistics
Sum the coordinates and count the points assigned to each cluster.
- 03
Update the EMA
Combine new statistics with retained mass. The cosine schedule reduces the step as training proceeds.
- 04
Close and evaluate
Form the closing means, then exhaustively assign the fitting rows against the returned centers to report final labels and distortion.
At scheduled checks, a centroid receiving too little mass can be revived by splitting a busy centroid. Random seed, update order and revival policy are part of the reproducible run.
Initialization selects distinct training row indices; duplicate coordinates can still occur. Rows are shuffled each pass. Every five updates, low mass centers can be revived by splitting weighted donors. Revival is disabled by the default recipe when D ≤ 2. The final full pass accumulates closing statistics, then forms means; empty closing clusters retain their current centers.
Fractional budgets put the full closing pass last. epochs: 2.5 processes [N, round(0.5*N), N] rows across its passes. Below one epoch, only a shuffled prefix is trained. Final output evaluation still assigns all fitting rows against the returned centers.
Recipe and reproducibility
The implementation follows the pinned FAISS source recipe, rather than treating rounded paper constants as a different specification:
B_throughput = 0.035134 * k^0.134749 * N^0.876473 * T^0.813344
B_quality = 0.00439175 * k^0.134749 * N^0.876473 * T^0.813344
alpha0 = clamp(0.8244 * k^-0.4617 * B^0.9003
* N^-0.4498 * T^-0.1057, 0.0001, 1.0)
alpha(t) = alpha0 * (0.1 + 0.9 * (1 + cos(pi*t/updates))/2)Automatic batches use the reference power of two rounding and row count caps. The default selects the quality batch law at D ≤ 16, throughput otherwise. Initial moving mass is 2^-16; the default relative revival threshold is 0.1 above two dimensions, with perturbation 1e-4. Inspect recipe(), batch_size() and alpha0() instead of assuming an unrecorded setting.
The stochastic stream and floating point arithmetic are native Aner policies. Bitwise agreement with NumPy, CUDA, Triton, other GPUs or another compiler is not promised. Float32 Metal and CPU Float64 also represent different numerical experiments. The legacy K-means exact accumulation guarantee does not transfer to these models.
M2 placement and workers
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_emeans(device_x, 2, 3.0, 42)
print(model.device())
print(model.summary())The GPU engine retains centers, moving masses, integer labels and reduction state in reusable native buffers. Assignment, reductions and updates share a batch command submission. Revival and o-means index maintenance require checked host synchronization. No dense N × k distance matrix is retained. Unified memory reduces transfer friction but does not remove dispatch, reduction or synchronization cost; small inputs may favor CPU execution.
CPU fitting uses the bounded local executor and stable reduction order. Avoid wrapping a single fit in competing worker tasks simply to request more cores. Multiple independent fits and one internally parallel fit are different resource plans. Distributed and multiple GPU clustering are separate extensions.
Native NVIDIA execution
The retained development CUDA builds passed the independent algorithm oracles, public fitting/query tests and NVIDIA memory, race and synchronization checks on a V100 PCIe 32 GB. Those results identify their exact development binaries; they do not qualify a rebuilt stable package. The supplementary 0.0.10 Linux CUDA profile is being prepared separately from the portable defaults, and stable profile L40 qualification remains pending. The backend uses native CUDA Float32 kernels and existing Aner Tensor storage, with Volta compatible reductions, ordered sums, reusable device buffers and bounded pinned transfer staging. There are no floating point atomic sums or retained N × k distance matrices. Index construction and revival remain host coordinated, so their discrete device transfers are included in total fit time.
Run the CUDA example only with a matching CUDA enabled runtime; the complete example includes e-means, o-means and p-means. Move Float32 features and queries explicitly with nn.to(input, "cuda"); the first visible CUDA device is used. The local context bounds host work. CUDA Float64 clustering and CPU fallback from an unavailable GPU are not supported.
V100 builds require a CUDA toolkit that still compiles Volta, such as the qualified CUDA 12.9 toolchain, and architecture 70. L40 code uses architecture 89. Compiling L40 code alone does not establish execution; the completed dev.6 L40 campaign separately passed CPU/CUDA correctness and timing. Language and memory/race/synchronization checks on the shared portable binaries remain scoped to V100.
Prediction and readouts
Both e-means and o-means return the same CentroidModel interface.
| Readout | Contract |
|---|---|
predict(input: Tensor, execution?, max_workspace_bytes?) | Exhaustive nearest final center assignment; same feature count, dtype and device as fitting. Returns CPU Float64 Q × 1 cluster IDs. |
score(input: Tensor, execution?, max_workspace_bytes?) | Nonnegative exhaustive squared distance sum on query rows, using the same arithmetic as inertia(). Divide by Q for held out MSE. The score is not negated. |
squared_distances(input: Tensor, execution?, max_workspace_bytes?) | Detached CPU Float64 Q × 1 distances to the nearest returned center. These are backend rounded squared distances, not probabilities or a dense Q × k matrix. |
centers() | Detached k × D final centers in the fitted dtype and device. |
labels() | Detached CPU Float64 N × 1 final nearest center IDs in original fitting row order. |
cluster_sizes() | Detached CPU Float64 k × 1 counts of final training labels, including unoccupied centers. Counts sum to training_rows(). |
inertia() | Compensated Float64 sum of the backend rounded squared distances from exhaustive final assignment. Metal and CUDA distances are computed in Float32, not independently rescored in Float64. Divide by N for MSE; there is no extra division by feature count. |
algorithm(), recipe(), device() | Algorithm name, empirical recipe identity and actual fitted backend. |
seed(), dtype(), training_rows(), features() | Recorded fitting seed, numerical dtype, training row count and feature count. These complement the caller's dataset, feature order and partition records. |
batch_size(), alpha0(), epochs() | Resolved batch and step, and requested epoch budget. |
unused_threshold() | Resolved relative revival threshold, including the selected default. |
updates(), samples_seen(), revivals() | Completed statistical updates, training row visits and revived centers. Final evaluation visits are separate from samples_seen(). |
coarse_cells(), probes() | Zero for e-means; resolved o-means index settings otherwise. |
workers(), workspace_bytes() | Admitted CPU workers and charged workspace estimate. |
training_seconds(), summary() | Native fitting duration including initialization, index maintenance, closing, final exhaustive assignment and output construction; and a readable description. The internal timer ends before backend/scratch destruction; the external benchmark timer includes that cleanup. |
The final exhaustive evaluation is an intentional API difference from upstream moving pass labels. Include its cost in end to end comparisons. No convergence flag is inferred from a fixed stochastic budget. Each prediction, score or distance call performs its own exhaustive query assignment; request only the outputs the experiment needs. The model does not retain a portable checkpoint or training continuation state.
Evidence and references
The authors report roughly 10 to 45× GPU speedups in their H100 benchmark regimes, with fewer epochs to their comparison loss. Those measurements are not M2 results or guarantees for Aner. Compare total time at a defined final objective, with the same data, preprocessing, dtype, initialization policy, warm up and timer boundaries.
- Original paper, Bessa et al., arXiv:2611.09501, submitted November 6, 2026.
- Official project.
- Pinned FAISS recipe and lifecycle, NumPy algorithm, Tensor implementation.
- Pinned benchmark protocol.
- Matched dev.4 M2/V100 benchmark protocol and results, including the offline L40 qualification procedure. L40 was pending at that retained study's cutoff; the separate dev.6 study above records its later execution.
- Historical dev.3 M2 benchmark protocol and results, with their original version and fingerprints.
The source reference is MIT licensed. See clustering attribution. Automatic recipes are empirical; evaluate several seeds and held out distortion before selecting a model for a new dataset.
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