Files

98 lines
5.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Потолки одного ядра (полоса памяти, пик вычислений) и график roofline.
BLAS должен быть ограничен одним потоком до импорта numpy (см. run_all.py)."""
import numpy as np
from numba import njit
from bench import bench
FLOP_PER_POINT = 7 # 3 сложения соседей, 4*c, вычитание, *r, +c
def measure_bandwidth(size=30_000_000):
"""Полоса на c = a + b: два чтения и запись, 3 * 8 байт на элемент. Возвращает (ГБ/с, разброс)."""
a = np.random.rand(size)
b = np.random.rand(size)
c = np.empty_like(a) # out=: замеряем трафик, а не выделение памяти на каждом вызове
c.fill(0.0) # empty_like выделяет страницы лениво: без этого первое касание (~3 ГБ/с)
# попадает в прогрев, а «разгон» ядра — в первый замер
t, tmin, tmax = bench(np.add, a, b, c, repeats=11)
traffic = 3 * 8 * size
return traffic / t / 1e9, (traffic / tmax / 1e9, traffic / tmin / 1e9), t
def measure_peak(n=1536):
"""Пик на A @ B, 2 n^3 операций. Возвращает (GFLOP/s, разброс)."""
A = np.random.rand(n, n)
B = np.random.rand(n, n)
t, tmin, tmax = bench(np.matmul, A, B, repeats=11)
flop = 2 * n**3
return flop / t / 1e9, (flop / tmax / 1e9, flop / tmin / 1e9), t
@njit
def _copy_kernel(u, v, steps):
n, m = u.shape
for _ in range(steps):
for i in range(1, n - 1):
for j in range(1, m - 1):
v[i, j] = u[i, j]
u, v = v, u
return u
def measure_copy(n, dtype=np.float64, k=12):
"""Практический потолок для схемы «одно чтение + одна запись на точку»: тот же обход,
что у ядра Numba, но без вычислений. Возвращает (время на k=1 шаг, ГБ/с)."""
u = np.random.rand(n, n).astype(dtype)
v = u.copy()
t = bench(_copy_kernel, u, v, k, repeats=11)[0] / k
return t, bandwidth_used(n, t, np.dtype(dtype).itemsize)
def gflops(n, t_step):
"""Производительность шага схемы: 7 (n-2)^2 / время, GFLOP/s."""
return FLOP_PER_POINT * (n - 2) ** 2 / t_step / 1e9
def bandwidth_used(n, t_step, itemsize=8):
"""Занятая полоса шага: одно чтение и одна запись на точку, ГБ/с."""
return 2 * itemsize * (n - 2) ** 2 / t_step / 1e9
# Оценка (не замер) пика NEON на P-ядре M1 без FMA: 4 векторных FP-конвейера x 2 числа float64
# в 128-битном регистре x 3.2 ГГц. P от A @ B выше, потому что Accelerate считает на сопроцессоре
# AMX, а код из Numba исполняется на обычных NEON-конвейерах.
NEON_F64_NO_FMA = 4 * 2 * 3.2
def plot(points, P, B, path="roofline.png"):
"""points: список (подпись, n, интенсивность FLOP/байт, GFLOP/s)."""
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
I_star = P / B
I = np.logspace(-3, 3, 400)
fig, ax = plt.subplots(figsize=(8, 5.5))
ax.loglog(I, np.minimum(I * B, P), color="black", lw=2, label="roofline min(I·B, P)")
ax.loglog(I, I * B, color="gray", lw=1, ls="--", label=f"память: I·B, B = {B:.1f} ГБ/с")
ax.axhline(P, color="gray", lw=1, ls=":", label=f"пик: P = {P:.1f} GFLOP/s")
ax.axvline(I_star, color="tab:red", lw=1, ls="-.", label=f"I* = {I_star:.2f} FLOP/байт")
ax.axhline(NEON_F64_NO_FMA, color="tab:blue", lw=1, ls=(0, (5, 2, 1, 2)),
label=f"NEON f64 без FMA (оценка): {NEON_F64_NO_FMA:.1f} GFLOP/s")
markers = {"Python": "x", "NumPy naive": "s", "NumPy out_view": "v", "NumPy out": "D",
"NumPy flat": "P", "Numba": "o", "Numba f32": "^"}
colors = {"Python": "tab:gray", "NumPy naive": "tab:orange", "NumPy out_view": "tab:brown",
"NumPy out": "tab:olive", "NumPy flat": "tab:green", "Numba": "tab:blue",
"Numba f32": "tab:purple"}
seen = set()
for label, n, intensity, perf in points:
ax.scatter(intensity, perf, marker=markers[label], color=colors[label], s=50, zorder=3,
label=label if label not in seen else None)
if label.startswith("Numba"):
ax.annotate(f"n={n}", (intensity, perf), textcoords="offset points", xytext=(7, -3), fontsize=7)
seen.add(label)
ax.set_xlim(1e-2, 1e3)
ax.set_ylim(1e-2, P * 3)
ax.set_xlabel("операционная интенсивность I, FLOP/байт")
ax.set_ylabel("производительность, GFLOP/s")
ax.set_title("Roofline, одно ядро Apple M1 (сетка 2048; Python — 1024; Numba — также 2000)")
ax.grid(True, which="both", alpha=0.3)
ax.legend(fontsize=8, loc="lower right")
fig.tight_layout()
fig.savefig(path, dpi=150)
plt.close(fig)