Skip to content

Share one squared-distance primitive across estimators - #520

Merged
godofecht merged 3 commits into
mainfrom
perf/498-hot-primitives
Nov 20, 2026
Merged

godofecht merged 3 commits into
mainfrom
perf/498-hot-primitives

Conversation

@godofecht

@godofecht godofecht commented Nov 19, 2026 •

Copy link
Copy Markdown
Owner

Part of #498. Part of #478.

Audit

benchmarks/audit_hot_primitives.py scans every function in lib/scikit for hot-loop shapes. Result on main at f1ed528, in benchmarks/hot_primitive_audit.json and HOT_PRIMITIVE_AUDIT.md:

Shape Primitive definitions Inline sites before Inline sites after
squared difference (row distances, but also squared error and variance sums) 0 127 116
scalar dot loop 1 (array_dot) 234 233
sum reduction 0 93 93
RBF exponential 0 16 16
row-partition functions 0 20 20

Duplication found:

  • dot_product and array_dot were the same loop twice. dot_product now calls array_dot.
  • The same row-to-row squared distance was written inline in three forms: a for loop over pointers (KMeans, KernelRidge, GaussianProcess, kernel approximation), a for loop through matrix_at (TSNE, SpectralClustering, GaussianProcessClassifier) and a while loop (KernelSVC, LabelSpreading).
  • _svm_kernel_vec and _rbf_kernel in svm.flow, kernel_compute in kernel_ridge.flow, _gp_rbf_kernel in gaussian_process.flow and _kernel_func in kernel_approximation.flow repeat the whole "squared distance then exp(-gamma * d)" kernel.

The scan matches loop shapes by text. It counts squared-error and variance sums with the distance loops, so the first row overstates how many are distances. Row-to-row distance loops remain in neighbors, DBSCAN, mean shift, BIRCH, OPTICS, HDBSCAN, LOF, KDE and the SVM and one-class predict paths. They were not separated from the squared-error sums by count.

Change

sqdist_f32 and sqdist_f32_acc_f64 in lib/scikit/matrix.flow. 11 sites now call them: _kmeans_sqdist, kernel_compute (KernelRidge), _svm_kernel_vec, _rbf_kernel (KernelSVC, f64 accumulation), _gp_rbf_kernel, the GaussianProcessClassifier fit and predict loops, compute_pairwise_distances (TSNE), _build_rbf_affinity (SpectralClustering), _build_affinity (LabelSpreading) and _kernel_func.

Not consolidated, with reason: _gaussian_nb_weighted_sq_dist (weighted, eight accumulators on purpose, explained in its comment), _euclidean_dist_row in impute.flow (skips NaN), the blocked sgemm RBF paths (BLAS with a size threshold), and the neighbors, DBSCAN, OPTICS and similar loops, each of which needs its own parity check.

Finding: loop form decides rounding on FMA targets

Flow emits for loops with a runtime stride that LLVM does not vectorize, and clang fuses s + d * d into one fmadd. The while loop is vectorized: the subtraction and multiplication run in vector lanes and the sum is added one term at a time with a plain fadd. Disassembly of both forms at -O3 on arm64 shows this. The two forms therefore round differently in the last bit on arm64 at -O3, and agree everywhere else:

  • -O0, arm64: identical, 14 lengths by 25 row pairs by 3 reference forms.
  • -O3, arm64: differ in some sums.
  • -O3, x86-64 without FMA (compiled with -arch x86_64 and run under Rosetta): identical.

CI runs tests at -O0 and the canonical benchmark on x86-64, so neither sees a difference. A local -O3 build on arm64 can differ from main by one ulp in a distance.

Benchmark

benchmarks/bench_primitives.flow runs the primitive and both old loop forms in one process, interleaved, at 4 (iris), 10 (diabetes), 64 (digits), 784 and 4096 features. benchmarks/check_primitive_bench.py fails if the primitive is more than 10% slower than either form or if the checksums differ. Three runs on arm64 at -O3 under load (time per row pair, primitive over inline for):

features run 1 run 2 run 3
4 0.50 0.44 0.56
10 0.41 0.38 0.49
64 0.38 0.38 0.60
784 0.53 0.53 0.68
4096 0.56 0.55 0.70

The same 19-row benchmark (bench_flow_v2.flow, -O3) built from main and from this branch and run alternately five times each, medians per row: every score is identical, and no estimator whose code changed moved by more than noise (KMeans Digits fit 0.99x, KernelRidge Diabetes fit 0.94x, KernelSVC Digits fit 1.00x and predict 1.00x). The sub-millisecond Iris rows quantize at 1 microsecond and are not a signal.

The primitive microbenchmark is added to the existing "Run repeated canonical benchmark" step in flow.yml, so it runs as a regression gate on the CI runner.

Not covered

  • Strided and column-major variants: no caller needs one yet. A row at an offset is passed as data + offset.
  • Dot, sum, RBF exponential and row-partition primitives. The audit lists their inline sites.
  • An allocation and copy audit. The audit shows which sites use matrix_at per element, which is a function call at -O0, but no allocation counts were taken.
  • Effect on the CI runner is unmeasured until the PR checks finish.

Tests

Before, on main: tests/test_shared_primitives.flow does not link (sqdist_f32 does not exist), exit 1.
After: it exits 0 at -O0 and checks both primitives against the three old loop forms bit for bit. Changing one expected value to a wrong one makes it exit 1.
The 17 existing test files that exercise the migrated estimators pass at -O0 (KMeans, KernelRidge, KernelSVC, GaussianProcess, TSNE, spectral and label propagation, kernel approximation).
python tools/run_all.py (pinned Flow 88aac509, macOS, FLOW_OPT_LEVEL=0): passed 120/120, the 119 of main plus the new test.

Audit: 127 squared-difference loops, 234 scalar dot loops, 93 sums, 16 RBF
exponentials and 20 row-partition functions in lib/scikit, almost all inline.
The scan is benchmarks/audit_hot_primitives.py.

sqdist_f32 and sqdist_f32_acc_f64 now carry the row-to-row distance that
KMeans, KernelRidge, KernelSVC, GaussianProcess, TSNE, SpectralClustering,
LabelSpreading and the kernel approximations wrote inline in three loop
forms, and dot_product delegates to array_dot. The primitive is a while loop
with a constant step, which LLVM vectorizes, and runs at 0.4 to 0.7 of the
time of the old loops. The 19 headline rows score the same.

On a target with fused multiply-add the vectorized loop rounds the last bit
differently from the old for loop at -O3. At -O0 and on x86-64 without FMA the
results are identical.
The first CI run of bench_primitives.flow did not finish in 40 minutes. The
repetition count came from a timed probe pass whose result was unused, and an
optimizer is free to delete such a pass, which makes the probe read as about
zero and asks for millions of repetitions. The probe result is now branched
on, the count is capped so that no pass exceeds 2e8 element operations, and
the CI step runs under a 10 minute timeout.
@godofecht
godofecht merged commit a5c9b2d into main Nov 20, 2026
11 checks passed
@godofecht
godofecht deleted the perf/498-hot-primitives branch November 20, 2026 02:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant