flash-sd-kde-repro / code /gpu_a10g.py
avengeryt22's picture
GPU arm using pinned Triton kernels
3387ad0 verified
Raw History Blame Contribute Delete
11.4 kB
"""GPU arm: run the authors' pinned Triton kernels on the 1D toy mixture.
Purpose: (1) test fused vs non-fused *output identity* on the hardware path the
paper describes, (2) measure the runtime ratio with the authors' own timing
protocol (one warmup + one discarded pass, then 3 CUDA-event-timed repeats),
(3) compare the fused GPU density against an independent float64 evaluation of
p - (h^2/2) Δp on the host.
The only harness deviation from benchmarks/toy_1d_mog_oracle.py: the gitbud
run-directory plumbing is bypassed (results are written as JSON here); the
timing functions and the call sequence are copied verbatim.
"""
import json
import math
import os
import subprocess
import sys
import time
from pathlib import Path
import numpy as np
REPO = Path("/work/Flash-SD-KDE")
COMMIT = "acaf8712f8c146c837e1d1dcccb56ce6322962bc"
OUT = Path(os.environ.get("OUT_DIR", "/work/results"))
OUT.mkdir(parents=True, exist_ok=True)
if not REPO.exists():
subprocess.run(["git", "clone", "--quiet",
"https://github.com/Elliotepsteino/Flash-SD-KDE.git", str(REPO)], check=True)
subprocess.run(["git", "-C", str(REPO), "checkout", "--quiet", COMMIT], check=True)
sys.path.insert(0, str(REPO))
import torch # noqa: E402
import triton # noqa: E402
from flash_sd_kde.kde import (kde_eval, kde_eval_linearized, # noqa: E402
kde_eval_linearized_nonfused)
from globals import DEFAULT_EPS # noqa: E402
SEED = 0
N_LIST = (128, 256, 512, 1024, 2048, 4096)
N_REPEATS = 3
N_GRID, GRID_MIN, GRID_MAX = 2048, -6.0, 6.0
W = np.array([0.3, 0.4, 0.3])
MU = np.array([-2.0, 0.0, 2.0])
SD = np.array([0.4, 0.7, 0.3])
INV_SQRT_2PI = 1.0 / math.sqrt(2.0 * math.pi)
PRECISION = "fast_tf32"
BACKEND = "splitk_stream"
trapz = np.trapezoid if hasattr(np, "trapezoid") else np.trapz
# ------------------------------------------------------------- host helpers
def mog_sample(rng, n):
comp = rng.choice(len(W), size=n, p=W)
return rng.normal(loc=MU[comp], scale=SD[comp]).astype(np.float32)
def mog_pdf(x):
x = np.asarray(x, np.float64)
out = np.zeros_like(x)
for w, mu, s in zip(W, MU, SD):
z = (x - mu) / s
out += w * (INV_SQRT_2PI / s) * np.exp(-0.5 * z * z)
return out
def silverman_bandwidth(data):
x = np.asarray(data, dtype=np.float32)
sigma = min(float(np.std(x)), float(np.percentile(x, 75) - np.percentile(x, 25)) / 1.34)
if sigma <= 0:
sigma = 1.0
return float(0.9 * sigma * x.size ** (-1.0 / 5.0))
def laplace_definition_f64(x, data, h):
"""Independent path: p - (h^2/2) * d2p/dx2, analytic Laplacian, float64."""
x = np.asarray(x, np.float64)
d = np.asarray(data, np.float64)
z = (x[:, None] - d[None, :]) / h
phi = np.exp(-0.5 * z * z)
p = (INV_SQRT_2PI / h) * phi.mean(axis=1)
lap = (INV_SQRT_2PI / h ** 3) * (((z * z) - 1.0) * phi).mean(axis=1)
return p - 0.5 * h * h * lap
def errors(x, est, true):
diff = est - true
return {"ise": float(trapz(diff * diff, x)),
"iae": float(trapz(np.abs(diff), x)),
"max_abs": float(np.max(np.abs(diff))),
"neg_mass": float(trapz(np.abs(np.minimum(est, 0.0)), x)),
"mass": float(trapz(est, x)),
"min": float(np.min(est))}
# ------------------------------------------------ authors' timing, verbatim
def _time_call(fn, device):
torch.cuda.synchronize(device)
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
start.record()
result = fn()
end.record()
torch.cuda.synchronize(device)
return result, start.elapsed_time(end) / 1000.0
def _time_repeated(fn, *, device, warmup, repeats):
for _ in range(warmup):
fn()
timings = []
for _ in range(repeats):
_, elapsed = _time_call(fn, device=device)
timings.append(elapsed)
return float(np.mean(timings)), float(np.std(timings))
def main():
device = torch.device("cuda")
props = torch.cuda.get_device_properties(0)
meta = {
"device_name": torch.cuda.get_device_name(0),
"sm_count": props.multi_processor_count,
"total_memory_gb": round(props.total_memory / 1e9, 1),
"capability": f"{props.major}.{props.minor}",
"torch": torch.__version__, "triton": triton.__version__,
"cuda": torch.version.cuda,
"tf32_matmul_allowed": bool(torch.backends.cuda.matmul.allow_tf32),
"commit": subprocess.run(["git", "-C", str(REPO), "rev-parse", "HEAD"],
capture_output=True, text=True).stdout.strip(),
"precision_mode": PRECISION, "kde_backend": BACKEND,
"timing": "warmup=1 (+1 discarded pass), 3 CUDA-event repeats, mean/std",
}
print("device:", meta["device_name"], "| SMs:", meta["sm_count"],
"| torch", meta["torch"], "| triton", meta["triton"])
rng = np.random.default_rng(SEED)
x_grid = np.linspace(GRID_MIN, GRID_MAX, N_GRID, dtype=np.float32)
true = mog_pdf(x_grid)
grid_t = torch.as_tensor(x_grid, device=device, dtype=torch.float32)
max_n = max(N_LIST)
results = {"meta": meta, "per_run": {}, "per_n": {}}
for rep in range(N_REPEATS):
train_all = mog_sample(rng, max_n)
for n in N_LIST:
data_np = train_all[:n]
h = silverman_bandwidth(data_np)
data_t = torch.as_tensor(data_np, device=device, dtype=torch.float32)
key = f"{n}"
def kde_fn():
return kde_eval(data_t, grid_t, h, device=device, precision_mode=PRECISION,
kde_backend=BACKEND, use_precomputed_norms=True, autotune=True)
def lin_fn():
return kde_eval_linearized(data_t, grid_t, h, device=device, precision_mode=PRECISION,
kde_backend=BACKEND, use_precomputed_norms=True, autotune=True)
def lin_nf_fn():
return kde_eval_linearized_nonfused(data_t, grid_t, h, device=device,
precision_mode=PRECISION, kde_backend=BACKEND,
use_precomputed_norms=True, autotune=True,
chunk_size=1024)
_time_repeated(kde_fn, device=device, warmup=1, repeats=1)
_time_repeated(lin_fn, device=device, warmup=1, repeats=1)
_time_repeated(lin_nf_fn, device=device, warmup=1, repeats=1)
d_kde = kde_fn().detach().cpu().numpy().astype(np.float64)
d_lin = lin_fn().detach().cpu().numpy().astype(np.float64)
d_nf = lin_nf_fn().detach().cpu().numpy().astype(np.float64)
shape_ok = (tuple(lin_fn().shape) == (N_GRID,)
and tuple(lin_nf_fn().shape) == (N_GRID,)
and lin_fn().dtype == torch.float32 == lin_nf_fn().dtype)
kde_mean, kde_std = _time_repeated(kde_fn, device=device, warmup=0, repeats=3)
lin_mean, lin_std = _time_repeated(lin_fn, device=device, warmup=0, repeats=3)
nf_mean, nf_std = _time_repeated(lin_nf_fn, device=device, warmup=0, repeats=3)
gold = laplace_definition_f64(x_grid, data_np, h)
scale = max(float(np.max(np.abs(gold))), 1e-30)
entry = {
"rep": rep, "n": n, "h": h, "shape_and_dtype_match": bool(shape_ok),
"fused_vs_nonfused_max_abs": float(np.max(np.abs(d_lin - d_nf))),
"fused_vs_nonfused_max_rel": float(np.max(np.abs(d_lin - d_nf)) / scale),
"fused_vs_nonfused_max_rel_pointwise": float(
np.max(np.abs(d_lin - d_nf) / np.maximum(np.abs(d_nf), 1e-6 * scale))),
"sign_disagreements": int(np.sum((d_lin < 0) != (d_nf < 0))),
"fused_vs_f64_definition_max_abs": float(np.max(np.abs(d_lin - gold))),
"fused_vs_f64_definition_max_rel": float(np.max(np.abs(d_lin - gold)) / scale),
"nonfused_vs_f64_definition_max_abs": float(np.max(np.abs(d_nf - gold))),
"metrics": {"kde": errors(x_grid, d_kde, true),
"laplace_fused": errors(x_grid, d_lin, true),
"laplace_nonfused": errors(x_grid, d_nf, true)},
"runtime_sec": {"kde": [kde_mean, kde_std],
"laplace_fused": [lin_mean, lin_std],
"laplace_nonfused": [nf_mean, nf_std]},
"speedup_nonfused_over_fused": (nf_mean / lin_mean) if lin_mean > 0 else None,
}
results["per_run"].setdefault(key, []).append(entry)
print(f"n={n:5d} h={h:.4f} fused={lin_mean*1e3:8.4f}ms nf={nf_mean*1e3:8.4f}ms "
f"ratio={nf_mean/lin_mean:6.2f}x maxdiff={entry['fused_vs_nonfused_max_abs']:.2e} "
f"vs_f64={entry['fused_vs_f64_definition_max_rel']:.2e}")
for key, runs in results["per_run"].items():
agg = {"n": runs[0]["n"], "h": [r["h"] for r in runs]}
for m in ("kde", "laplace_fused", "laplace_nonfused"):
for metric in ("ise", "iae", "neg_mass", "max_abs", "mass"):
v = np.array([r["metrics"][m][metric] for r in runs])
agg[f"{m}_{metric}_mean"] = float(v.mean())
agg[f"{m}_{metric}_std"] = float(v.std())
for stat in ("fused_vs_nonfused_max_abs", "fused_vs_nonfused_max_rel",
"fused_vs_f64_definition_max_abs", "fused_vs_f64_definition_max_rel"):
agg[stat] = float(max(r[stat] for r in runs))
for m in ("kde", "laplace_fused", "laplace_nonfused"):
agg[f"runtime_{m}_mean"] = float(np.mean([r["runtime_sec"][m][0] for r in runs]))
agg[f"runtime_{m}_std"] = float(np.mean([r["runtime_sec"][m][1] for r in runs]))
agg["speedup_nonfused_over_fused"] = agg["runtime_laplace_nonfused_mean"] / agg["runtime_laplace_fused_mean"]
agg["all_runs_shape_ok"] = bool(all(r["shape_and_dtype_match"] for r in runs))
results["per_n"][key] = agg
with open(OUT / "gpu_a10g.json", "w") as fh:
json.dump(results, fh, indent=2)
print("\n=== runtime table (authors' protocol) ===")
print(f"{'n':>6} {'h':>7} {'KDE ms':>9} {'fused ms':>10} {'nonfused ms':>12} {'nf/fused':>9}")
for key in map(str, N_LIST):
a = results["per_n"][key]
print(f"{a['n']:6d} {a['h'][0]:7.4f} {a['runtime_kde_mean']*1e3:9.4f} "
f"{a['runtime_laplace_fused_mean']*1e3:10.4f} "
f"{a['runtime_laplace_nonfused_mean']*1e3:12.4f} {a['speedup_nonfused_over_fused']:9.2f}")
print("\n=== signed error, GPU path (mean of 3 replicates) ===")
print(f"{'n':>6} {'method':>18} {'MISE':>12} {'MIAE':>12} {'neg_mass':>11}")
for key in map(str, N_LIST):
a = results["per_n"][key]
for m in ("kde", "laplace_fused", "laplace_nonfused"):
print(f"{a['n']:6d} {m:>18} {a[f'{m}_ise_mean']:12.6e} {a[f'{m}_iae_mean']:12.6e} "
f"{a[f'{m}_neg_mass_mean']:11.3e}")
print(f"\nwrote {OUT/'gpu_a10g.json'}")
if __name__ == "__main__":
main()