Skip to content

Vectorize GaussianNB class likelihood evaluation (#484) - #512

Merged
godofecht merged 3 commits into
mainfrom
perf/484-gaussian-nb-predict
Nov 19, 2026
Merged

godofecht merged 3 commits into
mainfrom
perf/484-gaussian-nb-predict

Conversation

@godofecht

Copy link
Copy Markdown
Owner

Closes #484

Reproduction

The gap reported in the issue (Digits predict 1.304 ms against scikit-learn 0.538 ms) is no longer on main. Earlier merges closed it. 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
GaussianNB digits predict 0.294 0.110 0.018 2.67x 16.41x
GaussianNB digits fit 0.542 0.076 0.082 7.13x 6.65x
GaussianNB digits end to end 0.836 0.186 0.100 4.49x 8.41x
GaussianNB iris predict 0.044 0.001 below 0.001 44x clock floor
KernelRidge_RBF diabetes (control) predict 0.267 0.079 0.079 3.38x 3.42x

The macOS monotonic clock resolves 1 us, so the Iris predict row reads 0 after the change. The interleaved comparison below resolves it. The fit difference is inside the run to run spread (IQR 0.0065 ms before).

The scaling benchmark added here did find a loss on main that the canonical rows do not show: at 128 and 256 features prediction ran at 0.97x and 0.75x of scikit-learn.

Profile

Digits shape, 360 rows by 64 features by 10 classes, old and new interleaved in one process, median of 15 rounds:

before after
predict, Digits test split 0.108 ms 0.018 ms
predict, 1437 Digits training rows 0.427 ms 0.071 ms
predict, Iris test split 0.26 us 0.12 us
per-call constant setup 1.36 us 0
log calls per predict call 650 0
divisions per predict call 640 0
allocations per predict call 3 1
likelihood terms per call 230,400 scalar, one chain 230,400 in eight lanes

Before the change 98.8 percent of predict time was the inner loop, at 0.46 ns per term. That is the latency of one f32 add: the sum was a single dependency chain, and the range loop it sat in is emitted with a runtime stride that blocks vectorization (flooooooooooow/flow#1004).

Change

  • _gaussian_nb_weighted_sq_dist evaluates sum_j (x[j] - mean[j])^2 / (2 var[j]) with eight partial sums in a while loop and a scalar tail. predict and predict_proba both call it.
  • gaussian_nb_fit computes the per-class constant and the 1 / (2 var) table once and stores them on the model as class_const and inv_two_var.
  • gaussian_nb_predict_joint_log_proba is new. It returns the n_samples by n_classes matrix that scikit-learn exposes under the same name.

The expanded form that would turn the batch into one gemm was rejected. var_smoothing leaves a constant feature with a weight near 1e8, and the three expanded terms then cancel in f32. The comment on the kernel records this.

Parity

  • Canonical scores are unchanged on all 19 rows. GaussianNB stays parity verified on Iris (0.966667) and Digits (0.741667).
  • The DETAIL|GaussianNB records for class priors, mean and variance row norms, Frobenius norms and variance min and max are byte identical before and after.
  • No predicted label differs between the old and new paths on the Iris test split, the Digits test split or the 1437 Digits training rows.
  • In the scaling benchmark the two sides predict the same labels in all 17 cases.

Scaling, prediction only

benchmarks/bench_predict_gaussian_nb.flow and benchmarks/bench_predict_gaussian_nb.py build bit-identical float32 inputs and time predict alone. 2000 training rows. Same machine, same command, before and after.

axis queries features classes scikit-learn ms Flow ms before Flow ms after before after
batch 1 64 10 0.077 0.0019 0.0001 39.9x 1330x
batch 10 64 10 0.084 0.0046 0.0005 18.1x 176x
batch 100 64 10 0.133 0.0314 0.0050 4.22x 27.3x
batch 360 64 10 0.282 0.1095 0.0178 2.57x 15.6x
batch 1000 64 10 0.532 0.3021 0.0499 1.76x 11.6x
batch 10000 64 10 4.596 3.0210 0.5047 1.52x 9.51x
features 1000 4 10 0.219 0.0219 0.0114 10.0x 19.3x
features 1000 8 10 0.245 0.0368 0.0118 6.64x 20.9x
features 1000 16 10 0.274 0.0754 0.0164 3.63x 16.8x
features 1000 32 10 0.361 0.1393 0.0276 2.59x 13.1x
features 1000 128 10 0.756 0.7824 0.1026 0.97x 7.57x
features 1000 256 10 1.313 1.7471 0.2130 0.75x 6.05x
classes 1000 64 2 0.148 0.0607 0.0105 2.44x 13.5x
classes 1000 64 3 0.200 0.0953 0.0158 2.10x 12.5x
classes 1000 64 5 0.311 0.1526 0.0252 2.04x 12.2x
classes 1000 64 20 1.133 0.6039 0.1027 1.88x 10.7x
classes 1000 64 50 2.718 1.4932 0.2460 1.82x 10.8x

Tests

tests/test_opt_gaussiannb_predict.flow compares every joint log-likelihood entry with an f64 reference at 1, 3, 7, 8, 9, 16, 23, 64 and 67 features, checks the constants fit stored, checks predict against the reference argmax and predict_proba against the reference softmax.

  • Against the library on main it exits 1.
  • With the tail loop made to skip one feature it exits 1 with 946 failed checks.
  • With one of the eight lanes dropped it exits 1 with 741 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.

Not done here

  • The machine was shared and its load average moved between 6 and 16 during these runs. The interleaved comparison is the number to trust for the ratio. CI is the authority for the published row.
  • The frozen benchmark artifacts are not regenerated in this branch. The freeze job on main writes them from the CI runner, and a local run would replace them with numbers from a different machine.
  • benchmarks/estimator_coverage.py and benchmarks/generate_estimator_bench.py were re-run and produce no diff.
  • A changelog entry was written and left out. The commit hook scans the whole of CHANGELOG.md and rejects a sentence that is already in it, at line 541.

The inner loop of gaussian_nb_predict was one running f32 sum written as a
range loop. Flow emits a range loop with a runtime stride, and a single
floating-point reduction may not be reordered, so the loop ran scalar with
every term waiting on the add before it.

The likelihood now goes through one kernel that keeps eight partial sums in
a while loop, which compiles to vector code. predict and predict_proba both
use it, and gaussian_nb_predict_joint_log_proba exposes the matrix they
reduce.

The per-class constant and the 1 / (2 * var) table are computed by fit and
stored on the model. They were rebuilt on every inference call: 650 log
calls and 640 divisions per call on the Digits shape.

Digits predict, old and new interleaved in one process on one machine:
0.108 ms to 0.018 ms. No predicted label changes on the Iris or Digits
test splits or on the 1437 Digits training rows, and the fitted priors,
means and variances are untouched.

tests/test_opt_gaussiannb_predict.flow checks every joint log-likelihood
entry against an f64 reference at feature counts on both sides of the
block width. benchmarks/bench_predict_gaussian_nb.flow and its .py
counterpart time prediction alone across batch size, feature count and
class count.
@godofecht

Copy link
Copy Markdown
Owner Author

CI on this PR, run 44422898512.

Passing: Canonical benchmark contract, Canonical 19/19 KMeans parity, FLOW syntax and imports, Python native package, sklearn execution architecture map, disparity-audit.

The canonical rows measured by that run, on an AMD EPYC 9V45 runner:

row stage scikit-learn ms Flow ms speedup
GaussianNB digits predict 0.2959 0.0698 4.24x
GaussianNB digits fit 0.700 0.129 5.43x
GaussianNB iris predict 0.0702 0.0008 91.1x

The frozen artifact on main has Digits predict at 0.4236 ms and 1.48x, from a different runner CPU in September, so the two are not a same-machine pair. The new test tests/test_opt_gaussiannb_predict.flow passes on the runner.

Three jobs fail, and all three fail the same way on unmodified main. I started a read-only run of the Flow workflow on main at 645e6e4 to check, run 44425142857:

job failure on this PR failure on main
Run all tests and examples tests/test_spectral_biclustering.flow, checkerboard blocks land in one cluster the same test, the same two assertions
Scaled benchmark report RandomForest fit_ms over the September baseline at three sizes RandomForest fit_ms over the baseline at three sizes
Wide estimator matrix linear_svr at 0.83x linear_svr at 0.69x

None of those rows touch lib/scikit/naive_bayes.flow. The last green run on main was 2026-09-29, and the runner image has moved since then (Python 3.12.14 to 3.12.16, EPYC 7763 to 9V45). I have not changed the baselines or the failing test. They are outside this issue.

@godofecht
godofecht merged commit ea6be87 into main Nov 19, 2026
11 checks passed
@godofecht
godofecht deleted the perf/484-gaussian-nb-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] GaussianNB Digits predict: vectorize class likelihood evaluation

1 participant