Files

365 lines
25 KiB
Bash

#!/usr/bin/env bash
# KAR file source A/B: the 5090 profile with the level-2 KAR archive as a sealed memfd (today, 55.3 GB of shmem made by a holder) against the same archive as an ordinary
# READ-ONLY FILE served through the page cache (profile rtx5090-32g-file, engine flag --kar-archive-file). Same binary, same frozen corpus, same
# 5-turn ~245k session as speedtrain3-ab.sh, seed OFF, upstream ranked profile, alternating arms.
#
# NOT A HOLDER JOB. The file arms need the RAM that the holder's memfd pins, so the holder must be stopped first (and MODEL.lock free): this script takes MODEL.lock and gpu.lock
# itself and seals its own memfd for the base arms (the same copy loop as kar_holder2.py, 16 MiB chunks, ~160 s for 55 GB from this disk; its time is reported as seal_s and is
# NOT part of the engine's "model ready after"). Run it from a shell on the server (nohup/tmux), never queue it behind the holder.
#
# once, by the owner of the file (no data is rewritten; it changes ctime, so existing verification stamps of the archive become void):
# chmod 0400 ~/work/leleka/models/leleka-gates/assets/qwen-iq3-s-l2-v4.kar
# stop the holder: touch ~/work/gpu-runs/holder2/jobs/STOP (it exits between jobs, releasing its 51.5 GiB memfd and MODEL.lock); start it again afterwards with
# cd ~/work/gpu-runs/holder2 && rm jobs/STOP && nohup bash run_holder2.sh > holder2.out 2>&1 &
# install: cp scripts/e2e/decode/kar-file-ab.sh /data/leleka-e2e/decode/dt/jobs-manual/kar-file-ab.sh (any directory that is not the holder queue)
# cp scripts/e2e/run-e2e.sh /data/leleka-e2e/decode/dt/scripts/e2e/run-e2e-karfile.sh (a NEW name: the frozen run-e2e.sh stays untouched)
# mkdir -p /data/leleka-e2e/decode/dt/bin-karfile && cp <build>/{leleka-inference,leleka-daemon,leleka-cli,leleka-api} there, plus COMMIT.txt
# run: bash /data/leleka-e2e/decode/dt/jobs-manual/kar-file-ab.sh 2>&1 | tee -a /data/leleka-e2e/runs/kar-file-ab.job.log
#
# Arms (the order in ARMS is the run order; default two blocks of base, new-cold, new-warm; ARMS="base-memfd new-file-cold base-memfd new-file-cold" is the 4-arm minimum):
# base-memfd archive -> sealed memfd (this script, as the holder does) -> engine --kar-archive-fd; no verification stamps (the engine hashes the memfd and the shards at start, as in
# every holder job so far)
# new-file-cold engine --kar-archive-file ARCHIVE --verify-stamps DIR; the page cache of the ARCHIVE is dropped (posix_fadvise DONTNEED, clean pages, no root) just before the start,
# so the first requests pay every random PLE read from the disk
# new-file-warm the same, started right after a new-file-cold arm WITHOUT dropping anything: the pages the previous engine read are still in the page cache (the property that
# a memfd cannot have: it dies with the holder, the page cache survives an engine restart)
# Only the KAR source differs between base and new. Both get --prefix-cache-mib $PREFIX_MIB (6144, explicit: with `auto` the file arm would be handed the RAM the memfd no longer pins,
# a 24 GiB cache, which is a different experiment); the 245k session needs about 4 GiB of it either way.
# Stamps: before the first arm the script runs `leleka-inference --verify-only --verify-stamps` twice (CPU only, no GPU): the first pass hashes the two shards and the archive if their
# stamps are absent or stale (about 138 GB of sequential reads, minutes, the heaviest I/O of this job; skip it with SEED_STAMPS=0 only if the stamps are current), the second must
# print `leleka-kar-startup ... verify=stamp ... total_read_bytes=` of about a megabyte: that line is the "what is read at start" evidence.
#
# Per arm it records (all in $OUTR/<tag>/): env-arm.txt (binaries, commit, hardware, kernel, file states), job.log (run-e2e output, seal_s, ready time), inference.log (engine: the
# leleka-kar-startup line, leleka-load-time phases, DBG window/profile lines), long-session.json (per-turn ttft_s, decode_tok_s, input_tokens), samples.txt (every 5 s: MemAvailable,
# Shmem, Cached, AnonPages, SwapFree, PSI io/memory, pswpin, pgmajfault, the engine's RssAnon/RssFile/RssShmem, rchar/read_bytes of the engine; every 15 s: bytes of the archive and of the
# two shards resident in the page cache, `fincore`), client.log (one UTC timestamp per turn line) and VALIDITY.txt. The summary at the end pairs each new arm with the base before it.
# Validity per run as in speedtrain3-ab.sh (5 turns, final-turn input >= 200000, turn-5 mean window.ple < 5 ms); a new arm whose engine hashed the archive in this start
# (verify=full-pass) is marked INVALID as a cold/warm measurement, because the hash fills the page cache.
# Quality is not decided here: the PLE rows are the same bytes by construction; greedy identity of the first turns is the cheap check (speedtrain3-id.sh shape, not part of this job).
set -uo pipefail
D=/data/leleka-e2e/decode/dt
BINDIR=${BINDIR:-$D/bin-karfile}
RUNNER=${RUNNER:-$D/scripts/e2e/run-e2e-karfile.sh}
LOCK=/data/leleka-e2e/gpu.lock
MODELLOCK=$HOME/work/gpu-runs/MODEL.lock
OUTR=${OUTR:-/data/leleka-e2e/runs/kar-file-ab}
CORPUS=/data/leleka-e2e/decode/corpus/src/crates
UP=/data/leleka-e2e/decode/assets/expert-profile-upstream.bin
ASSETS=${E2E_ASSETS:-$HOME/work/leleka/models/leleka-gates/assets}
ARCHIVE=$ASSETS/qwen-iq3-s-l2-v4.kar
SHARD0=$ASSETS/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf
SHARD1=$ASSETS/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf
STAMPS=${STAMPS:-$OUTR/stamps}
TOOLS=$OUTR/_tools
RUN_TAG=${RUN_TAG:-}
SEED_STAMPS=${SEED_STAMPS:-1}
PREFIX_MIB=${PREFIX_MIB:-6144}
GPU_BUDGET=${GPU_BUDGET:-32819404800}
ARMS=${ARMS:-"base-memfd new-file-cold new-file-warm base-memfd new-file-cold new-file-warm"}
SESSION_ARGS="--turns 5 --target-tokens 245000 --max-output 300 --min-final-tokens 200000"
export LD_LIBRARY_PATH=$HOME/cuda-toolkits/cublas-12.9.1.4/lib:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-}
for f in "$UP" "$D/tools/long-session.py" "$RUNNER" "$BINDIR/leleka-inference" "$BINDIR/leleka-daemon" "$BINDIR/leleka-cli" "$BINDIR/leleka-api" "$CORPUS/backend-api/src/lib.rs" \
"$ARCHIVE" "$ASSETS/qwen-iq3-s-l2-v4.kar.provenance.json" "$SHARD0" "$SHARD1"; do
[ -r "$f" ] || { echo "missing $f" >&2; exit 3; }
done
command -v fincore >/dev/null || { echo "fincore (util-linux) is needed" >&2; exit 3; }
if pgrep -u "$USER" -f 'kar_holder2?\.py' >/dev/null; then
echo "the holder is running and pins 51.5 GiB of memfd: stop it first (touch ~/work/gpu-runs/holder2/jobs/STOP, wait until it exits)" >&2; exit 3
fi
if [ "$(stat -c %h "$ARCHIVE")" != 1 ] || [ "$(( 0$(stat -c %a "$ARCHIVE") & 0222 ))" != 0 ]; then
echo "the archive must be a single-link file without write bits for the file source: chmod 0400 $ARCHIVE" >&2; exit 3
fi
case "$ARMS" in *new-file*) ;; *) SEED_STAMPS=0 ;; esac
avail_mib=$(awk '/^MemAvailable:/{print int($2/1024)}' /proc/meminfo)
[ "$avail_mib" -ge 100000 ] || { echo "MemAvailable is only $avail_mib MiB: something still pins RAM (the holder?); the file arm needs about 60 GiB free besides the page cache" >&2; exit 3; }
mkdir -p "$OUTR" "$TOOLS"
mkdir -p -m 700 "$STAMPS"; chmod 700 "$STAMPS"
# MODEL.lock for the whole job (the holder's start loop waits for it and takes it again afterwards)
mkdir "$MODELLOCK" 2>/dev/null || { echo "MODEL.lock is held: $(ls $MODELLOCK 2>&1)" >&2; exit 3; }
trap 'rmdir "$MODELLOCK" 2>/dev/null' EXIT
cat >"$TOOLS/seal_exec.py" <<'PY'
# the holder's copy loop (kar_holder2.py), then the command with the sealed descriptor inherited: seal_exec.py ARCHIVE CMD...
import fcntl, os, subprocess, sys, time
src, cmd = sys.argv[1], sys.argv[2:]
fd = os.memfd_create("kar-archive", os.MFD_ALLOW_SEALING)
t = time.time(); n = 0
with open(src, "rb", buffering=0) as f:
while chunk := f.read(16 << 20):
os.write(fd, chunk); n += len(chunk)
fcntl.fcntl(fd, fcntl.F_ADD_SEALS, fcntl.F_SEAL_WRITE | fcntl.F_SEAL_GROW | fcntl.F_SEAL_SHRINK | fcntl.F_SEAL_SEAL)
print(f"seal_s={time.time()-t:.1f} bytes={n} fd={fd} at={time.strftime('%T', time.gmtime())}Z", flush=True)
sys.exit(subprocess.run(cmd, pass_fds=[fd], env=dict(os.environ, LELEKA_STRA169_KAR_FD=str(fd))).returncode)
PY
cat >"$TOOLS/dropcache.py" <<'PY'
# posix_fadvise(DONTNEED) on a file: drops its clean page-cache pages (no root needed, no data is touched)
import os, sys
for path in sys.argv[1:]:
fd = os.open(path, os.O_RDONLY); os.posix_fadvise(fd, 0, 0, os.POSIX_FADV_DONTNEED); os.close(fd)
PY
resident() { fincore -b -n -o RES "$1" 2>/dev/null | tr -d ' '; } # bytes of the file in the page cache (mincore: no I/O)
sampler() { # $1 output file
local i=0 pid line
while sleep 5; do
i=$((i + 1))
pid=$(pgrep -u "$USER" -f 'leleka-inference --listen' | head -1)
line="$(date -u +%T) $(awk '/^(MemAvailable|MemFree|Cached|Shmem|AnonPages|Mapped|Dirty|SwapFree):/{printf "%s%d ", $1, $2/1024}' /proc/meminfo)"
line="$line io10=$(awk '/^some/{split($2,a,"=");print a[2]}' /proc/pressure/io) mem10=$(awk '/^some/{split($2,a,"=");print a[2]}' /proc/pressure/memory)"
line="$line $(awk '/^(pswpin|pswpout|pgmajfault|workingset_refault_file) /{printf "%s=%s ", $1, $2}' /proc/vmstat)"
if [ -n "$pid" ] && [ -r "/proc/$pid/smaps_rollup" ]; then
line="$line pid=$pid $(awk '/^(Rss|Pss_Anon|Pss_File|Pss_Shmem|Swap):/{printf "%s%d ", $1, $2/1024}' /proc/$pid/smaps_rollup)"
line="$line $(awk '/^(rchar|read_bytes):/{printf "%s%s ", $1, $2}' /proc/$pid/io 2>/dev/null)"
fi
if [ $((i % 3)) = 1 ]; then line="$line | archive_cached=$(resident "$ARCHIVE") shard0_cached=$(resident "$SHARD0") shard1_cached=$(resident "$SHARD1")"; fi
echo "$line"
done > "$1" 2>/dev/null
}
seed_stamps() { # CPU-only verification of shards and archive that records the stamps; twice, the second must be a stamp hit
local pass
for pass in 1 2; do
( export LELEKA_RUNTIME_TOKEN=$(head -c 24 /dev/urandom | base64 | tr -d '\n')
echo "=== seed pass $pass $(date -u +%FT%TZ)"
"$BINDIR/leleka-inference" --listen 127.0.0.1:18766 --token-env LELEKA_RUNTIME_TOKEN --shard0 "$SHARD0" --shard1 "$SHARD1" --gpu 0 --gpu-budget "$GPU_BUDGET" \
--context-tokens 262144 --kar-archive-file "$ARCHIVE" --kar-provenance "$ASSETS/qwen-iq3-s-l2-v4.kar.provenance.json" --verify-only --verify-stamps "$STAMPS" 2>&1
echo "rc=$? $(date -u +%FT%TZ)" ) | tee -a "$OUTR/seed-stamps.log" | grep -a -E "^===|leleka-kar-startup|leleka-load-time phase=(kar_inspect_verify|shard._sha256_and_index|sources_verified_in_parallel_wall|all_sources_verified)|^rc=|refus|rror" | cut -c1-300
done
}
ours() { # $1 tag, $2 arm
local tag=$1 arm=$2
( export E2E_BIN=$BINDIR E2E_OUT=$OUTR/$tag E2E_ASSETS=$ASSETS
mkdir -p "$E2E_OUT"
export LELEKA_BRINGUP_TRACE=1 LELEKA_PREFIX_TRACE=1
export LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto E2E_GPU_BUDGET=$GPU_BUDGET
export E2E_SAMPLE_S=10 LELEKA_CHAIN=all
export LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$UP
unset LELEKA_ORIGINAL_SERVE_SEED_MAX_ROWS LELEKA_SM120_ATTN_DAILY LELEKA_SM120_GU_SWIGLU LELEKA_SM120_SIDE_MIXER LELEKA_SM120_PERF LELEKA_SERVE_DRAFT_AFTER_COMMIT LELEKA_PROMPT_EMBED_ALIAS LELEKA_VRAM_LEDGER LELEKA_DENSE_SLAB LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB E2E_KAR_FILE
export LELEKA_ORIGINAL_SERVE_SEED=off
local engine_args="--prefix-cache-mib $PREFIX_MIB --prefix-cache-tail reply --original-prefill-capacity 8192 --prefix-cache-block 8192 --spec-min-p 0"
local cold_note="-"
case $arm in
base-memfd)
# the seal reads the whole archive: from a cold cache it costs what a holder start costs
python3 -I "$TOOLS/dropcache.py" "$ARCHIVE"; cold_note="archive page cache dropped before the seal: $(resident "$ARCHIVE") bytes resident" ;;
new-file-cold)
python3 -I "$TOOLS/dropcache.py" "$ARCHIVE"; cold_note="archive page cache dropped: $(resident "$ARCHIVE") bytes resident"
export E2E_KAR_FILE=$ARCHIVE; engine_args="$engine_args --verify-stamps $STAMPS" ;;
new-file-warm)
cold_note="archive page cache left as the previous engine made it: $(resident "$ARCHIVE") bytes resident"
export E2E_KAR_FILE=$ARCHIVE; engine_args="$engine_args --verify-stamps $STAMPS" ;;
*) echo "unknown arm $arm" >&2; exit 2 ;;
esac
export E2E_ENGINE_ARGS=$engine_args
{ echo "arm=$arm tag=$tag"; date -u +%FT%TZ; echo "cache: $cold_note"; free -m | sed -n 2p
echo "kernel: $(uname -r)"; nvidia-smi --query-gpu=name,driver_version,memory.total --format=csv,noheader
echo "resident before start: archive=$(resident "$ARCHIVE") shard0=$(resident "$SHARD0") shard1=$(resident "$SHARD1")"
stat -c "%n mode=%a ino=%i size=%s mtime=%y ctime=%z" "$ARCHIVE" "$SHARD0" "$SHARD1"
echo "read_ahead_kb=$(cat /sys/block/nvme0n1/queue/read_ahead_kb) scheduler=$(cat /sys/block/nvme0n1/queue/scheduler) swappiness=$(cat /proc/sys/vm/swappiness)"
sha256sum "$UP" "$BINDIR"/leleka-inference "$BINDIR"/leleka-daemon "$BINDIR"/leleka-cli "$BINDIR"/leleka-api "$RUNNER"
cat "$BINDIR/COMMIT.txt" 2>/dev/null; head -1 /data/leleka-e2e/decode/corpus/MANIFEST.txt
echo "engine args: $engine_args"
env | grep -E '^(LELEKA_|STRATA_|E2E_)' | sort; } >"$E2E_OUT/env-arm.txt"
export E2E_RUN_CMD='set -o pipefail; python3 -I '"$D"'/tools/long-session.py --src '"$CORPUS $SESSION_ARGS"' 2>&1 | while IFS= read -r l; do printf "%s %s\n" "$(date -u +%T)" "$l"; done'
sampler "$E2E_OUT/samples.txt" & SAMP=$!
if [ "$arm" = base-memfd ]; then
python3 -I "$TOOLS/seal_exec.py" "$ARCHIVE" bash "$RUNNER" 2>&1 | tee "$E2E_OUT/job.log" | grep -a -E "seal_s|^\{|^[0-9:]+ \{|expert cache|request outcome|ready after|rc=|refus|error|Error|long_session|client exit|leleka-kar-startup" | cut -c1-300
else
bash "$RUNNER" 2>&1 | tee "$E2E_OUT/job.log" | grep -a -E "^\{|^[0-9:]+ \{|expert cache|request outcome|ready after|rc=|refus|error|Error|long_session|client exit|leleka-kar-startup" | cut -c1-300
fi
kill $SAMP 2>/dev/null
echo "run-e2e done $tag $(date -u +%FT%TZ)" )
}
validity() { # $1 run dir, $2 arm
python3 -I - "$1" "$2" <<'PY'
import json, os, re, sys
d, arm = sys.argv[1], sys.argv[2]
f = os.path.join(d, "long-session.json")
verdict = "INVALID: no long-session.json"
if os.path.exists(f):
t = json.load(open(f))
final = (t[-1].get("input_tokens") or 0) if t else 0
if any("error" in r for r in t):
verdict = "INVALID: a turn failed"
elif len(t) < 5 or final < 200000:
verdict = "INVALID: %d turns, final-turn input tokens %d < 200000 (short corpus?)" % (len(t), final)
else:
verdict = "VALID: 5 turns, final-turn input tokens %d" % final
wins, last = [], []
log = open(os.path.join(d, "inference.log"), errors="replace").read().splitlines()
for ln in log:
if ln.startswith("DBG window "):
last.append(dict((k, float(v)) for k, v in re.findall(r"(\w+)=([-\d.]+)", ln)))
elif "leleka-serve request outcome" in ln:
wins.append(last); last = []
w = wins[-1] if wins else []
ple = sum(x.get("ple", 0) for x in w) / max(len(w), 1)
verdict += "; turn-5 window.ple mean %.2f ms over %d windows" % (ple, len(w))
if not w:
verdict = "INVALID: no turn-5 window lines (trace env missing?)"
elif ple >= 5:
verdict = "INVALID: turn-5 window.ple mean %.2f ms >= 5 ms (PLE scan back?)" % ple
start = [l for l in log if l.startswith("leleka-kar-startup")]
if not start:
verdict += "; NOTE: no leleka-kar-startup line (binary without the log line?)"
elif arm.startswith("new-file") and "source=file" not in start[0]:
verdict = "INVALID: new arm did not run with source=file: " + start[0]
elif arm.startswith("new-file") and "verify=stamp" not in start[0]:
verdict = "INVALID as a cold/warm measurement: the engine hashed the archive in this start (" + start[0] + ")"
elif arm == "base-memfd" and "source=memfd" not in start[0]:
verdict = "INVALID: base arm did not run with source=memfd: " + start[0]
open(os.path.join(d, "VALIDITY.txt"), "w").write(verdict + "\n")
print(os.path.basename(d), verdict)
PY
}
{ echo "kar-file-ab $(date -u +%FT%TZ) arms: $ARMS"; echo "archive: $(stat -c '%n mode=%a ino=%i size=%s mtime=%y ctime=%z' "$ARCHIVE")"; free -m | sed -n 2p; } | tee -a "$OUTR/job-start.txt"
[ "$SEED_STAMPS" = 1 ] && seed_stamps
n=0
for arm in $ARMS; do
n=$((n + 1)); tag="$arm-r$n$RUN_TAG"
got=0
for _ in $(seq 1 1080); do
if mkdir "$LOCK" 2>/dev/null; then echo "kar-file-ab $tag $(date -u +%FT%TZ)" >"$LOCK/owner"; got=1; break; fi
sleep 5
done
[ $got = 1 ] || { echo "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; exit 3; }
echo "=== $tag $(date -u +%FT%TZ)"; free -g | sed -n 2p
if [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader)" ]; then
echo "GPU busy, skipping $tag"; rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null; continue
fi
ours "$tag" "$arm"
validity "$OUTR/$tag" "$arm"
echo "arm done $tag $(date -u +%FT%TZ)"
rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null
sleep 15
done
# summary
python3 -I - "$OUTR" <<'PY'
import glob, json, os, re, statistics, sys
root = sys.argv[1]
def run_number(path):
tail = path.rsplit("-r", 1)[-1]
m = re.match(r"\d+", tail)
return int(m.group()) if m else 0
def secs(t):
h, m, s = t.split(":"); return int(h) * 3600 + int(m) * 60 + int(s)
runs = []
for d in sorted(glob.glob(os.path.join(root, "*-r[0-9]*")), key=run_number):
v = os.path.join(d, "VALIDITY.txt")
tag = os.path.basename(d)
if not os.path.exists(v):
print(tag, "not used: no VALIDITY.txt"); continue
verdict = open(v).read().strip()
arm = tag.rsplit("-r", 1)[0]
r = {"tag": tag, "arm": arm, "valid": verdict.startswith("VALID"), "verdict": verdict, "dir": d}
job = open(os.path.join(d, "job.log"), errors="replace").read() if os.path.exists(os.path.join(d, "job.log")) else ""
m = re.search(r"seal_s=([\d.]+)", job); r["seal_s"] = float(m.group(1)) if m else None
m = re.search(r"\[run-e2e (\d\d:\d\d:\d\d)\] model ready after (\d+)s", job)
r["ready_s"] = int(m.group(2)) if m else None; r["ready_at"] = secs(m.group(1)) if m else None
log = open(os.path.join(d, "inference.log"), errors="replace").read().splitlines() if os.path.exists(os.path.join(d, "inference.log")) else []
r["startup"] = next((l for l in log if l.startswith("leleka-kar-startup")), "-")
r["phases"] = {}
for l in log:
m = re.match(r"leleka-load-time phase=(\S+) seconds=([\d.]+)", l)
if m and m.group(1) in ("kar_inspect_verify", "shard0_sha256_and_index", "shard1_sha256_and_index", "sources_verified_in_parallel_wall"):
r["phases"][m.group(1)] = float(m.group(2))
cs = os.path.join(d, "long-session.json")
r["turns"] = json.load(open(cs)) if os.path.exists(cs) else []
ends = []
cl = os.path.join(d, "client.log")
if os.path.exists(cl):
for l in open(cl, errors="replace"):
m = re.match(r"(\d\d:\d\d:\d\d) \{", l)
if m and "ttft_s" in l: ends.append(secs(m.group(1)))
r["turn_ends"] = ends
samples = []
sp = os.path.join(d, "samples.txt")
if os.path.exists(sp):
for l in open(sp, errors="replace"):
p = l.split()
if not p: continue
row = {"t": secs(p[0])}
for k in ("MemAvailable", "Shmem", "Cached", "AnonPages", "SwapFree", "Dirty", "Rss", "Pss_Anon", "Pss_File", "Pss_Shmem", "Swap"):
m = re.search(r"\b%s:?(\d+)" % k, l); row[k] = int(m.group(1)) if m else None
for k in ("io10", "mem10"):
m = re.search(r"%s=([\d.]+)" % k, l); row[k] = float(m.group(1)) if m else None
for k in ("pswpin", "pgmajfault", "rchar", "read_bytes"):
m = re.search(r"%s[:=]?(\d+)" % k, l); row[k] = int(m.group(1)) if m else None
m = re.search(r"archive_cached=(\d+)", l); row["arch"] = int(m.group(1)) if m and m.group(1) else None
samples.append(row)
r["samples"] = samples
runs.append(r)
def at(r, t):
after = [s for s in r["samples"] if s["t"] >= t]
return after[0] if after else (r["samples"][-1] if r["samples"] else {})
def arch_at(r, t):
after = [s for s in r["samples"] if s["t"] >= t and s.get("arch") is not None]
return after[0]["arch"] if after else None
GIB = 1024.0 ** 3
print("== per run: start cost ==")
for r in runs:
total = (r["seal_s"] or 0) + (r["ready_s"] or 0)
print("%-26s %s | seal_s %s ready_s %s cold-start total %.0f s | verify %s | %s" % (
r["tag"], "valid " if r["valid"] else "INVALID", r["seal_s"], r["ready_s"], total,
" ".join("%s=%.1f" % (k.replace("_sha256_and_index", ""), v) for k, v in r["phases"].items()), r["startup"][:200]))
if not r["valid"]: print(" ", r["verdict"])
print("== per run: per-turn ttft_s | decode_tok_s | input_tokens | cached_tokens ==")
for r in runs:
t = r["turns"]
print(r["tag"], "|", " ".join("%.1f" % (x.get("ttft_s") or 0) for x in t), "|", " ".join("%.1f" % (x.get("decode_tok_s") or 0) for x in t), "|",
" ".join(str(x.get("input_tokens")) for x in t), "|", " ".join(str(x.get("cached_tokens")) for x in t))
print("== per run: host memory (GiB). at ready / after each turn: MemAvailable, Shmem, page cache of the archive; run minimum MemAvailable, max swap used, max io PSI some, major faults ==")
for r in runs:
if not r["samples"]: continue
first = at(r, r["ready_at"] or 0)
swap0 = r["samples"][0].get("SwapFree")
row = ["ready: avail %.1f shmem %.1f arch %s" % ((first.get("MemAvailable") or 0) / 1024, (first.get("Shmem") or 0) / 1024,
"%.2f" % (arch_at(r, r["ready_at"] or 0) / GIB) if arch_at(r, r["ready_at"] or 0) is not None else "-")]
for i, e in enumerate(r["turn_ends"]):
s = at(r, e); a = arch_at(r, e)
row.append("t%d: avail %.1f arch %s" % (i + 1, (s.get("MemAvailable") or 0) / 1024, "%.2f" % (a / GIB) if a is not None else "-"))
mins = min((s["MemAvailable"] for s in r["samples"] if s.get("MemAvailable")), default=0) / 1024
swapmax = max(((swap0 or 0) - s["SwapFree"]) for s in r["samples"] if s.get("SwapFree") is not None) / 1024 if swap0 is not None else 0
io = max((s["io10"] or 0 for s in r["samples"]), default=0)
maj = [s["pgmajfault"] for s in r["samples"] if s.get("pgmajfault") is not None]
rb = [s["read_bytes"] for s in r["samples"] if s.get("read_bytes") is not None]
print(r["tag"], "|", "; ".join(row), "| min avail %.1f swap max %.2f io-psi max %.1f majfault +%d engine read_bytes %.1f GiB" % (
mins, swapmax, io, (maj[-1] - maj[0]) if maj else 0, (max(rb) / GIB) if rb else 0))
print("== per run: PLE time seen by the engine (DBG window ple mean/max ms per request; DBG profile request keys containing 'ple': total ms/calls) ==")
for r in runs:
log = open(os.path.join(r["dir"], "inference.log"), errors="replace").read().splitlines() if os.path.isdir(r["dir"]) else []
reqs, last, prof, profs = [], [], None, []
for ln in log:
if ln.startswith("DBG window "):
last.append(dict((k, float(v)) for k, v in re.findall(r"(\w+)=([-\d.]+)", ln)))
elif ln.startswith("DBG profile request:"):
prof = {m[0]: (float(m[1]), int(m[2])) for m in re.findall(r"(\S*ple\S*?)=([\d.]+)/(\d+)", ln)}
elif "leleka-serve request outcome" in ln:
reqs.append(last); profs.append(prof); last, prof = [], None
cells = []
for i, (w, p) in enumerate(zip(reqs, profs)):
pl = [x.get("ple", 0) for x in w]
cells.append("r%d window.ple %.2f/%.2f%s" % (i + 1, statistics.mean(pl) if pl else 0, max(pl) if pl else 0,
(" " + ",".join("%s=%.0f/%d" % (k, v[0], v[1]) for k, v in sorted((p or {}).items()))) if p else ""))
print(r["tag"], "|", " ; ".join(cells))
print("== paired: each new arm minus the base arm before it (valid runs only), per turn ==")
for i, r in enumerate(runs):
if not r["arm"].startswith("new-file") or not r["valid"]: continue
base = next((b for b in reversed(runs[:i]) if b["arm"] == "base-memfd" and b["valid"]), None)
if not base: continue
for key, unit in (("ttft_s", "s"), ("decode_tok_s", "tok/s")):
a = [x.get(key) or 0 for x in r["turns"]]; b = [x.get(key) or 0 for x in base["turns"]]
print("%-24s minus %-18s %-12s per turn: %s mean %+.2f %s (%+.2f %%)" % (r["tag"], base["tag"], key, " ".join("%+.2f" % (x - y) for x, y in zip(a, b)),
statistics.mean(a) - statistics.mean(b), unit, 100 * (statistics.mean(a) / statistics.mean(b) - 1) if statistics.mean(b) else 0))
print("%-24s turn-1 ttft: base %.1f s, this arm %.1f s (the first-turn cost of the cold/warm page cache is the difference)" % (r["tag"], base["turns"][0].get("ttft_s") or 0, r["turns"][0].get("ttft_s") or 0))
PY