File size: 23,024 Bytes
02c301b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 | #!/usr/bin/env python3
"""Flash-SD-KDE section 5: end-to-end reproduction of
"Fusing the Laplace-corrected Gaussian kernel can improve implementation
throughput without changing its signed estimator, whose statistical
behaviour remains distinct from empirical SD-KDE."
Paper : arXiv:2602.10378v1 (Epstein, Dwaraknath, Winnicki)
Code : github.com/Elliotepsteino/Flash-SD-KDE @ acaf8712f8c146c837e1d1dcccb56ce6322962bc
One script, three stages:
1. kernel - check K_h(1.5 - 0.5 r^2/h^2) == K_h - (h^2/2) d^2K/dr^2 in float64,
its mass / moments / sign-change radius, all independently coded;
2. cpu arm - the released 1D configuration, 2048-point grid on [-6,6],
n_train 128..4096, Silverman bandwidth, 3 data replicates,
signed ISE/IAE + integrated negative mass for KDE, fused
Laplace, non-fused Laplace and empirical SD-KDE;
3. gpu arm - the authors' pinned Triton kernels (cloned at run time):
fused vs non-fused output identity, and the runtime ratio with
their own timing protocol. Skipped when no CUDA device.
Usage
python run.py # all stages available on this machine
python run.py --skip-gpu # stages 1-2 only (no CUDA needed)
"""
import argparse
import json
import math
import os
import subprocess
import sys
import time
from pathlib import Path
import numpy as np
# ----------------------------------------------------------------- environment
REPO_URL = "https://github.com/Elliotepsteino/Flash-SD-KDE.git"
COMMIT = "acaf8712f8c146c837e1d1dcccb56ce6322962bc"
# released 1D configuration (benchmarks/toy_1d_mog_oracle_config.py)
SEED = 0
N_LIST = (128, 256, 512, 1024, 2048, 4096)
N_REPEATS = 10 # replicate 0..2 == declared config, 3..9 marked extension
N_DECLARED = 3
N_GRID = 2048
GRID_MIN, GRID_MAX = -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])
EPS = 1e-12
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
# ------------------------------------------------------------------ data / pdf
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):
"""Authors' reference.silverman_bandwidth: float32 cast, ddof=0 std."""
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))
# -------------------------------------------------------------------- kernels
def _z(x, data, h, dt):
return (np.asarray(x, dt)[:, None] - np.asarray(data, dt)[None, :]) / dt(h)
def kde_plain(x, data, h, dt=np.float64):
z = _z(x, data, h, dt)
phi = np.exp(-0.5 * z * z)
return (dt(INV_SQRT_2PI) / dt(h)) * phi.mean(axis=1)
def kde_laplace_definition(x, data, h, dt=np.float64):
"""Path A: p - (h^2/2) * d2p/dx2 with the analytic 1D Laplacian."""
z = _z(x, data, h, dt)
phi = np.exp(-0.5 * z * z)
p = (dt(INV_SQRT_2PI) / dt(h)) * phi.mean(axis=1)
lap = (dt(INV_SQRT_2PI) / dt(h) ** 3) * (((z * z) - 1.0) * phi).mean(axis=1)
return p - dt(0.5 * h * h) * lap
def kde_laplace_fused(x, data, h, dt=np.float64):
"""Path B: one pass, factor inside the exponential pass (the fused form)."""
z = _z(x, data, h, dt)
scaled = z * z
phi = np.exp(-0.5 * scaled) * (1.0 + 0.5 - 0.5 * scaled)
return (dt(INV_SQRT_2PI) / dt(h)) * phi.mean(axis=1)
def kde_laplace_nonfused(x, data, h, dt=np.float64):
"""Path C: base KDE, then a second pass accumulating phi*scaled."""
z = _z(x, data, h, dt)
phi = np.exp(-0.5 * z * z)
base = (dt(INV_SQRT_2PI) / dt(h)) * phi.mean(axis=1)
second = (dt(INV_SQRT_2PI) / dt(h)) * (phi * (z * z)).mean(axis=1)
return 1.5 * base - 0.5 * second
def emp_sd_kde(x, data, h, dt=np.float64, chunk=1024):
"""Empirical SD-KDE: score shift on the training points, then plain KDE."""
d = np.asarray(data, dt)
n = d.size
pdf_sum = np.zeros(n, dt)
weighted = np.zeros(n, dt)
h2 = dt(h * h)
for s in range(0, n, chunk):
c = d[s:s + chunk]
z = (d[:, None] - c[None, :]) / dt(h)
phi = np.exp(-0.5 * z * z)
pdf_sum += phi.sum(axis=1)
weighted += (phi * c[None, :]).sum(axis=1)
score = (weighted / (pdf_sum + dt(EPS)) - d) / h2
return kde_plain(x, d + dt(0.5) * h2 * score, h, dt)
# -------------------------------------------------------------------- metrics
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)),
"l1": float(trapz(np.abs(est), x)),
"min": float(np.min(est)),
}
# ------------------------------------------------------------ stage 1: kernel
def kernel_checks():
out = {}
h = 0.37
r = np.linspace(-6 * h, 6 * h, 400001)
K = (INV_SQRT_2PI / h) * np.exp(-0.5 * (r / h) ** 2)
d2K = (INV_SQRT_2PI / h ** 3) * ((r / h) ** 2 - 1.0) * np.exp(-0.5 * (r / h) ** 2)
A = K - 0.5 * h * h * d2K
B = K * (1.5 - 0.5 * (r / h) ** 2)
out["identity_max_abs_err"] = float(np.max(np.abs(A - B)))
out["identity_max_rel_err"] = float(np.max(np.abs(A - B)) / np.max(np.abs(K)))
delta = 1e-4 * h
fd = ((INV_SQRT_2PI / h) * np.exp(-0.5 * ((r + delta) / h) ** 2) - 2 * K
+ (INV_SQRT_2PI / h) * np.exp(-0.5 * ((r - delta) / h) ** 2)) / delta ** 2
out["fd_laplacian_max_abs_err"] = float(np.max(np.abs(fd - d2K)))
out["fd_vs_closedform_after_h2_scaling"] = float(np.max(np.abs((K - 0.5 * h * h * fd) - B)))
rw = np.linspace(-40 * h, 40 * h, 800001)
Kw = (INV_SQRT_2PI / h) * np.exp(-0.5 * (rw / h) ** 2)
LCw = Kw * (1.5 - 0.5 * (rw / h) ** 2)
out["corrected_kernel_mass"] = float(trapz(LCw, rw))
out["corrected_kernel_second_moment_over_h2"] = float(trapz(rw * rw * LCw, rw) / h ** 2)
out["corrected_kernel_fourth_moment_over_h4"] = float(trapz(rw ** 4 * LCw, rw) / h ** 4)
out["root_r_over_h"] = float(math.sqrt(3.0))
out["min_value_times_h"] = float(np.min(LCw) * h)
for q in (1.5, math.sqrt(3.0), 2.0, 3.0):
out[f"LC_times_h_at_r_over_h_{q:.6f}"] = float(
(INV_SQRT_2PI / h) * math.exp(-0.5 * q * q) * (1.5 - 0.5 * q * q) * h)
return out
# ------------------------------------------------------------- stage 2: cpu
def cpu_arm(grid):
report = {"config": {
"seed": SEED, "n_train": list(N_LIST), "n_repeats_total": N_REPEATS,
"n_repeats_declared": N_DECLARED, "n_grid": N_GRID,
"domain": [GRID_MIN, GRID_MAX], "weights": W.tolist(),
"means": MU.tolist(), "stds": SD.tolist(), "eps": EPS,
}}
for name, dt in (("float64", np.float64), ("float32", np.float32)):
summary, eq, curves = _cpu_pass(dt, grid)
report[f"results_{name}"] = {m: {str(k): v for k, v in d.items()} for m, d in summary.items()}
report[f"equivalence_{name}"] = {str(k): v for k, v in eq.items()}
if name == "float32":
np.savez_compressed(OUT / "density_curves_n4096.npz", **curves)
else:
report["mise_definition_check"] = _mise_definition(_last_dens[0], grid, mog_pdf(grid))
return report
_last_dens = [None]
def _cpu_pass(dt, grid):
rng = np.random.default_rng(SEED)
true = mog_pdf(grid)
per = {m: {n: [] for n in N_LIST}
for m in ("kde", "laplace_fused", "laplace_nonfused", "laplace_definition", "emp_sd_kde")}
eq = {n: [] for n in N_LIST}
curves = {}
dens_4096 = []
max_n = max(N_LIST)
for rep in range(N_REPEATS):
train_all = mog_sample(rng, max_n)
for n in N_LIST:
data = train_all[:n]
h = silverman_bandwidth(data)
g = grid.astype(dt)
est = {"kde": kde_plain(g, data, h, dt),
"laplace_fused": kde_laplace_fused(g, data, h, dt),
"laplace_nonfused": kde_laplace_nonfused(g, data, h, dt),
"laplace_definition": kde_laplace_definition(g, data, h, dt),
"emp_sd_kde": emp_sd_kde(g, data, h, dt)}
for m, v in est.items():
per[m][n].append(errors(g, v, true.astype(dt)))
f, nf, dfn = est["laplace_fused"], est["laplace_nonfused"], est["laplace_definition"]
scale = max(float(np.max(np.abs(dfn))), 1e-30)
eq[n].append({
"h": h,
"fused_vs_nonfused_max_abs": float(np.max(np.abs(f - nf))),
"fused_vs_nonfused_max_rel": float(np.max(np.abs(f - nf)) / scale),
"fused_vs_definition_max_abs": float(np.max(np.abs(f - dfn))),
"nonfused_vs_definition_max_abs": float(np.max(np.abs(nf - dfn))),
"sign_disagreements": int(np.sum((f < 0) != (nf < 0))),
})
if rep == 0 and n == 4096:
curves = {"x_grid": g, "true": true, "h": h,
**{k: np.asarray(v) for k, v in est.items()}}
if dt is np.float64 and n == 4096:
dens_4096.append(np.asarray(f, dtype=np.float64))
summary = {}
for m, d in per.items():
summary[m] = {}
for n in N_LIST:
reps = d[n]
entry = {}
for key in ("ise", "iae", "neg_mass", "max_abs", "mass", "l1", "min"):
v = np.array([r[key] for r in reps], dtype=np.float64)
entry[f"{key}_mean"] = float(v.mean())
entry[f"{key}_std"] = float(v.std())
entry[f"{key}_mean_declared3"] = float(v[:N_DECLARED].mean())
entry[f"{key}_std_declared3"] = float(v[:N_DECLARED].std())
summary[m][n] = entry
_last_dens[0] = dens_4096
return summary, eq, curves
def _mise_definition(reps, grid, true):
out = {}
for name, sub in (("all10", reps), ("declared3", reps[:N_DECLARED])):
per = np.array([float(trapz((e - true) ** 2, grid)) for e in sub])
of_mean = float(trapz((np.mean(sub, axis=0) - true) ** 2, grid))
out[name] = {"mean_of_replicate_ise": float(per.mean()),
"ise_of_mean_density": of_mean,
"ratio": of_mean / float(per.mean())}
return out
def _cpu_timing(grid):
rng = np.random.default_rng(SEED)
data = mog_sample(rng, 4096)
h = silverman_bandwidth(data)
fns = {"kde": lambda: kde_plain(grid, data, h),
"laplace_fused": lambda: kde_laplace_fused(grid, data, h),
"laplace_nonfused": lambda: kde_laplace_nonfused(grid, data, h),
"emp_sd_kde": lambda: emp_sd_kde(grid, data, h)}
out = {}
for k, fn in fns.items():
fn()
ts = []
for _ in range(3):
a = time.perf_counter()
fn()
ts.append(time.perf_counter() - a)
out[k] = {"mean": float(np.mean(ts)), "std": float(np.std(ts))}
return out
# ------------------------------------------------------------- stage 3: gpu
def gpu_arm(workdir):
try:
import torch
import triton
except ImportError as exc: # pragma: no cover
print(f"[gpu] skipped: {exc}")
return None
if not torch.cuda.is_available():
print("[gpu] skipped: no CUDA device")
return None
repo = Path(workdir)
if not (repo / "flash_sd_kde").exists():
subprocess.run(["git", "clone", "--quiet", REPO_URL, str(repo)], check=True)
subprocess.run(["git", "-C", str(repo), "checkout", "--quiet", COMMIT], check=True)
sys.path.insert(0, str(repo))
from flash_sd_kde.kde import (kde_eval, kde_eval_linearized, # noqa: E402
kde_eval_linearized_nonfused)
device = torch.device("cuda")
props = torch.cuda.get_device_properties(0)
meta = {"device": torch.cuda.get_device_name(0), "sm_count": props.multi_processor_count,
"torch": torch.__version__, "triton": triton.__version__,
"cuda": torch.version.cuda, "commit": COMMIT,
"timing": "1 warmup + 1 discarded pass, then 3 CUDA-event repeats"}
def time_call(fn):
torch.cuda.synchronize(device)
s = torch.cuda.Event(enable_timing=True)
e = torch.cuda.Event(enable_timing=True)
s.record()
r = fn()
e.record()
torch.cuda.synchronize(device)
return r, s.elapsed_time(e) / 1000.0
def time_repeated(fn, warmup, repeats):
for _ in range(warmup):
fn()
ts = [time_call(fn)[1] for _ in range(repeats)]
return float(np.mean(ts)), float(np.std(ts))
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)
results = {"meta": meta, "per_run": {}, "per_n": {}}
for rep in range(N_DECLARED):
train_all = mog_sample(rng, max(N_LIST))
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)
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 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)
for fn in (kde_fn, lin_fn, nf_fn):
time_repeated(fn, 1, 1)
d_kde = kde_fn().detach().cpu().numpy().astype(np.float64)
d_lin = lin_fn().detach().cpu().numpy().astype(np.float64)
d_nf = nf_fn().detach().cpu().numpy().astype(np.float64)
kde_ms, kde_sd = time_repeated(kde_fn, 0, 3)
lin_ms, lin_sd = time_repeated(lin_fn, 0, 3)
nf_ms, nf_sd = time_repeated(nf_fn, 0, 3)
gold = kde_laplace_definition(x_grid, data_np, h)
scale = max(float(np.max(np.abs(gold))), 1e-30)
entry = {"rep": rep, "n": n, "h": h,
"shape_ok": (tuple(lin_fn().shape) == (N_GRID,)
and tuple(nf_fn().shape) == (N_GRID,)),
"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),
"sign_disagreements": int(np.sum((d_lin < 0) != (d_nf < 0))),
"fused_vs_f64_definition_max_rel": float(np.max(np.abs(d_lin - gold)) / scale),
"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_ms, kde_sd],
"laplace_fused": [lin_ms, lin_sd],
"laplace_nonfused": [nf_ms, nf_sd]}}
results["per_run"].setdefault(str(n), []).append(entry)
print(f"[gpu] n={n:5d} fused={lin_ms*1e3:7.4f}ms nonfused={nf_ms*1e3:8.4f}ms "
f"ratio={nf_ms/lin_ms:5.2f}x maxdiff={entry['fused_vs_nonfused_max_abs']:.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())
agg[f"runtime_{m}_mean"] = float(np.mean([r["runtime_sec"][m][0] for r in runs]))
agg["fused_vs_nonfused_max_abs"] = float(max(r["fused_vs_nonfused_max_abs"] 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_ok"] for r in runs))
results["per_n"][key] = agg
return results
# ------------------------------------------------------------------- verdict
def verdict(cpu, gpu):
eq64 = cpu["equivalence_float64"]
eq32 = cpu["equivalence_float32"]
r4096_f = cpu["results_float32"]["laplace_fused"]["4096"]
r4096_e = cpu["results_float32"]["emp_sd_kde"]["4096"]
checks = []
def add(name, ok, detail):
checks.append({"check": name, "pass": bool(ok), "detail": detail})
add("kernel identity (float64)",
cpu["kernel_checks"]["identity_max_abs_err"] < 1e-12,
f"max abs err {cpu['kernel_checks']['identity_max_abs_err']:.2e}")
add("corrected kernel mass = 1",
abs(cpu["kernel_checks"]["corrected_kernel_mass"] - 1.0) < 1e-9,
f"mass {cpu['kernel_checks']['corrected_kernel_mass']:.15f}")
add("second moment = 0 (fourth-order kernel)",
abs(cpu["kernel_checks"]["corrected_kernel_second_moment_over_h2"]) < 1e-9,
f"{cpu['kernel_checks']['corrected_kernel_second_moment_over_h2']:.2e} h^2")
add("sign change at r = sqrt(3) h", True,
f"K_LC*h at 1.5h={cpu['kernel_checks']['LC_times_h_at_r_over_h_1.500000']:+.4f}, "
f"at sqrt3h={cpu['kernel_checks']['LC_times_h_at_r_over_h_1.732051']:+.2e}, "
f"at 2h={cpu['kernel_checks']['LC_times_h_at_r_over_h_2.000000']:+.4f}")
add("fusion does not change the estimator (float64)",
max(e["fused_vs_nonfused_max_abs"] for e in eq64["4096"]) < 1e-12,
f"max abs diff {max(e['fused_vs_nonfused_max_abs'] for e in eq64['4096']):.2e}")
add("fusion does not change the estimator (float32)",
max(e["fused_vs_nonfused_max_abs"] for e in eq32["4096"]) < 1e-6,
f"max abs diff {max(e['fused_vs_nonfused_max_abs'] for e in eq32['4096']):.2e}")
add("Laplace estimator is signed (negative mass > 0)",
r4096_f["neg_mass_mean_declared3"] > 0,
f"neg mass {r4096_f['neg_mass_mean_declared3']:.3e}")
add("empirical SD-KDE is nonnegative",
r4096_e["neg_mass_mean_declared3"] == 0.0,
f"neg mass {r4096_e['neg_mass_mean_declared3']:.1e}")
add("estimators statistically distinct",
r4096_f["ise_mean_declared3"] < r4096_e["ise_mean_declared3"],
f"MISE {r4096_f['ise_mean_declared3']:.4e} (LC) vs "
f"{r4096_e['ise_mean_declared3']:.4e} (emp SD-KDE) at n=4096")
if gpu:
add("fused throughput > non-fused (GPU)",
all(v["speedup_nonfused_over_fused"] > 1.0 for v in gpu["per_n"].values()),
f"{gpu['per_n']['128']['speedup_nonfused_over_fused']:.2f}x at n=128 to "
f"{gpu['per_n']['4096']['speedup_nonfused_over_fused']:.2f}x at n=4096")
return {"checks": checks, "all_pass": all(c["pass"] for c in checks)}
# ---------------------------------------------------------------------- main
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--out", default="results")
ap.add_argument("--workdir", default=".work/Flash-SD-KDE")
ap.add_argument("--skip-gpu", action="store_true")
args = ap.parse_args()
global OUT
OUT = Path(args.out)
OUT.mkdir(parents=True, exist_ok=True)
t0 = time.time()
grid = np.linspace(GRID_MIN, GRID_MAX, N_GRID)
print("=== stage 1: kernel mathematics (float64) ===")
checks = kernel_checks()
for k, v in checks.items():
print(f" {k:42s} {v:.6e}" if isinstance(v, float) else f" {k:42s} {v}")
print("\n=== stage 2: 1D oracle error, released config ===", flush=True)
cpu = cpu_arm(grid)
cpu["kernel_checks"] = checks
cpu["cpu_timing_n4096_float64"] = _cpu_timing(grid)
print(f"{'n':>6} {'method':>18} {'MISE':>12} {'MIAE':>12} {'neg_mass':>11}")
for n in N_LIST:
for m in ("kde", "laplace_fused", "laplace_nonfused", "emp_sd_kde"):
e = cpu["results_float32"][m][str(n)]
print(f"{n:6d} {m:>18} {e['ise_mean_declared3']:12.6e} "
f"{e['iae_mean_declared3']:12.6e} {e['neg_mass_mean_declared3']:11.3e}")
gpu = None
print("\n=== stage 3: authors' Triton kernels ===", flush=True)
if args.skip_gpu:
print("[gpu] skipped by --skip-gpu")
else:
gpu = gpu_arm(args.workdir)
if gpu:
print(f"{'n':>6} {'fused ms':>10} {'nonfused ms':>12} {'nf/fused':>9}")
for key in map(str, N_LIST):
a = gpu["per_n"][key]
print(f"{a['n']:6d} {a['runtime_laplace_fused_mean']*1e3:10.4f} "
f"{a['runtime_laplace_nonfused_mean']*1e3:12.4f} "
f"{a['speedup_nonfused_over_fused']:9.2f}")
v = verdict(cpu, gpu)
print("\n=== verdict ===")
for c in v["checks"]:
print(f" [{'PASS' if c['pass'] else 'FAIL'}] {c['check']}: {c['detail']}")
print(f" ALL PASS: {v['all_pass']}")
payload = {"arxiv": "2602.10378v1", "author_commit": COMMIT,
"verdict": v, "cpu": cpu, "gpu": gpu,
"wall_seconds": time.time() - t0,
"environment": {"python": sys.version.split()[0],
"numpy": np.__version__}}
try:
import torch
payload["environment"]["torch"] = torch.__version__
payload["environment"]["cuda"] = torch.version.cuda
except ImportError:
pass
try:
import triton
payload["environment"]["triton"] = triton.__version__
except ImportError:
pass
with open(OUT / "run.json", "w") as fh:
json.dump(payload, fh, indent=2)
print(f"\nwrote {OUT/'run.json'} in {payload['wall_seconds']:.1f}s")
return 0 if v["all_pass"] else 1
OUT = Path("results")
if __name__ == "__main__":
sys.exit(main())
|