Laptop identity gate: base-vs-new bitwise comparison on the 3080 (identity-gate.sh, identity_compare.py with self-test, lap_lib.sh gates and the gpu-wanted flag)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-11-14 11:54:45 +01:00
co-authored by Claude Sonnet 5.5
parent 4336283163
commit e9580fb6b9
3 changed files with 279 additions and 0 deletions
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env bash
# LAPTOP identity gate (bitwise, base against new, on the RTX 3080 laptop; inside WSL2). One command verifies a refactor:
#
# bash scripts/laptop/identity-gate.sh [--base REF=23bdbb308] [--new REF=main] [--out DIR] [--steps prepare,run,compare] [--four]
#
# What it compares: the evidence lines of the laptop bench (`original_serve_laptop_bench`, the Original serve stack in the laptop form: mapped experts, KAR file,
# MTP depth 4) for two fixed agent-style prompts of 2,048 and 3,072 tokens (below the context where the sm_86 prefill fault of STRA-235 shows), greedy, 96 new
# tokens each, every prompt served twice in one process (pass 0, pass 1), tier placement frozen (3,000 slots from the profile, no adaptive swaps, seed off, global
# fill, 7 CPU workers, no prefix cache). Evidence per request, bit for bit: the residual hash of every prompt chunk (PREFILL-R), the top-16 log-probability rows
# and argmax ids of every verify window, the draft trace with the IEEE bits of the probabilities, and the output token ids.
#
# Processes (one engine load each, ~10 GPU-minutes, every one under the laptop safety protocol: flag, build/memory gates, lock, 15 s guard, power-limit
# preflight): P1 base, P2 new, P3 base again; with --four also P4 new again. The A/A floor comes first and must be ZERO differences: pass 1 against pass 0 inside P1
# and P2, and P3 against P1 across processes. Only then are `P2 against P1` (new against base) and, with --four, `P4 against P2` read. VERDICT IDENTICAL means
# every pair is identical and every evidence category was present. A DIFFERENT floor means the gate cannot judge the refactor on this machine (run-to-run
# nondeterminism); say so rather than reading new against base.
#
# Inputs are frozen under OUT/inputs (corpus from the base tree's docs, the two prompt files, MANIFEST.sha256) and refused when a digest differs. The two engine test
# binaries are built from exported source trees (`git archive`, no worktree metadata) under OUT/src-<label>-<sha9>, target dirs inside OUT. OUT defaults to
# C:\Users\pavel\work\leleka\.git\laptop-identity (untracked). Re-running `run` repeats the processes; `prepare` is idempotent.
set -uo pipefail
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO=${LAP_REPO:-/mnt/c/Users/pavel/work/leleka}
base=23bdbb308; new=main; out="$REPO/.git/laptop-identity"; steps=prepare,run,compare; four=0
while [ $# -gt 0 ]; do case "$1" in
--base) base=$2; shift 2;; --new) new=$2; shift 2;; --out) out=$2; shift 2;; --steps) steps=$2; shift 2;; --four) four=1; shift;;
*) echo "unknown argument $1" >&2; exit 2;; esac; done
source "$here/lap_lib.sh"
# shellcheck disable=SC1090
source "$HOME/.cargo/env"
git_in_repo() { git -c safe.directory='*' -C "$REPO" "$@"; }
sha_of() { git_in_repo rev-parse --verify "$1^{commit}"; }
bin_of() { echo "$out/bin/rt-$1-${2:0:9}"; }
mkdir -p "$out/bin" "$out/inputs" "$out/runs" "$out/mtp-staging"; chmod 700 "$out/mtp-staging"
base_sha=$(sha_of "$base") || { echo "unknown ref $base" >&2; exit 2; }
new_sha=$(sha_of "$new") || { echo "unknown ref $new" >&2; exit 2; }
export_tree() { # label sha: the source tree of a commit, exported once
local dir="$out/src-$1-${2:0:9}"
[ -d "$dir/crates" ] || { mkdir -p "$dir" && git_in_repo archive "$2" | tar -x -C "$dir"; }
echo "$dir"
}
build_test_binary() { # label sha
local dir bin log
dir=$(export_tree "$1" "$2"); bin=$(bin_of "$1" "$2"); log="$out/build-$1-${2:0:9}.log"
[ -x "$bin" ] && { echo "binary present: $bin"; return 0; }
while [ -e "$LAP_LOCK" ]; do echo "a GPU stretch holds the lock: the build waits"; sleep 30; done
( cd "$dir" && CARGO_TARGET_DIR="$dir/target" CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-8} \
cargo test --release --locked -p leleka-engine-qwen35-cuda --features sm86 --lib --no-run --message-format=json > "$log" 2> "$log.err" ) || { tail -5 "$log.err"; return 1; }
local exe; exe=$(grep -o '"executable":"[^"]*leleka_engine_qwen35_cuda-[^"]*"' "$log" | tail -1 | cut -d'"' -f4)
[ -n "$exe" ] && cp "$exe" "$bin" && sha256sum "$bin" | tee -a "$out/binaries.sha256"
}
make_inputs() { # frozen corpus and the two prompts, from the BASE tree
[ -s "$out/inputs/MANIFEST.sha256" ] && return 0
local dir tok; dir=$(export_tree base "$base_sha"); tok="$HOME/leleka-assets/tokenizer-assets/tokenizer"
cat "$dir"/docs/laptop-profile.md "$dir"/docs/windows.md "$dir"/docs/deploy.md "$dir"/docs/laptop-vs-vanilla.md > "$out/inputs/corpus.txt"
( cd "$dir" && CARGO_TARGET_DIR="$dir/target" cargo run --release --locked -q -p leleka-tokenizer --example long_prompts -- "$tok" "$out/inputs/corpus.txt" "$out/inputs" 2048 3072 ) || return 1
cat "$out/inputs/prompt-2048.ids" "$out/inputs/prompt-3072.ids" > "$out/inputs/prompts.ids"
( cd "$out/inputs" && sha256sum corpus.txt prompt-2048.ids prompt-3072.ids prompts.ids > MANIFEST.sha256 && chmod a-w ./* )
}
bench_env() { # the frozen configuration of every process
local m="$HOME/leleka-assets"
export LELEKA_LAPTOP_BENCH=yes LELEKA_LAPTOP_KAR_FILE="$m/qwen-iq3-s-l2-v4.kar" LELEKA_STRA169_KAR_PROVENANCE="$m/qwen-iq3-s-l2-v4.kar.provenance.json"
export LELEKA_STRA169_IQ3S_SHARD0="$m/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf" LELEKA_STRA169_IQ3S_SHARD1="$m/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf"
export LELEKA_STRA169_MTP_PACK="$m/data/mtp-rt" LELEKA_STRA169_MTP_STAGING="$out/mtp-staging" LELEKA_ORIGINAL_SERVE_RT_DIR="$m/data/mtp-rt"
export LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE="$m/data/expert-profile.bin" LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=3000 LELEKA_ORIGINAL_SERVE_BUDGET_GIB=15
export LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0 LELEKA_ORIGINAL_SERVE_SEED=off LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=no LELEKA_LAPTOP_CPU_WORKERS=7
export LELEKA_LAPTOP_PROMPT_IDS="$out/inputs/prompts.ids" LELEKA_LAPTOP_PROMPT_CACHE=0 LELEKA_LAPTOP_MAX_NEW=96 LELEKA_LAPTOP_REPEAT=2
export LELEKA_BRINGUP_TRACE=1 LELEKA_TRACE_LOGPROBS=16 LELEKA_TRACE_DRAFT=1 LELEKA_TRACE_PREFILL_R=1
export LD_LIBRARY_PATH="$(ls -d "$HOME"/cublas-12.9.1.4/x/*/lib 2>/dev/null | head -1):${LD_LIBRARY_PATH:-}"
}
run_process() { # n label sha
local n="$1" label="$2" bin res
bin=$(bin_of "$label" "$3"); res="$out/runs/$n-$label"; mkdir -p "$res"
[ -x "$bin" ] || { echo "missing binary $bin (run the prepare step)" >&2; return 3; }
( cd "$out/inputs" && sha256sum --quiet -c MANIFEST.sha256 ) || { echo "inputs differ from MANIFEST.sha256" >&2; return 3; }
printf '#!/usr/bin/env bash\npkill -TERM -f "%s/bin/rt-" 2>/dev/null\n' "$out" > "$out/stop-bench.sh"
lap_wait_and_lock "identity $n $label"
lap_preflight "$res" || { echo "REFUSED: $n $label (preflight)"; lap_done; return 4; }
bash "$here/lap_guard.sh" "$res/guard.tsv" "$res/run.log" "$out/stop-bench.sh" 15 2> "$res/guard.err" &
bench_env
timeout -s TERM -k 30 1800 "$bin" --ignored --exact backend::original_serve_laptop::original_serve_laptop_bench --nocapture --test-threads 1 > "$res/run.out" 2> "$res/run.log"
local rc=$?; touch "$res/guard.tsv.done"; lap_done; [ -e "$res/guard.tsv.abort" ] && echo "GUARD ABORT: $(head -1 "$res/guard.tsv.abort")"
echo "process $n $label rc=$rc log $(wc -l < "$res/run.log") lines"; [ "$rc" = 0 ] || return 5
[ -e "$res/guard.tsv.abort" ] && { echo "GUARD ABORT: $(head -1 "$res/guard.tsv.abort")"; return 5; }
return 0
}
compare_all() {
local r="$out/runs"; local args=(--prompts 2 "base1=$r/1-base/run.log" "new1=$r/2-new/run.log" "base2=$r/3-base/run.log" --pair base1 base1 --pair new1 new1 --pair base1 base2 --pair base1 new1)
[ -s "$r/4-new/run.log" ] && args+=("new2=$r/4-new/run.log" --pair new1 new2)
echo "base $base ($base_sha) against new $new ($new_sha)"; python3 -I "$here/identity_compare.py" "${args[@]}" | tee "$out/verdict.txt"
}
case ",$steps," in *,prepare,*) build_test_binary base "$base_sha" && build_test_binary new "$new_sha" && make_inputs || exit 1;; esac
case ",$steps," in *,run,*)
trap 'lap_done' EXIT
run_process 1 base "$base_sha" && run_process 2 new "$new_sha" && run_process 3 base "$base_sha" || { echo "a process did not complete: no verdict" >&2; exit 4; }
[ "$four" = 1 ] && { run_process 4 new "$new_sha" || exit 4; };; esac
case ",$steps," in *,compare,*) compare_all;; esac
+126
View File
@@ -0,0 +1,126 @@
#!/usr/bin/env python3
"""Bitwise comparison of the evidence lines of laptop identity runs (scripts/laptop/identity-gate.sh).
The laptop bench (`original_serve_laptop_bench`) is run with LELEKA_BRINGUP_TRACE=1 LELEKA_TRACE_LOGPROBS=16 LELEKA_TRACE_DRAFT=1
LELEKA_TRACE_PREFILL_R=1 and serves every prompt twice in one process (pass 0, pass 1). The evidence of a request is, in order of the log:
PREFILL-R lines residual hash of every prompt chunk
DBG logprobs window the window's inputs and argmax ids, followed by its tab-separated top-16 rows (position, target, lp, top1, lp, ...)
DRAFT lines position, accepted row, first cell, draft ids and the IEEE bits of the probabilities
LAPTOP output the output token ids of the first pass (printed once per prompt)
identity_compare.py --prompts N LABEL=LOG [LABEL=LOG ...] --pair A B [--pair C D ...]
identity_compare.py --self-test
Each log is split into passes by its `LAPTOP request` lines (N prompts per pass). A pair `A B` compares pass 0 and pass 1 of the two runs line
by line; a pair `A A` is the floor inside one process (pass 1 against pass 0). Verdict per pair: IDENTICAL (same number of lines, every line equal) or the
first differing line with its index. Exit 0 only when every pair is identical and at least one evidence line was compared per category.
"""
import argparse
import sys
CATEGORIES = ("PREFILL-R", "logprobs window", "DRAFT", "LAPTOP output")
def category(line):
if line.startswith("PREFILL-R"):
return "PREFILL-R"
if line.startswith("DBG logprobs window"):
return "logprobs window"
if line.startswith("DRAFT "):
return "DRAFT"
if line.startswith("LAPTOP output"):
return "LAPTOP output"
return None
def is_row(line):
"""A top-k row of the line before it: tab separated, starts with the position."""
return "\t" in line and line[:1].isdigit()
def passes(text, prompts):
"""The evidence lines of each pass: [(category, line), ...] per pass index."""
out, requests, previous = {}, 0, None
for raw in text.splitlines():
line = raw.rstrip("\r\n")
if line.startswith("LAPTOP request"):
requests += 1
previous = None
continue
kind = category(line)
if kind is None and previous == "logprobs window" and is_row(line):
kind = "logprobs row"
if kind is None:
previous = None if not is_row(line) else previous
continue
previous = kind if kind in ("logprobs window", "logprobs row") else None
out.setdefault(requests // prompts, []).append((kind, line))
return out
def compare(a, b, label):
kinds = {}
for kind, _ in a:
kinds[kind] = kinds.get(kind, 0) + 1
if len(a) != len(b):
print(f"{label}: DIFFERENT, {len(a)} against {len(b)} evidence lines")
return False
for i, ((ka, la), (kb, lb)) in enumerate(zip(a, b)):
if la != lb:
print(f"{label}: DIFFERENT at evidence line {i} ({ka})\n A: {la[:300]}\n B: {lb[:300]}")
return False
missing = [c for c in ("PREFILL-R", "logprobs window", "logprobs row", "DRAFT") if kinds.get(c, 0) == 0]
if not a or missing:
print(f"{label}: NO EVIDENCE ({len(a)} lines, missing {missing or 'everything'}): not a pass")
return False
print(f"{label}: IDENTICAL, {len(a)} lines " + ", ".join(f"{k} {n}" for k, n in sorted(kinds.items())))
return True
def run(args):
logs = {}
for item in args.logs:
label, _, path = item.partition("=")
with open(path, encoding="utf-8", errors="replace") as handle:
logs[label] = passes(handle.read(), args.prompts)
ok = True
for first, second in args.pair:
for index in (0, 1):
if first == second:
if index == 1:
ok &= compare(logs[first].get(0, []), logs[first].get(1, []), f"{first} pass 1 against pass 0 (A/A floor)")
continue
ok &= compare(logs[first].get(index, []), logs[second].get(index, []), f"{second} against {first}, pass {index}")
print("VERDICT:", "IDENTICAL" if ok else "DIFFERENT or no evidence")
return 0 if ok else 1
def self_test():
def log(extra=""):
lines = []
for _ in range(2): # two passes of one prompt
lines += ["PREFILL-R first=0 rows=2048 fnv1a64=abc", "DBG logprobs window position=5 inputs=[1, 2] argmax_ids=[3]",
"5\t3\t-0.1\t3\t-0.1\t1", "DRAFT position=5 accepted_row=0 cell=9 ids=[4] pbits=[3f800000]" + extra,
"LAPTOP request 1: x"]
return "\n".join(lines)
same, other = passes(log(), 1), passes(log("1"), 1)
assert compare(same[0], same[1], "floor")
assert not compare(same[0], other[1], "different")
assert not compare([], [], "empty")
print("self-test ok")
return 0
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--prompts", type=int, default=1)
parser.add_argument("--pair", nargs=2, action="append", default=[])
parser.add_argument("--self-test", action="store_true")
parser.add_argument("logs", nargs="*")
args = parser.parse_args()
return self_test() if args.self_test else run(args)
if __name__ == "__main__":
sys.exit(main())
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env bash
# Shared gates of the laptop GPU runs (source it; inside WSL2): the fairness flag, the build and memory gates, the lock, the preflight and the
# guard. The protocol is the owner's safety protocol of 2026-11-13 (docs/laptop-profile.md "Update 2026-11-13"); lap_stretch.sh carries an older
# copy of the same logic and is to be reduced to a user of this file once no stretch is waiting on it.
#
# lap_want_gpu LABEL create the flag C:\...\.git\laptop-gpu-wanted.flag: the refactor agents start no new build while it exists
# lap_wait_and_lock LABEL wait for: no cargo/rustc/link in WSL or Windows, Windows available RAM >= 10 GB, no lock; then take the lock
# lap_preflight RESULT_DIR refuse (return 4) at a power limit < 100 W, SW cap / thermal slowdown at idle, P5, a bad turbo watchdog, WSL RAM < 10 GB
# lap_done remove the lock and the flag (call from a trap)
# lap_gpu_idle_check print the GPU state line
LAP_REPO=${LAP_REPO:-/mnt/c/Users/pavel/work/leleka}
LAP_LOCK="$LAP_REPO/.git/laptop-gpu-run.lock"
LAP_FLAG="$LAP_REPO/.git/laptop-gpu-wanted.flag"
LAP_AGENT=${LAP_AGENT:-laptop-3080-live}
LAP_HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
lap_want_gpu() { echo "$LAP_AGENT $(date -u +%FT%TZ) $1" > "$LAP_FLAG"; }
lap_builds_running() {
{ pgrep -x cargo || pgrep -x rustc || pgrep -x ld || pgrep -x cc1plus; } >/dev/null 2>&1 && return 0
[ "$(powershell.exe -NoProfile -Command 'Get-Process cargo,rustc,link,lld-link -ErrorAction SilentlyContinue | Measure-Object | % Count' | tr -dc '0-9')" != 0 ]
}
# Windows "available" physical memory (free + standby), whole GB; the WSL VM's page cache is held by vmmemWSL and does not count.
lap_windows_avail_gb() {
powershell.exe -NoProfile -Command 'Add-Type -AssemblyName Microsoft.VisualBasic; [math]::Floor((New-Object Microsoft.VisualBasic.Devices.ComputerInfo).AvailablePhysicalMemory/1GB)' | tr -dc '0-9'
}
lap_power_limit_w() { nvidia-smi -q -d POWER | awk -F: '/Current Power Limit/ && $2 !~ /N\/A/ {gsub(/[ W]/, "", $2); printf "%d", $2; exit}'; }
# Waits as long as it takes (the caller bounds it with `timeout` when it must report), then holds the lock.
lap_wait_and_lock() {
lap_want_gpu "$1"
until ! lap_builds_running && [ "$(lap_windows_avail_gb)" -ge 10 ] && (set -C; echo "$LAP_AGENT $(date -u +%FT%TZ) $1" > "$LAP_LOCK") 2>/dev/null; do sleep 20; done
}
lap_done() { rm -f "$LAP_LOCK" "$LAP_FLAG"; }
lap_preflight() {
local res="$1" lim q avail wfree turbo
lim=$(lap_power_limit_w); q=$(nvidia-smi -q -d PERFORMANCE,POWER)
avail=$(awk '$1=="MemAvailable:" {printf "%d", $2/1048576}' /proc/meminfo); wfree=$(lap_windows_avail_gb)
turbo=$(bash "$LAP_HERE/turbo_status.sh")
echo "preflight: limit=${lim:-?} W $(nvidia-smi --query-gpu=pstate,temperature.gpu,clocks.sm --format=csv,noheader) wsl_avail=${avail} GB win_avail=${wfree} GB turbo=${turbo}" | tee "$res/preflight.txt"
[ "${lim:-0}" -ge 100 ] || return 4
! grep -E "SW Power Cap|SW Thermal Slowdown" <<< "$q" | grep -q ": Active" || return 4
! grep "Performance State" <<< "$q" | grep -q P5 || return 4
[ "${turbo%% *}" != BAD ] && [ "$avail" -ge 10 ] && [ "${wfree:-0}" -ge 10 ]
}