p-means clustering
Explore recency weighted closing statistics, inspect the native recipe and fit p-means with bounded CPU or Metal execution.
ImplementedAner 0.1.0 or newerRecent batches keep more influence
Online EMA centers guide each assignment. Separately, weighted sums and counts accumulate toward the final returned centers. Change the decay length to inspect how much earlier batches contribute.
A decay length is not a cutoff. Shorter lengths emphasize recent assignments; they do not guarantee lower distortion. The final ratio is formed after training, while online centers continue their inherited EMA updates.
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.
ml.fit_pmeans adds an experimental training recipe to Aner's native centroid engine. It keeps o-means two level assignment, moving mass updates and revival, then forms its returned centers from recency weighted sums and counts at every epoch budget. The online centers used for assignment and the final closing means are separate states.
This API requires Aner 0.0.10 or newer. It returns the same immutable CentroidModel as e-means and o-means. aner.tensor owns the data and device placement; aner.parallel bounds local CPU work. The implementation shares the native CPU, Metal and CUDA engine. Portable release profiles provide CPU execution and Metal on compatible Apple builds; CUDA requires a separate CUDA enabled profile. The supplementary stable Linux CUDA profile is being prepared, with stable L40 qualification pending. Retained development measurements do not qualify a rebuilt stable binary on any device.
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_pmeans(features: x, clusters: 2,
epochs: 3.0, seed: 42, execution: execution,
closing_length: 0.5)
print(model.summary())
print(model.closing_mode())
print(model.closing_length())
print(model.inertia())
let queries = [[0.0, 1.0], [10.0, 11.0]]
let distances = model.squared_distances(input: queries)
print(tensor.value(distances, 0, 0))Run the complete CPU example or M2 example with the matching 0.0.10 backend. The CUDA e/o/p example additionally requires a separately enabled CUDA build. These small inputs explain the API; they do not establish a speedup or clustering quality advantage. Cluster IDs are arbitrary. Use the data science workflow to fit preprocessing on training observations, compare declared seeds and reserve test observations.
Two kinds of centroid state
Each logical batch is assigned against the current online centers using the coarse index. Its cluster counts and coordinate sums feed two paths:
- The inherited occupancy aware EMA updates the online centers for subsequent assignments.
- The closing path accumulates recency weighted sums and counts for the final returned centers.
Train online, then form the closing mean
- 01 · Assign
Use the online centers
Probe coarse cells and search their centroids. Aggregate each cluster's assigned coordinate sums and point count.
- 02 · Update
Continue the moving mean
The occupancy aware EMA updates centers for the next batch. The inherited index and revival schedule remain active.
- 03 · Accumulate
Keep a separate closing state
Multiply each batch's sums and counts by its recency weight. Revival splits this accumulated state with the donor.
- 04 · Finalize
Divide, then evaluate exhaustively
Return weighted sums divided by weighted mass, retaining the online center when mass is too small. Evaluate final labels and loss against every center.
The weighted closing ratio is a final estimate. It does not replace the online EMA center after every batch. Approximate training and exhaustive output evaluation remain distinct.
For a batch ending after r processed rows, total scheduled rows R, input rows N and resolved closing length L:
age_in_passes = (R - r) / N
weight = exp(-age_in_passes / L)
closing_sum[j] += weight * batch_sum[j]
closing_mass[j] += weight * batch_count[j]
final_center[j] = closing_sum[j] / closing_mass[j]The final ratio is used when closing mass exceeds 1e-3; otherwise the online center is retained. Revival splits donor closing sums and mass along with the moving state. The closing ratio does not replace the online center after each batch.
L=0.5 is an exponential decay length of half a pass, not a cutoff. A batch half a pass older receives exp(-1), about 36.8%, of the weight of an equally populated batch at the end. The half life is L*ln(2), about 0.347 passes. Earlier batches still contribute. Batch occupancy also matters because the final estimate divides weighted coordinate sums by weighted counts, not by the number of batches.
For native p-means with Float32, weights strictly below the minimum normal Float32 value, approximately 1.17549e-38, are explicitly zero. Float64 retains double precision exponential weights and their natural underflow. This makes the treatment of subnormal closing weights explicit across backends. It is a recorded numerical port choice; summary() exposes closing_weight_floor. Later Float32 products and sums can still underflow. Very short closing lengths can therefore discard sufficiently old Float32 contributions. The low mass fallback still applies.
Parameters and native defaults
ml.fit_pmeans(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,
coarse_cells: Int64 = 0, probes: Int64 = 0,
closing_length: Float64 = 0.0) -> CentroidModel
// The context overload inserts execution: ParallelContext after seed.Named optional arguments may be omitted independently and reordered. Shared e-means input and execution contracts apply: finite dense inputs, 1 ≤ clusters ≤ N, finite positive epochs, explicit device placement and charged workspace admission. The context bounds CPU work; it does not choose the GPU.
| Control | Native p-means behavior |
|---|---|
closing_length | Zero resolves to 0.5; an override must be finite and positive. Its unit is training passes. It controls the final closing estimate, not the online EMA step. |
| Closing mode | Always recency_weighted, including runs of two or more epochs. |
batch_size | Zero uses the inherited o-means automatic law: throughput at N ≤ 2,000,000, quality above that, with recipe epochs at least one. A positive override is capped at N. |
probes | Zero resolves to min(coarse_cells, 4). An explicit value must be between 1 and min(coarse_cells, 24) after resolving cells. |
coarse_cells | Zero uses the inherited o-means cell law. An explicit value is between 1 and clusters. |
alpha0 | Zero uses the inherited empirical step law; a finite override is in (0, 1]. The cosine schedule and occupancy still determine online movement. |
unused_threshold | -1.0 selects the inherited revival recipe. Zero disables revival; a finite nonnegative override sets the relative moving mass threshold. |
max_workspace_bytes | Positive charged scratch budget, default 256 MiB. It excludes input storage and allocator/driver overhead. Admission failure does not silently reduce the statistical batch. |
Automatic p-means batches are deliberately distinct from the reported H100 benchmark preset. That preset used closing_length=0.5, probes=4, and fixed batches of 65,536 at 1M rows or 262,144 at 10M. It was tuned on those workloads and is not a validated automatic rule for arbitrary inputs. The reference constructor itself defaults its closing length to 1.0; Aner's explicit native recipe resolves zero to 0.5. Inspect the returned settings rather than assuming reference defaults.
Initialization, shuffling, fractional pass ordering, revival checks and coarse index rebuilding follow the shared engine. Native p-means preserves o-means' fractional schedule: a fractional pass precedes the final full pass when the budget exceeds one pass. Final output evaluation still assigns all input rows exhaustively against the returned centers.
Inspect, predict and evaluate
The model exposes centers(), labels(), inertia(), cluster_sizes(), predict(input), score(input) and squared_distances(input). Score is nonnegative total squared distance; MSE is score divided by the query row count. Distances are not calibrated anomaly probabilities. Query dtype and device must match the fitted model. Centers preserve device placement; labels and per row diagnostics use CPU Float64 output tensors as documented in the shared guide.
Record algorithm(), recipe(), seed(), dtype(), device(), training_rows(), features(), batch_size(), alpha0(), unused_threshold(), coarse_cells(), probes(), closing_mode() and closing_length() with input and build hashes. The resolved closing length is 0.5 by default for p-means, 1.0 for o-means below two epochs, and 0.0 with last_pass mode for e-means and longer o-means runs. These closing readouts are included in 0.0.10 for all three methods.
Final labels, query assignment and loss are exhaustive despite approximate training assignment. This does not prove a global optimum. Compare distortion, occupied clusters and repeated seeds. A smaller closing length favors recent assignments; it does not guarantee better loss or semantic groups.
Native M2 placement and memory
import aner.ml
import aner.nn
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 device_x = nn.to(x.astype("Float32"), "mps")
let model = ml.fit_pmeans(device_x, 2, 3.0, 42,
execution: parallel.local(workers: 4), closing_length: 0.5)
print(model.device())
print(model.closing_mode())
print(model.summary())Metal uses native Float32 storage, direct squared differences, stable external centroid IDs and ordered grouped reductions. CPU supports Float32/Float64. The dev.6 arithmetic policy explicitly disables Metal floating point contraction and matches the CPU full step mean shortcut. Metal safe math alone does not disable contraction. This correction is part of the source identity required for new dev.6 measurements.
The historical dev.4 report described its Metal arithmetic as noncontracted, but its safe math setting did not enforce that property. Those retained measurements keep their original identity; their precision description should be read with this correction. The reference trainer also uses different reduced precision assignment and accumulation policies; equal seeds do not imply identical results. A closing policy change alone does not reproduce H100 kernel throughput.
The existing input, update and coordinate work admission limits still apply. The input limit of 256 million elements excludes 1M by 1024 features and all cited 10M by 96 or wider shapes. For the current GPU grouping histogram, B=262144 and k=65536 alone require 512 MiB before other scratch, exceeding the default budget. A 10M by 1024 Float32 input alone occupies 40.96 GB, beyond V100 32 GB capacity. Resident and streamed experiments are different protocols; out of core training is not added by this API.
The language API returns an immutable, single device model. It does not expose sample weights, automatic cluster count selection, distributed fitting or checkpoint/resume. The native C++ interface supports progress/cancellation and supplied initial centers and row orders; these controls are not all exposed by the language entry point shown here. Read workflow limitations before designing an experiment.
Evidence and interpretation
The native M2/V100/L40 comparison measures e-means, o-means and p-means with the corrected dev.6 arithmetic policy. It retains three declared seeds, CPU worker budgets, Metal/CUDA runs and every repeated timing and loss. L40 passed its actual CPU/CUDA correctness checks and completed the measurement campaign. Language and memory/race/synchronization checks on the identical portable binaries remain scoped to V100. Inspect resolved controls and quality alongside elapsed time; the default recipes differ. The earlier M2/V100 study retains its original observations.
The upstream H100 study reports a 2.76× geometric mean time to target advantage over historical e-means results and 218.5× over historical Flash KMeans@25 on DINOv3 10M. Independent arithmetic checks of the retained JSON reproduce those ratios; they do not reproduce the GPU experiment or establish Aner performance.
The rule was selected using seed 10, which also participates in evaluation. The final p-means results use ten seeds at 1M and three at 10M, while recorded o-means uses three at both scales. Historical e-means/Lloyd timings were not rerun, hardware/session differences remain, and reusable kernel improvements were applied only to p-means. Forty eight of 52 p-means target crossings have margins below 0.1%, comparable to the authors' reported run to run loss variation. The supplied sweep stops at six epochs although the common rule SPACEV 10M results require up to 10.4.
These measurements concern a squared distance target, not downstream prediction accuracy or universal model quality. P-means required more epochs than e-means in seven of eight cases and was slightly slower than o-means on SPACEV 10M. Fair native evaluation uses a shared optimized backend, matched inputs and precision, parameters frozen on validation data, untouched test seeds and repeated quality measurements. Existing dev.4 M2/V100 results measure e/o-means only and retain their historical identity.
- Pinned
p-meansrepository and results, November 15, 2026. - Reference trainer.
- Benchmark protocol and retained results.
- Clustering attribution and upstream MIT license.
- Apple Metal Shading Language specification, section 1.6.3, distinguishes safe math from the explicit contraction control.
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.6. 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 · Metal + CPU budget: 4 workers · Float32 | 6.72130 | 13765.2 | 5 |
| o-means · Metal + CPU budget: 4 workers · Float32 | 11.1275 | 22789.0 | 5 |
| p-means · Metal + CPU budget: 4 workers · Float32 | 11.1406 | 22816.0 | 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.
Each selected seed is shown separately. These observations use Aner's shared native engine; they do not reproduce the upstream H100 comparison. Resolved batch and probe settings can differ across methods, so this is a comparison of complete recipes. CPU counts are requested worker budgets; small jobs may use fewer workers. Quality shown is from the final timed fit; every timing and inertia repetition is retained in the evidence.
Resolved controls and input provenance
| Configuration | Probes / cells | Closing | Batch | Initial α |
|---|---|---|---|---|
| e-means · Metal + CPU budget: 4 workers · Float32 | 0 / 0 | Last pass | 16 | 0.0582655 |
| o-means · Metal + CPU budget: 4 workers · Float32 | 16 / 16 | Last pass | 128 | 0.378847 |
| p-means · Metal + CPU budget: 4 workers · Float32 | 4 / 16 | Recency L=0.5 | 128 | 0.378847 |
Input SHA256: 698db4434ad2cfda96964d58e26b3a07e7c8f4899a5ba1eefd621dfeab0ba538
Compiled source SHA256: 648fe42e52ea5c6f62857fcb10aa416a832147e374bf3af03b156b383e601db3
The raw report also preserves recipe identifiers, revival thresholds and the executable identity. The common seed is an experiment identifier; it does not guarantee identical final centers across methods.