File size: 6,590 Bytes
6ec9472 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | """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")
|