Browse documentation
aner.ml · Reference

How clustering runs natively

Follow K-means, e-means, o-means and p-means from a native model call through bounded CPU workers or Tensor GPU kernels.

ImplementedAner 0.1.0 or newer

Keep aner.tensor, aner.parallel and aner.ml as explicit modules. They already expose native runtime operations. Removing their imports would change name visibility and language rules; it would not remove the clustering kernels' distance calculations, memory traffic or synchronization. The practical optimization is to place data once, reuse a suitable worker context and choose a measured algorithm/backend combination.

This guide describes Aner 0.0.10 or newer. K-means returns KMeansModel; e-means, o-means and p-means share CentroidModel. Their numerical and stopping contracts remain distinct. Portable release profiles provide CPU execution and Metal on compatible Apple builds. CUDA requires a separately enabled profile; historical CUDA qualification does not establish availability or qualification of a new stable package. The supplementary stable Linux CUDA profile is being prepared, with L40 qualification pending.

The dev.7 optimization study separately qualifies larger final evaluation tiles and optional native phase profiles for e/o/p-means. It preserves their training recipes and leaves strict Lloyd unchanged; profiling and tile controls are native C++/benchmark facilities, not new Aner language arguments.

Quick start

One local worker context can be reused by sequential fits of all four methods:

aner
import aner.ml
import aner.parallel

let x = [[0.0], [2.0], [10.0], [12.0]]
let workers = parallel.local(workers: 4)
let k = ml.fit_kmeans(x, 2, 20, 0.0, 42, execution: workers)
let e = ml.fit_emeans(x, 2, 3.0, 42, execution: workers)
let o = ml.fit_omeans(x, 2, 3.0, 42, execution: workers)
let p = ml.fit_pmeans(x, 2, 3.0, 42, execution: workers)
print(k.inertia())
print(e.inertia())
print(o.inertia())
print(p.inertia())

The example requires four admitted CPU slots; it does not demonstrate a speedup on four rows. K-means' 20 is an iteration cap and 0.0 a movement tolerance. The other methods' 3.0 is a fixed pass budget. Equal seeds and different algorithms do not imply the same initialization or final model.

What an import and a call do

For these included modules, the parser records import flags. The checker verifies visibility, binds named/default arguments and records the chosen native overload. At execution, the interpreter dispatches through that resolved entry to a C++ function. It does not interpret a source language loop for every observation or coordinate.

tensor::Tensor is currently a public alias of the existing native nn::Tensor storage type. Fitting receives that same Tensor handle. The GPU engines read its native buffer; introducing another public name for Tensor would not eliminate a conversion layer because this path has none. Actual dtype conversions and device moves still have costs.

InterfaceResponsibilityWhat selects execution
aner.mlModel algorithms, validation and diagnosticsThe selected fit function and its options
aner.tensorNumerical Tensor facade, shapes and readoutsExisting storage and supported operation
aner.nn Tensor methodsCurrent dtype conversion and device placement APIastype("Float32"), to("mps") or to("cuda")
aner.parallelCPU allocation and a reusable native executorparallel.local(workers: ...)

The compact CPU example needs only aner.ml and aner.parallel. Import aner.tensor when calling its inspection or transformation functions. Import aner.nn for the current Tensor placement API. A future placement facade under aner.tensor could improve organization, but it is an API design decision, not an established performance optimization.

Where the computation runs

One model call enters native execution

Choose a method to inspect its assignment and update policy. Tensor placement selects supported device kernels; a local execution context sets a CPU worker budget.

Clustering method
  1. 01 · Aner sourceml.fit_pmeans(...)
  2. 02 · Checked bindingValidate data and controls
  3. 03 · Native engineAdmit memory and dispatch

Imports select and check API namespaces. They do not execute the numerical loop in another language. Assignment, accumulation and updates run inside the native implementation.

CPU path · all four methods

Bounded local workers

parallel.local(workers: 4) requests a budget. Native kernels divide admitted work among workers and join each phase before the next update.

The centroid engine supports CPU Float32 and Float64, with tiled assignments and bounded reduction scratch. Small jobs may use fewer workers.

GPU path · e / o / p

Resident Float32 tensors

A Tensor on mps or cuda selects the corresponding native kernels. Assignment, stable grouping, ordered reduction and updates operate on device data.

The CPU coordinator launches device work. A worker context does not select the GPU, create remote workers or distribute a fit across machines.

  1. Assign

    Use the o-means search policy with four default probes, capped by the cell count.

  2. Update

    Keep online EMA centers separate from the recency weighted coordinate sums and counts.

  3. Close and evaluate

    Form the weighted closing ratio at every epoch budget, with a low mass fallback. Final evaluation is exhaustive.

Workers, GPU threads and the requested number of clusters are different quantities. Preserve the input, precision, seed, resolved recipe and build identity when comparing performance.

The source paths behind this design are src/frontend.cpp for import flags, src/core.cpp for checking and indexed native dispatch, include/aner/tensor.hpp for the storage alias, and src/clustering.cpp for e/o/p orchestration. Moving functions to unqualified built ins would not change these native algorithm paths. It would introduce compatibility, name resolution, editor and documentation work without a measured kernel benefit.

The four execution paths

MethodTraining assignment and updateCPU workersGPU support
Lloyd K-meansExhaustive assignment; full assigned means; stop on unchanged assignments, movement tolerance or iteration capSerial by default; explicit local CPU Float64 context enables phasesCPU algorithm; accelerator input can cause host readback
e-meansExhaustive batch assignment; occupancy weighted EMA; closing means from the last scheduled passBounded automatic selection, or explicit local contextNative Metal/CUDA Float32
o-meansProbe coarse cells, search their member centers and revival descendants; EMA; recency closing below two epochs, last pass closing otherwiseSame shared executor; coarse index construction also uses CPU workNative Metal/CUDA Float32 with host index/revival boundaries
p-meansSame two level mechanism; default four probes; recency weighted closing at every budgetSame shared executorSame native Metal/CUDA engine; closing length defaults to 0.5 passes

Lloyd computes coordinate ordered Float64 hypot distances and exact accumulated means and squared computed distances. The e/o/p engine uses direct squared differences and ordered Float32 or Float64 sums, with compensated Float64 final SSE. Their costs and numerical behavior differ; these models are not interchangeable accuracy baselines.

CPU e/o/p assignment processes independent center lanes using a prepared contiguous layout. Grouped row indices retain batch order for each center's reduction. Coordinate updates run independently, and no worker owns a complete private copy of every center's accumulator. The executor session spans the operation; short phases remain serial when dispatch would be wasteful. More requested workers therefore need not mean more active workers or less elapsed time.

Metal and CUDA retain features, centers, moving masses and closing statistics in native buffers. A batch performs assignment, integer histogram/prefix grouping, ordered sums and EMA updates. Integer counts are exact; floating point atomic sums are not used. Metal uses command buffers; CUDA uses a private stream and bounded pinned transfer staging. Both synchronize to check completion and arithmetic errors. Host generated row indices, index rebuilds and donor revival still cross coordination boundaries. This is a resident single GPU implementation, not an asynchronous multi GPU trainer.

Dev.6 explicitly disables multiply/add contraction in all three e/o/p backends and uses the direct batch mean when an occupancy fraction rounds to one. This fixed a Metal trajectory discrepancy found by multi seed testing. Matching policies do not promise bitwise equality on arbitrary hardware; preserve the binary and source identity with numerical results.

Concise GPU placement

The existing fluent Tensor API already supports conversion followed by placement:

aner
import aner.ml
import aner.nn
import aner.parallel

let raw = [[0.0], [2.0], [10.0], [12.0]]
let x = raw.astype("Float32").to("mps")
let workers = parallel.local(workers: 4)
let e = ml.fit_emeans(x, 2, 3.0, 42, execution: workers)
let o = ml.fit_omeans(x, 2, 3.0, 42, execution: workers)
let p = ml.fit_pmeans(x, 2, 3.0, 42, execution: workers)
let raw_query = [[1.0]]
let query = raw_query.astype("Float32").to("mps")
print(e.device())
print(o.device())
print(p.score(query))

The complete CUDA example checks fitting, scoring and prediction for all three centroid methods on the matching dev.6 backend.

Use "cuda" in both placement calls on a qualified CUDA enabled runtime. GPU availability is required; there is no silent CPU fallback. The context bounds host CPU work, while the Tensor chooses the GPU. A one row query is valid even when the model has more centers. Query dtype and device must match the fitted e/o/p model.

Convert and upload once outside a repeated fit loop. Returning centers keeps the fitted device; labels and per row diagnostics are CPU Float64 tensors. Reading GPU values on the host can synchronize or materialize a host view. Requesting predict, score and squared_distances separately performs three exhaustive assignments; select the diagnostic the workflow needs.

Work and memory costs

Let N be rows, D features, k centers, B logical batch rows, S batch updates, G coarse cells, p probes and Q query rows.

OperationPrincipal distance work
Lloyd, I completed updates plus final evaluationO((I+1) N k D)
e-means training plus final evaluationO(S B k D + N k D), with shorter remainder batches
o/p batch assignmentO(B D (G + C)), where C is the total membership of selected cells, plus bounded probe selection and up to two descendant checks per row
One host coarse rebuild with J assignment roundsO(J k G D)
Lloyd prediction; e/o/p prediction, score or per row distancesO(Q k D) for exhaustive query assignment

If cells are balanced, C is approximately p*k/G. This is an estimate, not a worst case bound: selected cells can contain most centers. When every cell is probed, the engine uses exhaustive assignment. Index construction, probing, center layout preparation and final exhaustive evaluation still cost time. Approximate training does not make final model scoring approximate.

Reductions additionally visit batch coordinates and center state, roughly O(BD + kD) per update. GPU stable grouping also charges an integer histogram with ceil(B/128)*k entries and local grouping work; reducing candidate distances alone does not remove this cost. At B=262144, k=65536, that histogram alone occupies 512 MiB. There is no retained N*k distance matrix.

Lloyd's default charged workspace cap is 64 MiB; e/o/p default to 256 MiB. The latter retain host orchestration/output storage proportional to N + kD + GD, GPU center state proportional to kD + GD, batch scratch, probed cell IDs and the histogram above. Input storage, allocator and driver overhead are separate. Admission checks can reject a request before fitting; a byte cap is not a process RSS guarantee. The e/o/p input ceiling remains 256 million elements, with separate update and coordinate work ceilings. Lloyd retains its distinct one million element input limit and 50 million distance coordinate work cap, checked against its requested iteration cap before fitting.

Do not wrap one internally parallel fit in competing tasks to request more cores. Contexts do not pin physical cores, and an executor session has exclusive operation ownership. Sequential reuse is the concise supported pattern. Distributed fitting, multiple GPUs and out of core e/o/p training are separate capabilities that this API does not provide. The contextual K-means workflow has its own streaming, restart and persistence contracts.

What the measured M2 results imply

These dev.6 M2 Max results come from the matched study and full observations. Each time below is the median of the five fit medians for seeds 42, 43 and 44, at three epochs with automatic recipes. Both columns use a four worker CPU budget; Metal still performs host coordination.

Shape (N,D,k)MethodCPU millisecondsMetal millisecondsMedian final MSE
(2048,16,32)e-means0.92186.8225.788248
(2048,16,32)o-means1.71315.5618.412811
(2048,16,32)p-means2.35318.2848.681518
(65536,32,4096)e-means1238.235139.08214.584420
(65536,32,4096)o-means1301.648211.81714.468577
(65536,32,4096)p-means624.803137.27814.009819
(8192,1024,128)e-means148.69540.687612.110170
(8192,1024,128)o-means468.695180.966649.485679
(8192,1024,128)p-means319.545119.905670.013864

Fit timing includes initialization, index work, closing, final exhaustive evaluation, outputs and backend/scratch destruction. Input preparation/upload and returned model destruction are outside that interval. MSE is SSE divided by rows. These are complete default recipe comparisons, not equal quality speedups or an isolation of closing policy. CPU and Metal recorded the same paired losses here; the table does not establish universal portability.

Small inputs favor CPU in this campaign. The large case benefits from GPU execution, while the wide case shows that fewer candidate centers do not guarantee a faster or better fit. The separate Lloyd study measures its exact accumulation algorithm; it is not a matched fourth series in the dev.6 table. Historical dev.3 M2 results and dev.4 M2/V100 results retain their original artifacts and contracts. They do not qualify new dev.6 CUDA binaries or imply completed L40 testing.

Optimization priorities

  1. Profile phases before changing APIs. Separate input preparation/upload, assignment, grouping, updates, host index/revival and final exhaustive scoring. The current benchmark measures the complete fit, so it does not alone prove which internal phase dominates.
  2. Reduce short batch dispatch and synchronization costs. The small e-means case has 384 logical updates. Investigate command/stream scheduling while preserving statistical batch boundaries, cancellation and error checks; changing batch_size changes the model recipe.
  3. Improve index economics. Measure cell balance, candidates visited and rebuild cost on high dimensional data. Tune probes and rebuild policy only with declared validation data, preserving stable center IDs and descendants. The current wide case results do not justify assuming an index win.
  4. Reduce grouping workspace and memory traffic. A replacement for the ceil(B/128)*k histogram could admit larger configurations, but must preserve deterministic membership order and bounded storage. Raising limits alone does not make paper scale inputs fit GPU memory.
  5. Measure CPU allocation and independent seeds. Compare one, four and other admitted worker budgets; retain every seed's loss and timing. Concurrent fits require a deliberate combined resource budget. Choosing the fastest observed worker count after measurement is a reported tuning decision.

These are engineering priorities, not implemented speedup claims. Keep the module boundaries, immutable model API and explicit placement while improving the native kernels. Use the data science workflow for training only scaling, seed/model selection, held out scoring and experiment provenance.

The same source three host study now includes actual V100 and L40 CUDA/host-CPU measurements and separate strict Lloyd host comparisons. All 54 matched Metal/V100/L40 GPU configurations recorded equal repeated losses. Hardware and method rankings still depend on shape and recipe. L40 used CPU budgets 1/4/8/12 on its 32 reported logical CPUs; it did not measure a 32 worker fit. Its completed dev.6 campaign remains separate from the preserved dev.4 evidence, and sanitizer qualification remains scoped to V100.

See the Machine learning module reference for the shared API.

Separate strict Float64 study

K-means across CPU worker budgets

CPU execution on the Apple M2 Max machine with Aner 0.0.10-dev.6. This Lloyd engine uses exact accumulation and an iteration cap; it is a separate numerical experiment from the Float32 e/o/p series.

2,048 rows · 16 features · 32 centers · at most 3 Lloyd iterations · seed 42

CPU budget: 1 worker29.690 ms
CPU budget: 4 workers8.005 ms
CPU budget: 8 workers6.248 ms
CPU budget: 12 workers5.477 ms
Warm CPU fit including input host materialization if needed, initialization, up to three Lloyd updates and final evaluation; excludes generation/hashing and returned model destruction. Each bar is the median of five timed fits after one warm up. A budget does not guarantee every worker remains active.
Final timed fit at the selected seed
CPU budgetMSEMedian msInertia
1 worker10.9831629.69022493.51
4 workers10.983168.00522493.51
8 workers10.983166.24822493.51
12 workers10.983165.47722493.51

Float32 input is widened for Float64 computation. The configured workspace cap is 64 MiB. Completed iterations and actual charged workspace were not captured by this frozen harness; its zero placeholders do not mean zero work or memory. A three iteration cap is not three e/o/p epochs or an equal quality target.

Inspect the Lloyd evidence and field corrections
Aner documentation · Reference and guides