mkvn's picture
Paper, codec, routing traces and measurements
6ec9472 verified
Raw
History Blame Contribute Delete
6.59 kB
"""Unbuffered (page-cache-bypassing) NVMe random-read benchmark + PCIe H2D + RAM copy.
Uses Win32 CreateFileW with FILE_FLAG_NO_BUFFERING so measurements reflect true
device behaviour at MoE-expert block granularity rather than page-cache hits.
"""
import ctypes, ctypes.wintypes as wt
import json, mmap, os, random, sys, time
from concurrent.futures import ThreadPoolExecutor
GENERIC_READ = 0x80000000
GENERIC_WRITE = 0x40000000
FILE_SHARE_READ = 0x00000001
OPEN_EXISTING = 3
CREATE_ALWAYS = 2
FILE_FLAG_NO_BUFFERING = 0x20000000
FILE_FLAG_WRITE_THROUGH = 0x80000000
FILE_FLAG_RANDOM_ACCESS = 0x10000000
FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000
INVALID_HANDLE = ctypes.c_void_p(-1).value
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
k32.CreateFileW.restype = wt.HANDLE
k32.CreateFileW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ctypes.c_void_p,
wt.DWORD, wt.DWORD, wt.HANDLE]
k32.ReadFile.argtypes = [wt.HANDLE, ctypes.c_void_p, wt.DWORD,
ctypes.POINTER(wt.DWORD), ctypes.c_void_p]
k32.WriteFile.argtypes = [wt.HANDLE, ctypes.c_void_p, wt.DWORD,
ctypes.POINTER(wt.DWORD), ctypes.c_void_p]
k32.SetFilePointerEx.argtypes = [wt.HANDLE, ctypes.c_longlong,
ctypes.POINTER(ctypes.c_longlong), wt.DWORD]
k32.CloseHandle.argtypes = [wt.HANDLE]
SECTOR = 4096
def aligned_buf(nbytes):
n = (nbytes + SECTOR - 1) // SECTOR * SECTOR
mm = mmap.mmap(-1, n)
ptr = ctypes.addressof(ctypes.c_char.from_buffer(mm))
assert ptr % SECTOR == 0, "buffer not sector aligned"
return mm, ptr
def open_unbuffered(path, write=False):
access = (GENERIC_READ | GENERIC_WRITE) if write else GENERIC_READ
create = CREATE_ALWAYS if write else OPEN_EXISTING
flags = FILE_FLAG_NO_BUFFERING | (FILE_FLAG_WRITE_THROUGH if write
else FILE_FLAG_RANDOM_ACCESS)
h = k32.CreateFileW(path, access, FILE_SHARE_READ, None, create, flags, None)
if h == INVALID_HANDLE:
raise ctypes.WinError(ctypes.get_last_error())
return h
def make_file(path, size_gb):
if os.path.exists(path) and os.path.getsize(path) >= size_gb * (1 << 30):
return
h = open_unbuffered(path, write=True)
chunk = 32 << 20
mm, ptr = aligned_buf(chunk)
mm.write(os.urandom(1 << 20) * (chunk >> 20))
written = wt.DWORD(0)
n = size_gb * (1 << 30) // chunk
for i in range(n):
if not k32.WriteFile(h, ptr, chunk, ctypes.byref(written), None):
raise ctypes.WinError(ctypes.get_last_error())
k32.CloseHandle(h)
del mm
def read_worker(path, offsets, block):
h = open_unbuffered(path)
mm, ptr = aligned_buf(block)
got = wt.DWORD(0)
newpos = ctypes.c_longlong(0)
total = 0
for off in offsets:
k32.SetFilePointerEx(h, ctypes.c_longlong(off), ctypes.byref(newpos), 0)
if not k32.ReadFile(h, ptr, block, ctypes.byref(got), None):
raise ctypes.WinError(ctypes.get_last_error())
total += got.value
k32.CloseHandle(h)
del mm
return total
def bench_random(path, fsize, block, nthreads, target_bytes=1 << 30):
nreads = max(nthreads * 4, int(target_bytes // block))
rng = random.Random(1234 + block + nthreads)
maxoff = (fsize - block) // SECTOR
offs = [rng.randrange(maxoff) * SECTOR for _ in range(nreads)]
parts = [offs[i::nthreads] for i in range(nthreads)]
t0 = time.perf_counter()
with ThreadPoolExecutor(nthreads) as ex:
tot = sum(ex.map(lambda o: read_worker(path, o, block), parts))
dt = time.perf_counter() - t0
return dict(block_kb=block // 1024, threads=nthreads,
mb_s=tot / dt / 1e6, iops=nreads / dt,
lat_ms=dt / nreads * nthreads * 1000)
def bench_sequential(path, fsize):
h = open_unbuffered(path)
block = 32 << 20
mm, ptr = aligned_buf(block)
got = wt.DWORD(0)
n = min(64, fsize // block)
t0 = time.perf_counter()
for _ in range(n):
k32.ReadFile(h, ptr, block, ctypes.byref(got), None)
dt = time.perf_counter() - t0
k32.CloseHandle(h)
del mm
return n * block / dt / 1e6
def bench_pcie():
import torch
if not torch.cuda.is_available():
return {}
out = {}
for mb in [1, 4, 16, 64]:
n = mb * (1 << 20)
cpu = torch.empty(n, dtype=torch.uint8).pin_memory()
gpu = torch.empty(n, dtype=torch.uint8, device="cuda")
for _ in range(3):
gpu.copy_(cpu, non_blocking=True)
torch.cuda.synchronize()
reps = max(5, 512 // mb)
t0 = time.perf_counter()
for _ in range(reps):
gpu.copy_(cpu, non_blocking=True)
torch.cuda.synchronize()
dt = time.perf_counter() - t0
out[f"h2d_{mb}MB_GBs"] = n * reps / dt / 1e9
del gpu, cpu
torch.cuda.empty_cache()
return out
def bench_ram():
import numpy as np
a = np.empty(1 << 28, dtype=np.uint8)
b = np.empty(1 << 28, dtype=np.uint8)
a[:] = 7
for _ in range(2):
b[:] = a
t0 = time.perf_counter()
reps = 8
for _ in range(reps):
b[:] = a
dt = time.perf_counter() - t0
return a.nbytes * reps / dt / 1e9
if __name__ == "__main__":
scratch = sys.argv[1]
path = os.path.join(scratch, "iobench.bin")
FSIZE_GB = 8
print("creating test file...", flush=True)
make_file(path, FSIZE_GB)
fsize = os.path.getsize(path)
res = {"file_gb": FSIZE_GB, "random": [], "host": {}}
res["host"]["seq_read_mb_s"] = bench_sequential(path, fsize)
print(f"sequential unbuffered read: {res['host']['seq_read_mb_s']:.0f} MB/s", flush=True)
for block_kb in [64, 256, 1024, 4096, 16384]:
for nt in [1, 2, 4, 8]:
r = bench_random(path, fsize, block_kb * 1024, nt,
target_bytes=512 << 20)
res["random"].append(r)
print(f" {block_kb:>6} KB x {nt} thr: {r['mb_s']:8.1f} MB/s "
f"{r['iops']:8.1f} IOPS {r['lat_ms']:.3f} ms", flush=True)
res["host"]["ram_copy_GBs"] = bench_ram()
print(f"RAM copy: {res['host']['ram_copy_GBs']:.2f} GB/s", flush=True)
res["host"].update(bench_pcie())
for k, v in res["host"].items():
if k.startswith("h2d"):
print(f"{k}: {v:.2f} GB/s", flush=True)
with open(os.path.join(os.path.dirname(__file__), "..", "results",
"io_bench.json"), "w") as f:
json.dump(res, f, indent=2)
os.remove(path)
print("saved results/io_bench.json")