Files
leleka/scripts/e2e/decode/baseline-prefetch.py
T

61 lines
2.9 KiB
Python

#!/usr/bin/env python3
"""Pre-read files into the page cache with large asynchronous readahead (posix_fadvise WILLNEED, a sliding window 3 GiB ahead of the reader). Read-only.
python3 -I baseline-prefetch.py FILE_OR_DIR [...] (a directory = every regular file in it, largest first)
Why: after a reboot the page cache is cold and the server's NVMe serves the plain buffered 128 KiB-readahead pattern of the holder / loaders at only ~30 MB/s (r_await 4 ms, queue
depth 1; measured 2026-11-01: 31 GB of the 55 GB KAR file in 15 min), while the same file read with large or WILLNEED requests runs at ~600 MB/s. Without this a reboot cycle
costs about an hour of cold loading. The reads change no data; the page cache ends up in the state a normal run starts from (model files cached).
"""
import mmap, os, sys, time
W = 1 << 30
AHEAD = 3
def shmem_bytes():
for ln in open("/proc/meminfo"):
if ln.startswith("Shmem:"):
return int(ln.split()[1]) * 1024
return 0
if sys.argv[1] == "--follow":
# --follow FILE READYFILE : the holder reads FILE sequentially into a memfd (Shmem grows with its position); keep 8 GiB of FILE ahead of that position in the page cache until
# READYFILE exists. Needed because the pages read ahead by a plain pre-read are partly evicted again before the holder gets to them.
path, ready = sys.argv[2], sys.argv[3]
size = os.path.getsize(path); fd = os.open(path, os.O_RDONLY); base = shmem_bytes(); t0 = time.time()
while not (os.path.exists(ready) and os.path.getsize(ready) > 0) and time.time() - t0 < 3600:
cur = max(0, shmem_bytes() - base)
lo = max(0, cur - (64 << 20)); hi = min(size, cur + (8 << 30))
if hi > lo:
os.posix_fadvise(fd, lo, hi - lo, os.POSIX_FADV_WILLNEED)
time.sleep(0.5)
print("follow %s done after %.0f s" % (path, time.time() - t0), flush=True)
sys.exit(0)
def files(args):
for a in args:
if os.path.isdir(a):
fs = [os.path.join(a, f) for f in os.listdir(a) if os.path.isfile(os.path.join(a, f))]
for f in sorted(fs, key=os.path.getsize, reverse=True):
yield f
else:
yield a
for path in files(sys.argv[1:]):
size = os.path.getsize(path)
if size == 0:
continue
fd = os.open(path, os.O_RDONLY)
t0 = time.time()
for o in range(0, min(size, AHEAD * W), W):
os.posix_fadvise(fd, o, min(W, size - o), os.POSIX_FADV_WILLNEED)
off = 0
while off < size:
n = min(W, size - off)
nxt = off + AHEAD * W
if nxt < size:
os.posix_fadvise(fd, nxt, min(W, size - nxt), os.POSIX_FADV_WILLNEED)
m = mmap.mmap(fd, n, prot=mmap.PROT_READ, offset=off)
for i in range(0, n, 1 << 20):
m[i]
m.close()
off += n
os.close(fd)
dt = time.time() - t0
print("prefetch %s %.1f GiB in %.0f s (%.0f MB/s)" % (path, size / 2**30, dt, size / 1e6 / max(dt, 1e-6)), flush=True)