Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/flow.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ jobs:
python benchmarks/test_generate_headline_summary.py
python benchmarks/test_disparity_regression_policy.py
python benchmarks/test_config_equivalence.py
python benchmarks/test_rank_optimization_stages.py
python benchmarks/publish_headline_v2.py --check
python benchmarks/validate_execution_substrate.py
python -m py_compile \
Expand Down
206 changes: 104 additions & 102 deletions benchmarks/OPTIMIZATION_ROADMAP.md

Large diffs are not rendered by default.

156 changes: 156 additions & 0 deletions benchmarks/bench_predict_kernel_svc.flow
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
# Prediction-only scaling benchmark for the one-vs-one RBF KernelSVC
# (issue #481).
#
# Times kernel_svc_multi_predict alone, with fit outside the timing window,
# along three axes: query batch size, training-set size and feature count. The
# training-set size is what moves the support-vector count, and each row
# reports the count the fit ended with. Every case is generated from integers
# on a dyadic grid, so bench_predict_kernel_svc.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_svc.flow > flow_predict_ksvc.txt
# python benchmarks/bench_predict_kernel_svc.py --flow flow_predict_ksvc.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 pksvc_raw(i: i32, j: i32, cls: i32) -> i32 {
return ((i * 37 + j * 19 + cls * 7) % 128) + cls * (8 + ((j * 5) % 7) * 2)
}

function pksvc_fill(X: Matrix, y: ptr<f32>, 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<f32> = X.data + i * p
let mut j: i32 = 0
while j < p {
row[j] = ((pksvc_raw(src, j, cls)) as f32) / 64.0
j = j + 1
}
i = i + 1
}
}

function pksvc_sort(v: ptr<f64>, 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 pksvc_percentile(sorted: ptr<f64>, 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 pksvc_window_ms(model: KernelSVCMulti, Q: Matrix, repeats: i32) -> f64 {
let t0: i64 = flow_now_ns()
let mut k: i32 = 0
while k < repeats {
let pred: ptr<f32> = kernel_svc_multi_predict(model, Q)
array_free_f32(pred)
k = k + 1
}
let t1: i64 = flow_now_ns()
return ((t1 - t0) as f64) / 1000000.0
}

function pksvc_case(axis: string, n_query: i32, n_train: i32, p: i32) -> void {
let n_classes: i32 = 3
let samples: i32 = 7
let X: Matrix = matrix_new(n_train, p)
let y: ptr<f32> = array_new_f32(n_train)
pksvc_fill(X, y, 0, n_classes)
let Q: Matrix = matrix_new(n_query, p)
let yq: ptr<f32> = array_new_f32(n_query)
pksvc_fill(Q, yq, n_train, n_classes)

# gamma = 1 / n_features, exact in f32 for the power-of-two widths used.
let gamma: f32 = 1.0 / (p as f32)
let model: KernelSVCMulti = kernel_svc_multi_fit(X, y, n_classes, gamma, 1.0, 1000)

let warm: f64 = pksvc_window_ms(model, Q, 2)
let mut repeats: i32 = 1
let mut window: f64 = pksvc_window_ms(model, Q, repeats)
while window < 10.0 && repeats < 1048576 {
repeats = repeats * 2
window = pksvc_window_ms(model, Q, repeats)
}

let per_call: ptr<f64> = array_new_f64(samples)
let mut s: i32 = 0
while s < samples {
per_call[s] = pksvc_window_ms(model, Q, repeats) / (repeats as f64)
s = s + 1
}
pksvc_sort(per_call, samples)
let median: f64 = pksvc_percentile(per_call, samples, 0.5)
let iqr: f64 = pksvc_percentile(per_call, samples, 0.75) - pksvc_percentile(per_call, samples, 0.25)

let pred: ptr<f32> = kernel_svc_multi_predict(model, Q)
let mut correct: i32 = 0
let mut i: i32 = 0
while i < n_query {
if pred[i] == yq[i] { correct = correct + 1 }
i = i + 1
}

printf("PREDICT|KernelSVC_RBF|%s|%d|%d|%d|%.9f|%.9f|%d|%d|%d\n", axis, n_query, n_train, p, median, iqr, repeats, model.n_sv, correct)

if warm < 0.0 { printf("unreachable\n") }
array_free_f32(pred)
array_free_f64(per_call)
kernel_svc_multi_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|n_support|correct\n")

# Batch size at 300 training rows and 16 features.
pksvc_case("batch", 1, 300, 16)
pksvc_case("batch", 10, 300, 16)
pksvc_case("batch", 100, 300, 16)
pksvc_case("batch", 1000, 300, 16)
pksvc_case("batch", 10000, 300, 16)

# Training-set size, which sets the support-vector count, at 1000 queries
# and 16 features.
pksvc_case("train", 1000, 60, 16)
pksvc_case("train", 1000, 120, 16)
pksvc_case("train", 1000, 1000, 16)

# Feature count at 1000 queries and 300 training rows.
pksvc_case("features", 1000, 300, 4)
pksvc_case("features", 1000, 300, 64)
pksvc_case("features", 1000, 300, 256)
return 0
}
142 changes: 142 additions & 0 deletions benchmarks/bench_predict_kernel_svc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
#!/usr/bin/env python3
"""Prediction-only scaling benchmark for the RBF SVC, scikit-learn side.

Builds the same float32 inputs as bench_predict_kernel_svc.flow, times
``SVC.predict`` alone with the shared adaptive timer, and optionally joins the
Flow output into one table.

python benchmarks/bench_predict_kernel_svc.py --flow flow_predict_ksvc.txt
"""
from __future__ import annotations

import argparse
import json
from pathlib import Path

import warnings

import numpy as np
from sklearn.exceptions import ConvergenceWarning
from sklearn.svm import SVC

from timing import measure

N_CLASSES = 3

# The canonical KernelSVC rows are approximately equivalent under an accuracy
# tolerance of 0.03 (parity_contract.json). The same tolerance applies here.
ACCURACY_TOLERANCE = 0.03

# (axis, n_query, n_train, features), in the order the Flow benchmark emits.
CASES = (
[("batch", n, 300, 16) for n in (1, 10, 100, 1000, 10000)]
+ [("train", 1000, n, 16) for n in (60, 120, 1000)]
+ [("features", 1000, 300, p) for p in (4, 64, 256)]
)


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, :]
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|KernelSVC_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]),
"n_support": int(p[9]),
"correct": 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_kernel_svc.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, yq = make(n_train, n_query, p)
with warnings.catch_warnings():
# Both sides cap the solver at max_iter=1000, as the canonical rows
# do. The cap binding on one case is expected and is not an error.
warnings.simplefilter("ignore", ConvergenceWarning)
model = SVC(C=1.0, kernel="rbf", gamma=1.0 / p, max_iter=1000).fit(X, y)
timing = measure(lambda: model.predict(Q), min_window_ms=10.0, samples=7)
pred = timing.value
row = {
"estimator": "KernelSVC_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_n_support": int(model.support_.size),
"sklearn_accuracy": float((pred == yq).mean()),
"timing_unit": "ms",
}
f = flow.get((axis, n_query, n_train, p))
if f:
flow_accuracy = f["correct"] / n_query
row.update({
"flow_ms": f["median_ms"],
"flow_iqr_ms": f["iqr_ms"],
"flow_n_support": f["n_support"],
"flow_accuracy": flow_accuracy,
"speedup": timing.median_ms / f["median_ms"] if f["median_ms"] > 0 else None,
"accuracy_abs_diff": abs(flow_accuracy - row["sklearn_accuracy"]),
})
# One query row cannot carry an accuracy tolerance of 0.03.
row["within_tolerance"] = n_query < 34 or row["accuracy_abs_diff"] <= ACCURACY_TOLERANCE
if not row["within_tolerance"]:
mismatches += 1
rows.append(row)

if flow:
print("| axis | queries | train rows | features | support (sklearn / Flow) | sklearn ms | Flow ms | speedup | accuracy (sklearn / Flow) |")
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_n_support']} / {r['flow_n_support']} | "
f"{r['sklearn_ms']:.4f} | {r['flow_ms']:.4f} | {r['speedup']:.2f}x | "
f"{r['sklearn_accuracy']:.3f} / {r['flow_accuracy']:.3f} |"
)
else:
for r in rows:
print(f"PREDICT|KernelSVC_RBF|{r['axis']}|{r['n_query']}|{r['n_train']}|{r['features']}|{r['sklearn_ms']:.9f}|{r['sklearn_iqr_ms']:.9f}|{r['sklearn_n_support']}")

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 accuracy differs by more than {ACCURACY_TOLERANCE}")
return 1
return 0


if __name__ == "__main__":
raise SystemExit(main())
Loading
Loading