Repository navigation
Share one squared-distance primitive across estimators - #520
Merged
Merged
Conversation
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Part of #498. Part of #478.
Audit
benchmarks/audit_hot_primitives.pyscans every function inlib/scikitfor hot-loop shapes. Result on main at f1ed528, inbenchmarks/hot_primitive_audit.jsonandHOT_PRIMITIVE_AUDIT.md:array_dot)Duplication found:
dot_productandarray_dotwere the same loop twice.dot_productnow callsarray_dot.forloop over pointers (KMeans, KernelRidge, GaussianProcess, kernel approximation), aforloop throughmatrix_at(TSNE, SpectralClustering, GaussianProcessClassifier) and awhileloop (KernelSVC, LabelSpreading)._svm_kernel_vecand_rbf_kernelinsvm.flow,kernel_computeinkernel_ridge.flow,_gp_rbf_kernelingaussian_process.flowand_kernel_funcinkernel_approximation.flowrepeat 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_f32andsqdist_f32_acc_f64inlib/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_rowinimpute.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
forloops with a runtime stride that LLVM does not vectorize, and clang fusess + d * dinto onefmadd. Thewhileloop is vectorized: the subtraction and multiplication run in vector lanes and the sum is added one term at a time with a plainfadd. Disassembly of both forms at-O3on 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_64and run under Rosetta): identical.CI runs tests at
-O0and the canonical benchmark on x86-64, so neither sees a difference. A local-O3build on arm64 can differ from main by one ulp in a distance.Benchmark
benchmarks/bench_primitives.flowruns 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.pyfails if the primitive is more than 10% slower than either form or if the checksums differ. Three runs on arm64 at-O3under load (time per row pair, primitive over inlinefor):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
data + offset.matrix_atper element, which is a function call at-O0, but no allocation counts were taken.Tests
Before, on main:
tests/test_shared_primitives.flowdoes not link (sqdist_f32does not exist), exit 1.After: it exits 0 at
-O0and 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.