Files
leleka/scripts/e2e/evidence/capture_vanilla.py
T
Pavlo Ratushnyi b4db01728c Keep the Strata files Rust and the product read in third_party/strata (STRA-406)
Owner decision 2026-11-23: the vendored Strata tree engine/strata is removed for good. This first step moves what is still read
at build, test or ship time into one small directory, byte for byte:

- third_party/strata/LICENSE (MIT; `leleka engine license` embeds it, the packagers ship it)
- third_party/strata/ggml/LICENSE, project-maya/LICENSE, project-maya/NOTICE.md (licence texts the release packager ships)
- third_party/strata/serve/chat_template.jinja (one copy, embedded by control-plane server_api.rs and gateway-text prompt.rs)
- third_party/strata/serve/chat_golden.json (gateway-text prompt tests)
- third_party/strata/tests/data/native_experts/*.txt (control-plane native_pack tests)
- control-plane/tests/mcp_hub/mcp_fake_server.py next to its test harness
- third_party/strata/UPSTREAM.md replaces engine/upstream.md: pin 41cf05a0, URL, the 25 locally patched files, where the removed tree is in history

include_str! paths, deploy/build.rs (the `leleka version` Strata pin now reads third_party/strata/UPSTREAM.md), Dockerfile.static-cli,
.dockerignore, .gitattributes, the release packagers (package-5090.sh, package-release.py: the subtree facts of the removed tree are
dropped from PROVENANCE) and the evidence capture scripts follow the move. The tree itself is deleted in a later commit.
2026-11-23 21:11:53 +01:00

624 lines
37 KiB
Python

#!/usr/bin/env python3
"""Run capture, VANILLA arms (STRA-315, S0.2b of STRA-245): build ONE S0.1 END_TO_END record from a finished vanilla Strata run, and check
the three-arm set of one block. Offline tooling, stdlib only, Python >= 3.9, Windows and Linux. It reads outputs; it never launches an 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. The ours arm is built by capture.py (STRA-251), not here.
CLI v1 (fixed by the leaf):
capture_vanilla.py --log ENGINE.log --arm vanilla_default|vanilla_noskip --replay-output REPLAY.json --power-series POWER.csv
--meta META.json --out REC.json [--family-dir DIR] [--parsed-out PARSED.json]
capture_vanilla.py check-set --dir DIR_OF_THE_THREE_RECORDS --row-b-env ROW_B_FILE
Exit codes
0 record written / the set is consistent
1 check-set only: inconsistent (every finding names the arm and the turn, or the variable)
2 a mandatory input is missing (the message names it)
3 an input is damaged or inconsistent with another (log-line drift, count mismatch, cpu: lines in a vanilla log, positive control not alive, an
existing --out: a record is never overwritten)
4 the ENFORCED GPU power limit is N/A, empty or not a positive number in a sample (fail closed, as capture.py)
64 usage error (`ours` is refused here: it is captured by capture.py)
The vanilla engine log (the lines STRA-247 names; stderr of `strata --serve`, one set of lines
per request, the warm-up request of the launcher first):
strata decode timing: N windows, avg T x, y tokens/window, z ms/window = verify v (GPU-reach wait ..) ... STRATA_DECODE_TIMING=1, per request
strata decode GPU stages (ms/window): GDN layers: ... | QSA layers: ... | total t ms/window over n windows STRATA_VERIFY_PROFILE=1, per request
strata serve: prompt P tokens = R reused + F read in M ms (S tok/s), G generated in D ms (T tok/s), drafts accepted a of b, c checkpoints
The two timing lines come BEFORE the `strata serve: prompt` line of the request they belong to, which closes the request. The log is aligned with the
replay output from the END: the last N requests are the N turns, anything before them is the warm-up; the prompt token counts must agree (+-1).
Per turn the record takes ttft_s and wall_s from the replay output (the client; the same source as the ours capture), prefill_tok_s and decode_tok_s from
the engine's own printed rates, the sha256 and token counts from the replay output. The per-round timing (the decode timing and GPU stages lines) does not
fit the S0.1 turn object (additionalProperties false): it is parsed and written to --parsed-out when asked, never into the record.
--meta: the file layout of capture.py (arm, series_id, block, pair_id, position, predecessor, schedule_hash, h0_id, machine, ours_build_id; optional
synthetic, long_session_argv, source_snapshot_sha256, owner_attestation, foreign_load) PLUS the facts a vanilla log cannot carry:
model {digest, digest_mapping}, configuration {context_tokens, kv, slots, batch, speculation}, cache {state, metric, value, unit},
hardware {cpu_model, gpu_name (optional: sampler or nvidia-smi), os (optional: this machine)}, software {cuda_version, driver_version (optional),
strata_upstream_commit (optional: third_party/strata/UPSTREAM.md)}, vanilla_noskip_environment [NAME=VALUE, ...] (vanilla_noskip only: the environment the engine
was started with), vanilla_family {control_printed [lines], predicate {tool, output} | "unavailable: <blocker>", binary_identity {engine_version, sha256}}
(the fallback of --family-dir).
--family-dir: control.log (the engine log of the start-up with STRATA_FORCE_AVX2=1), predicate.json ({tool, output}; absent and not in --meta =
"unavailable: ..."), binary_identity.json ({engine_version, sha256}). A control or binary identity found nowhere is exit 2.
--replay-output, --power-series: as capture.py (parsed by its functions; this file loads capture.py from its own directory by path).
The vanilla_cpu_family block is "determined by negative line + control + predicate", never "printed" (ARCHITECT comment 395f0394 section 2): the
vanilla engine prints no `cpu:` line; its only family-related stderr lines at the pin 41cf05a0 are generate.cpp 3485 / 3502 / 3505 / 3687.
"""
import argparse
import importlib.util
import json
import os
import re
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
EXIT_OK, EXIT_INCONSISTENT, EXIT_MISSING, EXIT_INPUT, EXIT_POWER_NA, EXIT_USAGE = 0, 1, 2, 3, 4, 64
ARMS = ("ours", "vanilla_default", "vanilla_noskip")
VANILLA_ARMS = ("vanilla_default", "vanilla_noskip")
ALIGN_TOLERANCE_TOKENS = 1
CONTROL_ENV = "STRATA_FORCE_AVX2=1"
READING_RULE = ("determined by negative line + control + predicate, not 'printed': on a native pack the absence of the generate.cpp:3687 line means "
"cpu_avx512_ok() was true in that process and its presence means false (negative indicator only; the silent 512-bit IQ-row gating "
"STRATA_NO_IQ512 / STRATA_NO_IQ256 / STRATA_NO_IQ_GATHER is not covered); the control must print the line, the predicate dump proves "
"the pin's source, not the release binary")
# (source line at the pin 41cf05a0, regex of the line as the engine prints it on stderr)
FAMILY_PATTERNS = (
("generate.cpp:3485", re.compile(r"^strata generate: this CPU \(.*\) does not support AVX2 with FMA and F16C")),
("generate.cpp:3502", re.compile(r"^strata generate: EXPERIMENTAL older-CPU build \(ggml-cpu for ")),
("generate.cpp:3505", re.compile(r"^strata generate: this is the older-CPU build \(ggml-cpu for ")),
("generate.cpp:3687", re.compile(r"^strata generate: this CPU has no AVX-512: the expert kernels run on ")),
)
LINE_3687 = FAMILY_PATTERNS[3][1]
BARE_CPU_LINE = re.compile(r"^(leleka-serve )?cpu:")
NUM = r"(\d+(?:\.\d+)?)"
RE_SERVE = re.compile(r"^strata serve: prompt (\d+) tokens = (\d+) reused \+ (\d+) read in " + NUM + r" ms \(" + NUM + r" tok/s\), (\d+) generated in "
+ NUM + r" ms \(" + NUM + r" tok/s\)(?:, drafts accepted (\d+) of (\d+))?(?:, (\d+) checkpoints?)?")
RE_TIMING = re.compile(r"^strata decode timing: (\d+) windows?\b")
RE_STAGES = re.compile(r"^strata decode GPU stages \(ms/window\): (.*)$")
RE_ENGINE_UP = re.compile(r"^strata generate: session is up \(engine ([0-9][^)]*)\)")
RE_STAGE_ITEM = re.compile(r"([A-Za-z(][A-Za-z0-9+/\-() ]*?)\s+(\d+\.\d+)(?=\s|$)")
RE_STAGE_TOTAL = re.compile(r"^total " + NUM + r" ms/window over (\d+) windows")
ROUND_FIELDS = (
("windows", re.compile(r"^strata decode timing: (\d+) windows?\b"), int),
("avg_t", re.compile(r"avg T " + NUM), float),
("tokens_per_window", re.compile(r", " + NUM + r" tokens/window"), float),
("ms_per_window", re.compile(r", " + NUM + r" ms/window ="), float),
("verify_ms", re.compile(r"= verify " + NUM), float),
("gpu_reach_wait_ms", re.compile(r"GPU-reach wait " + NUM), float),
("per_layer_host_ms", re.compile(r"per-layer host " + NUM), float),
("plan_ms", re.compile(r"\[plan " + NUM), float),
("actq_ms", re.compile(r"\bactq " + NUM), float),
("jobs_ms", re.compile(r"\bjobs " + NUM), float),
("cpu_ms", re.compile(r"\bCPU " + NUM + r"\]"), float),
("stage_ms", re.compile(r"\+ stage " + NUM + r"\)"), float),
("commit_emit_ms", re.compile(r"\+ commit/emit " + NUM), float),
("draft_ms", re.compile(r"\+ draft " + NUM), float),
("cpu_experts_per_layer_window", re.compile(r"per layer-window: CPU experts " + NUM), float),
("vram_hits_per_layer_window", re.compile(r"VRAM hits " + NUM + r", PCIe"), float),
("pcie_per_layer_window", re.compile(r"PCIe " + NUM + r"; adapt"), float),
("adapt_wait_ms", re.compile(r"adapt wait " + NUM), float),
("adapt_join_ms", re.compile(r"\bjoin " + NUM + r","), float),
("swaps_per_window", re.compile(r", " + NUM + r" swaps/window"), float),
)
MANDATORY_ROUND_FIELDS = ("windows", "tokens_per_window", "ms_per_window")
class Fail(Exception):
def __init__(self, code, message):
Exception.__init__(self, message)
self.code = code
self.message = message
def missing(message):
return Fail(EXIT_MISSING, message)
def damaged(message):
return Fail(EXIT_INPUT, message)
def load_capture():
"""capture.py (STRA-251) by path: its readers of the shared input formats (--meta, --replay-output, --power-series) are reused, not copied."""
path = os.path.join(HERE, "capture.py")
if not os.path.isfile(path):
raise damaged("capture.py (STRA-251) not found next to this script (%s): the shared input readers live there" % path)
spec = importlib.util.spec_from_file_location("leleka_capture_ours", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
# ---- the vanilla engine log ----------------------------------------------------------------------------------------------------------------------
def parse_rounds(line):
"""The per-round timing of one `strata decode timing:` line; the three core fields are mandatory (log-line drift is exit 3, never a guess)."""
out = {}
for name, pattern, cast in ROUND_FIELDS:
m = pattern.search(line)
out[name] = cast(m.group(1)) if m else None
gone = [n for n in MANDATORY_ROUND_FIELDS if out[n] is None]
if gone:
raise damaged("`strata decode timing:` line lacks %s (log-line drift?): %s" % (", ".join(gone), line[:160]))
return out
def parse_stages(body):
"""`strata decode GPU stages (ms/window):` body -> {group: {stage: ms}, total_ms_per_window, windows}."""
out = {}
for part in body.split(" | "):
part = part.strip()
m = RE_STAGE_TOTAL.match(part)
if m:
out["total_ms_per_window"] = float(m.group(1))
out["windows"] = int(m.group(2))
continue
g = re.match(r"^([A-Za-z]+) layers:\s*(.*)$", part)
if g:
out[g.group(1) + " layers"] = {name.strip(): float(value) for name, value in RE_STAGE_ITEM.findall(g.group(2))}
if not any(isinstance(v, dict) and v for v in out.values()):
raise damaged("`strata decode GPU stages` line holds no `<group> layers:` stage list (log-line drift?): %s" % body[:160])
return out
def parse_serve_log(lines):
"""Every request of the log, in order: the `strata serve: prompt ...` line closes a request; the decode timing / GPU stages lines since the
previous request belong to it. Returns (requests, family_lines, cpu_lines, engine_versions)."""
requests, family, cpu_lines, versions = [], [], [], []
rounds, stages = None, None
for raw in lines:
line = raw.strip()
if not line:
continue
if BARE_CPU_LINE.match(line):
cpu_lines.append(line)
continue
for _source, pattern in FAMILY_PATTERNS:
if pattern.match(line):
if line not in family:
family.append(line)
break
m = RE_ENGINE_UP.match(line)
if m and m.group(1) not in versions:
versions.append(m.group(1))
if RE_TIMING.match(line):
rounds = parse_rounds(line)
continue
m = RE_STAGES.match(line)
if m:
stages = parse_stages(m.group(1))
continue
m = RE_SERVE.match(line)
if m:
g = m.groups()
requests.append({
"index": len(requests) + 1,
"prompt_tokens": int(g[0]), "reused_tokens": int(g[1]), "read_tokens": int(g[2]),
"ttft_s": float(g[3]) / 1000.0, "prompt_read_ms": float(g[3]), "prefill_tok_s": float(g[4]),
"generated_tokens": int(g[5]), "decode_ms": float(g[6]), "decode_tok_s": float(g[7]),
"drafts_accepted": int(g[8]) if g[8] is not None else None, "drafts_total": int(g[9]) if g[9] is not None else None,
"checkpoints": int(g[10]) if g[10] is not None else None,
"rounds": rounds, "stages": stages,
})
rounds, stages = None, None
return requests, family, cpu_lines, versions
def align_turns(requests, turns):
"""The last len(turns) requests are the turns; the requests before them are the warm-up. Prompt token counts must agree (+-1)."""
n = len(turns)
if len(requests) < n:
raise damaged("the engine log holds %d `strata serve: prompt` lines, the replay output has %d turns" % (len(requests), n))
tail = requests[len(requests) - n:]
for k, (req, turn) in enumerate(zip(tail, turns)):
if abs(req["prompt_tokens"] - turn["prompt_tokens"]) > ALIGN_TOLERANCE_TOKENS:
raise damaged("turn %d: engine log prompt %d tokens, replay output %d (the log's last %d requests are taken as the turns; %d earlier ones as warm-up)"
% (k + 1, req["prompt_tokens"], turn["prompt_tokens"], n, len(requests) - n))
return tail
# ---- the vanilla_cpu_family block ------------------------------------------------------------------------------------------------------------------
def family_lines(lines):
out = []
for raw in lines:
line = raw.strip()
if any(p.match(line) for _s, p in FAMILY_PATTERNS) and line not in out:
out.append(line)
return out
def read_optional_json(path, what):
if not os.path.isfile(path):
return None
try:
with open(path, "rb") as f:
return json.loads(f.read().decode("utf-8-sig"))
except (OSError, ValueError) as exc:
raise damaged("%s: %s is not readable JSON: %s" % (what, path, exc))
def build_family_block(cap, log_family_lines, log_engine_versions, family_dir, meta):
"""printed / control / predicate / binary_identity from --family-dir files, else from meta.vanilla_family; control and binary identity are mandatory."""
from_meta = meta.get("vanilla_family") if isinstance(meta.get("vanilla_family"), dict) else {}
control_lines = None
if family_dir:
control_path = os.path.join(family_dir, "control.log")
if os.path.isfile(control_path):
control_lines = family_lines(cap.read_text_lines(control_path, "--family-dir/control.log"))
if control_lines is None and isinstance(from_meta.get("control_printed"), list):
control_lines = family_lines([str(x) for x in from_meta["control_printed"]])
if control_lines is None:
raise missing("the STRATA_FORCE_AVX2=1 positive-control output (--family-dir/control.log or meta.vanilla_family.control_printed)")
if not any(LINE_3687.match(l) for l in control_lines):
raise damaged("the positive control (STRATA_FORCE_AVX2=1) did not print the generate.cpp:3687 line: the detector is not proven alive in this binary, "
"so the absence of that line in the arm's log proves nothing")
predicate = None
if family_dir:
predicate = read_optional_json(os.path.join(family_dir, "predicate.json"), "--family-dir/predicate.json")
if predicate is None:
predicate = from_meta.get("predicate")
if predicate is None:
predicate = "unavailable: no predicate-dump output (STRA-307 / S0.7c) was supplied to capture_vanilla.py"
ok_object = isinstance(predicate, dict) and set(predicate) == {"tool", "output"} and all(isinstance(v, str) and v for v in predicate.values())
ok_text = isinstance(predicate, str) and predicate.startswith("unavailable: ") and len(predicate) > len("unavailable: ")
if not (ok_object or ok_text):
raise damaged("predicate: must be {tool, output} or 'unavailable: <blocker>', got %r" % (predicate,))
identity = None
if family_dir:
identity = read_optional_json(os.path.join(family_dir, "binary_identity.json"), "--family-dir/binary_identity.json")
if identity is None:
identity = from_meta.get("binary_identity")
if not isinstance(identity, dict) or not identity.get("sha256") or not identity.get("engine_version"):
raise missing("the binary identity {engine_version, sha256} of the engine (--family-dir/binary_identity.json or meta.vanilla_family.binary_identity)")
if set(identity) != {"engine_version", "sha256"}:
raise damaged("binary_identity must hold exactly engine_version and sha256, got %s" % sorted(identity))
for version in log_engine_versions:
if version not in identity["engine_version"]:
sys.stderr.write("capture_vanilla: warning: the log says `session is up (engine %s)`, the binary identity says %r\n" % (version, identity["engine_version"]))
return {
"printed": list(log_family_lines) if log_family_lines else "none printed",
"reading_rule": READING_RULE,
"control": {"env": CONTROL_ENV, "printed": control_lines},
"predicate": predicate,
"binary_identity": {"engine_version": identity["engine_version"], "sha256": identity["sha256"]},
}
# ---- the record -----------------------------------------------------------------------------------------------------------------------------------
def need(meta, key, subkeys):
section = meta.get(key)
if not isinstance(section, dict):
raise missing("--meta: section %s (the vanilla log cannot carry it)" % key)
gone = [k for k in subkeys if section.get(k) in (None, "")]
if gone:
raise missing("--meta: %s.%s" % (key, ", ".join(gone)))
return section
def int_of(value, what):
if isinstance(value, bool) or not isinstance(value, int):
raise damaged("--meta: %s must be an integer, got %r" % (what, value))
return value
def assemble(cap, args, meta, rep, aligned, power, power_raw, facts, block):
turns_out = []
for k, (t, req) in enumerate(zip(rep["turns"], aligned)):
prefill = req["prefill_tok_s"]
if not prefill > 0:
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 damaged("turn %d: no prefill rate (the engine printed 0 tok/s and nothing uncached to divide by)" % (k + 1))
decode = req["decode_tok_s"] if req["generated_tokens"] > 0 and req["decode_tok_s"] > 0 else None
if abs(req["generated_tokens"] - t["output_tokens"]) > ALIGN_TOLERANCE_TOKENS:
sys.stderr.write("capture_vanilla: warning: turn %d: engine log %d generated tokens, replay output %d\n" % (k + 1, req["generated_tokens"], t["output_tokens"]))
if abs(req["reused_tokens"] - t["cached_tokens"]) > ALIGN_TOLERANCE_TOKENS:
sys.stderr.write("capture_vanilla: warning: turn %d: engine log %d reused tokens, replay output cached_tokens %d\n" % (k + 1, req["reused_tokens"], t["cached_tokens"]))
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": decode, "wall_s": t["latency_s"],
"prompt_sha256": t["prompt_sha256"], "reply_sha256": t["reply_sha256"]})
cfg, cache, model = facts["configuration"], facts["cache"], facts["model"]
value = cap.to_float(cache["value"])
if value is None:
raise damaged("--meta: cache.value %r is not a number" % (cache["value"],))
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 cap.sha256_hex("\n".join(t["prompt_sha256"] for t in rep["turns"]).encode("ascii"))
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": None,
"ours_build_id_frozen": {k: meta["ours_build_id"][k] for k in cap.BUILD_KEYS},
"countable": False,
"invalid_reasons": [],
"power_sample_summary": {"min_w": cap.number_out(power["min_w"]), "max_w": cap.number_out(power["max_w"]), "mean_w": cap.number_out(power["mean_w"]),
"gap_count": power["gap_count"], "series_sha256": cap.sha256_hex(power_raw),
"power_max_limit_w": cap.number_out(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": cap.number_out(value), "unit": cache["unit"]}},
"hardware": {"machine_role": meta["machine"], "cpu_model": facts["cpu_model"], "gpu_name": facts["gpu_name"], "os": facts["os"],
"enforced_power_limit_w_start": cap.number_out(power["limit_start"]), "enforced_power_limit_w_end": cap.number_out(power["limit_end"]),
"power_sample_series_file": os.path.basename(args.power_series),
"owner_attestation": meta.get("owner_attestation", {"present": False, "identifier": None, "time_utc": None}),
"foreign_load": meta.get("foreign_load", {"samples": []})},
"software": {"driver_version": facts["driver_version"], "cuda_version": facts["cuda_version"], "leleka_commit": meta["ours_build_id"]["commit"],
"strata_upstream_commit": facts["upstream_commit"]},
"model": {"digest": model["digest"], "digest_mapping": model["digest_mapping"]},
"configuration": {"context_tokens": int_of(cfg["context_tokens"], "configuration.context_tokens"), "kv": cfg["kv"],
"slots": int_of(cfg["slots"], "configuration.slots"), "batch": int_of(cfg["batch"], "configuration.batch"),
"speculation": cfg["speculation"]},
# draft acceptance, expert cache hit and KV streaming hit are not taken from the vanilla log: its counters are not defined like the ours ones
"metrics": {"turns": turns_out, "wall_s": rep["wall"], "wall_norm_s": rep["wall_norm"], "draft_acceptance": None,
"expert_cache_hit": 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"},
"vanilla_cpu_family": block,
})
if meta["arm"] == "vanilla_noskip":
env = meta.get("vanilla_noskip_environment")
if not isinstance(env, list) or not env or not all(isinstance(e, str) and re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", e) for e in env):
raise missing("--meta: vanilla_noskip_environment (the NAME=VALUE list the vanilla_noskip engine was started with)")
rec["vanilla_noskip_environment"] = list(env)
elif "vanilla_noskip_environment" in meta:
raise damaged("--meta: vanilla_noskip_environment given for arm %s" % meta["arm"])
return rec
def run_capture(args):
if args.arm == "ours":
raise Fail(EXIT_USAGE, "arm ours is captured by capture.py (STRA-251), this script captures vanilla_default and vanilla_noskip")
if args.arm not in VANILLA_ARMS:
raise Fail(EXIT_USAGE, "--arm must be vanilla_default or vanilla_noskip, got %r" % args.arm)
for flag, path in (("--log", args.log), ("--replay-output", args.replay_output), ("--power-series", args.power_series), ("--meta", args.meta)):
if not os.path.isfile(path):
raise missing("%s %s does not exist" % (flag, path))
if args.family_dir and not os.path.isdir(args.family_dir):
raise missing("--family-dir %s is not a directory" % args.family_dir)
if os.path.exists(args.out):
raise damaged("--out %s exists; a record is never overwritten" % args.out)
cap = load_capture()
try:
meta = cap.load_meta(args.meta, args.arm)
except cap.Fail as exc:
raise missing(exc.message) if "missing key" in exc.message else damaged(exc.message)
try:
rep = cap.load_replay(args.replay_output, meta)
except cap.Fail as exc:
raise damaged(exc.message)
lines = cap.read_text_lines(args.log, "--log")
requests, log_family, cpu_lines, versions = parse_serve_log(lines)
if cpu_lines:
raise damaged("the log carries a `cpu:` line (%r): the vanilla engine prints none, this is not a vanilla log" % cpu_lines[0][:120])
aligned = align_turns(requests, rep["turns"])
block = build_family_block(cap, log_family, versions, args.family_dir, meta)
facts = {"model": need(meta, "model", ("digest", "digest_mapping")),
"configuration": need(meta, "configuration", ("context_tokens", "kv", "slots", "batch", "speculation")),
"cache": need(meta, "cache", ("state", "metric", "value", "unit"))}
hardware = need(meta, "hardware", ("cpu_model",))
software = need(meta, "software", ("cuda_version",))
power_raw = cap.read_bytes(args.power_series, "--power-series")
try:
power = cap.parse_power(power_raw)
except cap.Fail as exc:
raise Fail(exc.code if exc.code == EXIT_POWER_NA else EXIT_INPUT, exc.message)
for key in ("thresholds_source", "thresholds_sha256"):
if not power["header"].get(key):
raise missing("--power-series: header line `# %s=`" % key)
max_limit = cap.machine_fact(power, "power_max_limit_w", "power.max_limit")
power_max = cap.to_float(max_limit) if max_limit else None
if power_max is None or not power_max > 0:
raise missing("power_max_limit_w: not in the power-series header or columns and nvidia-smi unreadable")
driver = software.get("driver_version") or cap.machine_fact(power, "driver_version", "driver_version")
if not driver:
raise missing("driver_version: not in --meta software, the power-series header or columns, and nvidia-smi unreadable")
gpu = hardware.get("gpu_name") or cap.machine_fact(power, "gpu_name", "name")
if not gpu:
raise missing("gpu_name: not in --meta hardware, the sampler column, and nvidia-smi unreadable")
facts.update({"power_max_limit_w": power_max, "driver_version": driver, "gpu_name": gpu, "cpu_model": hardware["cpu_model"],
"os": hardware.get("os") or cap.sys_os(), "cuda_version": software["cuda_version"],
"upstream_commit": software.get("strata_upstream_commit") or cap.upstream_commit(args.upstream_doc)})
try:
rec = assemble(cap, args, meta, rep, aligned, power, power_raw, facts, block)
except cap.Fail as exc:
raise damaged(exc.message)
out_dir = os.path.dirname(os.path.abspath(args.out))
os.makedirs(out_dir, exist_ok=True)
if args.parsed_out:
parsed = [dict(r, turn=t["turn"]) for r, t in zip(aligned, rep["turns"])]
with open(args.parsed_out, "w", encoding="utf-8", newline="\n") as f:
json.dump({"arm": args.arm, "warmup_requests": len(requests) - len(aligned), "turns": parsed}, f, indent=2)
f.write("\n")
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
# ---- check-set ------------------------------------------------------------------------------------------------------------------------------------
def read_row_b(path):
"""Same two formats as validate.py --row-b-env: a JSON list of NAME=VALUE strings, or one NAME=VALUE per line (# lines and blanks ignored)."""
try:
with open(path, "r", encoding="utf-8-sig") as f:
text = f.read()
except OSError as exc:
raise missing("--row-b-env %s: %s" % (path, exc.strerror or exc))
try:
entries = json.loads(text) if path.lower().endswith(".json") else [l.strip() for l in text.splitlines() if l.strip() and not l.lstrip().startswith("#")]
except ValueError as exc:
raise damaged("--row-b-env %s is not valid JSON: %s" % (path, exc))
if not isinstance(entries, list) or not all(isinstance(e, str) and "=" in e for e in entries):
raise damaged("--row-b-env %s must hold a list of NAME=VALUE strings" % path)
return dict(e.split("=", 1) for e in entries)
def env_dict(entries):
out = {}
for e in entries:
name, _, value = e.partition("=")
out[name] = value
return out
def load_records(directory):
if not os.path.isdir(directory):
raise missing("--dir %s is not a directory" % directory)
found = {}
names = sorted(n for n in os.listdir(directory) if n.lower().endswith(".json"))
if not names:
raise missing("--dir %s holds no record (*.json)" % directory)
for name in names:
path = os.path.join(directory, name)
try:
with open(path, "rb") as f:
rec = json.loads(f.read().decode("utf-8-sig"))
except (OSError, ValueError) as exc:
raise damaged("%s: not readable JSON: %s" % (name, exc))
arm = rec.get("arm_identity", {}).get("arm") if isinstance(rec, dict) and isinstance(rec.get("arm_identity"), dict) else None
if arm not in ARMS:
raise damaged("%s: not an S0.1 record (no arm_identity.arm of %s)" % (name, "/".join(ARMS)))
found.setdefault(arm, []).append((name, rec))
return found
def check_set(directory, row_b_path):
"""Returns the list of findings; each names the arm and the turn, or the variable."""
row_b = read_row_b(row_b_path)
found = load_records(directory)
problems = []
records = {}
for arm in ARMS:
if arm not in found:
problems.append("arm %s: no record in the set" % arm)
elif len(found[arm]) > 1:
problems.append("arm %s: %d records in the set (%s), one per arm expected" % (arm, len(found[arm]), ", ".join(n for n, _ in found[arm])))
if arm in found:
records[arm] = found[arm][0][1]
if not records:
return problems
ref_arm = "ours" if "ours" in records else sorted(records)[0]
ref = records[ref_arm]
def get(rec, path):
cur = rec
for key in path:
if not isinstance(cur, dict) or key not in cur:
return None
cur = cur[key]
return cur
scalar_fields = (("series_id", ("arm_identity", "series_id")), ("block", ("arm_identity", "block")), ("pair_id", ("arm_identity", "pair_id")),
("schedule_sha256", ("arm_identity", "schedule_sha256")), ("H0 id (h0_id)", ("arm_identity", "h0_id")),
("workload source_snapshot_sha256", ("workload", "source_snapshot_sha256")),
("machine (hardware.machine_role)", ("hardware", "machine_role")), ("hardware.cpu_model", ("hardware", "cpu_model")),
("hardware.gpu_name", ("hardware", "gpu_name")), ("hardware.os", ("hardware", "os")),
("model digest mapping (model.digest_mapping)", ("model", "digest_mapping")),
("cache state (cache.state)", ("cache", "state")),
("configuration.context_tokens", ("configuration", "context_tokens")),
("ours_build_id_frozen", ("ours_build_id_frozen",)))
for arm, rec in records.items():
if get(rec, ("cache", "state")) in (None, ""):
problems.append("arm %s: cache state is not recorded" % arm)
for arm, rec in records.items():
if arm == ref_arm:
continue
for label, path in scalar_fields:
a, b = get(ref, path), get(rec, path)
if a != b:
problems.append("arm %s: %s differs from arm %s (%r against %r)" % (arm, label, ref_arm, b, a))
ref_turns, turns = get(ref, ("metrics", "turns")) or [], get(rec, ("metrics", "turns")) or []
if len(ref_turns) != len(turns):
problems.append("arm %s: %d turns against %d in arm %s" % (arm, len(turns), len(ref_turns), ref_arm))
for k, (ta, tb) in enumerate(zip(ref_turns, turns)):
if ta.get("prompt_sha256") != tb.get("prompt_sha256"):
problems.append("arm %s, turn %d: prompt_sha256 %s differs from arm %s (%s)" % (arm, tb.get("turn", k + 1), tb.get("prompt_sha256"), ref_arm, ta.get("prompt_sha256")))
by_position = {}
for arm, rec in records.items():
position = get(rec, ("arm_identity", "position"))
if position in by_position:
problems.append("arm %s: position %r is also the position of arm %s" % (arm, position, by_position[position]))
by_position[position] = arm
for arm, rec in records.items():
position, predecessor = get(rec, ("arm_identity", "position")), get(rec, ("arm_identity", "predecessor_arm"))
expected = "none" if position == 1 else by_position.get(position - 1) if isinstance(position, int) else None
if expected is not None and predecessor != expected:
problems.append("arm %s: predecessor_arm %r, but the arm at position %d is %s" % (arm, predecessor, position - 1, expected))
for arm in ("ours", "vanilla_default"):
if arm in records and "vanilla_noskip_environment" in records[arm]:
problems.append("arm %s: carries vanilla_noskip_environment, only vanilla_noskip does" % arm)
if "vanilla_noskip" in records:
env = get(records["vanilla_noskip"], ("vanilla_noskip_environment",))
if not isinstance(env, list):
problems.append("arm vanilla_noskip: vanilla_noskip_environment is absent")
else:
have = env_dict(env)
for name in sorted(set(row_b) | set(have)):
if name not in have:
problems.append("arm vanilla_noskip: environment variable %s is missing (row (b) of S0.7 has %s=%s)" % (name, name, row_b[name]))
elif name not in row_b:
problems.append("arm vanilla_noskip: environment variable %s=%s is not in row (b) of S0.7" % (name, have[name]))
elif have[name] != row_b[name]:
problems.append("arm vanilla_noskip: environment variable %s is %r, row (b) of S0.7 has %r" % (name, have[name], row_b[name]))
return problems
def run_check_set(args):
problems = check_set(args.dir, args.row_b_env)
if problems:
for p in problems:
sys.stdout.write("INCONSISTENT %s\n" % p)
return EXIT_INCONSISTENT
sys.stdout.write("CONSISTENT ours, vanilla_default, vanilla_noskip\n")
return EXIT_OK
# ---- CLI ------------------------------------------------------------------------------------------------------------------------------------------
class Parser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write("capture_vanilla.py: usage error: %s\n" % message)
raise SystemExit(EXIT_USAGE)
def main(argv=None):
argv = list(sys.argv[1:] if argv is None else argv)
try:
if argv and argv[0] == "check-set":
ap = Parser(prog="capture_vanilla.py check-set", description="validate the three-arm set of one block")
ap.add_argument("--dir", required=True, help="directory of the records of one block")
ap.add_argument("--row-b-env", required=True, help="file with the literal list of row (b) of S0.7")
return run_check_set(ap.parse_args(argv[1:]))
ap = Parser(description=__doc__.split("\n")[0])
ap.add_argument("--log", required=True, help="vanilla engine log (stderr of strata --serve)")
ap.add_argument("--arm", required=True)
ap.add_argument("--replay-output", required=True)
ap.add_argument("--power-series", required=True)
ap.add_argument("--meta", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--family-dir", default=None, help="control.log, predicate.json, binary_identity.json")
ap.add_argument("--parsed-out", default=None, help="write the parsed per-turn engine values and per-round timing here (not part of the record)")
ap.add_argument("--upstream-doc", default=os.path.normpath(os.path.join(HERE, "..", "..", "..", "third_party", "strata", "UPSTREAM.md")),
help="third_party/strata/UPSTREAM.md (default: this checkout's)")
return run_capture(ap.parse_args(argv))
except Fail as exc:
sys.stderr.write("capture_vanilla: %s\n" % exc.message)
return exc.code
if __name__ == "__main__":
sys.exit(main())