validity.py trusted --machine alone, so laptop records declared "server" skipped the 100 W power floor and the owner attestation. derive_pairs now refuses (MACHINE_MISMATCH, exit 3, run ids named) records whose hardware.machine_role differs from the declared machine and a "server" declaration over a Laptop GPU. A schedule `machine` key pre-registers the machine; run_core finalize reads it from there (--machine only a fallback) and refuses a conflicting flag. The golden fixture builder stamps machine_role = machine; golden cases unchanged (0 differences). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
669 lines
38 KiB
Python
669 lines
38 KiB
Python
#!/usr/bin/env python3
|
|
"""Run capture, OURS arm (STRA-251, S0.2 of STRA-245): build ONE S0.1 END_TO_END record from a finished run. Offline tooling, stdlib only,
|
|
Python >= 3.9, Windows and Linux. It reads outputs; it never launches the engine, a GPU job or the replay driver, and it changes no
|
|
existing file. Records belong in the run root (server ~/work/leleka-e2e/runs/<series>/<pair>/<arm>/, laptop main checkout artifacts/runs),
|
|
never in Git.
|
|
|
|
CLI v1 (fixed by the leaf):
|
|
|
|
capture.py --arm ours --meta META.json --replay-output REPLAY.json --engine-log strata-next.log --inference-log inference.log
|
|
--power-series POWER.csv --out REC.json [--analyze-session PATH]
|
|
|
|
Exit codes
|
|
0 record written
|
|
2 the logs carry no `leleka-serve cpu: ` line (message: "missing leleka-serve cpu: lines"); check C0, nothing written
|
|
3 another input is missing, damaged or inconsistent (the message names it); includes an existing --out (never overwritten)
|
|
4 the ENFORCED GPU power limit is N/A, empty or not a positive number in a sample (fail closed)
|
|
5 scripts/e2e/analyze_session.py failed or its --csv columns drifted
|
|
64 usage error (not 2, so that 2 stays unambiguous); the vanilla arms are STRA-315 and are refused here
|
|
|
|
How the pieces are obtained
|
|
analyze_session.py is a flat script (argparse and the whole report at module level, no main guard), so it is NEVER imported: it is wrapped
|
|
by SUBPROCESS and its `--csv` output is parsed (STRA-251 round-5 re-cut). The two logs are staged under their fixed names
|
|
(strata-next.log, inference.log) in a private temporary directory, with CRLF folded to LF (raw bytes are never stored; comparisons are on
|
|
the normalised text), because the script reads a RUN directory.
|
|
--meta (written by the runner, STRA-257): arm, series_id, block, pair_id, position, predecessor, schedule_hash, h0_id, machine (a real series writes laptop|server: validity.py requires
|
|
hardware.machine_role == the declared machine, STRA-326) and
|
|
ours_build_id (an object commit / target_triple / cargo_features / profile_value_sha256 = the FROZEN build id, STRA-304/322). Optional:
|
|
owner_attestation {present, identifier, time_utc}, foreign_load {samples}, synthetic, long_session_argv, source_snapshot_sha256.
|
|
--replay-output: the run JSON of replay_session.py (STRA-308); status must be "ok".
|
|
Engine logs (inference.log first, then strata-next.log; CRLF tolerated, a trailing CR is stripped):
|
|
`leleka-serve cpu: ...` and `leleka-serve gpu: ...` lines are copied VERBATIM, with the prefix, into kernel_lines (cpu lines required).
|
|
`leleka-serve gpu N: <name>, cc ...` gives gpu_name, `leleka-serve cpu: logical ...: <brand>; ...` gives cpu_model,
|
|
`leleka-serve gpu: CUDA driver X.Y ...` gives cuda_version.
|
|
RUN-FACTS CONTRACT v1 (key=value tokens separated by blanks; a missing line is exit 3, never a guess; repeated lines must agree).
|
|
The engine itself prints build, model and config since STRA-325 as `leleka-serve meta: <section> v=1 k=v ...` (build/model/config below are read
|
|
from either form; fields: scripts/e2e/evidence/engine_meta_lines.md). `meta: build` carries profile_sha256 (the profile FILE hash when the
|
|
launcher set LELEKA_PROFILE_SHA256, else `unset`: then its values_sha256 is used, with a warning) and dirty (warned about when not 0). The cache
|
|
line stays the runner's (the OS page cache is not the engine's to know); an engine `meta: cache` line is only cross-checked (EMPTY engine):
|
|
leleka-serve build: commit=<hex> target=<triple> features=<a,b|empty> profile_sha256=<hex> the OBSERVED BUILD ID
|
|
leleka-serve model: digest=<text> mapping=<text>
|
|
leleka-serve config: context_tokens=<int> kv=<text> slots=<int> batch=<int> speculation=<text>
|
|
leleka-serve cache: state=<WARM-OS/EMPTY-ENGINE|COLD> metric=<text> value=<number> unit=<text> measured before the run
|
|
--power-series (laptop: the S3.8 watchdog samples.tsv; server: an nvidia-smi sampler; both accepted): `# key=value` header lines, then a
|
|
header row and rows, tab or comma separated. Columns (names are matched case-insensitively, units in [] ignored):
|
|
limit = limit_w | enforced.power.limit power = power_w | power.draw time = utc | timestamp | t_s ok = ok (optional; 0 = a gap)
|
|
Header lines needed: thresholds_source (BOOTSTRAP|S3.7) and thresholds_sha256; optional power_limit_source (default enforced.power.limit),
|
|
power_max_limit_w, driver_version, gpu_name. power_max_limit_w, driver_version and (if the log has no gpu line) gpu_name are otherwise read
|
|
from `nvidia-smi --query-gpu` on this machine (process PATH); unreadable = exit 3.
|
|
gap_count = rows with ok=0 plus consecutive usable samples more than GAP_S seconds apart.
|
|
power_sample_summary.min_w / max_w / mean_w are the min / max / mean of the ENFORCED POWER LIMIT column (limit_w | enforced.power.limit), the
|
|
series E2(1) and validity.py judge (floor 100 W, spread 20 W, server spread 0). They are NEVER computed from the power-draw column (STRA-251
|
|
rework, defect D251-1: a constant 130 W limit with a draw of 60..120 W must stay min = max = mean = 130). The draw column is only read to
|
|
check that the sampler delivered it; its min / max / mean are printed on stdout as an informational line and are NOT in the record, because
|
|
schema v1 (STRA-246) has no field for them (power_sample_summary is additionalProperties:false); the series file, named by its sha256 in the
|
|
record, holds the draw. Recording draw in the record would be a schema change (STRA-246) and is not made here.
|
|
owner_attestation (E2(2), BA decision 9dcb717a: laptop pairs only): taken from --meta owner_attestation {present, identifier, time_utc} when
|
|
the runner supplies it, validated for shape (present true needs identifier and time_utc, false needs both null) and carried through
|
|
unchanged. Nothing is invented and nothing is required: without it the record carries the schema-required absent form
|
|
{present:false, identifier:null, time_utc:null} (the only schema-valid "none"), a server record needs no attestation, and for a laptop
|
|
record the runner (STRA-316) must supply it or the evaluator marks the pair ATTESTATION_MISSING/OWNER. A note on stderr says so.
|
|
Not derived here, on purpose: `countable` and `invalid_reasons`. Schema v1 types them as a required boolean and a required string list
|
|
(null is not allowed and there is no "pending" field), so capture.py writes the neutral placeholders false / [] and they MEAN "pending": the
|
|
runner finalize command (STRA-316) overwrites both from validity.py (STRA-312) and nobody may read them from a bare capture record. A bare
|
|
record is therefore never countable. In particular a mismatch between ours_build_id_observed and ours_build_id_frozen is only stored.
|
|
`quality` is a NOT_CHECKED placeholder that scripts/e2e/evidence/quality_step.py replaces.
|
|
"""
|
|
import argparse
|
|
import csv
|
|
import datetime
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
DEFAULT_ANALYZE = os.path.normpath(os.path.join(HERE, "..", "analyze_session.py"))
|
|
DEFAULT_UPSTREAM_DOC = os.path.normpath(os.path.join(HERE, "..", "..", "..", "docs", "upstream.md"))
|
|
|
|
EXIT_OK, EXIT_NO_CPU, EXIT_INPUT, EXIT_POWER_NA, EXIT_ANALYZE, EXIT_USAGE = 0, 2, 3, 4, 5, 64
|
|
GAP_S = 10.0 # a sample gap above this is counted (scripts/laptop/monitor.sh uses 10 s)
|
|
SMI_TIMEOUT_S = 5
|
|
ANALYZE_TIMEOUT_S = 300
|
|
KERNEL_LINE = re.compile(r"^leleka-serve (cpu|gpu): ")
|
|
CSV_COLUMNS = ("idx", "prompt_tokens", "reused_tokens", "engine_prefill_tok_s", "vram_expert_share", "join_ok")
|
|
META_KEYS = ("arm", "series_id", "block", "pair_id", "position", "predecessor", "schedule_hash", "h0_id", "machine", "ours_build_id")
|
|
BUILD_KEYS = ("commit", "target_triple", "cargo_features", "profile_value_sha256")
|
|
NA_TOKENS = {"", "n/a", "[n/a]", "na", "nan", "[not supported]", "[unknown error]", "unknown", "none", "null"}
|
|
|
|
|
|
class Fail(Exception):
|
|
def __init__(self, code, message):
|
|
Exception.__init__(self, message)
|
|
self.code = code
|
|
self.message = message
|
|
|
|
|
|
def fail_input(message):
|
|
return Fail(EXIT_INPUT, message)
|
|
|
|
|
|
# ---- small readers -------------------------------------------------------------------------------------------------------------------------
|
|
|
|
def read_bytes(path, what):
|
|
try:
|
|
with open(path, "rb") as f:
|
|
return f.read()
|
|
except OSError as exc:
|
|
raise fail_input("%s: cannot read %s: %s" % (what, path, exc.strerror or exc))
|
|
|
|
|
|
def normalise(raw):
|
|
return raw.decode("utf-8", "replace").replace("\r\n", "\n").replace("\r", "\n")
|
|
|
|
|
|
def read_text_lines(path, what):
|
|
return normalise(read_bytes(path, what)).split("\n")
|
|
|
|
|
|
def read_json(path, what):
|
|
try:
|
|
return json.loads(read_bytes(path, what).decode("utf-8-sig"))
|
|
except ValueError as exc:
|
|
raise fail_input("%s: %s is not valid JSON: %s" % (what, path, exc))
|
|
|
|
|
|
def sha256_hex(data):
|
|
return hashlib.sha256(data).hexdigest()
|
|
|
|
|
|
def to_float(token):
|
|
"""A number, or None for an N/A-like token or anything unparsable (units like ' W' are stripped)."""
|
|
t = str(token).strip()
|
|
if t.lower() in NA_TOKENS:
|
|
return None
|
|
t = re.sub(r"\s*(w|mhz|mib|%)\s*$", "", t, flags=re.I)
|
|
try:
|
|
v = float(t)
|
|
except ValueError:
|
|
return None
|
|
return v if v == v and v not in (float("inf"), float("-inf")) else None
|
|
|
|
|
|
def number_out(v):
|
|
return int(v) if float(v).is_integer() and abs(v) < 1e15 else v
|
|
|
|
|
|
# ---- meta ------------------------------------------------------------------------------------------------------------------------------------
|
|
|
|
def load_meta(path, arm):
|
|
meta = read_json(path, "--meta")
|
|
if not isinstance(meta, dict):
|
|
raise fail_input("--meta: %s is not a JSON object" % path)
|
|
for key in META_KEYS:
|
|
if key not in meta:
|
|
raise fail_input("--meta: missing key %s" % key)
|
|
if meta["arm"] != arm:
|
|
raise fail_input("--meta: arm %r differs from --arm %s" % (meta["arm"], arm))
|
|
for key in ("series_id", "pair_id", "predecessor", "schedule_hash", "h0_id", "machine"):
|
|
if not isinstance(meta[key], str) or not meta[key]:
|
|
raise fail_input("--meta: %s must be a non-empty string" % key)
|
|
for key in ("block", "position"):
|
|
if isinstance(meta[key], bool) or not isinstance(meta[key], int):
|
|
raise fail_input("--meta: %s must be an integer" % key)
|
|
if "owner_attestation" in meta:
|
|
check_attestation(meta["owner_attestation"])
|
|
frozen = meta["ours_build_id"]
|
|
if not isinstance(frozen, dict) or any(k not in frozen for k in BUILD_KEYS):
|
|
raise fail_input("--meta: ours_build_id must be an object with %s" % ", ".join(BUILD_KEYS))
|
|
return meta
|
|
|
|
|
|
def check_attestation(att):
|
|
"""--meta owner_attestation, when supplied, must have the schema shape (RULE_ATTESTATION); it is carried through unchanged."""
|
|
if not isinstance(att, dict) or set(att) != {"present", "identifier", "time_utc"}:
|
|
raise fail_input("--meta: owner_attestation must be an object with exactly present, identifier, time_utc")
|
|
if not isinstance(att["present"], bool):
|
|
raise fail_input("--meta: owner_attestation.present must be a boolean")
|
|
if att["present"]:
|
|
if not isinstance(att["identifier"], str) or not att["identifier"] or not isinstance(att["time_utc"], str) or not att["time_utc"]:
|
|
raise fail_input("--meta: owner_attestation.present true needs a non-empty identifier and time_utc")
|
|
elif att["identifier"] is not None or att["time_utc"] is not None:
|
|
raise fail_input("--meta: owner_attestation.present false needs identifier and time_utc null")
|
|
|
|
|
|
ABSENT_ATTESTATION = {"present": False, "identifier": None, "time_utc": None}
|
|
|
|
|
|
# ---- replay output -----------------------------------------------------------------------------------------------------------------------------
|
|
|
|
def load_replay(path, meta):
|
|
rep = read_json(path, "--replay-output")
|
|
if not isinstance(rep, dict) or rep.get("mode") != "replay":
|
|
raise fail_input("--replay-output: %s is not a replay_session.py run JSON" % path)
|
|
if rep.get("status") != "ok":
|
|
raise fail_input("--replay-output: run status is %r, not ok (%s)" % (rep.get("status"), rep.get("error") or rep.get("mismatches") or "no detail"))
|
|
if rep.get("h0_id") != meta["h0_id"]:
|
|
raise fail_input("--replay-output: h0_id %r differs from --meta h0_id %r" % (rep.get("h0_id"), meta["h0_id"]))
|
|
turns = rep.get("turns")
|
|
if not isinstance(turns, list) or not turns:
|
|
raise fail_input("--replay-output: no turns")
|
|
need = ("turn", "prompt_sha256", "reply_sha256", "prompt_tokens", "cached_tokens", "output_tokens", "ttft_s", "latency_s", "decode_time_s")
|
|
for k, t in enumerate(turns):
|
|
for key in need:
|
|
if t.get(key) is None:
|
|
raise fail_input("--replay-output: turn %d has no usable %s" % (k + 1, key))
|
|
if t["turn"] != k + 1:
|
|
raise fail_input("--replay-output: turns are not numbered 1..n in order (position %d holds turn %r)" % (k + 1, t["turn"]))
|
|
if not t["ttft_s"] > 0 or not t["latency_s"] > 0:
|
|
raise fail_input("--replay-output: turn %d has a non-positive ttft_s or latency_s" % (k + 1))
|
|
for key in ("wall", "wall_norm"):
|
|
if not isinstance(rep.get(key), (int, float)) or not rep[key] > 0:
|
|
raise fail_input("--replay-output: %s missing or not positive" % key)
|
|
return rep
|
|
|
|
|
|
# ---- analyze_session.py by subprocess --------------------------------------------------------------------------------------------------------
|
|
|
|
def run_analyze(analyze_path, strata_lines, inference_lines):
|
|
"""Stage the logs under the names the script reads, run it with --csv, return the CSV rows. The script is never imported."""
|
|
if not os.path.isfile(analyze_path):
|
|
raise Fail(EXIT_ANALYZE, "analyze_session.py not found at %s" % analyze_path)
|
|
with tempfile.TemporaryDirectory(prefix="leleka-capture-") as tmp:
|
|
run_dir = os.path.join(tmp, "run")
|
|
os.mkdir(run_dir)
|
|
for name, lines in (("strata-next.log", strata_lines), ("inference.log", inference_lines)):
|
|
with open(os.path.join(run_dir, name), "w", encoding="utf-8", newline="\n") as f:
|
|
f.write("\n".join(lines))
|
|
csv_path = os.path.join(tmp, "trace.csv")
|
|
env = dict(os.environ)
|
|
env["PYTHONDONTWRITEBYTECODE"] = "1"
|
|
try:
|
|
proc = subprocess.run([sys.executable, analyze_path, run_dir, "--csv", csv_path], cwd=tmp, env=env, stdout=subprocess.PIPE,
|
|
stderr=subprocess.PIPE, timeout=ANALYZE_TIMEOUT_S)
|
|
except (OSError, subprocess.SubprocessError) as exc:
|
|
raise Fail(EXIT_ANALYZE, "analyze_session.py could not run: %s" % exc)
|
|
if proc.returncode != 0:
|
|
tail = proc.stderr.decode("utf-8", "replace").strip().splitlines()[-3:]
|
|
raise Fail(EXIT_ANALYZE, "analyze_session.py exited %d: %s" % (proc.returncode, " | ".join(tail)))
|
|
if not os.path.isfile(csv_path):
|
|
raise Fail(EXIT_ANALYZE, "analyze_session.py wrote no --csv file")
|
|
with open(csv_path, newline="", encoding="utf-8") as f:
|
|
reader = csv.DictReader(f)
|
|
rows = list(reader)
|
|
columns = reader.fieldnames or []
|
|
if not rows:
|
|
raise fail_input("engine logs: no `generation done:` lines for analyze_session.py (is --engine-log strata-next.log?)")
|
|
missing = [c for c in CSV_COLUMNS if c not in columns]
|
|
if missing:
|
|
raise Fail(EXIT_ANALYZE, "analyze_session.py --csv columns drifted, missing: %s" % ", ".join(missing))
|
|
return rows
|
|
|
|
|
|
# ---- engine logs ---------------------------------------------------------------------------------------------------------------------------------
|
|
|
|
def parse_kv(text):
|
|
out = {}
|
|
for token in text.split():
|
|
if "=" in token:
|
|
k, v = token.split("=", 1)
|
|
out[k] = v
|
|
return out
|
|
|
|
|
|
META_VERSION = "1"
|
|
HEX_SHA256 = re.compile(r"^[0-9a-f]{64}$")
|
|
HEX_COMMIT = re.compile(r"^[0-9a-f]{7,64}$")
|
|
|
|
|
|
def meta_build_view(kv):
|
|
"""The run-facts view of a `leleka-serve meta: build` line (STRA-325): profile_sha256 is the hash of the profile FILE when the launcher handed
|
|
it to the engine, else the engine's own hash of the effective tuning values (values_sha256). The commit must be a real hex commit."""
|
|
commit = kv.get("commit")
|
|
if commit is not None and not HEX_COMMIT.match(commit):
|
|
raise fail_input("engine logs: `leleka-serve meta: build` commit %r is not a hex commit (a build without git needs LELEKA_BUILD_COMMIT)" % commit)
|
|
if kv.get("dirty") not in (None, "0"):
|
|
sys.stderr.write("capture: warning: the engine build reports dirty=%s (tracked files differ from the commit); the record schema has no field for it\n" % kv.get("dirty"))
|
|
sha = kv.get("profile_sha256")
|
|
if sha is None or not HEX_SHA256.match(sha):
|
|
sha = kv.get("values_sha256")
|
|
if sha is not None and HEX_SHA256.match(sha):
|
|
sys.stderr.write("capture: warning: the engine got no profile file hash (profile_sha256=%s); using its values_sha256\n" % kv.get("profile_sha256"))
|
|
return {"commit": commit, "target": kv.get("target"), "features": kv.get("features"), "profile_sha256": sha}
|
|
|
|
|
|
def one_fact(lines, kind, keys, meta=True):
|
|
"""Every `leleka-serve <kind>: k=v ...` line (run-facts contract v1) and every `leleka-serve meta: <kind> v=1 k=v ...` line (the engine's own
|
|
start-up report, STRA-325, scripts/e2e/evidence/engine_meta_lines.md); they must all agree (meta=False: the legacy form only, for the runner's cache line).
|
|
Returns {key: value} or raises exit 3."""
|
|
found = []
|
|
prefix = "leleka-serve %s: " % kind
|
|
meta_prefix = "leleka-serve meta: %s " % kind
|
|
for l in lines:
|
|
if l.startswith(prefix):
|
|
kv = parse_kv(l[len(prefix):])
|
|
found.append({k: kv.get(k) for k in keys})
|
|
elif meta and l.startswith(meta_prefix):
|
|
kv = parse_kv(l[len(meta_prefix):])
|
|
if kv.get("v") != META_VERSION:
|
|
raise fail_input("engine logs: `%s` line has v=%s, this capture.py reads v=%s" % (meta_prefix.strip(), kv.get("v"), META_VERSION))
|
|
if kind == "build":
|
|
kv = meta_build_view(kv)
|
|
found.append({k: kv.get(k) for k in keys})
|
|
if not found:
|
|
raise fail_input("engine logs: no `%s` line and no `leleka-serve meta: %s` line (run-facts contract v1)" % (prefix.strip(), kind))
|
|
for f in found[1:]:
|
|
if f != found[0]:
|
|
raise fail_input("engine logs: `%s` lines disagree: %s vs %s" % (prefix.strip(), found[0], f))
|
|
got = found[0]
|
|
absent = [k for k in keys if got[k] is None]
|
|
if absent:
|
|
raise fail_input("engine logs: `%s` line lacks %s" % (prefix.strip(), ", ".join(absent)))
|
|
return got
|
|
|
|
|
|
def check_engine_cache(lines, cache):
|
|
"""The engine's `leleka-serve meta: cache` line (when it printed one) must not contradict the runner's cache state: a WARM-OS/EMPTY-ENGINE
|
|
record needs an empty engine (engine_state=EMPTY, prefix_entries=0). The OS page cache itself is the runner's measurement, not the engine's."""
|
|
prefix = "leleka-serve meta: cache "
|
|
for l in lines:
|
|
if not l.startswith(prefix):
|
|
continue
|
|
kv = parse_kv(l[len(prefix):])
|
|
if kv.get("v") != META_VERSION:
|
|
raise fail_input("engine logs: `%s` line has v=%s, this capture.py reads v=%s" % (prefix.strip(), kv.get("v"), META_VERSION))
|
|
if cache["state"] == "WARM-OS/EMPTY-ENGINE" and (kv.get("engine_state") != "EMPTY" or kv.get("prefix_entries") != "0"):
|
|
raise fail_input("engine logs: cache state is %s but the engine reports engine_state=%s prefix_entries=%s"
|
|
% (cache["state"], kv.get("engine_state"), kv.get("prefix_entries")))
|
|
|
|
|
|
def to_int(value, what):
|
|
try:
|
|
return int(value)
|
|
except (TypeError, ValueError):
|
|
raise fail_input("engine logs: %s is not an integer: %r" % (what, value))
|
|
|
|
|
|
def parse_engine(lines):
|
|
kernel_lines = []
|
|
for l in lines:
|
|
if KERNEL_LINE.match(l) and l not in kernel_lines:
|
|
kernel_lines.append(l)
|
|
cpu_lines = [l for l in kernel_lines if l.startswith("leleka-serve cpu: ")]
|
|
if not cpu_lines:
|
|
raise Fail(EXIT_NO_CPU, "missing leleka-serve cpu: lines")
|
|
brands = []
|
|
for l in cpu_lines:
|
|
m = re.match(r"leleka-serve cpu: logical \S+ \(\d+\): (.*?); AVX2/FMA/F16C:", l)
|
|
if m and m.group(1) not in brands:
|
|
brands.append(m.group(1))
|
|
if not brands:
|
|
raise fail_input("engine logs: no `leleka-serve cpu: logical ...` line names the CPU model")
|
|
gpus = []
|
|
for l in lines:
|
|
m = re.match(r"leleka-serve gpu \d+: (.*?), cc \d", l)
|
|
if m and m.group(1) not in gpus:
|
|
gpus.append(m.group(1))
|
|
cuda = None
|
|
for l in kernel_lines:
|
|
m = re.match(r"leleka-serve gpu: CUDA driver (\d+\.\d+)", l)
|
|
if m:
|
|
cuda = m.group(1)
|
|
break
|
|
if cuda is None:
|
|
raise fail_input("engine logs: no `leleka-serve gpu: CUDA driver X.Y` line (cuda_version)")
|
|
build = one_fact(lines, "build", ("commit", "target", "features", "profile_sha256"))
|
|
model = one_fact(lines, "model", ("digest", "mapping"))
|
|
config = one_fact(lines, "config", ("context_tokens", "kv", "slots", "batch", "speculation"))
|
|
cache = one_fact(lines, "cache", ("state", "metric", "value", "unit"), meta=False)
|
|
check_engine_cache(lines, cache)
|
|
return {"kernel_lines": kernel_lines, "cpu_model": " + ".join(brands), "gpu_names": gpus, "cuda_version": cuda, "build": build, "model": model,
|
|
"config": config, "cache": cache}
|
|
|
|
|
|
# ---- power series -----------------------------------------------------------------------------------------------------------------------------------
|
|
|
|
def norm_column(name):
|
|
return re.sub(r"\s*\[.*?\]\s*", "", name).strip().lower()
|
|
|
|
|
|
def parse_time(token):
|
|
v = to_float(token)
|
|
if v is not None:
|
|
return v
|
|
t = str(token).strip()
|
|
if t.endswith("Z"):
|
|
t = t[:-1]
|
|
for fmt in ("%Y-%m-%dT%H:%M:%S.%f", "%Y-%m-%dT%H:%M:%S", "%Y/%m/%d %H:%M:%S.%f", "%Y/%m/%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M:%S"):
|
|
try:
|
|
return (datetime.datetime.strptime(t, fmt) - datetime.datetime(1970, 1, 1)).total_seconds()
|
|
except ValueError:
|
|
continue
|
|
return None
|
|
|
|
|
|
def parse_power(raw):
|
|
header, table = {}, []
|
|
for line in normalise(raw).split("\n"):
|
|
if not line.strip():
|
|
continue
|
|
if line.startswith("#"):
|
|
m = re.match(r"#\s*([A-Za-z0-9_.]+)\s*=\s*(.*)$", line)
|
|
if m:
|
|
header[m.group(1)] = m.group(2).strip()
|
|
continue
|
|
table.append(line)
|
|
if len(table) < 2:
|
|
raise fail_input("--power-series: no header row and samples")
|
|
delim = "\t" if "\t" in table[0] else ","
|
|
cols = [norm_column(c) for c in table[0].split(delim)]
|
|
|
|
def col(*names):
|
|
for n in names:
|
|
if n in cols:
|
|
return cols.index(n)
|
|
return None
|
|
|
|
i_limit, i_power = col("limit_w", "enforced.power.limit"), col("power_w", "power.draw")
|
|
i_time, i_ok = col("utc", "timestamp", "t_s"), col("ok")
|
|
if i_limit is None or i_power is None or i_time is None:
|
|
raise fail_input("--power-series: needs limit (limit_w | enforced.power.limit), power (power_w | power.draw) and time (utc | timestamp | t_s) columns")
|
|
i_maxlim, i_driver, i_name = col("power_max_limit_w", "power.max_limit"), col("driver_version"), col("name")
|
|
rows, gaps_ok0, extras = [], 0, {}
|
|
for line in table[1:]:
|
|
f = line.split(delim)
|
|
if len(f) != len(cols):
|
|
raise fail_input("--power-series: a row has %d fields, the header has %d" % (len(f), len(cols)))
|
|
if i_ok is not None and f[i_ok].strip() == "0":
|
|
gaps_ok0 += 1
|
|
continue
|
|
t = parse_time(f[i_time])
|
|
if t is None:
|
|
raise fail_input("--power-series: unparsable time %r" % f[i_time])
|
|
rows.append({"t": t, "limit_raw": f[i_limit], "limit": to_float(f[i_limit]), "power": to_float(f[i_power])})
|
|
for key, idx in (("power_max_limit_w", i_maxlim), ("driver_version", i_driver), ("gpu_name", i_name)):
|
|
if idx is not None and f[idx].strip().lower() not in NA_TOKENS and key not in extras:
|
|
extras[key] = f[idx].strip()
|
|
if not rows:
|
|
raise fail_input("--power-series: no usable sample")
|
|
for r in rows:
|
|
if r["limit"] is None or not r["limit"] > 0:
|
|
raise Fail(EXIT_POWER_NA, "enforced power limit is N/A or not a positive number in a sample (%r): fail closed" % r["limit_raw"].strip())
|
|
powers = [r["power"] for r in rows if r["power"] is not None]
|
|
if not powers:
|
|
raise fail_input("--power-series: no sample carries a power draw")
|
|
gaps = gaps_ok0 + sum(1 for a, b in zip(rows, rows[1:]) if b["t"] - a["t"] > GAP_S)
|
|
limits = [r["limit"] for r in rows]
|
|
# min_w / max_w / mean_w describe the ENFORCED LIMIT series (power_limit_source), never the draw (D251-1); the draw is kept apart as draw_*.
|
|
return {"header": header, "extras": extras, "min_w": min(limits), "max_w": max(limits), "mean_w": sum(limits) / len(limits), "gap_count": gaps,
|
|
"draw_min_w": min(powers), "draw_max_w": max(powers), "draw_mean_w": sum(powers) / len(powers),
|
|
"limit_start": limits[0], "limit_end": limits[-1], "limit_min": min(limits), "limit_max": max(limits)}
|
|
|
|
|
|
def smi_query(fields):
|
|
"""One `nvidia-smi --query-gpu` line from this machine, as a list of strings, or None."""
|
|
exe = shutil.which("nvidia-smi")
|
|
if not exe:
|
|
return None
|
|
try:
|
|
proc = subprocess.run([exe, "--query-gpu=" + ",".join(fields), "--format=csv,noheader,nounits"], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
|
timeout=SMI_TIMEOUT_S)
|
|
except (OSError, subprocess.SubprocessError):
|
|
return None
|
|
if proc.returncode != 0:
|
|
return None
|
|
first = proc.stdout.decode("utf-8", "replace").strip().splitlines()
|
|
if not first:
|
|
return None
|
|
parts = [p.strip() for p in first[0].split(",")]
|
|
return parts if len(parts) == len(fields) else None
|
|
|
|
|
|
def machine_fact(power, key, smi_field):
|
|
"""header line, then a sampler column, then the machine (nvidia-smi); None when unreadable."""
|
|
for source in (power["header"], power["extras"]):
|
|
v = source.get(key)
|
|
if v and v.lower() not in NA_TOKENS:
|
|
return v
|
|
got = smi_query([smi_field])
|
|
if got and got[0].lower() not in NA_TOKENS:
|
|
return got[0]
|
|
return None
|
|
|
|
|
|
# ---- software ------------------------------------------------------------------------------------------------------------------------------------
|
|
|
|
def upstream_commit(doc_path):
|
|
try:
|
|
with open(doc_path, encoding="utf-8") as f:
|
|
text = f.read()
|
|
except OSError as exc:
|
|
raise fail_input("docs/upstream.md not readable (%s): %s" % (doc_path, exc.strerror or exc))
|
|
m = re.search(r"\|\s*Upstream commit SHA\s*\|\s*`([0-9a-f]{40})`", text)
|
|
if not m:
|
|
raise fail_input("docs/upstream.md: no `Upstream commit SHA` row with a 40-hex commit")
|
|
return m.group(1)
|
|
|
|
|
|
# ---- assembly --------------------------------------------------------------------------------------------------------------------------------------
|
|
|
|
def build_id(commit, target, features, profile):
|
|
feats = [x for x in (features or "").split(",") if x and x != "-"]
|
|
return {"commit": commit, "target_triple": target, "cargo_features": feats, "profile_value_sha256": profile}
|
|
|
|
|
|
def assemble(args, meta, rep, eng, power, power_raw, rows, smi_facts):
|
|
turns_out = []
|
|
for k, (t, row) in enumerate(zip(rep["turns"], rows)):
|
|
engine_rate = to_float(row.get("engine_prefill_tok_s", "")) if row.get("join_ok") == "True" else None
|
|
if engine_rate is not None and engine_rate > 0:
|
|
prefill = engine_rate
|
|
else:
|
|
fresh = t["prompt_tokens"] - t["cached_tokens"]
|
|
prefill = fresh / t["ttft_s"] if fresh > 0 else None
|
|
if prefill is None or not prefill > 0:
|
|
raise fail_input("turn %d: no prefill rate (no engine PREFILL-PROFILE chunk and nothing uncached to divide by)" % (k + 1))
|
|
dec = t["output_tokens"] / t["decode_time_s"] if t["decode_time_s"] > 0 and t["output_tokens"] > 0 else None
|
|
turns_out.append({"turn": t["turn"], "prompt_tokens": t["prompt_tokens"], "cached_tokens": t["cached_tokens"], "output_tokens": t["output_tokens"],
|
|
"ttft_s": t["ttft_s"], "prefill_tok_s": prefill, "decode_tok_s": dec, "wall_s": t["latency_s"],
|
|
"prompt_sha256": t["prompt_sha256"], "reply_sha256": t["reply_sha256"]})
|
|
vram = [to_float(r.get("vram_expert_share", "")) for r in rows]
|
|
vram = [v for v in vram if v is not None]
|
|
cfg = eng["config"]
|
|
if to_int(cfg["context_tokens"], "config context_tokens") != rep.get("context_tokens"):
|
|
sys.stderr.write("capture: warning: engine config context_tokens %s differs from the replay context_tokens %s\n" % (cfg["context_tokens"], rep.get("context_tokens")))
|
|
gpu_name = " + ".join(eng["gpu_names"]) if eng["gpu_names"] else smi_facts.get("gpu_name")
|
|
argv = meta.get("long_session_argv") or ["replay_session.py", "replay", "--turns", str(len(rep["turns"])), "--target-tokens", str(rep.get("target_tokens")),
|
|
"--context", str(rep.get("context_tokens"))]
|
|
snapshot = meta.get("source_snapshot_sha256") or sha256_hex("\n".join(t["prompt_sha256"] for t in rep["turns"]).encode("ascii"))
|
|
cache = eng["cache"]
|
|
value = to_float(cache["value"])
|
|
if value is None:
|
|
raise fail_input("engine logs: cache value %r is not a number" % cache["value"])
|
|
build = eng["build"]
|
|
series_name = os.path.basename(args.power_series)
|
|
rec = {
|
|
"schema_version": "1",
|
|
"level": "END_TO_END",
|
|
}
|
|
if meta.get("synthetic") is True:
|
|
rec["synthetic"] = True
|
|
rec.update({
|
|
"arm_identity": {"arm": meta["arm"], "series_id": meta["series_id"], "schedule_sha256": meta["schedule_hash"], "block": meta["block"],
|
|
"position": meta["position"], "predecessor_arm": meta["predecessor"], "pair_id": meta["pair_id"], "h0_id": meta["h0_id"]},
|
|
"ours_build_id_observed": build_id(build["commit"], build["target"], build["features"], build["profile_sha256"]),
|
|
"ours_build_id_frozen": {k: meta["ours_build_id"][k] for k in BUILD_KEYS},
|
|
"countable": False,
|
|
"invalid_reasons": [],
|
|
"power_sample_summary": {"min_w": number_out(power["min_w"]), "max_w": number_out(power["max_w"]), "mean_w": number_out(power["mean_w"]),
|
|
"gap_count": power["gap_count"], "series_sha256": sha256_hex(power_raw),
|
|
"power_max_limit_w": number_out(smi_facts["power_max_limit_w"]),
|
|
"power_limit_changed": power["limit_start"] != power["limit_end"],
|
|
"power_limit_source": power["header"].get("power_limit_source", "enforced.power.limit")},
|
|
"thresholds_source": power["header"]["thresholds_source"],
|
|
"thresholds_sha256": power["header"]["thresholds_sha256"],
|
|
"workload": {"long_session_argv": argv, "source_snapshot_sha256": snapshot, "turn1_tokens": turns_out[0]["prompt_tokens"]},
|
|
"cache": {"state": cache["state"], "page_cache_residency_before": {"metric": cache["metric"], "value": number_out(value), "unit": cache["unit"]}},
|
|
"hardware": {"machine_role": meta["machine"], "cpu_model": eng["cpu_model"], "gpu_name": gpu_name, "os": smi_facts["os"],
|
|
"enforced_power_limit_w_start": number_out(power["limit_start"]), "enforced_power_limit_w_end": number_out(power["limit_end"]),
|
|
"power_sample_series_file": series_name,
|
|
"owner_attestation": meta["owner_attestation"] if "owner_attestation" in meta else dict(ABSENT_ATTESTATION),
|
|
"foreign_load": meta.get("foreign_load", {"samples": []})},
|
|
"software": {"driver_version": smi_facts["driver_version"], "cuda_version": eng["cuda_version"], "leleka_commit": build["commit"],
|
|
"strata_upstream_commit": smi_facts["upstream_commit"]},
|
|
"model": {"digest": eng["model"]["digest"], "digest_mapping": eng["model"]["mapping"]},
|
|
"configuration": {"context_tokens": to_int(cfg["context_tokens"], "config context_tokens"), "kv": cfg["kv"], "slots": to_int(cfg["slots"], "config slots"),
|
|
"batch": to_int(cfg["batch"], "config batch"), "speculation": cfg["speculation"]},
|
|
"metrics": {"turns": turns_out, "wall_s": rep["wall"], "wall_norm_s": rep["wall_norm"], "draft_acceptance": None,
|
|
"expert_cache_hit": round(sum(vram) / len(vram), 4) if vram else None, "kv_streaming_hit": None},
|
|
"quality": {"verdict": "NOT_CHECKED", "tolerance": "none", "basis": "quality_step.py runs after capture and replaces this block", "baseline": "none",
|
|
"tool_call_integrity": "NOT_CHECKED"},
|
|
"kernel_lines": eng["kernel_lines"],
|
|
})
|
|
return rec
|
|
|
|
|
|
def run(args):
|
|
if args.arm != "ours":
|
|
raise Fail(EXIT_USAGE, "arm %s is captured by STRA-315, this script captures --arm ours only" % args.arm)
|
|
if os.path.exists(args.out):
|
|
raise fail_input("--out %s exists; a record is never overwritten" % args.out)
|
|
meta = load_meta(args.meta, args.arm)
|
|
rep = load_replay(args.replay_output, meta)
|
|
inference_lines = read_text_lines(args.inference_log, "--inference-log")
|
|
strata_lines = read_text_lines(args.engine_log, "--engine-log")
|
|
eng = parse_engine(inference_lines + strata_lines)
|
|
power_raw = read_bytes(args.power_series, "--power-series")
|
|
power = parse_power(power_raw)
|
|
for key in ("thresholds_source", "thresholds_sha256"):
|
|
if not power["header"].get(key):
|
|
raise fail_input("--power-series: header line `# %s=` missing" % key)
|
|
rows = run_analyze(args.analyze_session, strata_lines, inference_lines)
|
|
if len(rows) != len(rep["turns"]):
|
|
raise fail_input("engine log holds %d generations, the replay output %d turns" % (len(rows), len(rep["turns"])))
|
|
for k, (t, row) in enumerate(zip(rep["turns"], rows)):
|
|
try:
|
|
logged = int(row["prompt_tokens"])
|
|
except ValueError:
|
|
raise Fail(EXIT_ANALYZE, "analyze_session.py --csv: prompt_tokens of row %d is not an integer" % (k + 1))
|
|
if abs(logged - t["prompt_tokens"]) > 1:
|
|
raise fail_input("turn %d: engine log prompt_tokens %d differs from the replay output %d" % (k + 1, logged, t["prompt_tokens"]))
|
|
max_limit = machine_fact(power, "power_max_limit_w", "power.max_limit")
|
|
driver = machine_fact(power, "driver_version", "driver_version")
|
|
gpu_fallback = None
|
|
if not eng["gpu_names"]:
|
|
gpu_fallback = machine_fact(power, "gpu_name", "name")
|
|
if gpu_fallback is None:
|
|
raise fail_input("gpu_name: no `leleka-serve gpu N:` line, no sampler column and nvidia-smi unreadable")
|
|
smi = {"power_max_limit_w": to_float(max_limit) if max_limit else None, "driver_version": driver, "os": sys_os(),
|
|
"gpu_name": gpu_fallback, "upstream_commit": upstream_commit(args.upstream_doc)}
|
|
if smi["power_max_limit_w"] is None or not smi["power_max_limit_w"] > 0:
|
|
raise fail_input("power_max_limit_w: not in the power-series header or columns and nvidia-smi unreadable")
|
|
if not smi["driver_version"]:
|
|
raise fail_input("driver_version: not in the power-series header or columns and nvidia-smi unreadable")
|
|
rec = assemble(args, meta, rep, eng, power, power_raw, rows, smi)
|
|
if power["limit_min"] != power["limit_max"] and not rec["power_sample_summary"]["power_limit_changed"]:
|
|
sys.stderr.write("capture: warning: the enforced limit moved inside the run (%s..%s W) and returned to its start value\n" % (power["limit_min"], power["limit_max"]))
|
|
if not rec["hardware"]["owner_attestation"]["present"]:
|
|
sys.stderr.write("capture: note: no owner_attestation in --meta; the record carries the absent form. A laptop pair needs one (E2(2), else "
|
|
"ATTESTATION_MISSING/OWNER); a server pair needs none\n")
|
|
sys.stdout.write("capture: power draw (informational, not in the record) min %s max %s mean %.3f W; enforced limit min %s max %s mean %.3f W\n"
|
|
% (number_out(power["draw_min_w"]), number_out(power["draw_max_w"]), power["draw_mean_w"],
|
|
number_out(power["limit_min"]), number_out(power["limit_max"]), power["mean_w"]))
|
|
out_dir = os.path.dirname(os.path.abspath(args.out))
|
|
os.makedirs(out_dir, exist_ok=True)
|
|
tmp_path = args.out + ".tmp"
|
|
with open(tmp_path, "w", encoding="utf-8", newline="\n") as f:
|
|
json.dump(rec, f, indent=2)
|
|
f.write("\n")
|
|
os.replace(tmp_path, args.out)
|
|
return EXIT_OK
|
|
|
|
|
|
def sys_os():
|
|
import platform
|
|
return platform.platform()
|
|
|
|
|
|
class Parser(argparse.ArgumentParser):
|
|
def error(self, message):
|
|
sys.stderr.write("capture.py: usage error: %s\n" % message)
|
|
raise SystemExit(EXIT_USAGE)
|
|
|
|
|
|
def main(argv=None):
|
|
ap = Parser(description=__doc__.split("\n")[0], add_help=True)
|
|
ap.add_argument("--arm", required=True)
|
|
ap.add_argument("--meta", required=True)
|
|
ap.add_argument("--replay-output", required=True)
|
|
ap.add_argument("--engine-log", required=True, help="strata-next.log")
|
|
ap.add_argument("--inference-log", required=True, help="inference.log")
|
|
ap.add_argument("--power-series", required=True)
|
|
ap.add_argument("--out", required=True)
|
|
ap.add_argument("--analyze-session", default=DEFAULT_ANALYZE, help="path of analyze_session.py (default: the sibling in scripts/e2e)")
|
|
ap.add_argument("--upstream-doc", default=DEFAULT_UPSTREAM_DOC, help="docs/upstream.md (default: this checkout's)")
|
|
args = ap.parse_args(argv)
|
|
try:
|
|
return run(args)
|
|
except Fail as exc:
|
|
sys.stderr.write("capture: %s\n" % exc.message)
|
|
return exc.code
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|