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
7 changes: 6 additions & 1 deletion .github/workflows/flow.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ jobs:
benchmarks/test_config_equivalence.py \
benchmarks/test_disparity_regression_policy.py \
benchmarks/publish_headline_v2.py \
benchmarks/audit_hot_primitives.py \
benchmarks/check_primitive_bench.py \
benchmarks/generate_operation_rows.py \
benchmarks/test_generate_operation_rows.py \
benchmarks/validate_execution_substrate.py
Expand Down Expand Up @@ -151,7 +153,10 @@ jobs:
FLOW_OPT_LEVEL: "3"
FLOW_LDFLAGS: "-lm -lopenblas lib/scikit/flow_time.c lib/scikit/flow_parallel.c"
FLOW_HEADLINE_COMMAND: ${{ github.workspace }}/.flow-toolchain/flow run benchmarks/bench_flow_v2.flow
run: python benchmarks/run_headline.py --repeats 5
run: |
python benchmarks/run_headline.py --repeats 5
timeout 600 ${{ github.workspace }}/.flow-toolchain/flow run benchmarks/bench_primitives.flow > /tmp/primitives.txt
python benchmarks/check_primitive_bench.py /tmp/primitives.txt

- uses: actions/upload-artifact@v4
with:
Expand Down
16 changes: 16 additions & 0 deletions benchmarks/HOT_PRIMITIVE_AUDIT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Hot primitive audit

Generated by `benchmarks/audit_hot_primitives.py`. A static scan of `lib/scikit` for hot-loop shapes.
A site is `shared` when its function calls a shared primitive and `inline` otherwise.

Defined primitives: `array_dot`, `blas_dot`, `blas_dot_strided_f64`, `blas_matvec`, `cblas_ddot`, `cblas_dgemm`, `cblas_sdot`, `cblas_sgemm`, `dot_product`, `sqdist_f32`, `sqdist_f32_acc_f64`

Call sites per primitive: `array_dot` 1, `blas_dot` 11, `blas_dot_strided_f64` 3, `blas_matvec` 13, `cblas_ddot` 1, `cblas_dgemm` 2, `cblas_sdot` 1, `cblas_sgemm` 15, `dot_product` 4, `sqdist_f32` 10, `sqdist_f32_acc_f64` 1

| Category | Primitive definitions | Shared call sites | Inline sites | Functions with inline sites |
|---|---:|---:|---:|---|
| squared-distance | 2 | 0 | 116 | `_bic_kmeans`, `_bic_piecewise_error`, `_euclidean_dist_row`, `_fs_anova_f_scores`, `_kernel_compute`, `_kmeans_assign`, `_kmeans_lloyd_scratch`, `_kmeans_nearest_centroid`, `_kmeans_run`, `_kmeans_sk_pp_init`, `_mse`, `_mtl_columns` and 81 more |
| dot | 1 | 14 | 233 | `_build_regressor_tree`, `_centered_dot`, `_gp_linear_kernel`, `_gram_schmidt`, `_ipca_top_eigenvectors`, `_kernel_compute`, `_kernel_func`, `_kernel_svc_smo_precomputed`, `_kmeans_sk_pp_init`, `_kr_dot_f64`, `_mcd_distances`, `_omp_sparse_coding_update` and 147 more |
| sum-reduction | 0 | 0 | 93 | `_array_sum_f32`, `_bic_bistochastic`, `_build_classifier_tree`, `_build_classifier_tree_rf`, `_build_regressor_tree`, `_col_means`, `_find_best_hist_split`, `_fs_anova_f_scores`, `_kmeans_assign`, `_kmeans_sk_pp_init`, `_mean_val`, `_mse` and 60 more |
| rbf | 0 | 0 | 16 | `_beta_func`, `_build_affinity`, `_build_rbf_affinity`, `_gp_rbf_kernel`, `_kernel_compute`, `_kernel_func`, `_rbf_exp`, `_rbf_exp_f64`, `_svm_kernel_vec`, `gaussian_process_classifier_fit`, `gaussian_process_classifier_predict`, `kernel_compute` and 3 more |
| row-partition | 0 | 0 | 20 | `_find_best_hist_split`, `_hist_tree_add_split`, `_split_samples`, `_tree_split_goes_left`, `bootstrap_oob_get_split`, `bootstrap_oob_init`, `group_kfold_split`, `group_shuffle_split_get_split`, `group_shuffle_split_init`, `leave_one_group_out_split`, `leave_p_group_out_split`, `leave_p_out_get_split` and 8 more |
22 changes: 22 additions & 0 deletions benchmarks/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,28 @@ of it found a heap-buffer-overflow in `_solve_lstsq_qr`, which assumed a design
has at least as many rows as columns; RANSAC reaches it by fitting 5 sampled
rows against the 10 features of diabetes.

## Shared hot primitives

[`audit_hot_primitives.py`](audit_hot_primitives.py) scans `lib/scikit` for hot-loop shapes
(squared differences, dot products, sums, RBF exponentials, row partitioning) and records which
sites call a shared primitive. The result is in [`hot_primitive_audit.json`](hot_primitive_audit.json)
and [`HOT_PRIMITIVE_AUDIT.md`](HOT_PRIMITIVE_AUDIT.md). `--check` fails when it is stale. The scan
matches loop shapes by text, so it counts squared-error and variance sums with the distance loops.

`sqdist_f32` and `sqdist_f32_acc_f64` in `lib/scikit/matrix.flow` hold the row-to-row squared
distance that KMeans, KernelRidge, KernelSVC, GaussianProcess, TSNE, SpectralClustering,
LabelSpreading and the kernel approximations used to carry inline. `tests/test_shared_primitives.flow`
compares them with the loops they replaced, bit for bit. `bench_primitives.flow` times them against
both inline forms in one process, and `check_primitive_bench.py` fails when the primitive is more
than 10% slower than either form or when the checksums differ.

The loop form decides the rounding on a target with fused multiply-add. Flow emits `for` loops with
a runtime stride, which LLVM does not vectorize, so the compiler fuses `s + d * d` into one
instruction. A `while` loop with a constant step is vectorized, and the compiler then does the
subtraction and multiplication in vector lanes and adds the products one at a time, unfused. On
arm64 at `-O3` the two forms differ in the last bit of some sums. On x86-64 without FMA, the CI
target, and at `-O0` on both, they are identical.

## Operation rows

The canonical result classifies an estimator and dataset from fit plus
Expand Down
182 changes: 182 additions & 0 deletions benchmarks/audit_hot_primitives.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
#!/usr/bin/env python3
"""Inventory the hot-loop call sites in lib/scikit and which ones use a shared primitive.

Scans every function body in lib/scikit/*.flow (datasets_real.flow, which is
data, is skipped) for these loop shapes:

squared-distance acc = acc + d * d, with d defined as a difference
dot acc = acc + x[..] * y[..] in a scalar loop
sum-reduction acc = acc + x[..] in a scalar loop
rbf exp() applied to gamma or length scale times a distance
row-partition functions that gather, split, sample or select rows

A site is "shared" when its function is itself a shared primitive or calls one
(sqdist_f32, array_dot, blas_dot, cblas_sdot and the like). Everything else is
"inline". Static scan only, so the output is deterministic. `--check` fails
when the committed audit differs from a fresh scan.

This finds loop shapes by text. It does not prove two loops have the same
semantics, so each consolidation still needs the bit-exactness check in
tests/test_shared_primitives.flow.
"""
from __future__ import annotations

import argparse
import json
import re
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
LIB = ROOT / "lib" / "scikit"
SKIP = {"datasets_real.flow"}

SHARED_PRIMITIVES = {
"sqdist_f32": "squared-distance",
"sqdist_f32_acc_f64": "squared-distance",
"array_dot": "dot",
"dot_product": "dot",
"blas_dot": "dot",
"cblas_sdot": "dot",
"cblas_ddot": "dot",
"blas_dot_strided_f64": "dot",
"blas_matvec": "dot",
"cblas_sgemm": "dot",
"cblas_dgemm": "dot",
}
# Functions that define the primitives; their own loop is the implementation.
PRIMITIVE_DEFINITIONS = {"sqdist_f32", "sqdist_f32_acc_f64", "array_dot", "blas_dot", "blas_dot_strided_f64"}

FUNC = re.compile(r"^\s*(?:export\s+)?function\s+([A-Za-z_0-9]+)\s*\(")
ACC_SQ = re.compile(r"^\s*([A-Za-z_]\w*)\s*=\s*\1\s*\+\s*([A-Za-z_]\w*)\s*\*\s*\2\s*$")
ACC_PROD = re.compile(r"^\s*([A-Za-z_]\w*)\s*=\s*\1\s*\+\s*(.+?\S)\s*\*\s*(.+\S)\s*$")
ACC_SUM = re.compile(r"^\s*([A-Za-z_]\w*)\s*=\s*\1\s*\+\s*([A-Za-z_]\w*\[[^\]]+\]|matrix_at\([^)]*\))\s*$")
DIFF = re.compile(r"^\s*let\s+(?:mut\s+)?([A-Za-z_]\w*)\s*:\s*f(?:32|64)\s*=\s*.*\s-\s.*$")
RBF = re.compile(r"\bexp\(.*(gamma|length_scale|neg_gamma)", re.I)
PARTITION_NAME = re.compile(r"(split|partition|gather|take_rows|select_rows|subset|bootstrap|subsample|sample_rows)", re.I)
INDEXED = re.compile(r"\[[^\]]+\]|matrix_at\(")


def functions(text: str):
"""Yield (name, start_line, [(line_no, line), ...]) for each function."""
lines = text.splitlines()
starts = [(i, FUNC.match(ln).group(1)) for i, ln in enumerate(lines) if FUNC.match(ln)]
for k, (i, name) in enumerate(starts):
end = starts[k + 1][0] if k + 1 < len(starts) else len(lines)
yield name, i + 1, [(j + 1, lines[j]) for j in range(i, end)]


def scan_function(name: str, body: list[tuple[int, str]]) -> list[dict]:
sites: list[dict] = []
calls = {p for p in SHARED_PRIMITIVES if re.search(rf"\b{p}\s*\(", "\n".join(b for _, b in body[1:]))}
shared_calls = {SHARED_PRIMITIVES[p] for p in calls}
diffs: dict[str, int] = {}
for no, line in body:
stripped = line.split("#", 1)[0]
m = DIFF.match(stripped)
if m:
diffs[m.group(1)] = no
sq = ACC_SQ.match(stripped)
if sq and sq.group(2) in diffs and no - diffs[sq.group(2)] <= 4:
sites.append({"line": no, "category": "squared-distance"})
continue
pr = ACC_PROD.match(stripped)
if pr and INDEXED.search(pr.group(2)) and INDEXED.search(pr.group(3)):
sites.append({"line": no, "category": "dot"})
continue
if ACC_SUM.match(stripped):
sites.append({"line": no, "category": "sum-reduction"})
continue
if RBF.search(stripped):
sites.append({"line": no, "category": "rbf"})
if PARTITION_NAME.search(name):
sites.append({"line": body[0][0], "category": "row-partition"})
for s in sites:
if name in PRIMITIVE_DEFINITIONS and s["category"] == SHARED_PRIMITIVES.get(name):
s["status"] = "primitive"
elif s["category"] in shared_calls:
s["status"] = "shared"
else:
s["status"] = "inline"
return sites


def audit() -> dict:
rows = []
for path in sorted(LIB.glob("*.flow")):
if path.name in SKIP:
continue
text = path.read_text()
for name, _start, body in functions(text):
for s in scan_function(name, body):
rows.append({"file": f"lib/scikit/{path.name}", "function": name, **s})
categories = ["squared-distance", "dot", "sum-reduction", "rbf", "row-partition"]
summary = {c: {"primitive": 0, "shared": 0, "inline": 0, "inline_functions": []} for c in categories}
for r in rows:
entry = summary[r["category"]]
entry[r["status"]] += 1
if r["status"] == "inline" and r["function"] not in entry["inline_functions"]:
entry["inline_functions"].append(r["function"])
for entry in summary.values():
entry["inline_functions"].sort()
primitives = sorted(
{r["function"] for r in rows if r["status"] == "primitive"}
| {p for p in SHARED_PRIMITIVES if any(re.search(rf"function\s+{p}\s*\(", pth.read_text()) for pth in LIB.glob("*.flow") if pth.name not in SKIP)}
)
call_sites = {}
for name in sorted(SHARED_PRIMITIVES):
n = 0
for pth in LIB.glob("*.flow"):
if pth.name in SKIP:
continue
for ln in pth.read_text().splitlines():
code = ln.split("#", 1)[0]
if re.search(rf"\b{name}\s*\(", code) and not FUNC.match(code) and "function " not in code:
n += 1
if n:
call_sites[name] = n
return {"schema_version": 1, "defined_primitives": primitives, "primitive_call_sites": call_sites,
"summary": summary, "sites": rows}


def render_markdown(doc: dict) -> str:
out = ["# Hot primitive audit", "",
"Generated by `benchmarks/audit_hot_primitives.py`. A static scan of `lib/scikit` for hot-loop shapes.",
"A site is `shared` when its function calls a shared primitive and `inline` otherwise.", "",
"Defined primitives: " + ", ".join(f"`{p}`" for p in doc["defined_primitives"]), "",
"Call sites per primitive: " + ", ".join(f"`{k}` {v}" for k, v in doc["primitive_call_sites"].items()), "",
"| Category | Primitive definitions | Shared call sites | Inline sites | Functions with inline sites |",
"|---|---:|---:|---:|---|"]
for cat, e in doc["summary"].items():
funcs = ", ".join(f"`{f}`" for f in e["inline_functions"][:12])
more = len(e["inline_functions"]) - 12
if more > 0:
funcs += f" and {more} more"
out.append(f"| {cat} | {e['primitive']} | {e['shared']} | {e['inline']} | {funcs} |")
return "\n".join(out) + "\n"


def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--json", type=Path, default=ROOT / "benchmarks" / "hot_primitive_audit.json")
ap.add_argument("--markdown", type=Path, default=ROOT / "benchmarks" / "HOT_PRIMITIVE_AUDIT.md")
ap.add_argument("--check", action="store_true")
args = ap.parse_args()
doc = audit()
text = json.dumps(doc, indent=2) + "\n"
md = render_markdown(doc)
if args.check:
if not args.json.exists() or args.json.read_text() != text or not args.markdown.exists() or args.markdown.read_text() != md:
print("hot primitive audit is stale. Run: python benchmarks/audit_hot_primitives.py")
return 1
print("hot primitive audit matches lib/scikit")
return 0
args.json.write_text(text)
args.markdown.write_text(md)
for cat, e in doc["summary"].items():
print(f"{cat:18} primitive {e['primitive']:3} shared {e['shared']:3} inline {e['inline']:4}")
return 0


if __name__ == "__main__":
sys.exit(main())
Loading
Loading