import time
N_LAGS = 15
N_REPEATS = 3
df_gp = pd.read_csv("../../../../Data/00_shared/data_geostatistics/gp_data_5000.csv")
gp_coords = df_gp[["x", "y"]].to_numpy(dtype=float)
gp_vals = df_gp["SOC"].to_numpy(dtype=float)
SIZES = [len(coords), 500, 1000, 2000, 4000, len(gp_coords)]
def _time_variogram(xy, values, use_gpu, repeats=N_REPEATS, warmup=True):
"""Median wall time of Variogram.fit() over *repeats* runs."""
if warmup:
k = min(80, len(xy))
Variogram(xy[:k], values[:k], model="spherical",
n_lags=10, use_gpu=use_gpu).fit()
if use_gpu:
import cupy as cp
cp.cuda.Device(0).synchronize()
times = []
last = None
for _ in range(repeats):
t0 = time.perf_counter()
last = Variogram(xy, values, model="spherical",
n_lags=N_LAGS, use_gpu=use_gpu).fit()
if use_gpu:
import cupy as cp
cp.cuda.Device(0).synchronize()
times.append(time.perf_counter() - t0)
return float(np.median(times)), last
print(f"GPU usable : {USE_GPU}")
print(f"Repeats : {N_REPEATS} (median wall time of Variogram.fit())")
print(f"GP SOC : {len(gp_vals)} samples from data/gp_data_5000.csv")
print()
rows = []
for n in SIZES:
if n == len(coords):
xy, vals, label = coords, z_model, "Jura (Cd)"
else:
xy, vals = gp_coords[:n], gp_vals[:n]
label = "GP (SOC)"
cpu_t, v_cpu = _time_variogram(xy, vals, use_gpu=False)
row = {
"n": n, "dataset": label,
"CPU (s)": cpu_t, "GPU (s)": np.nan,
"speedup": np.nan, "match": "n/a",
}
if USE_GPU:
gpu_t, v_gpu = _time_variogram(xy, vals, use_gpu=True)
row["GPU (s)"] = gpu_t
row["speedup"] = cpu_t / gpu_t
row["match"] = bool(np.allclose(
v_cpu.experimental, v_gpu.experimental, rtol=1e-5, equal_nan=True
))
import cupy as cp
cp.get_default_memory_pool().free_all_blocks()
rows.append(row)
df_bench = pd.DataFrame(rows)
df_show = df_bench.copy()
df_show["CPU (ms)"] = (df_show["CPU (s)"] * 1000).round(1)
df_show["GPU (ms)"] = (df_show["GPU (s)"] * 1000).round(1)
df_show["speedup"] = df_show["speedup"].map(
lambda x: "n/a" if pd.isna(x) else f"{x:.2f}×"
)
print(df_show[["dataset", "n", "CPU (ms)", "GPU (ms)", "speedup", "match"]].to_string(index=False))
fig, axes = plt.subplots(1, 2, figsize=(12, 4.2))
n_vals = df_bench["n"].to_numpy()
cpu_ms = df_bench["CPU (s)"].to_numpy() * 1000
gpu_ms = df_bench["GPU (s)"].to_numpy() * 1000
x = np.arange(len(n_vals))
w = 0.36
axes[0].bar(x - w / 2, cpu_ms, w, label="CPU (NumPy)", color="steelblue")
if USE_GPU and np.isfinite(gpu_ms).all():
axes[0].bar(x + w / 2, gpu_ms, w, label="GPU (CuPy)", color="darkorange")
axes[0].set_xticks(x)
axes[0].set_xticklabels(
[f"{int(n)}\n({lab})" for n, lab in zip(n_vals, df_bench["dataset"])],
fontsize=8,
)
axes[0].set_ylabel("Median time (ms)")
axes[0].set_title("Variogram.fit(): CPU vs GPU")
axes[0].legend()
axes[0].set_yscale("log")
if USE_GPU:
axes[1].plot(n_vals, df_bench["speedup"], "o-", color="darkgreen", lw=2)
axes[1].axhline(1.0, color="grey", ls="--", lw=1)
axes[1].set_xlabel("Number of observations $n$")
axes[1].set_ylabel("Speedup (CPU time / GPU time)")
axes[1].set_title("GPU speedup vs sample size")
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()