File size: 11,358 Bytes
3387ad0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()