Browse documentation
aner.ml · Reference

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 newer
Explore one update

A 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.

Points assigned in this batch
The centroid moves toward the batch meanPrevious centroid 2, batch mean 8, previous EMA mass 8. The new centroid is 3.500, with a batch influence of 25.0 percent.012345678910New center · 3.50Previous centerBatch mean
An arithmetic illustration in one dimension. The batch mean stays at 8 and the previous centroid stays at 2. This is not a measured training trajectory.
Retained mass6.00(1 − α) × 8
Incoming mass2.00α × 8
Batch influence25.0%incoming ÷ total mass

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

aner
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

text
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
ParameterMeaning and effect
featuresFinite N × D Tensor, with positive dimensions. CPU Float32/Float64, Metal Float32 and native CUDA Float32 are supported. Device placement selects the engine.
clustersRequired Int64 from 1 through N. More centers change both the objective and computational cost; occupied clusters are not guaranteed.
epochsRequired 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.
seedRequired signed Int64 seed for initial rows and shuffling. Record it with data order, dtype, backend, binary and recipe.
executionOptional 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_sizeZero selects the empirical recipe. A positive override selects logical statistical batch rows, capped at N. Physical kernel tiles do not create additional EMA updates.
alpha0Zero selects the empirical step law. An explicit value must be in (0, 1]; occupancy and cosine decay determine actual center movement.
max_workspace_bytesPositive 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_thresholdDefault -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:

text
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.

From data to fitted centers

The training loop, in four steps

  1. 01

    Assign a batch

    Compare rows against the current centroid snapshot. Keep one winning cluster per row.

  2. 02

    Collect statistics

    Sum the coordinates and count the points assigned to each cluster.

  3. 03

    Update the EMA

    Combine new statistics with retained mass. The cosine schedule reduces the step as training proceeds.

  4. 04

    Close and evaluate

    Form the closing means, then exhaustively assign the fitting rows against the returned centers to report final labels and distortion.

Revival keeps clusters useful.

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:

text
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

aner
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.

ReadoutContract
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.

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.

Measured native execution

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

e-means · 1 CPU worker · Float321.559 ms
e-means · 4 CPU workers · Float321.201 ms
e-means · 8 CPU workers · Float321.246 ms
e-means · 12 CPU workers · Float321.159 ms
e-means · Metal + 4 CPU workers · Float3289.407 ms
o-means · 1 CPU worker · Float320.833 ms
o-means · 4 CPU workers · Float321.704 ms
o-means · 8 CPU workers · Float322.82 ms
o-means · 12 CPU workers · Float323.818 ms
o-means · Metal + 4 CPU workers · Float3217.131 ms
Lloyd k-means · 1 CPU worker · Float6430.58 ms
Lloyd k-means · 4 CPU workers · Float648.14 ms
Warm resident fit including initialization, index maintenance, training, closing, exhaustive final assignment and output construction; excludes data generation/upload and destruction. One warm up fit per process, serial cases. Lower time is faster. Equal epoch budgets do not imply equal clustering quality.
Quality from the same measured configurations
ConfigurationMSEInertiaTiming runs
e-means · 1 CPU worker · Float326.7213013765.25
e-means · 4 CPU workers · Float326.7213013765.25
e-means · 8 CPU workers · Float326.7213013765.25
e-means · 12 CPU workers · Float326.7213013765.25
e-means · Metal + 4 CPU workers · Float326.7213013765.25
o-means · 1 CPU worker · Float3211.127522789.05
o-means · 4 CPU workers · Float3211.127522789.05
o-means · 8 CPU workers · Float3211.127522789.05
o-means · 12 CPU workers · Float3211.127522789.05
o-means · Metal + 4 CPU workers · Float3211.127522789.05
Lloyd k-means · 1 CPU worker · Float6410.983222493.55
Lloyd k-means · 4 CPU workers · Float6410.983222493.55

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
Aner documentation · Reference and guides