diff --git a/benchmarks/bench_predict_kernel_ridge.flow b/benchmarks/bench_predict_kernel_ridge.flow new file mode 100644 index 0000000..419f771 --- /dev/null +++ b/benchmarks/bench_predict_kernel_ridge.flow @@ -0,0 +1,154 @@ +# Prediction-only scaling benchmark for KernelRidge with an RBF kernel +# (issue #488). +# +# Times kernel_ridge_predict alone, with fit outside the timing window, along +# three axes: query batch size, training-set size and feature count. Every +# case is generated from integers on a dyadic grid, so +# bench_predict_kernel_ridge.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_kernel_ridge.flow > flow_predict_krr.txt +# python benchmarks/bench_predict_kernel_ridge.py --flow flow_predict_krr.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 pkrr_fill(X: Matrix, y: ptr, first_row: i32) -> void { + let p: i32 = X.cols + let mut i: i32 = 0 + while i < X.rows { + let src: i32 = first_row + i + y[i] = (((src * 29 + 3) % 97) as f32) / 8.0 + let row: ptr = X.data + i * p + let mut j: i32 = 0 + while j < p { + row[j] = (((src * 131 + j * 17) % 257) as f32) / 128.0 - 1.0 + j = j + 1 + } + i = i + 1 + } +} + +function pkrr_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 pkrr_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 pkrr_window_ms(model: KernelRidge, Q: Matrix, repeats: i32) -> f64 { + let t0: i64 = flow_now_ns() + let mut k: i32 = 0 + while k < repeats { + let pred: ptr = kernel_ridge_predict(model, Q) + array_free_f32(pred) + k = k + 1 + } + let t1: i64 = flow_now_ns() + return ((t1 - t0) as f64) / 1000000.0 +} + +function pkrr_case(axis: string, n_query: i32, n_train: i32, p: i32) -> void { + let samples: i32 = 7 + let X: Matrix = matrix_new(n_train, p) + let y: ptr = array_new_f32(n_train) + pkrr_fill(X, y, 0) + let Q: Matrix = matrix_new(n_query, p) + let yq: ptr = array_new_f32(n_query) + pkrr_fill(Q, yq, n_train) + + let model: KernelRidge = kernel_ridge_fit(X, y, 1.0, KERNEL_TYPE_RBF, 0.1, 3, 0.0) + + let warm: f64 = pkrr_window_ms(model, Q, 2) + let mut repeats: i32 = 1 + let mut window: f64 = pkrr_window_ms(model, Q, repeats) + while window < 10.0 && repeats < 1048576 { + repeats = repeats * 2 + window = pkrr_window_ms(model, Q, repeats) + } + + let per_call: ptr = array_new_f64(samples) + let mut s: i32 = 0 + while s < samples { + per_call[s] = pkrr_window_ms(model, Q, repeats) / (repeats as f64) + s = s + 1 + } + pkrr_sort(per_call, samples) + let median: f64 = pkrr_percentile(per_call, samples, 0.5) + let iqr: f64 = pkrr_percentile(per_call, samples, 0.75) - pkrr_percentile(per_call, samples, 0.25) + + # Two checksums of the predictions: a plain sum and a position-weighted + # one, so a permuted or shifted output cannot pass as agreement. + let pred: ptr = kernel_ridge_predict(model, Q) + let mut total: f64 = 0.0 + let mut weighted: f64 = 0.0 + let mut total_abs: f64 = 0.0 + let mut i: i32 = 0 + while i < n_query { + let v: f64 = (pred[i]) as f64 + total = total + v + weighted = weighted + v * (((i % 7) + 1) as f64) + if v < 0.0 { total_abs = total_abs - v } else { total_abs = total_abs + v } + i = i + 1 + } + + printf("PREDICT|KernelRidge_RBF|%s|%d|%d|%d|%.9f|%.9f|%d|%.9g|%.9g|%.9g\n", axis, n_query, n_train, p, median, iqr, repeats, total, weighted, total_abs) + + if warm < 0.0 { printf("unreachable\n") } + array_free_f32(pred) + array_free_f64(per_call) + kernel_ridge_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|n_train|features|median_ms|iqr_ms|repeats|pred_sum|pred_weighted_sum|pred_abs_sum\n") + + # Batch size at the Diabetes shape: 353 training rows, 10 features. + pkrr_case("batch", 1, 353, 10) + pkrr_case("batch", 10, 353, 10) + pkrr_case("batch", 89, 353, 10) + pkrr_case("batch", 1000, 353, 10) + pkrr_case("batch", 10000, 353, 10) + + # Training-set size, which is the support size for kernel ridge, at 1000 + # queries and 10 features. + pkrr_case("train", 1000, 100, 10) + pkrr_case("train", 1000, 1000, 10) + pkrr_case("train", 1000, 3000, 10) + + # Feature count at 1000 queries and 353 training rows. + pkrr_case("features", 1000, 353, 2) + pkrr_case("features", 1000, 353, 32) + pkrr_case("features", 1000, 353, 128) + return 0 +} diff --git a/benchmarks/bench_predict_kernel_ridge.py b/benchmarks/bench_predict_kernel_ridge.py new file mode 100644 index 0000000..acdb2b4 --- /dev/null +++ b/benchmarks/bench_predict_kernel_ridge.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +"""Prediction-only scaling benchmark for KernelRidge (RBF), scikit-learn side. + +Builds the same float32 inputs as bench_predict_kernel_ridge.flow, times +``KernelRidge.predict`` alone with the shared adaptive timer, and optionally +joins the Flow output into one table. + + python benchmarks/bench_predict_kernel_ridge.py --flow flow_predict_krr.txt +""" +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np +from sklearn.kernel_ridge import KernelRidge + +from timing import measure + +# Agreement tolerance on the prediction checksums, relative to the sum of +# absolute predictions. scikit-learn solves the float32 system in float32 and +# Flow solves it in float64, so the dual coefficients differ in their last +# digits before prediction starts. +CHECKSUM_RELATIVE_TOLERANCE = 1e-3 + +# (axis, n_query, n_train, features), in the order the Flow benchmark emits. +CASES = ( + [("batch", n, 353, 10) for n in (1, 10, 89, 1000, 10000)] + + [("train", 1000, n, 10) for n in (100, 1000, 3000)] + + [("features", 1000, 353, p) for p in (2, 32, 128)] +) + + +def make(first_row: int, n: int, p: int): + i = np.arange(first_row, first_row + n, dtype=np.int64)[:, None] + j = np.arange(p, dtype=np.int64)[None, :] + # Integers over a power of two: exact in float32. + X = (((i * 131 + j * 17) % 257) / 128.0 - 1.0).astype(np.float32) + y = (((i[:, 0] * 29 + 3) % 97) / 8.0).astype(np.float32) + return X, y + + +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|KernelRidge_RBF|"): + 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]), + "pred_sum": float(p[9]), + "pred_weighted_sum": float(p[10]), + "pred_abs_sum": float(p[11]), + } + 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_kernel_ridge.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, n_train, p in CASES: + X, y = make(0, n_train, p) + Q, _ = make(n_train, n_query, p) + model = KernelRidge(alpha=1.0, kernel="rbf", gamma=0.1).fit(X, y) + timing = measure(lambda: model.predict(Q), min_window_ms=10.0, samples=7) + pred = np.asarray(timing.value, dtype=np.float64) + weights = (np.arange(n_query) % 7 + 1).astype(np.float64) + row = { + "estimator": "KernelRidge_RBF", + "axis": axis, + "n_query": n_query, + "n_train": n_train, + "features": p, + "sklearn_ms": timing.median_ms, + "sklearn_iqr_ms": timing.iqr_ms, + "sklearn_pred_sum": float(pred.sum()), + "sklearn_pred_weighted_sum": float((pred * weights).sum()), + "sklearn_pred_abs_sum": float(np.abs(pred).sum()), + "timing_unit": "ms", + } + f = flow.get((axis, n_query, n_train, p)) + if f: + scale = max(row["sklearn_pred_abs_sum"], 1e-12) + sum_diff = abs(f["pred_sum"] - row["sklearn_pred_sum"]) / scale + weighted_diff = abs(f["pred_weighted_sum"] - row["sklearn_pred_weighted_sum"]) / (7.0 * scale) + row.update({ + "flow_ms": f["median_ms"], + "flow_iqr_ms": f["iqr_ms"], + "flow_pred_sum": f["pred_sum"], + "flow_pred_weighted_sum": f["pred_weighted_sum"], + "speedup": timing.median_ms / f["median_ms"] if f["median_ms"] > 0 else None, + "checksum_relative_diff": max(sum_diff, weighted_diff), + "predictions_agree": max(sum_diff, weighted_diff) <= CHECKSUM_RELATIVE_TOLERANCE, + }) + if not row["predictions_agree"]: + mismatches += 1 + rows.append(row) + + if flow: + print("| axis | queries | train rows | features | sklearn ms | Flow ms | speedup | checksum rel. diff |") + print("| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |") + for r in rows: + if "flow_ms" not in r: + continue + print( + f"| {r['axis']} | {r['n_query']} | {r['n_train']} | {r['features']} | " + f"{r['sklearn_ms']:.4f} | {r['flow_ms']:.4f} | {r['speedup']:.2f}x | " + f"{r['checksum_relative_diff']:.1e} |" + ) + else: + for r in rows: + print(f"PREDICT|KernelRidge_RBF|{r['axis']}|{r['n_query']}|{r['n_train']}|{r['features']}|{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 prediction checksums differ by more than {CHECKSUM_RELATIVE_TOLERANCE:g}") + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/lib/scikit/kernel_ridge.flow b/lib/scikit/kernel_ridge.flow index 0255953..981b007 100644 --- a/lib/scikit/kernel_ridge.flow +++ b/lib/scikit/kernel_ridge.flow @@ -20,7 +20,13 @@ export struct KernelRidge { n_samples: i32, n_features: i32, n_outputs: i32, - fitted: bool + fitted: bool, + # Squared norm of every training row, and the dual coefficients widened to + # f64. RBF prediction needs both on every call and both depend on the + # fitted state alone, so fit computes them once. They are derived from + # X_train and dual_coef and must be rebuilt if either is edited by hand. + x_train_sq: ptr, + dual_coef_d: ptr } const KR_KERNEL_LINEAR: i32 = 0 @@ -185,9 +191,25 @@ export function kernel_ridge_fit(X: Matrix, y: ptr, alpha: f32, kernel_type } array_free_f64(K_reg) - array_free_f64(dual_coef_d) + + # Store the f32 coefficients widened to f64. Prediction has always summed + # the rounded values, and widening the stored ones keeps that unchanged. + # The unrounded f64 solution would move every prediction. + for i in 0 to n { + dual_coef_d[i] = (dual_coef[i]) as f64 + } let X_copy: Matrix = matrix_copy(X) + let x_train_sq: ptr = array_new_f32(n) + for i in 0 to n { + let r: ptr = X_copy.data + i * n_features + let mut s: f32 = 0.0 + for f in 0 to n_features { + let v: f32 = r[f] + s = s + v * v + } + x_train_sq[i] = s + } return KernelRidge { alpha: alpha, @@ -200,7 +222,9 @@ export function kernel_ridge_fit(X: Matrix, y: ptr, alpha: f32, kernel_type n_samples: n, n_features: X.cols, n_outputs: 1, - fitted: true + fitted: true, + x_train_sq: x_train_sq, + dual_coef_d: dual_coef_d } } @@ -219,63 +243,169 @@ function _kr_exp_f32(x: f32) -> f32 { return expf(x) } -export function kernel_ridge_predict(model: KernelRidge, X: Matrix) -> ptr { +# exp(v[k]) in place for a block of RBF exponents. +# +# An RBF kernel entry is exp(-gamma * d^2). Its argument is never positive for +# a valid gamma, and an argument below -104 gives a value under the smallest +# f32 denormal. On that range the exponential needs no libm call: +# +# exp(x) = exp(x / 1024) ^ 1024 +# +# x / 1024 lies in [-0.1016, 0], where the degree 8 Taylor polynomial is +# within 3.2e-15 relative, and ten squarings raise the result to the 1024th +# power. Each squaring doubles the relative error, so truncation contributes +# at most 3.3e-12 at x = -104 and far less towards x = 0. With rounding the +# measured worst case over the range is 3.6e-12. The squared distance +# feeding it is assembled from f32 norms and an sgemm cross term and carries +# about 1e-6 relative, so this is far below what the input can resolve. +# +# The point of the form is that the body is straight-line arithmetic with no +# call and no data-dependent branch, so the compiler vectorizes the loop. A +# libm exp per element is a call the loop vectorizer cannot see through, and +# it was 97 percent of predict time on the Diabetes row. +# +# Arguments below -104 return exactly 0. The polynomial is symmetric in the +# size of its argument, so a positive exponent up to 104, which is past where +# an f32 result overflows, meets the same bound. A negative gamma therefore +# needs no separate path. +export function rbf_exp_block(v: ptr, n: i32) -> void { + let mut k: i32 = 0 + while k < n { + let x: f64 = v[k] + let mut xc: f64 = x + if xc < -104.0 { xc = -104.0 } + let y: f64 = xc * 0.0009765625 + let mut e: f64 = 1.0 + y * (1.0 + y * (0.5 + y * (0.16666666666666666 + y * (0.041666666666666664 + y * (0.008333333333333333 + y * (0.001388888888888889 + y * (0.0001984126984126984 + y * 0.0000248015873015873))))))) + e = e * e + e = e * e + e = e * e + e = e * e + e = e * e + e = e * e + e = e * e + e = e * e + e = e * e + e = e * e + if x < -104.0 { e = 0.0 } + v[k] = e + k = k + 1 + } +} + +# f64 dot product over eight partial sums. One running sum is a single +# dependency chain the compiler may not reorder; eight give it vector lanes. +# This stays in Flow rather than calling cblas_ddot or cblas_dgemv because a +# block is small enough that a threaded BLAS spends longer dispatching than +# computing, which AGENTS.md records at roughly 0.1 ms per call on OpenBLAS. +function _kr_dot_f64(a: ptr, b: ptr, n: i32) -> f64 { + let mut s0: f64 = 0.0 + let mut s1: f64 = 0.0 + let mut s2: f64 = 0.0 + let mut s3: f64 = 0.0 + let mut s4: f64 = 0.0 + let mut s5: f64 = 0.0 + let mut s6: f64 = 0.0 + let mut s7: f64 = 0.0 + let n8: i32 = (n / 8) * 8 + let mut j: i32 = 0 + while j < n8 { + s0 = s0 + a[j] * b[j] + s1 = s1 + a[j + 1] * b[j + 1] + s2 = s2 + a[j + 2] * b[j + 2] + s3 = s3 + a[j + 3] * b[j + 3] + s4 = s4 + a[j + 4] * b[j + 4] + s5 = s5 + a[j + 5] * b[j + 5] + s6 = s6 + a[j + 6] * b[j + 6] + s7 = s7 + a[j + 7] * b[j + 7] + j = j + 8 + } + let mut tail: f64 = 0.0 + while j < n { + tail = tail + a[j] * b[j] + j = j + 1 + } + return ((s0 + s1) + (s2 + s3)) + ((s4 + s5) + (s6 + s7)) + tail +} + +# Rows of the test-to-train kernel evaluated per block. The block holds one +# f32 cross term and one f64 kernel entry per pair, 12 bytes, and is sized to +# stay inside a 256 KiB second-level cache however large the batch is. The +# full kernel used to be materialized at n_queries * n_train. +function _kr_rbf_block_rows(n: i32, nt: i32) -> i32 { + let mut rows: i32 = 16384 + if nt > 0 { rows = 16384 / nt } + if rows < 1 { rows = 1 } + if rows > n { rows = n } + return rows +} + +function _kr_predict_rbf(model: KernelRidge, X: Matrix, result: ptr) -> void { let n: i32 = X.rows let nt: i32 = model.n_samples let nf: i32 = model.n_features - let result: ptr = array_new_f32(n) - let gamma_d: f64 = (model.gamma) as f64 - - if model.kernel_type == 2 || model.kernel_type == KR_KERNEL_RBF { - let x_data: ptr = X.data - let xt_data: ptr = model.X_train.data - - let x_sq: ptr = array_new_f32(n) - for i in 0 to n { - let r: ptr = x_data + i * nf - let mut s: f32 = 0.0 - for f in 0 to nf { - let v: f32 = r[f] - s = s + v * v + let x_data: ptr = X.data + let xt_data: ptr = model.X_train.data + let xt_sq: ptr = model.x_train_sq + let neg_gamma: f64 = 0.0 - ((model.gamma) as f64) + + let block: i32 = _kr_rbf_block_rows(n, nt) + let cross: ptr = malloc((block as i64) * (nt as i64) * 4) as ptr + let kern: ptr = malloc((block as i64) * (nt as i64) * 8) as ptr + + let mut start: i32 = 0 + while start < n { + let mut rows: i32 = n - start + if rows > block { rows = block } + let xb: ptr = x_data + start * nf + + # Cross terms for the block: one sgemm. + cblas_sgemm(101, 111, 112, rows, nt, nf, 1.0, xb, nf, xt_data, nf, 0.0, cross, nt) + + # Exponent -gamma * max(0, |x|^2 + |t|^2 - 2 x.t) for every pair. + let mut i: i32 = 0 + while i < rows { + let r: ptr = xb + i * nf + let mut xi_sq: f32 = 0.0 + let mut f: i32 = 0 + while f < nf { + xi_sq = xi_sq + r[f] * r[f] + f = f + 1 } - x_sq[i] = s - } - - let xt_sq: ptr = array_new_f32(nt) - for j in 0 to nt { - let r: ptr = xt_data + j * nf - let mut s: f32 = 0.0 - for f in 0 to nf { - let v: f32 = r[f] - s = s + v * v + let cross_row: ptr = cross + i * nt + let kern_row: ptr = kern + i * nt + let mut j: i32 = 0 + while j < nt { + let mut sq: f64 = (xi_sq + xt_sq[j] - 2.0 * cross_row[j]) as f64 + if sq < 0.0 { sq = 0.0 } + kern_row[j] = neg_gamma * sq + j = j + 1 } - xt_sq[j] = s + i = i + 1 } - let cross: ptr = malloc((n as i64) * (nt as i64) * 4) as ptr - cblas_sgemm(101, 111, 112, n, nt, nf, 1.0, x_data, nf, xt_data, nf, 0.0, cross, nt) + rbf_exp_block(kern, rows * nt) - let dual_coef_d: ptr = array_new_f64(nt) - for j in 0 to nt { - dual_coef_d[j] = (model.dual_coef[j]) as f64 + # Kernel row times the dual coefficients. + i = 0 + while i < rows { + result[start + i] = _kr_dot_f64(kern + i * nt, model.dual_coef_d, nt) as f32 + i = i + 1 } + start = start + rows + } - for i in 0 to n { - let xi_sq: f32 = x_sq[i] - let cross_row: ptr = cross + i * nt - let mut sum: f64 = 0.0 - for j in 0 to nt { - let mut sq: f64 = (xi_sq + xt_sq[j] - 2.0 * cross_row[j]) as f64 - if sq < 0.0 { sq = 0.0 } - sum = sum + dual_coef_d[j] * _kr_exp_f64(0.0 - gamma_d * sq) - } - result[i] = sum as f32 - } + free(kern as ptr) + free(cross as ptr) +} - array_free_f64(dual_coef_d) - free(cross as ptr) - array_free_f32(x_sq) - array_free_f32(xt_sq) +export function kernel_ridge_predict(model: KernelRidge, X: Matrix) -> ptr { + let n: i32 = X.rows + let nt: i32 = model.n_samples + let nf: i32 = model.n_features + let result: ptr = array_new_f32(n) + + if model.kernel_type == 2 || model.kernel_type == KR_KERNEL_RBF { + _kr_predict_rbf(model, X, result) } else { let xt_data2: ptr = model.X_train.data if model.kernel_type == KR_KERNEL_LINEAR { @@ -306,5 +436,7 @@ export function kernel_ridge_predict(model: KernelRidge, X: Matrix) -> ptr export function kernel_ridge_free(model: KernelRidge) -> void { array_free_f32(model.dual_coef) + array_free_f32(model.x_train_sq) + array_free_f64(model.dual_coef_d) matrix_free(model.X_train) } diff --git a/tests/test_opt_kernelridge_predict.flow b/tests/test_opt_kernelridge_predict.flow new file mode 100644 index 0000000..70f9844 --- /dev/null +++ b/tests/test_opt_kernelridge_predict.flow @@ -0,0 +1,302 @@ +# Regression test for blocked KernelRidge RBF prediction (issue #488). +# +# Prediction evaluates the test-to-train kernel a block of rows at a time, +# takes the exponential with a vectorizable polynomial in place of a libm call +# per pair, and reads the training-row norms and f64 dual coefficients that +# fit stored on the model. The checks below: +# +# 1. bound the polynomial exponential against libm on [-104, 104], +# 2. confirm fit stored the derived state, +# 3. compare predictions with an independent f64 sum that takes direct +# squared differences and libm exp, 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 only +# differences left are the exponential and the final f32 rounding, +# 4. require a row predicted alone to match the same row in a batch, +# 5. predict with a negative gamma, where every exponent is positive, +# 6. confirm the polynomial kernel branch still matches its reference. + +import "lib/scikit/scikit.flow" + +function kropt_abs(v: f64) -> f64 { + if v < 0.0 { return 0.0 - v } + return v +} + +function kropt_exp(v: f64) -> f64 { + let r: f64 = exp(v) + return r +} + +function kropt_value(i: i32, j: i32) -> f32 { + return (((i * 131 + j * 17) % 257) as f32) / 128.0 - 1.0 +} + +function kropt_fill(X: Matrix, first_row: i32) -> void { + for i in 0 to X.rows { + for j in 0 to X.cols { matrix_set(X, i, j, kropt_value(first_row + i, j)) } + } +} + +function kropt_target(X: Matrix, i: i32) -> f32 { + let mut s: f32 = 0.0 + for j in 0 to X.cols { + let v: f32 = matrix_at(X, i, j) + s = s + v * (0.5 + (j as f32) * 0.25) + v * v + } + return s +} + +function kropt_check_exp() -> i32 { + let mut failures: i32 = 0 + let n: i32 = 16001 + let v: ptr = array_new_f64(n) + let x: ptr = array_new_f64(n) + # 104 down to -116 in steps of 0.01375, which crosses the -104 cutoff. + for k in 0 to n { + x[k] = 104.0 - (k as f64) * 0.01375 + v[k] = x[k] + } + rbf_exp_block(v, n) + + let mut max_rel: f64 = 0.0 + let mut below_cutoff: i32 = 0 + for k in 0 to n { + if x[k] < -104.0 { + below_cutoff = below_cutoff + 1 + if v[k] != 0.0 { + printf("FAIL: exp(%.6f) below the cutoff returned %.9g, expected 0\n", x[k], v[k]) + failures = failures + 1 + } + } else { + let r: f64 = kropt_exp(x[k]) + let rel: f64 = kropt_abs(v[k] - r) / r + if rel > max_rel { max_rel = rel } + } + } + printf("polynomial exp max relative error on [-104, 104] = %.3g\n", max_rel) + if max_rel > 0.00000000001 { + printf("FAIL: polynomial exp relative error %.3g exceeds 1e-11\n", max_rel) + failures = failures + 1 + } + if below_cutoff < 100 { + printf("FAIL: the grid no longer reaches below the cutoff\n") + failures = failures + 1 + } + v[0] = 0.0 + rbf_exp_block(v, 1) + if v[0] != 1.0 { + printf("FAIL: exp(0) returned %.17g\n", v[0]) + failures = failures + 1 + } + + # Lengths around the vector width, so a remainder loop is covered. + for len in 1 to 10 { + for k in 0 to len { v[k] = 0.0 - (k as f64) * 0.75 - 0.125 } + rbf_exp_block(v, len) + for k in 0 to len { + let r: f64 = kropt_exp(0.0 - (k as f64) * 0.75 - 0.125) + if kropt_abs(v[k] - r) > 0.00000000001 * r { + printf("FAIL: length %d entry %d returned %.17g, expected %.17g\n", len, k, v[k], r) + failures = failures + 1 + } + } + } + + array_free_f64(v) + array_free_f64(x) + return failures +} + +# Independent f64 RBF prediction for row i of Q. abs_out[0] receives the sum +# of |dual * kernel|, the scale rounding in the f32 distance acts on. +function kropt_ref_rbf(model: KernelRidge, gamma: f64, Q: Matrix, i: i32, abs_out: ptr) -> f64 { + let mut total: f64 = 0.0 + let mut total_abs: f64 = 0.0 + for j in 0 to model.n_samples { + let mut d2: f64 = 0.0 + for f in 0 to model.n_features { + let d: f64 = ((matrix_at(Q, i, f)) as f64) - ((matrix_at(model.X_train, j, f)) as f64) + d2 = d2 + d * d + } + let term: f64 = ((model.dual_coef[j]) as f64) * kropt_exp(0.0 - gamma * d2) + total = total + term + total_abs = total_abs + kropt_abs(term) + } + abs_out[0] = total_abs + return total +} + +function kropt_case(n_train: i32, nf: i32, n_query: i32, gamma: f32) -> i32 { + let mut failures: i32 = 0 + let X: Matrix = matrix_new(n_train, nf) + kropt_fill(X, 0) + let y: ptr = array_new_f32(n_train) + for i in 0 to n_train { y[i] = kropt_target(X, i) } + let Q: Matrix = matrix_new(n_query, nf) + kropt_fill(Q, n_train + 7) + + let model: KernelRidge = kernel_ridge_fit(X, y, 1.0, KERNEL_TYPE_RBF, gamma, 3, 0.0) + + # 2. Derived state stored by fit. + for j in 0 to n_train { + let mut sq: f64 = 0.0 + for f in 0 to nf { + let v: f64 = (matrix_at(X, j, f)) as f64 + sq = sq + v * v + } + if kropt_abs(((model.x_train_sq[j]) as f64) - sq) > 0.00001 * (1.0 + sq) { + printf("FAIL: train=%d row %d stored squared norm %.9g, expected %.9g\n", n_train, j, model.x_train_sq[j], sq) + failures = failures + 1 + } + if model.dual_coef_d[j] != ((model.dual_coef[j]) as f64) { + printf("FAIL: train=%d row %d f64 dual coefficient differs from the stored f32 one\n", n_train, j) + failures = failures + 1 + } + } + + # 3. Batched prediction against the f64 reference. + let pred: ptr = kernel_ridge_predict(model, Q) + let scale: ptr = array_new_f64(1) + let mut max_err: f64 = 0.0 + for i in 0 to n_query { + let r: f64 = kropt_ref_rbf(model, gamma as f64, Q, i, scale) + let err: f64 = kropt_abs(((pred[i]) as f64) - r) + if err > max_err { max_err = err } + if err > 0.000001 * (1.0 + scale[0]) { + printf("FAIL: train=%d features=%d row %d predicted %.9g, expected %.9g\n", n_train, nf, i, pred[i], r) + failures = failures + 1 + } + } + printf("train=%d features=%d queries=%d max abs prediction error %.3g\n", n_train, nf, n_query, max_err) + + # 4. A row predicted alone must match the same row inside the batch. + let one: Matrix = matrix_new(1, nf) + let mut i: i32 = 0 + while i < n_query { + for f in 0 to nf { matrix_set(one, 0, f, matrix_at(Q, i, f)) } + let p1: ptr = kernel_ridge_predict(model, one) + if kropt_abs(((p1[0]) as f64) - ((pred[i]) as f64)) > 0.00001 * (1.0 + kropt_abs((pred[i]) as f64)) { + printf("FAIL: train=%d row %d alone %.9g, in batch %.9g\n", n_train, i, p1[0], pred[i]) + failures = failures + 1 + } + array_free_f32(p1) + i = i + 13 + } + + # An empty batch is valid and must not read or write anything. + let empty: Matrix = matrix_new(0, nf) + let p0: ptr = kernel_ridge_predict(model, empty) + array_free_f32(p0) + matrix_free(empty) + + matrix_free(one) + array_free_f64(scale) + array_free_f32(pred) + kernel_ridge_free(model) + matrix_free(Q) + array_free_f32(y) + matrix_free(X) + return failures +} + +# 5. Negative gamma makes every exponent positive. It is not a meaningful +# kernel, but predict must still evaluate what it was asked for. +function kropt_negative_gamma() -> i32 { + let mut failures: i32 = 0 + let n_train: i32 = 40 + let nf: i32 = 3 + let X: Matrix = matrix_new(n_train, nf) + kropt_fill(X, 0) + let y: ptr = array_new_f32(n_train) + for i in 0 to n_train { y[i] = kropt_target(X, i) } + let Q: Matrix = matrix_new(11, nf) + kropt_fill(Q, 300) + + let mut model: KernelRidge = kernel_ridge_fit(X, y, 1.0, KERNEL_TYPE_RBF, 0.5, 3, 0.0) + model.gamma = -0.25 + let pred: ptr = kernel_ridge_predict(model, Q) + let scale: ptr = array_new_f64(1) + for i in 0 to Q.rows { + let r: f64 = kropt_ref_rbf(model, -0.25, Q, i, scale) + if kropt_abs(((pred[i]) as f64) - r) > 0.000001 * (1.0 + scale[0]) { + printf("FAIL: negative gamma row %d predicted %.9g, expected %.9g\n", i, pred[i], r) + failures = failures + 1 + } + } + + array_free_f64(scale) + array_free_f32(pred) + kernel_ridge_free(model) + matrix_free(Q) + array_free_f32(y) + matrix_free(X) + return failures +} + +# 6. The polynomial branch is untouched and must still match its reference. +function kropt_poly() -> i32 { + let mut failures: i32 = 0 + let n_train: i32 = 30 + let nf: i32 = 4 + let X: Matrix = matrix_new(n_train, nf) + kropt_fill(X, 0) + let y: ptr = array_new_f32(n_train) + for i in 0 to n_train { y[i] = kropt_target(X, i) } + let Q: Matrix = matrix_new(9, nf) + kropt_fill(Q, 200) + + let model: KernelRidge = kernel_ridge_fit(X, y, 1.0, KERNEL_TYPE_POLY, 0.5, 2, 1.0) + let pred: ptr = kernel_ridge_predict(model, Q) + for i in 0 to Q.rows { + let mut total: f64 = 0.0 + let mut total_abs: f64 = 0.0 + for j in 0 to n_train { + let mut dot: f64 = 0.0 + for f in 0 to nf { + dot = dot + ((matrix_at(Q, i, f)) as f64) * ((matrix_at(X, j, f)) as f64) + } + let base: f64 = 0.5 * dot + 1.0 + let term: f64 = ((model.dual_coef[j]) as f64) * base * base + total = total + term + total_abs = total_abs + kropt_abs(term) + } + if kropt_abs(((pred[i]) as f64) - total) > 0.0002 * (1.0 + total_abs) { + printf("FAIL: polynomial row %d predicted %.9g, expected %.9g\n", i, pred[i], total) + failures = failures + 1 + } + } + + array_free_f32(pred) + kernel_ridge_free(model) + matrix_free(Q) + array_free_f32(y) + matrix_free(X) + return failures +} + +function main() -> i32 { + let mut failures: i32 = 0 + failures = failures + kropt_check_exp() + + # One block: 37 training rows allow 442 query rows per block. + failures = failures + kropt_case(37, 3, 50, 0.5) + # Exactly on a block edge: 16384 / 128 = 128 rows, and 256 queries. + failures = failures + kropt_case(128, 5, 256, 0.25) + # Several blocks with a short last one: 16384 / 200 = 81 rows, 300 queries. + failures = failures + kropt_case(200, 10, 300, 0.1) + # A single query row. + failures = failures + kropt_case(60, 7, 1, 0.3) + # Large gamma drives distant pairs past the -104 cutoff. + failures = failures + kropt_case(50, 6, 40, 40.0) + + failures = failures + kropt_negative_gamma() + failures = failures + kropt_poly() + + if failures > 0 { + printf("FAIL: %d KernelRidge prediction checks failed\n", failures) + return 1 + } + printf("OK: blocked KernelRidge RBF prediction matches the f64 reference\n") + return 0 +}