import importlib
NSIM_LIST = [1, 2, 4, 8, 16, 32]
N_PRED_NSIM = 100
grid_xy_nsim = grid_xy[:N_PRED_NSIM]
print(f"n_pred : {N_PRED_NSIM} (fixed, first {N_PRED_NSIM} nodes of meuse_grid.csv)")
print(f"neighbors : k={K}; radius={RADIUS:.0f}; thresholds={len(thresholds)}")
print(f"nsim : {NSIM_LIST}")
print()
def _time_sis_nsim(nsim, use_gpu):
"""Single-call wall time of sisim at a given nsim."""
kw = dict(
prediction_grid=grid_xy_nsim, df=df, xx="x", yy="y", zz="zinc",
thresholds=thresholds, global_cdf=global_cdf, vario=vario,
num_points=K, radius=RADIUS, kriging_type="ordinary",
nsim=nsim, seed=SEED, quiet=True, use_gpu=use_gpu,
)
t0 = time.perf_counter()
out = sisim(**kw)
if use_gpu:
import cupy as cp
cp.cuda.Device(0).synchronize()
return time.perf_counter() - t0, out
rows_nsim = []
for nsim in NSIM_LIST:
cpu_t, out_cpu = _time_sis_nsim(nsim, use_gpu=False)
row = {"nsim": nsim, "CPU (s)": cpu_t, "GPU (s)": np.nan, "speedup": np.nan, "match": "n/a"}
if USE_GPU:
gpu_t, out_gpu = _time_sis_nsim(nsim, use_gpu=True)
row["GPU (s)"] = gpu_t
row["speedup"] = cpu_t / gpu_t
row["match"] = bool(np.allclose(out_cpu, out_gpu, rtol=1e-2, atol=1e-2))
import cupy as cp
cp.get_default_memory_pool().free_all_blocks()
rows_nsim.append(row)
df_bench_nsim = pd.DataFrame(rows_nsim)
df_show_nsim = df_bench_nsim.copy()
df_show_nsim["CPU (s)"] = df_show_nsim["CPU (s)"].round(3)
df_show_nsim["GPU (s)"] = df_show_nsim["GPU (s)"].round(3)
df_show_nsim["speedup"] = df_show_nsim["speedup"].map(lambda x: "n/a" if pd.isna(x) else f"{x:.2f}×")
print(df_show_nsim.to_string(index=False))
print()
# Where does the time actually go? Time _octant_search itself (CPU, pandas,
# per-realization -- unaffected by GPU batching, and shared with sgsim) against
# total wall time at the largest nsim, on the GPU path.
if USE_GPU:
_sgsim_mod = importlib.import_module("pygstat.sgsim")
_orig_octant_search = _sgsim_mod._octant_search
_octant_elapsed = {"total": 0.0}
def _timed_octant_search(*args, **kwargs):
_t0 = time.perf_counter()
_result = _orig_octant_search(*args, **kwargs)
_octant_elapsed["total"] += time.perf_counter() - _t0
return _result
_sgsim_mod._octant_search = _timed_octant_search
try:
_t0 = time.perf_counter()
sisim(prediction_grid=grid_xy_nsim, df=df, xx="x", yy="y", zz="zinc",
thresholds=thresholds, global_cdf=global_cdf, vario=vario,
num_points=K, radius=RADIUS, kriging_type="ordinary",
nsim=NSIM_LIST[-1], seed=SEED, quiet=True, use_gpu=True)
import cupy as cp
cp.cuda.Device(0).synchronize()
_total = time.perf_counter() - _t0
finally:
_sgsim_mod._octant_search = _orig_octant_search
print(f"At nsim={NSIM_LIST[-1]}: octant search (CPU, pandas, per-realization) took "
f"{_octant_elapsed['total']:.2f}s of {_total:.2f}s total "
f"({100 * _octant_elapsed['total'] / _total:.0f}%) -- batching the GPU solve "
f"doesn't touch this, so it caps how much §12.2's batching can win.")
fig, axes = plt.subplots(1, 2, figsize=(12, 4.2))
n_vals = df_bench_nsim["nsim"].to_numpy()
cpu_s = df_bench_nsim["CPU (s)"].to_numpy()
gpu_s = df_bench_nsim["GPU (s)"].to_numpy()
x = np.arange(len(n_vals))
w = 0.36
axes[0].bar(x - w / 2, cpu_s, w, label="CPU (NumPy)", color="steelblue")
if USE_GPU and np.isfinite(gpu_s).all():
axes[0].bar(x + w / 2, gpu_s, w, label="GPU (CuPy, batched)", color="darkorange")
axes[0].set_xticks(x)
axes[0].set_xticklabels([str(int(n)) for n in n_vals], fontsize=9)
axes[0].set_xlabel("nsim")
axes[0].set_ylabel("Wall time (s)")
axes[0].set_title(f"sisim (n_pred={N_PRED_NSIM}, k={K}, {len(thresholds)} thresholds): CPU vs batched GPU")
axes[0].legend()
if USE_GPU:
axes[1].plot(n_vals, df_bench_nsim["speedup"], "o-", color="darkgreen", lw=2)
axes[1].axhline(1.0, color="grey", ls="--", lw=1)
axes[1].set_xlabel("nsim")
axes[1].set_ylabel("Speedup (CPU time / GPU time)")
axes[1].set_title("GPU speedup vs nsim (realization batching)")
axes[1].grid(True, alpha=0.3)
else:
axes[1].text(0.5, 0.5, "GPU not usable in this environment\nCPU-only timings shown",
ha="center", va="center", transform=axes[1].transAxes)
axes[1].set_axis_off()
plt.tight_layout()
plt.show()
record(
"GPU realization-batching speedup grows with nsim",
"PASS" if (not USE_GPU or df_bench_nsim["speedup"].iloc[-1] >= df_bench_nsim["speedup"].iloc[0]) else "FAIL",
(f"speedup at nsim={NSIM_LIST[0]}: {df_bench_nsim['speedup'].iloc[0]:.2f}x, "
f"at nsim={NSIM_LIST[-1]}: {df_bench_nsim['speedup'].iloc[-1]:.2f}x") if USE_GPU else "GPU not usable",
)