High-performance mixed-precision linear solvers using CUDA
View the Project on GitHub OleBo/mixed-precision-iterative-refinement-gpu
Establish a reliable numerical ground truth for evaluating the mixed-precision GPU solver.
This baseline:
These metrics serve as the gold standard for all subsequent comparisons.
We solve:
\[A x = b\]where:
This construction ensures:
Properties:
Properties:
Interpretation:
Interpretation:
A solver may have:
The following script defines the CPU baseline experiment:
#!/usr/bin/env python3
import argparse
import numpy as np
from numpy.linalg import norm, solve
def make_hilbert(n):
return np.array([[1.0 / (i + j + 1) for j in range(n)] for i in range(n)], dtype=np.float64)
def make_random(n, scale=1.0, seed=0):
rng = np.random.default_rng(seed)
A = rng.standard_normal((n, n), dtype=np.float64)
return A * scale
def compute_metrics(A, x, b, x_true):
residual = norm(A.dot(x) - b)
error = norm(x - x_true)
return residual, error
def run_baseline(n, matrix_type="random"):
if matrix_type == "hilbert":
A = make_hilbert(n)
else:
A = make_random(n)
x_true = np.ones(n, dtype=np.float64)
b = A.dot(x_true)
# FP64 ground truth
x64 = solve(A, b)
residual64, error64 = compute_metrics(A, x64, b, x_true)
print(f"Baseline FP64 | n={n} | residual={residual64:.3e} | error={error64:.3e}")
return {
"n": n,
"matrix_type": matrix_type,
"residual64": residual64,
"error64": error64,
}
def main():
parser = argparse.ArgumentParser(description="Run CPU baseline experiments for mixed precision refinement.")
parser.add_argument("--size", type=int, default=128, help="Matrix size")
parser.add_argument("--matrix", choices=["random", "hilbert"], default="random", help="Matrix family")
args = parser.parse_args()
run_baseline(args.size, args.matrix)
if __name__ == "__main__":
main()
Interpretation:
Interpretation:
Example:
python baseline.py --size 128 --matrix random
python baseline.py --size 128 --matrix hilbert
Recommended sizes:
\[n \in \{64, 128, 256, 512, 1024\}\]Store results in a table:
| n | matrix | residual (FP64) | error (FP64) |
|---|---|---|---|
| 128 | random | … | … |
| 128 | hilbert | … | … |
This baseline is used to:
The CPU FP64 solution is not just a reference — it defines what “correct” means numerically.
All GPU results should be evaluated relative to this baseline.
Possible improvements:
Add condition number estimation: \(\kappa(A) = \|A\| \|A^{-1}\|\)
This experiment establishes:
Random matrices introduce stochastic variability:
Therefore, a single run is not sufficient to draw conclusions.
For each configuration (n, matrix type):
Typical choice: K = 20 to 100
Compute:
Mean: r_bar = (1/K) sum r_i e_bar = (1/K) sum e_i
Standard deviation: sigma_r = sqrt( (1/(K-1)) sum (r_i - r_bar)^2 )
Assuming approximate normality:
r_bar ± t * sigma_r / sqrt(K)
For 95% confidence: t ≈ 2
Use paired experiments:
Analyze: Delta e_i = e_i(method1) - e_i(method2)
Apply:
def run_multiple(n, K=50):
results = []
for seed in range(K):
A = make_random(n, seed=seed)
x_true = np.ones(n)
b = A.dot(x_true)
x = solve(A, b)
r, e = compute_metrics(A, x, b, x_true)
results.append((r, e))
results = np.array(results)
mean = results.mean(axis=0)
std = results.std(axis=0, ddof=1)
return mean, std
Without statistical analysis, performance claims on random matrices are unreliable.
This benchmark framework now provides:
Status: Baseline + Statistical Validation — COMPLETE
This section upgrades the baseline into a reproducible benchmarking pipeline with:
experiments/
baseline.py
run_experiments.py
plot_results.py
results/
baseline_results.csv
summary_results.csv
plots/
Each run produces one row:
| n | matrix | seed | residual | error | |—|——–|——|———-|——-|
# run_experiments.py
import csv
import numpy as np
from numpy.linalg import solve, norm
from baseline import make_random, make_hilbert, compute_metrics
def run_experiments(sizes, K=50, matrix_type="random", out_file="results/baseline_results.csv"):
rows = []
for n in sizes:
for seed in range(K):
if matrix_type == "hilbert":
A = make_hilbert(n)
else:
A = make_random(n, seed=seed)
x_true = np.ones(n)
b = A.dot(x_true)
x = solve(A, b)
r, e = compute_metrics(A, x, b, x_true)
rows.append([n, matrix_type, seed, r, e])
with open(out_file, "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["n", "matrix", "seed", "residual", "error"])
writer.writerows(rows)
print(f"Saved {len(rows)} rows to {out_file}")
if __name__ == "__main__":
sizes = [64, 128, 256, 512, 1024]
run_experiments(sizes, K=50, matrix_type="random")
# aggregate_results.py
import pandas as pd
def aggregate(in_file="results/baseline_results.csv", out_file="results/summary_results.csv"):
df = pd.read_csv(in_file)
grouped = df.groupby(["n", "matrix"]).agg(
residual_mean=("residual", "mean"),
residual_std=("residual", "std"),
error_mean=("error", "mean"),
error_std=("error", "std"),
).reset_index()
grouped.to_csv(out_file, index=False)
print(grouped)
if __name__ == "__main__":
aggregate()
# plot_results.py
import pandas as pd
import matplotlib.pyplot as plt
def plot(file="results/summary_results.csv"):
df = pd.read_csv(file)
for metric in ["residual", "error"]:
plt.figure()
for matrix in df["matrix"].unique():
sub = df[df["matrix"] == matrix]
x = sub["n"]
y = sub[f"{metric}_mean"]
err = sub[f"{metric}_std"]
plt.errorbar(x, y, yerr=err, label=matrix, marker='o')
plt.xscale("log")
plt.yscale("log")
plt.xlabel("Matrix size n")
plt.ylabel(metric)
plt.title(f"{metric} vs size")
plt.legend()
plt.grid(True)
plt.savefig(f"results/plots/{metric}.png")
plt.close()
if __name__ == "__main__":
plot()
# 1. Run experiments
python run_experiments.py
# 2. Aggregate statistics
python aggregate_results.py
# 3. Generate plots
python plot_results.py
You should obtain:
Key observations:
Add columns:
Then plot all curves together to show:
A benchmark is only credible if it is reproducible, statistical, and visual.
This pipeline satisfies all three.
This section extends the pipeline to include:
Assume you expose your CUDA code via a shared library:
nvcc -O3 -Xcompiler -fPIC -shared solver.cu refinement.cu -o libmpsolver.so -lcublas -lcusolver
# gpu_wrapper.py
import numpy as np
import ctypes
lib = ctypes.CDLL("./libmpsolver.so")
lib.gpuSolve.argtypes = [
ctypes.POINTER(ctypes.c_float),
ctypes.POINTER(ctypes.c_float),
ctypes.POINTER(ctypes.c_float),
ctypes.c_int,
]
lib.refineSolution.argtypes = [
ctypes.POINTER(ctypes.c_double),
ctypes.POINTER(ctypes.c_double),
ctypes.POINTER(ctypes.c_double),
ctypes.c_int,
ctypes.c_int,
]
def gpu_solve(A, b):
n = A.shape[0]
A32 = A.astype(np.float32).copy(order="C")
b32 = b.astype(np.float32).copy(order="C")
x32 = np.zeros_like(b32)
lib.gpuSolve(
A32.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
b32.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
x32.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
n,
)
return x32.astype(np.float64)
def gpu_refine(A, b, max_iter=10):
n = A.shape[0]
A64 = A.astype(np.float64).copy(order="C")
b64 = b.astype(np.float64).copy(order="C")
x64 = np.zeros_like(b64)
lib.refineSolution(
A64.ctypes.data_as(ctypes.POINTER(ctypes.c_double)),
b64.ctypes.data_as(ctypes.POINTER(ctypes.c_double)),
x64.ctypes.data_as(ctypes.POINTER(ctypes.c_double)),
n,
max_iter,
)
return x64
# run_full_experiments.py
import csv
import numpy as np
from numpy.linalg import solve
from baseline import make_random, compute_metrics
from gpu_wrapper import gpu_solve, gpu_refine
def run(sizes, K=30, out_file="results/full_results.csv"):
rows = []
for n in sizes:
for seed in range(K):
A = make_random(n, seed=seed)
x_true = np.ones(n)
b = A.dot(x_true)
# FP64 baseline
x64 = solve(A, b)
r64, e64 = compute_metrics(A, x64, b, x_true)
# FP32 GPU
x32 = gpu_solve(A, b)
r32, e32 = compute_metrics(A, x32, b, x_true)
# Mixed precision
xm = gpu_refine(A, b)
rm, em = compute_metrics(A, xm, b, x_true)
rows.append([n, seed, r64, e64, r32, e32, rm, em])
with open(out_file, "w", newline="") as f:
writer = csv.writer(f)
writer.writerow([
"n","seed",
"res64","err64",
"res32","err32",
"res_mixed","err_mixed"
])
writer.writerows(rows)
# aggregate_full.py
import pandas as pd
def aggregate(file="results/full_results.csv"):
df = pd.read_csv(file)
return df.groupby("n").agg({
"err64": ["mean","std"],
"err32": ["mean","std"],
"err_mixed": ["mean","std"],
})
# plot_full.py
import pandas as pd
import matplotlib.pyplot as plt
def plot(file="results/full_results.csv"):
df = pd.read_csv(file)
grouped = df.groupby("n").mean().reset_index()
plt.figure()
plt.plot(grouped["n"], grouped["err64"], marker='o', label="FP64")
plt.plot(grouped["n"], grouped["err32"], marker='o', label="FP32 GPU")
plt.plot(grouped["n"], grouped["err_mixed"], marker='o', label="Mixed Precision")
plt.xscale("log")
plt.yscale("log")
plt.xlabel("n")
plt.ylabel("Error")
plt.title("Solver Accuracy Comparison")
plt.legend()
plt.grid(True)
plt.savefig("results/plots/comparison.png")
plt.close()
You should observe:
This demonstrates:
Mixed precision recovers FP64 accuracy at near FP32 cost.
You now have a publication-grade benchmark:
Status: Full GPU-Integrated Benchmark — COMPLETE