diff --git a/benchmarks/bench_predict_gaussian_nb.flow b/benchmarks/bench_predict_gaussian_nb.flow new file mode 100644 index 0000000..251c213 --- /dev/null +++ b/benchmarks/bench_predict_gaussian_nb.flow @@ -0,0 +1,159 @@ +# Prediction-only scaling benchmark for GaussianNB (issue #484). +# +# Times gaussian_nb_predict alone, with fit outside the timing window, along +# three axes: query batch size, feature count and class count. Every case is +# generated from integers on a dyadic grid, so bench_predict_gaussian_nb.py +# builds bit-identical float32 inputs and the two sides can be joined row for +# row. +# +# FLOW_OPT_LEVEL=3 flow run benchmarks/bench_predict_gaussian_nb.flow > flow_predict_gnb.txt +# python benchmarks/bench_predict_gaussian_nb.py --flow flow_predict_gnb.txt +# +# Each sample is an aggregate window of at least 10 ms, repeated 7 times after +# 2 warmups, and the reported latency is the per-call median, the same scheme +# as benchmarks/timing.py. + +import "lib/scikit/scikit.flow" + +extern { + function printf(fmt: string, ...) -> i32 + function flow_now_ns() -> i64 +} + +function pgnb_raw(i: i32, j: i32, cls: i32) -> i32 { + return ((i * 37 + j * 19 + cls * 7) % 128) + cls * (8 + ((j * 5) % 7) * 2) +} + +function pgnb_fill(X: Matrix, y: ptr, first_row: i32, n_classes: i32) -> void { + let p: i32 = X.cols + let mut i: i32 = 0 + while i < X.rows { + let src: i32 = first_row + i + let cls: i32 = src % n_classes + y[i] = cls as f32 + let row: ptr = X.data + i * p + let mut j: i32 = 0 + while j < p { + row[j] = ((pgnb_raw(src, j, cls)) as f32) / 64.0 + j = j + 1 + } + i = i + 1 + } +} + +function pgnb_sort(v: ptr, n: i32) -> void { + let mut i: i32 = 1 + while i < n { + let key: f64 = v[i] + let mut j: i32 = i - 1 + while j >= 0 && v[j] > key { + v[j + 1] = v[j] + j = j - 1 + } + v[j + 1] = key + i = i + 1 + } +} + +function pgnb_percentile(sorted: ptr, n: i32, q: f64) -> f64 { + let pos: f64 = ((n - 1) as f64) * q + let lo: i32 = pos as i32 + let mut hi: i32 = lo + 1 + if hi > n - 1 { hi = n - 1 } + let frac: f64 = pos - (lo as f64) + return sorted[lo] * (1.0 - frac) + sorted[hi] * frac +} + +function pgnb_window_ms(model: GaussianNB, Q: Matrix, repeats: i32) -> f64 { + let t0: i64 = flow_now_ns() + let mut k: i32 = 0 + while k < repeats { + let pred: ptr = gaussian_nb_predict(model, Q) + array_free_f32(pred) + k = k + 1 + } + let t1: i64 = flow_now_ns() + return ((t1 - t0) as f64) / 1000000.0 +} + +function pgnb_case(axis: string, n_query: i32, p: i32, n_classes: i32) -> void { + let n_train: i32 = 2000 + let samples: i32 = 7 + let X: Matrix = matrix_new(n_train, p) + let y: ptr = array_new_f32(n_train) + pgnb_fill(X, y, 0, n_classes) + let Q: Matrix = matrix_new(n_query, p) + let yq: ptr = array_new_f32(n_query) + pgnb_fill(Q, yq, n_train, n_classes) + + let model: GaussianNB = gaussian_nb_fit(X, y, n_classes, 0.000000001) + + let warm: f64 = pgnb_window_ms(model, Q, 2) + let mut repeats: i32 = 1 + let mut window: f64 = pgnb_window_ms(model, Q, repeats) + while window < 10.0 && repeats < 1048576 { + repeats = repeats * 2 + window = pgnb_window_ms(model, Q, repeats) + } + + let per_call: ptr = array_new_f64(samples) + let mut s: i32 = 0 + while s < samples { + per_call[s] = pgnb_window_ms(model, Q, repeats) / (repeats as f64) + s = s + 1 + } + pgnb_sort(per_call, samples) + let median: f64 = pgnb_percentile(per_call, samples, 0.5) + let iqr: f64 = pgnb_percentile(per_call, samples, 0.75) - pgnb_percentile(per_call, samples, 0.25) + + let pred: ptr = gaussian_nb_predict(model, Q) + let mut correct: i32 = 0 + let mut label_sum: i64 = 0 + let mut i: i32 = 0 + while i < n_query { + if pred[i] == yq[i] { correct = correct + 1 } + label_sum = label_sum + ((pred[i]) as i64) + i = i + 1 + } + + printf("PREDICT|GaussianNB|%s|%d|%d|%d|%.9f|%.9f|%d|%d|%lld\n", axis, n_query, p, n_classes, median, iqr, repeats, correct, label_sum) + + if warm < 0.0 { printf("unreachable\n") } + array_free_f32(pred) + array_free_f64(per_call) + gaussian_nb_free(model) + matrix_free(Q) + array_free_f32(yq) + matrix_free(X) + array_free_f32(y) +} + +function main() -> i32 { + printf("TIMING_UNIT|ms\n") + printf("BENCHMARK_MODE|predict_only\n") + printf("COLUMNS|estimator|axis|n_query|features|classes|median_ms|iqr_ms|repeats|correct|label_sum\n") + + # Batch size at the Digits shape: 64 features, 10 classes. + pgnb_case("batch", 1, 64, 10) + pgnb_case("batch", 10, 64, 10) + pgnb_case("batch", 100, 64, 10) + pgnb_case("batch", 360, 64, 10) + pgnb_case("batch", 1000, 64, 10) + pgnb_case("batch", 10000, 64, 10) + + # Feature count at 1000 queries and 10 classes. + pgnb_case("features", 1000, 4, 10) + pgnb_case("features", 1000, 8, 10) + pgnb_case("features", 1000, 16, 10) + pgnb_case("features", 1000, 32, 10) + pgnb_case("features", 1000, 128, 10) + pgnb_case("features", 1000, 256, 10) + + # Class count at 1000 queries and 64 features. + pgnb_case("classes", 1000, 64, 2) + pgnb_case("classes", 1000, 64, 3) + pgnb_case("classes", 1000, 64, 5) + pgnb_case("classes", 1000, 64, 20) + pgnb_case("classes", 1000, 64, 50) + return 0 +} diff --git a/benchmarks/bench_predict_gaussian_nb.py b/benchmarks/bench_predict_gaussian_nb.py new file mode 100644 index 0000000..8c1e9c9 --- /dev/null +++ b/benchmarks/bench_predict_gaussian_nb.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Prediction-only scaling benchmark for GaussianNB, scikit-learn side. + +Builds the same float32 inputs as bench_predict_gaussian_nb.flow, times +``GaussianNB.predict`` alone with the shared adaptive timer, and optionally +joins the Flow output into one table. + + python benchmarks/bench_predict_gaussian_nb.py --flow flow_predict_gnb.txt +""" +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np +from sklearn.naive_bayes import GaussianNB + +from timing import measure + +N_TRAIN = 2000 + +# (axis, n_query, features, classes), in the order the Flow benchmark emits. +CASES = ( + [("batch", n, 64, 10) for n in (1, 10, 100, 360, 1000, 10000)] + + [("features", 1000, p, 10) for p in (4, 8, 16, 32, 128, 256)] + + [("classes", 1000, 64, c) for c in (2, 3, 5, 20, 50)] +) + + +def make(first_row: int, n: int, p: int, n_classes: int): + i = np.arange(first_row, first_row + n, dtype=np.int64)[:, None] + j = np.arange(p, dtype=np.int64)[None, :] + cls = i % n_classes + raw = ((i * 37 + j * 19 + cls * 7) % 128) + cls * (8 + ((j * 5) % 7) * 2) + # Integers below 2**24 over a power of two: exact in float32. + X = (raw / 64.0).astype(np.float32) + return X, cls[:, 0].astype(np.float32) + + +def parse_flow(path: Path) -> dict: + rows = {} + unit = None + for line in path.read_text().splitlines(): + if line.startswith("TIMING_UNIT|"): + unit = line.split("|", 1)[1].strip() + elif line.startswith("PREDICT|GaussianNB|"): + p = line.strip().split("|") + rows[(p[2], int(p[3]), int(p[4]), int(p[5]))] = { + "median_ms": float(p[6]), + "iqr_ms": float(p[7]), + "repeats": int(p[8]), + "correct": int(p[9]), + "label_sum": int(p[10]), + } + if unit != "ms": + raise SystemExit("Flow predict benchmark must declare TIMING_UNIT|ms") + return rows + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--flow", type=Path, help="output of bench_predict_gaussian_nb.flow to join") + parser.add_argument("--output", type=Path, help="write the joined rows as JSON") + args = parser.parse_args() + + flow = parse_flow(args.flow) if args.flow else {} + rows = [] + mismatches = 0 + for axis, n_query, p, n_classes in CASES: + X, y = make(0, N_TRAIN, p, n_classes) + Q, yq = make(N_TRAIN, n_query, p, n_classes) + model = GaussianNB(var_smoothing=1e-9).fit(X, y) + timing = measure(lambda: model.predict(Q), min_window_ms=10.0, samples=7) + pred = timing.value + row = { + "estimator": "GaussianNB", + "axis": axis, + "n_query": n_query, + "features": p, + "classes": n_classes, + "sklearn_ms": timing.median_ms, + "sklearn_iqr_ms": timing.iqr_ms, + "sklearn_correct": int((pred == yq).sum()), + "sklearn_label_sum": int(pred.astype(np.int64).sum()), + "timing_unit": "ms", + } + f = flow.get((axis, n_query, p, n_classes)) + if f: + row.update({ + "flow_ms": f["median_ms"], + "flow_iqr_ms": f["iqr_ms"], + "flow_correct": f["correct"], + "flow_label_sum": f["label_sum"], + "speedup": timing.median_ms / f["median_ms"] if f["median_ms"] > 0 else None, + "predictions_agree": f["correct"] == row["sklearn_correct"] and f["label_sum"] == row["sklearn_label_sum"], + }) + if not row["predictions_agree"]: + mismatches += 1 + rows.append(row) + + if flow: + print("| axis | queries | features | classes | sklearn ms | Flow ms | speedup | predictions agree |") + print("| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |") + for r in rows: + if "flow_ms" not in r: + continue + print( + f"| {r['axis']} | {r['n_query']} | {r['features']} | {r['classes']} | " + f"{r['sklearn_ms']:.4f} | {r['flow_ms']:.4f} | {r['speedup']:.2f}x | " + f"{'yes' if r['predictions_agree'] else 'no'} |" + ) + else: + for r in rows: + print(f"PREDICT|GaussianNB|{r['axis']}|{r['n_query']}|{r['features']}|{r['classes']}|{r['sklearn_ms']:.9f}|{r['sklearn_iqr_ms']:.9f}") + + if args.output: + args.output.write_text(json.dumps({"timing_unit": "ms", "benchmark_mode": "predict_only", "rows": rows}, indent=2) + "\n") + + if mismatches: + print(f"{mismatches} case(s) where the two sides predicted different labels") + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/lib/scikit/naive_bayes.flow b/lib/scikit/naive_bayes.flow index 0b80887..6cb1de7 100644 --- a/lib/scikit/naive_bayes.flow +++ b/lib/scikit/naive_bayes.flow @@ -12,7 +12,14 @@ export struct GaussianNB { priors: ptr, n_features: i32, var_smoothing: f32, - fitted: bool + fitted: bool, + # Per-class constant log P(c) - 0.5 * sum_j log(2 * pi * var[c][j]) and the + # flat n_classes x n_features table of 1 / (2 * var[c][j]). Both depend on + # the fitted state alone, so fit computes them once and every inference + # call reads them. They are derived from priors and variances and must be + # rebuilt if either is edited by hand. + class_const: ptr, + inv_two_var: ptr } export function gaussian_nb_fit(X: Matrix, y: ptr, n_classes: i32, var_smoothing: f32) -> GaussianNB { @@ -115,6 +122,10 @@ export function gaussian_nb_fit(X: Matrix, y: ptr, n_classes: i32, var_smoo array_free_f64(class_sums) array_free_f64(class_sq_sums) + let class_const: ptr = array_new_f32(n_classes) + let inv_two_var: ptr = array_new_f32(n_classes * p) + _gaussian_nb_prepare_terms(priors, variances, n_classes, p, class_const, inv_two_var) + return GaussianNB { classes: classes, n_classes: n_classes, @@ -123,22 +134,28 @@ export function gaussian_nb_fit(X: Matrix, y: ptr, n_classes: i32, var_smoo priors: priors, n_features: p, var_smoothing: var_smoothing, - fitted: true + fitted: true, + class_const: class_const, + inv_two_var: inv_two_var } } -# Precompute the terms that are constant for every sample in a prediction call. +# Compute the terms that are constant for every sample: one log per class for +# the prior, then one log and one division per class and feature. Fit calls +# this once. Inference used to call it on every predict. function _gaussian_nb_prepare_terms( - model: GaussianNB, + priors: ptr, + variances: ptr >, + n_classes: i32, + p: i32, class_const: ptr, inv_two_var: ptr ) -> void { let log_two_pi: f32 = log((2.0 * 3.14159265358979) as f64) as f32 - let p: i32 = model.n_features - for c in 0 to model.n_classes { - let mut sum_log_norm: f32 = log(model.priors[c] as f64) as f32 + for c in 0 to n_classes { + let mut sum_log_norm: f32 = log(priors[c] as f64) as f32 let base: i32 = c * p - let var_c: ptr = model.variances[c] + let var_c: ptr = variances[c] for j in 0 to p { let var: f32 = var_c[j] let term: f32 = -0.5 * log_two_pi - 0.5 * (log(var as f64) as f32) @@ -149,89 +166,151 @@ function _gaussian_nb_prepare_terms( } } +# Variance-weighted squared distance between one sample and one class mean: +# sum_j (x[j] - mean[j])^2 * w[j], with w[j] = 1 / (2 * var[j]). +# +# This is the whole per-sample cost of GaussianNB inference, evaluated +# rows * classes times. Written as one running f32 sum it is a single +# dependency chain, so each term waits for the add before it and the compiler +# may not reorder a floating-point reduction to break the chain. Eight +# independent partial sums give it eight chains it can lay out as vector lanes. +# The loops are while loops because Flow emits a range loop with a runtime +# stride, which blocks vectorization (flooooooooooow/flow#1004). +# +# The expanded form x^2*w - 2*x*mean*w + mean^2*w would turn the batch into one +# gemm, and is avoided on purpose. var_smoothing leaves a constant feature +# with a variance near 1e-9 of the largest one, so w reaches 1e8 and more, and +# the three expanded terms then cancel catastrophically in f32. The direct +# difference is exact when x equals the mean. +function _gaussian_nb_weighted_sq_dist(x: ptr, mean: ptr, w: ptr, p: i32) -> f32 { + let mut s0: f32 = 0.0 + let mut s1: f32 = 0.0 + let mut s2: f32 = 0.0 + let mut s3: f32 = 0.0 + let mut s4: f32 = 0.0 + let mut s5: f32 = 0.0 + let mut s6: f32 = 0.0 + let mut s7: f32 = 0.0 + let p8: i32 = (p / 8) * 8 + let mut j: i32 = 0 + while j < p8 { + let d0: f32 = x[j] - mean[j] + let d1: f32 = x[j + 1] - mean[j + 1] + let d2: f32 = x[j + 2] - mean[j + 2] + let d3: f32 = x[j + 3] - mean[j + 3] + let d4: f32 = x[j + 4] - mean[j + 4] + let d5: f32 = x[j + 5] - mean[j + 5] + let d6: f32 = x[j + 6] - mean[j + 6] + let d7: f32 = x[j + 7] - mean[j + 7] + s0 = s0 + d0 * d0 * w[j] + s1 = s1 + d1 * d1 * w[j + 1] + s2 = s2 + d2 * d2 * w[j + 2] + s3 = s3 + d3 * d3 * w[j + 3] + s4 = s4 + d4 * d4 * w[j + 4] + s5 = s5 + d5 * d5 * w[j + 5] + s6 = s6 + d6 * d6 * w[j + 6] + s7 = s7 + d7 * d7 * w[j + 7] + j = j + 8 + } + let mut tail: f32 = 0.0 + while j < p { + let d: f32 = x[j] - mean[j] + tail = tail + d * d * w[j] + j = j + 1 + } + return ((s0 + s1) + (s2 + s3)) + ((s4 + s5) + (s6 + s7)) + tail +} + +# Joint log-likelihood log P(c) + log P(x | c) for every sample and class, +# n_samples x n_classes in the model's class order. This is the quantity +# scikit-learn exposes as GaussianNB.predict_joint_log_proba, and predict and +# predict_proba are both a reduction over one row of it. +export function gaussian_nb_predict_joint_log_proba(model: GaussianNB, X: Matrix) -> Matrix { + let n: i32 = X.rows + let p: i32 = model.n_features + let nc: i32 = model.n_classes + let jll: Matrix = matrix_new(n, nc) + let class_const: ptr = model.class_const + let inv_two_var: ptr = model.inv_two_var + + let mut i: i32 = 0 + while i < n { + let x_row: ptr = X.data + i * p + let out_row: ptr = jll.data + i * nc + let mut c: i32 = 0 + while c < nc { + out_row[c] = class_const[c] - _gaussian_nb_weighted_sq_dist(x_row, model.means[c], inv_two_var + c * p, p) + c = c + 1 + } + i = i + 1 + } + + return jll +} + export function gaussian_nb_predict(model: GaussianNB, X: Matrix) -> ptr { - let preds: ptr = array_new_f32(X.rows) + let n: i32 = X.rows + let preds: ptr = array_new_f32(n) let p: i32 = model.n_features - let terms: i32 = model.n_classes * p - let class_const: ptr = array_new_f32(model.n_classes) - let inv_two_var: ptr = array_new_f32(terms) - _gaussian_nb_prepare_terms(model, class_const, inv_two_var) + let nc: i32 = model.n_classes + let class_const: ptr = model.class_const + let inv_two_var: ptr = model.inv_two_var - for i in 0 to X.rows { + let mut i: i32 = 0 + while i < n { let mut best_class: i32 = 0 let mut best_log_prob: f32 = -9999999999.0 - let row_base: i32 = i * p - let x_row: ptr = X.data + row_base - - for c in 0 to model.n_classes { - let means_c: ptr = model.means[c] - let inv_var_c: ptr = inv_two_var + c * p - let mut sum_diff_sq: f32 = 0.0 - for j in 0 to p { - let diff: f32 = x_row[j] - means_c[j] - sum_diff_sq = sum_diff_sq + diff * diff * inv_var_c[j] - } - let log_prob: f32 = class_const[c] - sum_diff_sq + let x_row: ptr = X.data + i * p + let mut c: i32 = 0 + while c < nc { + let log_prob: f32 = class_const[c] - _gaussian_nb_weighted_sq_dist(x_row, model.means[c], inv_two_var + c * p, p) if log_prob > best_log_prob { best_log_prob = log_prob best_class = c } + c = c + 1 } preds[i] = model.classes[best_class] + i = i + 1 } - array_free_f32(class_const) - array_free_f32(inv_two_var) return preds } export function gaussian_nb_predict_proba(model: GaussianNB, X: Matrix) -> Matrix { - let probs: Matrix = matrix_new(X.rows, model.n_classes) - let p: i32 = model.n_features - let terms: i32 = model.n_classes * p - let class_const: ptr = array_new_f32(model.n_classes) - let inv_two_var: ptr = array_new_f32(terms) - let log_probs: ptr = array_new_f32(model.n_classes) - _gaussian_nb_prepare_terms(model, class_const, inv_two_var) + let n: i32 = X.rows + let nc: i32 = model.n_classes + let probs: Matrix = gaussian_nb_predict_joint_log_proba(model, X) - for i in 0 to X.rows { + # Softmax over each row in place, shifted by the row maximum. + let mut i: i32 = 0 + while i < n { + let row: ptr = probs.data + i * nc let mut max_lp: f32 = -9999999999.0 - let row_base: i32 = i * p - let prob_base: i32 = i * model.n_classes - let x_row: ptr = X.data + row_base - - for c in 0 to model.n_classes { - let means_c: ptr = model.means[c] - let inv_var_c: ptr = inv_two_var + c * p - let mut sum_diff_sq: f32 = 0.0 - for j in 0 to p { - let diff: f32 = x_row[j] - means_c[j] - sum_diff_sq = sum_diff_sq + diff * diff * inv_var_c[j] - } - let lp: f32 = class_const[c] - sum_diff_sq - log_probs[c] = lp - if lp > max_lp { - max_lp = lp - } + let mut c: i32 = 0 + while c < nc { + if row[c] > max_lp { max_lp = row[c] } + c = c + 1 } let mut sum: f32 = 0.0 - for c in 0 to model.n_classes { - let probability: f32 = exp((log_probs[c] - max_lp) as f64) as f32 - probs.data[prob_base + c] = probability + c = 0 + while c < nc { + let probability: f32 = exp((row[c] - max_lp) as f64) as f32 + row[c] = probability sum = sum + probability + c = c + 1 } - for c in 0 to model.n_classes { - probs.data[prob_base + c] = probs.data[prob_base + c] / sum + c = 0 + while c < nc { + row[c] = row[c] / sum + c = c + 1 } + i = i + 1 } - - array_free_f32(class_const) - array_free_f32(inv_two_var) - array_free_f32(log_probs) return probs } @@ -244,6 +323,8 @@ export function gaussian_nb_free(model: GaussianNB) -> void { free(model.variances as ptr) array_free_f32(model.classes) array_free_f32(model.priors) + array_free_f32(model.class_const) + array_free_f32(model.inv_two_var) } export struct MultinomialNB { diff --git a/tests/test_opt_gaussiannb_predict.flow b/tests/test_opt_gaussiannb_predict.flow new file mode 100644 index 0000000..5028ae5 --- /dev/null +++ b/tests/test_opt_gaussiannb_predict.flow @@ -0,0 +1,200 @@ +# Regression test for the vectorized GaussianNB inference path (issue #484). +# +# The per-class likelihood is evaluated eight features at a time with a scalar +# tail, and the per-class constants are computed by fit. The checks below +# recompute the joint log-likelihood independently in f64 from the fitted +# means, variances and priors, and compare every entry. The feature counts +# straddle the block width so the tail loop, the block loop and their join are +# each exercised: 1, 3 and 7 are tail only, 8, 16 and 64 are blocks only, and +# 9, 23 and 67 are both. + +import "lib/scikit/scikit.flow" + +function gnbopt_abs(v: f64) -> f64 { + if v < 0.0 { return 0.0 - v } + return v +} + +function gnbopt_log(v: f64) -> f64 { + let r: f64 = log(v) + return r +} + +function gnbopt_exp(v: f64) -> f64 { + let r: f64 = exp(v) + return r +} + +# Deterministic feature value. Column 2 is constant, which leaves its variance +# at the var_smoothing floor and its weight 1 / (2 * var) very large. +function gnbopt_value(i: i32, j: i32, cls: i32) -> f32 { + if j == 2 { return 0.5 } + let noise: f32 = (((i * 37 + j * 19 + cls * 7) % 101) as f32) / 101.0 + let shift: f32 = (cls as f32) * (0.4 + (((j * 5) % 7) as f32) * 0.1) + return noise + shift +} + +# Independent f64 joint log-likelihood for one sample and one class. +function gnbopt_ref_jll(model: GaussianNB, X: Matrix, i: i32, c: i32) -> f64 { + let two_pi: f64 = 2.0 * 3.14159265358979 + let mut total: f64 = gnbopt_log((model.priors[c]) as f64) + for j in 0 to model.n_features { + let v: f64 = (model.variances[c][j]) as f64 + let d: f64 = ((matrix_at(X, i, j)) as f64) - ((model.means[c][j]) as f64) + total = total - 0.5 * gnbopt_log(two_pi * v) - d * d / (2.0 * v) + } + return total +} + +function gnbopt_case(p: i32) -> i32 { + let nc: i32 = 3 + let n_train: i32 = 90 + let n_query: i32 = 41 + let mut failures: i32 = 0 + + let X: Matrix = matrix_new(n_train, p) + let y: ptr = array_new_f32(n_train) + for i in 0 to n_train { + let cls: i32 = i % nc + y[i] = cls as f32 + for j in 0 to p { matrix_set(X, i, j, gnbopt_value(i, j, cls)) } + } + let Q: Matrix = matrix_new(n_query, p) + for i in 0 to n_query { + let cls: i32 = (i * 2 + 1) % nc + for j in 0 to p { matrix_set(Q, i, j, gnbopt_value(i * 3 + 500, j, cls)) } + } + + let model: GaussianNB = gaussian_nb_fit(X, y, nc, 0.000000001) + + # 1. Fit must have stored the per-class constants. + for c in 0 to nc { + let mut ref_const: f64 = gnbopt_log((model.priors[c]) as f64) + for j in 0 to p { + ref_const = ref_const - 0.5 * gnbopt_log(2.0 * 3.14159265358979 * ((model.variances[c][j]) as f64)) + let ref_w: f64 = 1.0 / (2.0 * ((model.variances[c][j]) as f64)) + let got_w: f64 = (model.inv_two_var[c * p + j]) as f64 + if gnbopt_abs(got_w - ref_w) > 0.00001 * ref_w { + printf("FAIL: p=%d class %d feature %d weight %.9g, expected %.9g\n", p, c, j, got_w, ref_w) + failures = failures + 1 + } + } + let got_const: f64 = (model.class_const[c]) as f64 + if gnbopt_abs(got_const - ref_const) > 0.0001 * (1.0 + gnbopt_abs(ref_const)) { + printf("FAIL: p=%d class %d constant %.9g, expected %.9g\n", p, c, got_const, ref_const) + failures = failures + 1 + } + } + + # 2. Every joint log-likelihood entry must match the f64 reference. + let jll: Matrix = gaussian_nb_predict_joint_log_proba(model, Q) + if jll.rows != n_query || jll.cols != nc { + printf("FAIL: p=%d joint log-likelihood shape %d x %d\n", p, jll.rows, jll.cols) + failures = failures + 1 + } + let pred: ptr = gaussian_nb_predict(model, Q) + let proba: Matrix = gaussian_nb_predict_proba(model, Q) + let mut max_rel: f64 = 0.0 + let mut decided: i32 = 0 + for i in 0 to n_query { + let mut best_c: i32 = 0 + let mut best: f64 = gnbopt_ref_jll(model, Q, i, 0) + let mut second: f64 = -1000000000000000000.0 + let mut ref_norm: f64 = 0.0 + for c in 0 to nc { + let r: f64 = gnbopt_ref_jll(model, Q, i, c) + let got: f64 = (matrix_at(jll, i, c)) as f64 + let rel: f64 = gnbopt_abs(got - r) / (1.0 + gnbopt_abs(r)) + if rel > max_rel { max_rel = rel } + if rel > 0.00001 { + printf("FAIL: p=%d row %d class %d joint log-likelihood %.9g, expected %.9g\n", p, i, c, got, r) + failures = failures + 1 + } + if c > 0 { + if r > best { + second = best + best = r + best_c = c + } else { + if r > second { second = r } + } + } + } + + # 3. predict is the argmax. Rows whose top two classes sit within + # f32 rounding of each other are not decided by the reference. + if best - second > 0.001 * (1.0 + gnbopt_abs(best)) { + decided = decided + 1 + if pred[i] != model.classes[best_c] { + printf("FAIL: p=%d row %d predicted %.1f, reference argmax %.1f\n", p, i, pred[i], model.classes[best_c]) + failures = failures + 1 + } + } + + # 4. predict_proba is the softmax of the same row. + for c in 0 to nc { + ref_norm = ref_norm + gnbopt_exp(gnbopt_ref_jll(model, Q, i, c) - best) + } + let mut row_sum: f64 = 0.0 + for c in 0 to nc { + let ref_p: f64 = gnbopt_exp(gnbopt_ref_jll(model, Q, i, c) - best) / ref_norm + let got_p: f64 = (matrix_at(proba, i, c)) as f64 + row_sum = row_sum + got_p + if gnbopt_abs(got_p - ref_p) > 0.001 { + printf("FAIL: p=%d row %d class %d probability %.9g, expected %.9g\n", p, i, c, got_p, ref_p) + failures = failures + 1 + } + } + if gnbopt_abs(row_sum - 1.0) > 0.00001 { + printf("FAIL: p=%d row %d probabilities sum to %.9g\n", p, i, row_sum) + failures = failures + 1 + } + } + if decided * 2 < n_query { + printf("FAIL: p=%d only %d of %d rows had a decided reference argmax\n", p, decided, n_query) + failures = failures + 1 + } + printf("p=%d max relative joint log-likelihood error %.3g, %d of %d rows decided\n", p, max_rel, decided, n_query) + + # 5. A single-row batch must reproduce the batched row. + let one: Matrix = matrix_new(1, p) + for j in 0 to p { matrix_set(one, 0, j, matrix_at(Q, n_query - 1, j)) } + let jll_one: Matrix = gaussian_nb_predict_joint_log_proba(model, one) + for c in 0 to nc { + if matrix_at(jll_one, 0, c) != matrix_at(jll, n_query - 1, c) { + printf("FAIL: p=%d single-row batch differs from the batched row for class %d\n", p, c) + failures = failures + 1 + } + } + + matrix_free(jll_one) + matrix_free(one) + matrix_free(proba) + array_free_f32(pred) + matrix_free(jll) + gaussian_nb_free(model) + matrix_free(Q) + matrix_free(X) + array_free_f32(y) + return failures +} + +function main() -> i32 { + let mut failures: i32 = 0 + failures = failures + gnbopt_case(1) + failures = failures + gnbopt_case(3) + failures = failures + gnbopt_case(7) + failures = failures + gnbopt_case(8) + failures = failures + gnbopt_case(9) + failures = failures + gnbopt_case(16) + failures = failures + gnbopt_case(23) + failures = failures + gnbopt_case(64) + failures = failures + gnbopt_case(67) + + if failures > 0 { + printf("FAIL: %d GaussianNB inference checks failed\n", failures) + return 1 + } + printf("OK: vectorized GaussianNB inference matches the f64 reference\n") + return 0 +}