Skip to content

Evaluate the KernelRidge RBF kernel in blocks with a vectorizable exp (#488) - #513

Merged
godofecht merged 3 commits into
mainfrom
perf/488-kernel-ridge-predict
Nov 19, 2026
Merged

godofecht merged 3 commits into
mainfrom
perf/488-kernel-ridge-predict

Conversation

@godofecht

Copy link
Copy Markdown
Owner

Closes #488

Reproduction

The gap reported in the issue (Diabetes predict 4.861 ms against scikit-learn 0.628 ms) is no longer on main. Earlier merges closed it, including the kernel_type == 1 branch selection the issue comment points at. Baseline on main at 645e6e4, one machine (Apple M4 Max, Accelerate, Flow toolchain at the CI pin 88aac509, -O3):

FLOW_HOST=python FLOW_OPT_LEVEL=3 \
FLOW_LDFLAGS="-framework Accelerate lib/scikit/flow_time.c lib/scikit/flow_parallel.c" \
FLOW_HEADLINE_COMMAND="<pinned flow> run benchmarks/bench_flow_v2.flow" \
python benchmarks/run_headline.py --repeats 7
row stage scikit-learn ms Flow ms before Flow ms after speedup before speedup after
KernelRidge_RBF diabetes predict 0.267 0.079 0.054 3.38x 4.92x
KernelRidge_RBF diabetes fit 0.877 0.468 0.439 1.87x 1.98x
KernelRidge_RBF diabetes R2 0.461917818 0.461917520 0.461917579
GaussianNB digits (control) predict 0.294 0.110 0.109 2.67x 2.69x

Both targets in the issue, 0.95x and then 1.05x, were already met at baseline. The change below is what was left to take.

Profile

Diabetes shape, 89 queries by 353 training rows by 10 features, median of 15 rounds in one process:

stage on main ms share
training-row norms and f64 copy of the dual coefficients 0.0005 0.6%
cross term, one sgemm 0.0028 3.6%
squared distance, exp, weighted sum: 31,417 pairs (the remainder) 0.0733 96%
whole predict 0.0766

The first two stages were timed on their own and the third is the whole call less those two. A replica of the pair loop timed on its own gave 0.078 ms. The kernel was already one sgemm. What remained was a libm exp call per pair inside a range loop, feeding one running f64 sum.

Allocation audit: there was no allocation per element or per row before this change, and there is none after. Per call, main allocated five buffers including the full n_queries by n_train cross term. This branch allocates three, and the two scratch buffers are bounded at 64 KiB and 128 KiB whatever the batch size.

Change

  • rbf_exp_block computes exp for a block of exponents as exp(x / 1024) ^ 1024: a degree 8 polynomial and ten squarings. The body is straight-line arithmetic, so the compiler vectorizes the loop, which it cannot do through a libm call. Measured worst relative error against libm on [-104, 104] is 3.6e-12. Exponents below -104, where the result is under the smallest f32 denormal, return exactly 0.
  • Prediction evaluates the kernel a block of rows at a time: one sgemm for the block's cross terms, one pass to form the exponents, rbf_exp_block, then a dot product with eight partial sums.
  • kernel_ridge_fit stores the training-row squared norms and the f64 view of the dual coefficients on the model as x_train_sq and dual_coef_d. Both were rebuilt on every predict call.

The dot product stays in Flow. A block is small enough that a threaded BLAS would spend longer dispatching than computing, which AGENTS.md records at about 0.1 ms per call on OpenBLAS.

Parity

  • Canonical R2 moves from 0.461917520 to 0.461917579 against scikit-learn at 0.461917818. The row stays parity verified under its 0.005 tolerance. All 19 rows keep their parity status.
  • The DETAIL|KernelRidge_RBF records for alpha, gamma, training size and the dual coefficient norm, sum, min, max and mean are byte identical before and after. Fit numerics are untouched.
  • Largest prediction difference between the old and new paths: 6.1e-5 on the Diabetes test split and 9.2e-5 on the 353 training rows, on predictions up to 292. That is two to three f32 units in the last place.
  • In the scaling benchmark the prediction checksums agree with scikit-learn to 1.1e-6 relative or better in all 11 cases, before and after.

Scaling, prediction only

benchmarks/bench_predict_kernel_ridge.flow and benchmarks/bench_predict_kernel_ridge.py build bit-identical float32 inputs and time predict alone. For kernel ridge the support size is the training-set size. Same machine, same command, before and after.

axis queries train rows features scikit-learn ms Flow ms before Flow ms after before after
batch 1 353 10 0.171 0.0027 0.0006 64.6x 265x
batch 10 353 10 0.180 0.0118 0.0061 15.2x 29.3x
batch 89 353 10 0.266 0.0770 0.0528 3.45x 5.09x
batch 1000 353 10 1.088 0.7821 0.5837 1.39x 1.87x
batch 10000 353 10 9.589 7.7970 5.8355 1.23x 1.64x
train 1000 100 10 0.448 0.2395 0.1608 1.87x 2.79x
train 1000 1000 10 2.638 2.2461 1.6723 1.17x 1.59x
train 1000 3000 10 8.289 6.7210 5.2075 1.23x 1.56x
features 1000 353 2 1.078 0.7875 0.5720 1.37x 1.89x
features 1000 353 32 1.116 0.8190 0.6088 1.36x 1.84x
features 1000 353 128 1.395 0.9201 0.7269 1.52x 1.92x

Every case on main was already above 1.05x. The thinnest, 1000 queries against 1000 training rows, moves from 1.17x to 1.59x.

The old and new paths interleaved in one process give 0.0766 ms to 0.0522 ms on the Diabetes test split, 1.47x, and 2.68 us to 0.62 us for a single query row, 4.3x.

Tests

tests/test_opt_kernelridge_predict.flow:

  1. bounds the polynomial exponential against libm on [-104, 104] and checks the cutoff below it,
  2. confirms fit stored the derived state,
  3. compares predictions with an independent f64 sum on shapes that fit in one block, end exactly on a block edge, and span several blocks. The inputs sit on a 1/128 grid, so the f32 norms and cross terms are exact and the tolerance is 1e-6 of the summed term magnitudes,
  4. requires a row predicted alone to match the same row in a batch,
  5. predicts with a negative gamma, where every exponent is positive,
  6. confirms the polynomial kernel branch still matches its reference.
  • Against the library on main it exits 1.
  • With nine squarings in place of ten it exits 1 with 694 failed checks.
  • With the block loop made to skip a row at each seam it exits 1.
  • With one of the eight dot product lanes dropped it exits 1 with 655 failed checks.
  • On this branch it exits 0.

python tools/run_all.py at -O0: 106 of 106 tests on main, 118 of 118 tests and examples on this branch. A comment in the library was reworded while that run was in progress, so the 50 tests that had already run were run again on the final source. All 50 pass.

Not done here

  • The gain on this machine is modest because Apple's libm exp is already about 2 ns. glibc's is slower, so the CI runner should gain more. The canonical row from this PR's own CI run is the number to read, and I have not seen it yet.
  • A variant that evaluated the kernel one cache-resident stretch of a row at a time measured slower (0.061 ms against 0.052 ms) and was dropped.
  • The machine was shared and its load average sat between 6 and 8 during these runs.
  • The frozen benchmark artifacts are not regenerated in this branch. The freeze job on main writes them from the CI runner.
  • benchmarks/estimator_coverage.py and benchmarks/generate_estimator_bench.py were re-run and produce no diff.
  • Fit is untouched. It still calls libm exp per pair and belongs to [Perf #478] KernelRidge RBF fit: eliminate the ~9.7x training gap #487.
  • lssvm_classifier_fit in lib/scikit/svm.flow passes kernel type 1 to kernel_ridge_fit, which is the polynomial kernel. Its comments describe an RBF model. I left it alone because it changes what that estimator computes.

…#488)

Prediction was already one sgemm for the cross terms. What remained was a
libm exp call per query and training pair inside a range loop, feeding one
running f64 sum. That loop was 96 percent of predict time on the Diabetes
row.

rbf_exp_block computes exp(x) as exp(x / 1024) ^ 1024, a degree 8
polynomial and ten squarings. The body is straight-line arithmetic, so the
loop vectorizes, which it cannot do through a libm call. The measured worst
relative error against libm on [-104, 104] is 3.6e-12, and exponents below
-104 return exactly 0.

Prediction now works a block of rows at a time: one sgemm, one pass to form
the exponents, the block exponential, then a dot product over eight partial
sums. The scratch buffers are bounded at 64 KiB and 128 KiB where the full
n_queries by n_train cross term used to be allocated.

kernel_ridge_fit stores the training-row squared norms and the f64 view of
the dual coefficients on the model. Both were rebuilt on every predict call.

Diabetes predict, old and new interleaved in one process on one machine:
0.0766 ms to 0.0522 ms, and 2.68 us to 0.62 us for a single query row. The
canonical R2 moves from 0.461917520 to 0.461917579 against scikit-learn at
0.461917818, inside the row's 0.005 tolerance. Fit numerics are untouched.

tests/test_opt_kernelridge_predict.flow bounds the exponential against libm
and checks predictions against an f64 reference across block seams.
benchmarks/bench_predict_kernel_ridge.flow and its .py counterpart time
prediction alone across batch size, training-set size and feature count.
@godofecht

Copy link
Copy Markdown
Owner Author

CI on this PR, runs 44429712312 and 44429712322.

Passing: Run all tests and examples (118 of 118, including tests/test_opt_kernelridge_predict.flow), Canonical benchmark contract, Canonical 19/19 KMeans parity, FLOW syntax and imports, Python native package, sklearn execution architecture map, disparity-audit.

The canonical row from this run, which is the Linux number the description said I had not seen:

source runner CPU KernelRidge code scikit-learn predict ms Flow predict ms speedup
frozen artifact on main, September AMD EPYC 7763 main 0.7654 0.4139 1.85x
run 44422898477, today AMD EPYC 9V45 main 0.3242 0.1703 1.90x
this PR, run 44429712322 AMD EPYC 7763 this branch 0.7529 0.1944 3.87x

These are three separate runner sessions, so they are not a controlled pair. The first and third share a CPU model and scikit-learn's time agrees between them to 2 percent, and Flow's predict time roughly halves. R2 is 0.461918 on both sides and the row stays parity verified.

Two jobs fail, and both fail the same way on unmodified main in run 44425142857, which I started read-only to check:

job failure on this PR failure on main
Scaled benchmark report RandomForest fit_ms over the September baseline at two sizes RandomForest fit_ms over the baseline at three sizes
Wide estimator matrix linear_svr at 0.65x linear_svr at 0.69x

The kernel_ridge row in the wide matrix is at 14.4x. Neither failing row touches lib/scikit/kernel_ridge.flow. I have not changed the baselines.

tests/test_spectral_biclustering.flow fails on main and on #512, both of which drew an EPYC 9V45 runner, and passes here on an EPYC 7763. That points at a BLAS result that differs by CPU, which AGENTS.md warns about.

@godofecht
godofecht merged commit ed6ca61 into main Nov 19, 2026
11 checks passed
@godofecht
godofecht deleted the perf/488-kernel-ridge-predict branch November 19, 2026 19:55
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.

[Perf #478] KernelRidge RBF predict: eliminate ~7.7x inference gap with batched kernel evaluation

1 participant