Files
leleka/scripts/e2e/decode/sparse-memfd-ab.sh
T
Pavlo RatushnyiandClaude Sonnet 5.5 b856b615d3 sparse memfd (experimental, default OFF): seal, verify, lock and heal only the extents the serve path reads
Profile field memfd_extents: ple_only (needs kar_source memfd and an explicit prefix_cache_mib; default full, not serialized).
The sealed memfd keeps the archive's length and file offsets but holds only the ~16 GB the serve path reads (PLE rows, header,
directory, books); everything else is a hole, so readers need no change.

- deploy: sealed::seal_extents (parallel copy restricted to the extents, holes elsewhere, same seals; st_blocks test),
  leleka seal-exec [--sparse-ple] (Rust form of leleka-seal-exec for A/B runs outside leleka run), supervisor seals sparse,
  passes --kar-sparse-extents-sha256 to every engine, never attests or stamps the archive from a sparse copy, refuses to start
  without a pinned digest (PLE_EXTENTS_SHA256, or LELEKA_KAR_EXTENTS_SHA256 while that is unmeasured); resource planner,
  preflight RAM minimum and the inherited-descriptor credit use the memfd's real size.
- engine: --kar-sparse-extents-sha256, InheritedKarArchive::open_sparse, verify_sparse, extents handed to the governor.
- leleka-memory: FdMapping::lock_ranges, compact-space heal walk, guard_archive_extents. Locking or populating a hole allocates a
  zero page: tested with a negative control next to the extents-only test that asserts st_blocks does not move.
- scripts/e2e/decode/sparse-memfd-ab.sh (paired 5-turn 245k A/B + teacher-forced identity gate; NOT queued, not a holder job),
  docs/kar-sparse-memfd.md.

Not run on a GPU or against the real archive.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 12:28:52 +01:00

349 lines
23 KiB
Bash

#!/usr/bin/env bash
# Sparse-memfd A/B: the sealed KAR memfd that holds ONLY the byte ranges the serve path reads (the PLE rows, header, directory; about 16 GB of 55.3 GB, the rest is a hole)
# against the full memfd, SAME binaries in both arms, paired 5-turn ~245k session on the frozen corpus, counterbalanced arm order. Shape copied from draftvocab-ab.sh /
# speedtrain3-ab.sh (+ draftvocab-id.sh for the identity part). Design and the claims it tests: docs/kar-sparse-memfd.md, docs/design/memory-single-copy-and-elastic-state.md B0.
# THIS IS NOT A HOLDER JOB. It makes its own sealed memfd per arm (`leleka seal-exec`), and the holder's 55 GB memfd would not fit next to it (55.3 + 16 + 54 GiB of bank
# on a 121 GiB host). Run it with the holder STOPPED: it refuses to start while $G/MODEL.lock exists or while Shmem is above 8 GiB, and it takes MODEL.lock itself.
# It takes /data/leleka-e2e/gpu.lock per arm, one arm at a time, and skips an arm when something else uses the GPU. NOT QUEUED by its author: the orchestrator decides when.
#
# Install (laptop -> server, small files only):
# cp scripts/e2e/decode/sparse-memfd-ab.sh /data/leleka-e2e/decode/dt/jobs/sparse-memfd-ab.sh
# binaries, built once from claude/sparse-memfd in release mode and frozen read-only (record their sha256 in dt/BUILD.md):
# dt/bin-sparsememfd/{leleka,leleka-inference,leleka-daemon,leleka-cli,strata-next} the same five for both arms
# dt/rt-sparsememfd the leleka-runtime lib test binary (replay smoke) of the same commit
# EXTENTS_SHA256=<64 hex> the pinned digest of the archive's extents, from `kar_census ARCHIVE --hash-extents` on the archive that matched its full SHA-256 (docs/kar-sparse-memfd.md)
#
# EXTENTS_SHA256=... bash sparse-memfd-ab.sh # PHASES="id e2e": identity, then the 4-arm session A/B (about 90 GPU-min)
# PHASES=id EXTENTS_SHA256=... bash sparse-memfd-ab.sh # only the teacher-forced identity gate (2 processes, about 20 min)
# PHASES=e2e ARMS="full sparse sparse full full sparse" ... bash sparse-memfd-ab.sh # only the session A/B, 6 arms
#
# Arms. Every arm: the same binaries, seed OFF (LELEKA_ORIGINAL_SERVE_SEED=off), the ranked upstream profile, EXPERT_SLOTS auto (id: fixed 8000), GPU budget 32,819,404,800 (the product
# profile), prefix cache 6144 MiB (the explicit cap of the profile: `auto` would grow with the freed RAM and make the arms differ), tail reply, chunk and grid 8192. The ONLY variable:
# full `leleka seal-exec --file ARCHIVE` the whole 55.3 GB archive in the memfd, the engine verifies it against the archive SHA-256 (the pre-change form)
# sparse `leleka seal-exec --file ARCHIVE --sparse-ple` only the extents; the engine gets `--kar-sparse-extents-sha256 $EXTENTS_SHA256` (replay: LELEKA_KAR_SPARSE_EXTENTS_SHA256) and verifies the
# memfd against the pinned digest of the extents; the memory governor locks and heals the extents only
# Workload (the only valid one): the FROZEN corpus /data/leleka-e2e/decode/corpus/src/crates, 5 turns, target 245000 tokens, --max-output 300; identity: the 256k-class capture
# night5-long-256k, 5 requests, recorded replies, decode capped at 48 tokens each, teacher forced, top-16 logprobs of every row.
# Records per run (env-arm.txt): UTC time, binary sha256, extents digest, /proc/meminfo and `free -g` at start (page cache NOT dropped: this script may not write /proc/sys/vm),
# kernel, driver, the env; memsample.txt every 5 s: MemAvailable, Shmem, Cached, SwapFree, PSI, pswpin/pswpout/pgmajfault and, of the engine, RssAnon/RssShmem/VmLck.
# Validity per e2e run (VALIDITY.txt): 5 turns, no turn failed, final-turn input tokens >= 200000, turn-5 mean window.ple < 5 ms, "prefix cache budget: 6144 MiB" in the engine log, and for
# a sparse run the engine log shows no verification failure. An INVALID run is never used in a comparison.
#
# ACCEPTANCE (design doc T4; this script prints each line, it does not decide for the owner):
# G1 identity every forced row of every request: top-16 ids and logprobs BITWISE equal, sparse against full, and full against full (A/A) the same; 0 argmax flips. A lossless repack
# must be exactly equal, not "within tolerance".
# G2 memory system Shmem (/proc/meminfo, where a sealed memfd is counted) lower by 36.6 GiB +- 1.5 in the sparse arms at turn 5; MemAvailable at turn 5 higher by >= 35 GiB; swap in/out
# of the run zero in every arm. (The engine's own RssShmem is printed too, but a memfd that is not mlock-ed is not in its page tables, so it is not the gate.)
# G3 speed decode tok/s and TTFT per turn of sparse within the run-to-run noise of the full arms (decode-tail: 3-8 %); turn-5 window.ple unchanged. Reads hit the same pages, so no
# change is expected; a gain would be unexplained and a loss is a failure.
# G4 cap the prefix store stays at 6144 MiB in both arms (the engine log line) although the sparse arm has ~36 GiB more MemAvailable.
# NOT decided here: nothing about speed in other workloads, other hosts, the laptop (file-backed archive; no memfd there) or a different model.
set -uo pipefail
D=/data/leleka-e2e/decode/dt
LOCK=/data/leleka-e2e/gpu.lock
G=$HOME/work/gpu-runs
OUTR=/data/leleka-e2e/runs/sparsememfd-ab
CORPUS=/data/leleka-e2e/decode/corpus/src/crates
UP=/data/leleka-e2e/decode/assets/expert-profile-upstream.bin # ranked upstream profile; run-e2e.sh refuses any other digest
A=$HOME/work/leleka/models/leleka-gates/assets
KAR=${KAR:-$A/qwen-iq3-s-l2-v4.kar}
KAR_BYTES=55295529472
BIN=$D/bin-sparsememfd
RT=$D/rt-sparsememfd
CAP=/data/leleka-e2e/sm120/capture/night5-long-256k
RUN_TAG=${RUN_TAG:-} # suffix of the run directories (a rerun next to earlier ones)
PHASES=${PHASES:-"id e2e"}
ARMS=${ARMS:-"full sparse sparse full"}
EXTENTS_SHA256=${EXTENTS_SHA256:-}
SESSION_ARGS="--turns 5 --target-tokens 245000 --max-output 300 --min-final-tokens 200000"
CAP_MIB=6144
mkdir -p "$OUTR"
# ---- guards --------------------------------------------------------------------------------------------------------------------
for f in "$UP" "$D/tools/long-session.py" "$D/scripts/e2e/run-e2e.sh" "$BIN/leleka" "$BIN/leleka-inference" "$BIN/leleka-daemon" "$BIN/leleka-cli" "$BIN/strata-next" "$KAR" "$CORPUS/backend-api/src/lib.rs"; do
[ -r "$f" ] || { echo "missing $f" >&2; exit 3; }
done
case " $PHASES " in *" id "*) for f in "$RT" "$D/tools/q_pair.py" "$D/tools/q_lib.py" "$CAP"; do [ -e "$f" ] || { echo "missing $f (identity phase)" >&2; exit 3; }; done ;; esac
"$BIN/leleka" --help 2>&1 | grep -q "seal-exec" || { echo "$BIN/leleka has no seal-exec subcommand: build it from claude/sparse-memfd" >&2; exit 3; }
need_pin=0
case " $ARMS " in *" sparse "*) need_pin=1 ;; esac
case " $PHASES " in *" id "*) need_pin=1 ;; esac
if [ $need_pin = 1 ]; then
echo "$EXTENTS_SHA256" | grep -Eq '^[0-9a-f]{64}$' || { echo "EXTENTS_SHA256 must be the 64 hex digits printed by 'kar_census ARCHIVE --hash-extents' (docs/kar-sparse-memfd.md)" >&2; exit 3; }
fi
[ "$(stat -c %s "$KAR")" = "$KAR_BYTES" ] || { echo "$KAR is not $KAR_BYTES bytes" >&2; exit 3; }
if [ -d "$G/MODEL.lock" ]; then echo "refusing to start: $G/MODEL.lock exists (the holder is running). This job makes its own memfd; stop the holder first, a second 55 GB memfd does not fit" >&2; exit 3; fi
shmem_gib=$(awk '/^Shmem:/{print int($2/1048576)}' /proc/meminfo)
if [ "$shmem_gib" -ge 8 ]; then echo "refusing to start: Shmem is $shmem_gib GiB (a sealed memfd is still resident; stop the holder)" >&2; exit 3; fi
# ---- the environment of the processes (copied from run-e2e.sh / draftvocab-id.sh; nothing here differs between arms) ----------------------
export LD_LIBRARY_PATH=$HOME/cuda-toolkits/cublas-12.9.1.4/lib:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-}
take_locks() { # $1 label: gpu.lock, then MODEL.lock; 0 on success
local got=0
for _ in $(seq 1 1080); do
if mkdir "$LOCK" 2>/dev/null; then echo "sparse-memfd-ab $1 $(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)"; return 3; }
if [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null)" ]; then
echo "GPU busy, skipping $1"; rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null; return 4
fi
if ! mkdir "$G/MODEL.lock" 2>/dev/null; then echo "MODEL.lock appeared ($G): the holder is back; skipping $1"; rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null; return 5; fi
return 0
}
drop_locks() { rmdir "$G/MODEL.lock" 2>/dev/null; rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null; }
trap 'drop_locks' EXIT
sampler() { # $1 output file; runs until killed
while sleep 5; do
pid=$(pgrep -u "$USER" -x leleka-inference | head -1)
eng=""; [ -n "$pid" ] && eng=$(awk '/^(RssAnon|RssShmem|VmLck):/{printf "%s%s ", $1, $2}' /proc/$pid/status 2>/dev/null)
echo "$(date +%T) $(grep -E "SwapFree|MemAvailable|^Cached|^Shmem:|Dirty" /proc/meminfo | tr -s " " | tr "\n" " ") $(head -1 /proc/pressure/io) $(head -1 /proc/pressure/memory) $(awk '/pswpin|pswpout|pgmajfault/{printf "%s=%s ", $1, $2}' /proc/vmstat) ENGINE ${eng:-none}"
done > "$1" 2>/dev/null
}
record() { # $1 file, $2 arm, $3 tag
{ echo "arm=$2 tag=$3"; date -u +%FT%TZ; uname -r; nvidia-smi --query-gpu=driver_version --format=csv,noheader
echo "page cache NOT dropped (no write access to /proc/sys/vm); meminfo at start:"; grep -E "MemTotal|MemAvailable|^Cached|^Shmem:|SwapFree" /proc/meminfo; free -g | sed -n 2p
echo "extents_sha256=${EXTENTS_SHA256:-none} (arm sparse only)"; sha256sum "$UP" "$BIN"/leleka "$BIN"/leleka-inference "$BIN"/leleka-daemon "$BIN"/leleka-cli "$BIN"/strata-next ${RT:+"$RT"} 2>/dev/null
cat "$BIN/COMMIT.txt" 2>/dev/null; head -1 /data/leleka-e2e/decode/corpus/MANIFEST.txt
env | grep -E '^(LELEKA_|STRATA_|E2E_)' | sort; } > "$1"
}
# the sealed memfd of an arm, then the command: `{FD}` is the descriptor number (replaced by leleka seal-exec)
seal_run() { # $1 arm; rest: the command words (bash -c STRING ...)
local arm=$1; shift
local flag=""; [ "$arm" = sparse ] && flag="--sparse-ple"
"$BIN/leleka" seal-exec --file "$KAR" --expect-bytes $KAR_BYTES $flag -- "$@"
}
# ---- phase id: teacher-forced replay, top-16 logprobs, equal fixed slot count -----------------------------------------------------------
OI=$OUTR/id$RUN_TAG
id_env() { # the replay stack, as draftvocab-id.sh
export LELEKA_STRA169_KAR_PROVENANCE=$A/qwen-iq3-s-l2-v4.kar.provenance.json
export LELEKA_STRA169_IQ3S_SHARD0=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf
export LELEKA_STRA169_IQ3S_SHARD1=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf
export LELEKA_STRA169_MTP_PACK=$A/data/mtp-rt LELEKA_STRA169_MTP_STAGING=$G/mtp-staging-own LELEKA_ORIGINAL_SERVE_BUDGET_GIB=30
export LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=yes LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.55
export LELEKA_SMOKE_PROMPT_CACHE=0 LELEKA_SERVE_PROFILE=1 LELEKA_GRAPH_EXEC_REUSE=off
export LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$UP LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=8000 LELEKA_CHAIN=all
export LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0 LELEKA_ORIGINAL_SERVE_SEED=off LELEKA_ORIGINAL_SERVE_CPU_WORKERS=1 LELEKA_SPEC=4 LELEKA_SPEC_SUFFIX=0
export LELEKA_ORIGINAL_SERVE_RT_DIR=$A/data/mtp-rt
unset LELEKA_DRAFT_VOCAB LELEKA_SERVE_DRAFT_AFTER_COMMIT LELEKA_PROMPT_EMBED_ALIAS LELEKA_VRAM_LEDGER LELEKA_DENSE_SLAB LELEKA_KAR_SPARSE_EXTENTS_SHA256
}
id_run() { # $1 arm
local arm=$1 label=id-$1
take_locks "$label" || return $?
install -d -m 0700 "$G/mtp-staging-own"
echo "=== $label $(date -u +%FT%TZ)"; free -g | sed -n 2p
( id_env
[ "$arm" = sparse ] && export LELEKA_KAR_SPARSE_EXTENTS_SHA256=$EXTENTS_SHA256
shape="reply@8192/8192!orig!fast!nocluster!store!qpf!gpool!mspan"
export LELEKA_ORIGINAL_SERVE_REPLAY=yes LELEKA_BRINGUP_TRACE=1 LELEKA_REPLAY_DIR=$CAP LELEKA_PREFIX_TRACE=1 LELEKA_REPLAY_PREFIX_MIB=6000 LELEKA_TRACE_PREFILL_R=1 LELEKA_TRACE_LOGPROBS=16
export LELEKA_REPLAY_MAX_NEW=48 LELEKA_REPLAY_FORCE=1 LELEKA_REPLAY_ARMS="I1=$shape,I2=$shape"
record "$OI/$label.env" "$arm" "$label"
sampler "$OI/$label.memsample.txt" & SAMP=$!
seal_run "$arm" bash -c 'LELEKA_STRA169_KAR_FD={FD} exec nice -n 5 "$0" --ignored --exact --test-threads=1 --nocapture backend::original_serve_replay::original_serve_replay_smoke' "$RT" > "$OI/$label.full" 2>&1
echo "rc=$? label=$label"; kill $SAMP 2>/dev/null )
grep -a -E "leleka-seal-exec|leleka seal-exec|^REPLAY|test result|panicked|FAILED|expert cache [0-9]+ slots|prefix cache budget" "$OI/$label.full" | cut -c1-300 | tail -12
drop_locks
sleep 15
}
# ---- phase e2e: the session A/B -------------------------------------------------------------------------------------------------
e2e_run() { # $1 tag, $2 arm
local tag=$1 arm=$2
take_locks "$tag" || return $?
echo "=== $tag $(date -u +%FT%TZ)"; free -g | sed -n 2p
( export E2E_BIN=$BIN E2E_OUT=$OUTR/$tag
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:-32819404800}
export E2E_ENGINE_ARGS="--prefix-cache-mib $CAP_MIB --prefix-cache-tail reply --original-prefill-capacity 8192 --prefix-cache-block 8192 --spec-min-p 0"
[ "$arm" = sparse ] && E2E_ENGINE_ARGS="$E2E_ENGINE_ARGS --kar-sparse-extents-sha256 $EXTENTS_SHA256"
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 LELEKA_DRAFT_VOCAB
export LELEKA_ORIGINAL_SERVE_SEED=off
export E2E_RUN_CMD="python3 -I $D/tools/long-session.py --src $CORPUS $SESSION_ARGS"
record "$E2E_OUT/env-arm.txt" "$arm" "$tag"
sampler "$E2E_OUT/memsample.txt" & SAMP=$!
seal_run "$arm" bash -c 'LELEKA_STRA169_KAR_FD={FD} exec bash "$0"' "$D/scripts/e2e/run-e2e.sh" 2>&1 | grep -a -E "^\{|leleka-seal-exec|leleka seal-exec|expert cache|prefix cache budget|request outcome|ready after|rc=|refus|error|Error|long_session|client exit" | cut -c1-300
kill $SAMP 2>/dev/null
echo "run-e2e done $tag $(date -u +%FT%TZ)" )
drop_locks
sleep 15
}
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
log = open(os.path.join(d, "inference.log"), errors="replace").read() if os.path.exists(os.path.join(d, "inference.log")) else ""
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)
elif "prefix cache budget: 6144 MiB" not in log:
verdict = "INVALID: the engine log has no 'prefix cache budget: 6144 MiB' (cap not in force: the arms would differ)"
elif arm == "sparse" and re.search(r"leleka-kar phase=\w+ class=(ExtentsSha|ArchiveSha|Integrity|Range)", log):
verdict = "INVALID: the sparse memfd failed verification"
else:
verdict = "VALID: 5 turns, final-turn input tokens %d" % final
wins, last = [], []
for ln in log.splitlines():
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
open(os.path.join(d, "VALIDITY.txt"), "w").write(verdict + "\n")
print(os.path.basename(d), verdict)
PY
}
# ---- run ------------------------------------------------------------------------------------------------------------------------
case " $PHASES " in
*" id "*)
mkdir -p "$OI"
id_run full; id_run sparse
;;
esac
case " $PHASES " in
*" e2e "*)
n=0
for arm in $ARMS; do
case $arm in full|sparse) ;; *) echo "unknown arm $arm" >&2; exit 2 ;; esac
n=$((n + 1)); tag="$arm-r$n$RUN_TAG"
e2e_run "$tag" "$arm" || continue
validity "$OUTR/$tag" "$arm"
echo "arm done $tag $(date -u +%FT%TZ)"
done
;;
esac
# ---- summary --------------------------------------------------------------------------------------------------------------------
OUTR=$OUTR OI=$OI PHASES="$PHASES" python3 -I - <<'PY'
import glob, json, os, re, statistics as st, sys
root, oi, phases = os.environ["OUTR"], os.environ["OI"], os.environ["PHASES"].split()
if "id" in phases:
print("== G1 identity: top-16 rows of the teacher-forced replay (night5-long-256k), arm I1 and I2 of each process")
sys.path.insert(0, "/data/leleka-e2e/decode/dt/tools")
try:
import q_pair
logs = {a: os.path.join(oi, "id-%s.full" % a) for a in ("full", "sparse")}
rows = {a: [q_pair.rows_of(logs[a], i) for i in (0, 1)] for a in logs if os.path.exists(logs[a])}
verdicts = []
def cmp(a, b, label):
n, bad, flips, _ = q_pair.compare(a, b, label)
verdicts.append((label, n, bad, flips))
if "full" in rows:
cmp(rows["full"][0], rows["full"][1], "full, arm1 against arm0 (A/A noise floor; must be 0 different)")
if "sparse" in rows:
cmp(rows["sparse"][0], rows["sparse"][1], "sparse, arm1 against arm0 (A/A)")
if "full" in rows and "sparse" in rows:
cmp(rows["full"][0], rows["sparse"][0], "sparse against full, arm0")
cmp(rows["full"][1], rows["sparse"][1], "sparse against full, arm1")
ok = bool(verdicts) and all(n > 0 and bad == 0 and flips == 0 for _, n, bad, flips in verdicts)
print("G1 %s: %s" % ("PASS" if ok else "FAIL or incomplete", "; ".join("%s: common %d different %d flips %d" % v for v in verdicts)))
except Exception as e: # the tools may be missing; the logs are still there
print("G1 not computed:", e)
if "e2e" not in phases:
sys.exit(0)
def run_number(path):
tail = path.rsplit("-r", 1)[-1]
return int(re.sub(r"\D.*", "", tail) or 0)
runs, order = {}, []
for d in sorted(glob.glob(os.path.join(root, "*-r*")), key=run_number):
name = os.path.basename(d)
v = os.path.join(d, "VALIDITY.txt")
if not os.path.exists(v) or not open(v).read().startswith("VALID"):
print(name, "not used:", open(v).read().strip() if os.path.exists(v) else "no VALIDITY.txt")
continue
t = json.load(open(os.path.join(d, "long-session.json")))
runs[name] = dict(dec=[x.get("decode_tok_s") or 0.0 for x in t], ttft=[x.get("ttft_s") or 0.0 for x in t], tokens=[x.get("input_tokens") for x in t], cached=[x.get("cached_tokens") for x in t])
order.append(name)
def arm(name):
return name.rsplit("-r", 1)[0]
def line(label, xs, fmt="%.1f"):
return "%s %s mean %.2f" % (label, " ".join(fmt % x for x in xs), st.mean(xs))
for k in order:
print(k, "tokens", runs[k]["tokens"], "cached", runs[k]["cached"])
print(" " + line("decode tok/s", runs[k]["dec"]))
print(" " + line("ttft s ", runs[k]["ttft"]))
by = {}
for k in order:
by.setdefault(arm(k), []).append(k)
if "full" in by and "sparse" in by:
print("== G3 speed: per-turn mean of the repeats, sparse minus full, against the spread of the full arms (the A/A noise)")
for metric in ("dec", "ttft"):
mean = {a: [st.mean(c) for c in zip(*[runs[k][metric] for k in ks])] for a, ks in by.items()}
diff = [100 * (s / f - 1) if f else float("nan") for s, f in zip(mean["sparse"], mean["full"])]
fulls = [runs[k][metric] for k in by["full"]]
spread = [100 * (max(c) - min(c)) / st.mean(c) if st.mean(c) else float("nan") for c in zip(*fulls)] if len(fulls) > 1 else []
print("%s: full %s | sparse %s | sparse vs full per turn %s %%%s" % (metric, " ".join("%.1f" % x for x in mean["full"]), " ".join("%.1f" % x for x in mean["sparse"]),
" ".join("%+.1f" % x for x in diff), (" | full-vs-full spread %s %%" % " ".join("%.1f" % x for x in spread)) if spread else " | only one full run: no noise estimate"))
pairs = []
for i, k in enumerate(order[:-1]):
n = order[i + 1]
if {arm(k), arm(n)} == {"full", "sparse"}:
f, s = (k, n) if arm(k) == "full" else (n, k)
pairs.append(100 * (st.mean(runs[s]["dec"]) / st.mean(runs[f]["dec"]) - 1))
if pairs:
print("adjacent (full, sparse) pairs, all-turn mean decode tok/s, sparse over full: %s %% mean %+.2f %%" % (" ".join("%+.2f" % x for x in pairs), st.mean(pairs)))
print("== G2 memory (from memsample.txt; MemAvailable and Shmem in GiB at the last sample before the engine stopped, engine RssShmem/RssAnon/VmLck in GiB)")
mem = {}
for k in order:
f = os.path.join(root, k, "memsample.txt")
if not os.path.exists(f):
continue
lines = [l for l in open(f, errors="replace") if "ENGINE" in l and "RssShmem" in l]
if not lines:
print(k, "no engine sample")
continue
pick = lambda l, name: next((int(m) for m in re.findall(r"(?<![A-Za-z])" + name + r":?\s*(\d+)", l)), None)
last = lines[-1]
shmem_engine = pick(last, "RssShmem")
shmem_system = pick(last, "Shmem")
avail = pick(last, "MemAvailable")
swaps = [int(m) for l in (lines[0], last) for m in re.findall(r"pswp(?:in|out)=(\d+)", l)]
swapped = (swaps[2] - swaps[0] + swaps[3] - swaps[1]) if len(swaps) == 4 else None
mem[k] = dict(shmem=(shmem_system or 0) / 1048576, avail=(avail or 0) / 1048576, swap=swapped)
print("%-12s system Shmem %.2f GiB engine RssShmem %.2f GiB MemAvailable %.2f GiB pages swapped in+out during the run: %s (last sample with an engine: %s)" % (k, mem[k]["shmem"], (shmem_engine or 0) / 1048576, mem[k]["avail"], swapped, last.split()[0]))
if "full" in by and "sparse" in by and all(k in mem for k in order):
f = st.mean(mem[k]["shmem"] for k in by["full"]); s = st.mean(mem[k]["shmem"] for k in by["sparse"])
fa = st.mean(mem[k]["avail"] for k in by["full"]); sa = st.mean(mem[k]["avail"] for k in by["sparse"])
print("G2 system Shmem: full %.2f sparse %.2f GiB, lower by %.2f GiB (expected 36.6 +- 1.5): %s" % (f, s, f - s, "PASS" if abs((f - s) - 36.6) <= 1.5 else "FAIL"))
print("G2 MemAvailable: full %.2f sparse %.2f GiB, higher by %.2f GiB (expected >= 35): %s" % (fa, sa, sa - fa, "PASS" if sa - fa >= 35 else "FAIL"))
print("G2 swap: %s" % ("PASS (zero pages swapped in every run)" if all((mem[k]["swap"] or 0) == 0 for k in order) else "FAIL or unknown: " + str({k: mem[k]["swap"] for k in order})))
print("== G4 cap: the engine log line of every run")
for k in order:
log = os.path.join(root, k, "inference.log")
if os.path.exists(log):
got = [l.strip()[:200] for l in open(log, errors="replace") if "prefix cache budget:" in l][:1]
print(k, got or "NO LINE (cap unverified)")
PY
sha256sum "$OUTR"/*/long-session.json "$OI"/*.full 2>/dev/null | head -40
date -u +%FT%TZ