Add sequential single-GPU chat comparison runner
This commit is contained in:
@@ -238,7 +238,8 @@ def main():
|
||||
"model": args.model, "configuration": {"repeats": args.repeats,
|
||||
"max_tokens": args.max_tokens, "temperature": 0, "seed": 42,
|
||||
"reasoning_effort": "none", "stream": False, "cache_state":
|
||||
"one untimed warmup per case and arm, then sequential alternating arm order"},
|
||||
("one untimed warmup per case and arm, then sequential alternating arm order"
|
||||
if "candidate" in arms else "one untimed warmup per case, then sequential repeats")},
|
||||
"metadata": metadata, "rows": rows,
|
||||
"summary": summarize(rows, "candidate" in arms)}
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run private baseline/KAR-PLE Chat quality arms sequentially on one GPU.
|
||||
|
||||
The original server config is read but never changed. Per-arm config files live
|
||||
in tmpfs and are removed after each arm. This is an offline experiment helper;
|
||||
the production control plane remains independent of Python.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
|
||||
def sha256(path):
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as file:
|
||||
for chunk in iter(lambda: file.read(8 * 1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def safe_engine_args(values):
|
||||
allowed = {"--pack", "--native", "--ple-gguf", "--max-context", "--kv",
|
||||
"--kv-resident", "--spec", "--spec-min-p", "--expert-cache",
|
||||
"--prefill", "--vram-reserve-mib"}
|
||||
return {flag: values[index + 1] for index, flag in enumerate(values[:-1])
|
||||
if flag in allowed}
|
||||
|
||||
|
||||
def ready(port, process, timeout):
|
||||
deadline = time.monotonic() + timeout
|
||||
url = f"http://127.0.0.1:{port}/health"
|
||||
while time.monotonic() < deadline:
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError(f"server exited during load with code {process.returncode}")
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=3) as response:
|
||||
state = json.load(response)
|
||||
if state.get("loaded") and state.get("max_context", 0) > 0:
|
||||
return
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
time.sleep(2)
|
||||
raise TimeoutError("model did not become ready")
|
||||
|
||||
|
||||
def unload(port, key):
|
||||
request = urllib.request.Request(
|
||||
f"http://127.0.0.1:{port}/unload", data=b"{}",
|
||||
headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"},
|
||||
method="POST")
|
||||
with urllib.request.urlopen(request, timeout=180) as response:
|
||||
if response.status != 200:
|
||||
raise RuntimeError("model unload failed")
|
||||
|
||||
|
||||
def arm(name, exe, config, args):
|
||||
cfg = dict(config)
|
||||
cfg["exe"] = str(exe)
|
||||
cfg["args"] = list(config["args"])
|
||||
if name == "candidate":
|
||||
cfg["args"] += ["--ple-kar", str(args.kar), "--ple-kar-level", "2"]
|
||||
cfg["log"] = str(args.output_dir / f"{name}-engine.log")
|
||||
fd, config_name = tempfile.mkstemp(prefix="strata-next-ab-", suffix=".json", dir=args.tmpfs)
|
||||
temp_config = Path(config_name)
|
||||
process = None
|
||||
model_loaded = False
|
||||
server_log = args.output_dir / f"{name}-server.log"
|
||||
try:
|
||||
with os.fdopen(fd, "w") as file:
|
||||
json.dump(cfg, file)
|
||||
with server_log.open("x") as log:
|
||||
process = subprocess.Popen([
|
||||
str(args.server_python), str(args.server_script), "--engine", "strata",
|
||||
"--config", str(temp_config), "--host", "127.0.0.1",
|
||||
"--port", str(args.port),
|
||||
], stdout=log, stderr=subprocess.STDOUT, cwd=config["cwd"], start_new_session=True)
|
||||
ready(args.port, process, args.load_timeout_seconds)
|
||||
model_loaded = True
|
||||
metadata = {
|
||||
"arm": name,
|
||||
"engine_exe_sha256": sha256(exe),
|
||||
"kar_sha256": args.kar_sha256 if name == "candidate" else None,
|
||||
"project_commit": args.project_commit,
|
||||
"engine_settings": safe_engine_args(config["args"]),
|
||||
"experiment": "PLE-only KAR L2 CPU quality arm; all other weights native",
|
||||
"load_order": "baseline then candidate",
|
||||
"shared": args.shared_metadata,
|
||||
}
|
||||
metadata_file = args.output_dir / f"{name}-metadata.json"
|
||||
with metadata_file.open("x") as file:
|
||||
json.dump(metadata, file, indent=2)
|
||||
command = [
|
||||
sys.executable, str(args.benchmark_script), "--suite", str(args.suite),
|
||||
"--baseline-url", f"http://127.0.0.1:{args.port}/v1/chat/completions",
|
||||
"--baseline-ready-url", f"http://127.0.0.1:{args.port}/health",
|
||||
"--baseline-auth-config", str(temp_config), "--model", config["model_name"],
|
||||
"--repeats", str(args.repeats), "--max-tokens", str(args.max_tokens),
|
||||
"--metadata", str(metadata_file),
|
||||
"--output", str(args.output_dir / f"{name}-chat.json"),
|
||||
]
|
||||
subprocess.run(command, check=True)
|
||||
unload(args.port, cfg["api_key"])
|
||||
model_loaded = False
|
||||
finally:
|
||||
if process is not None:
|
||||
if model_loaded and process.poll() is None:
|
||||
try:
|
||||
unload(args.port, cfg["api_key"])
|
||||
except (OSError, RuntimeError):
|
||||
pass
|
||||
try:
|
||||
os.killpg(process.pid, signal.SIGTERM)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
try:
|
||||
process.wait(timeout=15)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
process.wait(timeout=15)
|
||||
temp_config.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--source-config", type=Path, required=True)
|
||||
parser.add_argument("--server-script", type=Path, required=True)
|
||||
parser.add_argument("--server-python", type=Path, required=True)
|
||||
parser.add_argument("--baseline-exe", type=Path, required=True)
|
||||
parser.add_argument("--candidate-exe", type=Path, required=True)
|
||||
parser.add_argument("--kar", type=Path, required=True)
|
||||
parser.add_argument("--kar-sha256", required=True)
|
||||
parser.add_argument("--project-commit", required=True)
|
||||
parser.add_argument("--shared-metadata", type=Path)
|
||||
parser.add_argument("--benchmark-script", type=Path, required=True)
|
||||
parser.add_argument("--compare-script", type=Path, required=True)
|
||||
parser.add_argument("--suite", type=Path, required=True)
|
||||
parser.add_argument("--output-dir", type=Path, required=True)
|
||||
parser.add_argument("--port", type=int, default=18081)
|
||||
parser.add_argument("--repeats", type=int, default=5)
|
||||
parser.add_argument("--max-tokens", type=int, default=128)
|
||||
parser.add_argument("--load-timeout-seconds", type=float, default=1800)
|
||||
parser.add_argument("--tmpfs", type=Path, default=Path("/dev/shm"))
|
||||
args = parser.parse_args()
|
||||
if args.port < 1024 or args.repeats < 1 or args.max_tokens < 1:
|
||||
parser.error("invalid port, repeats, or max tokens")
|
||||
repository = Path(__file__).resolve().parent.parent
|
||||
args.output_dir = args.output_dir.resolve()
|
||||
if args.output_dir == repository or repository in args.output_dir.parents:
|
||||
parser.error("output directory must be outside the repository")
|
||||
original = json.loads(args.source_config.read_text())
|
||||
if not original.get("api_key") or not original.get("model_name") or not original.get("cwd"):
|
||||
parser.error("source config lacks required private server fields")
|
||||
if sha256(args.kar) != args.kar_sha256.lower():
|
||||
raise ValueError("KAR archive SHA-256 does not match the expected digest")
|
||||
args.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
if any(args.output_dir.iterdir()):
|
||||
parser.error("output directory must be empty")
|
||||
raw_metadata = (json.loads(args.shared_metadata.read_text())
|
||||
if args.shared_metadata else {})
|
||||
allowed_metadata = {"engine_commit", "gpu", "model_quant", "model_shard_sha256",
|
||||
"profile", "storage", "config_sha256"}
|
||||
args.shared_metadata = {key: raw_metadata[key] for key in allowed_metadata
|
||||
if key in raw_metadata}
|
||||
old_mask = os.umask(0o077)
|
||||
try:
|
||||
for name, exe in (("baseline", args.baseline_exe), ("candidate", args.candidate_exe)):
|
||||
arm(name, exe, original, args)
|
||||
subprocess.run([
|
||||
sys.executable, str(args.compare_script),
|
||||
str(args.output_dir / "baseline-chat.json"),
|
||||
str(args.output_dir / "candidate-chat.json"),
|
||||
"--output", str(args.output_dir / "paired-comparison.json"),
|
||||
], check=True)
|
||||
finally:
|
||||
os.umask(old_mask)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -3,7 +3,7 @@ set -euo pipefail
|
||||
|
||||
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
|
||||
python3 -m py_compile "${repo_root}/scripts/bench-chat-paired.py" "${repo_root}/scripts/check-kar-cuda-records.py"
|
||||
python3 -m py_compile "${repo_root}/scripts/bench-chat-paired.py" "${repo_root}/scripts/compare-chat-reports.py" "${repo_root}/scripts/bench-chat-sequential-server.py" "${repo_root}/scripts/check-kar-cuda-records.py"
|
||||
python3 "${repo_root}/scripts/test-benchmark-harness.py"
|
||||
|
||||
cargo fmt --manifest-path "${repo_root}/control-plane/Cargo.toml" --check
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare two private, sequential runs of bench-chat-paired.py.
|
||||
|
||||
Useful on one GPU when both model arms cannot fit in VRAM together. The output
|
||||
is a descriptive paired report; load order and disk/cache drift still matter.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import statistics
|
||||
|
||||
|
||||
def normalized(row):
|
||||
try:
|
||||
message = row["response"]["choices"][0]["message"]
|
||||
return {
|
||||
"content": message.get("content"),
|
||||
"tool_calls": [
|
||||
{"name": call["function"]["name"],
|
||||
"arguments": json.loads(call["function"]["arguments"])}
|
||||
for call in message.get("tool_calls") or []
|
||||
],
|
||||
}
|
||||
except (KeyError, IndexError, TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def selected(report):
|
||||
rows = {}
|
||||
for row in report["rows"]:
|
||||
if row["warmup"]:
|
||||
continue
|
||||
key = (row["case_id"], row["repeat"])
|
||||
if key in rows:
|
||||
raise ValueError(f"duplicate run {key}")
|
||||
rows[key] = row
|
||||
return rows
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("baseline", type=Path)
|
||||
parser.add_argument("candidate", type=Path)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
repository = Path(__file__).resolve().parent.parent
|
||||
output = args.output.resolve()
|
||||
if output == repository or repository in output.parents:
|
||||
parser.error("output must be outside the repository")
|
||||
base, candidate = (json.loads(path.read_text()) for path in
|
||||
(args.baseline, args.candidate))
|
||||
for field in ("schema", "suite_sha256", "model", "configuration"):
|
||||
if base[field] != candidate[field]:
|
||||
raise ValueError(f"reports differ in {field}")
|
||||
b_rows, c_rows = selected(base), selected(candidate)
|
||||
if not b_rows or b_rows.keys() != c_rows.keys():
|
||||
raise ValueError("reports do not contain the same measured cases")
|
||||
pairs = []
|
||||
for key in sorted(b_rows):
|
||||
b, c = b_rows[key], c_rows[key]
|
||||
if b["category"] != c["category"]:
|
||||
raise ValueError("case category differs")
|
||||
pairs.append({
|
||||
"case_id": key[0], "repeat": key[1], "category": b["category"],
|
||||
"baseline_wall_seconds": b["wall_seconds"],
|
||||
"candidate_wall_seconds": c["wall_seconds"],
|
||||
"candidate_over_baseline_wall_ratio": c["wall_seconds"] / b["wall_seconds"],
|
||||
"baseline_quality_passed": b["quality"]["passed"],
|
||||
"candidate_quality_passed": c["quality"]["passed"],
|
||||
"same_normalized_output": normalized(b) == normalized(c),
|
||||
"baseline_usage": b["response"].get("usage") if isinstance(b["response"], dict) else None,
|
||||
"candidate_usage": c["response"].get("usage") if isinstance(c["response"], dict) else None,
|
||||
})
|
||||
categories = {}
|
||||
for category in sorted({pair["category"] for pair in pairs}):
|
||||
members = [pair for pair in pairs if pair["category"] == category]
|
||||
categories[category] = {
|
||||
"pairs": len(members),
|
||||
"same_normalized_output": sum(p["same_normalized_output"] for p in members),
|
||||
"both_quality_passed": sum(p["baseline_quality_passed"] and
|
||||
p["candidate_quality_passed"] for p in members),
|
||||
"candidate_over_baseline_wall_median_ratio": statistics.median(
|
||||
p["candidate_over_baseline_wall_ratio"] for p in members),
|
||||
}
|
||||
report = {
|
||||
"schema": 1, "created_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
|
||||
"baseline_report": str(args.baseline.resolve()),
|
||||
"candidate_report": str(args.candidate.resolve()),
|
||||
"baseline_metadata": base.get("metadata", {}),
|
||||
"candidate_metadata": candidate.get("metadata", {}),
|
||||
"comparison_limit": "Sequential model loads on one GPU; wall times include API and may drift with I/O and cache state.",
|
||||
"summary": {
|
||||
"pairs": len(pairs),
|
||||
"baseline_quality_passed": sum(p["baseline_quality_passed"] for p in pairs),
|
||||
"candidate_quality_passed": sum(p["candidate_quality_passed"] for p in pairs),
|
||||
"same_normalized_output": sum(p["same_normalized_output"] for p in pairs),
|
||||
"candidate_over_baseline_wall_median_ratio": statistics.median(
|
||||
p["candidate_over_baseline_wall_ratio"] for p in pairs),
|
||||
"categories": categories,
|
||||
},
|
||||
"pairs": pairs,
|
||||
}
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
old_mask = os.umask(0o077)
|
||||
try:
|
||||
with output.open("x", encoding="utf-8") as file:
|
||||
json.dump(report, file, indent=2, ensure_ascii=False)
|
||||
file.write("\n")
|
||||
finally:
|
||||
os.umask(old_mask)
|
||||
print(json.dumps(report["summary"], indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -79,6 +79,28 @@ def main():
|
||||
assert summary["paired"]["pairs"] == 3
|
||||
assert summary["paired"]["same_normalized_output"] == 3
|
||||
assert HEALTH_CHECKS >= 3
|
||||
solo = []
|
||||
for name in ("baseline", "candidate"):
|
||||
path = private / f"{name}.json"
|
||||
subprocess.run([
|
||||
"python3", str(root / "scripts/bench-chat-paired.py"),
|
||||
"--suite", str(root / "benchmarks/fixtures/chat/paired-smoke.json"),
|
||||
"--baseline-url", url + "/chat",
|
||||
"--baseline-auth-config", str(config),
|
||||
"--model", "mock", "--repeats", "1", "--output", str(path),
|
||||
], check=True, capture_output=True, text=True)
|
||||
solo.append(path)
|
||||
compared = private / "sequential-comparison.json"
|
||||
subprocess.run([
|
||||
"python3", str(root / "scripts/compare-chat-reports.py"),
|
||||
str(solo[0]), str(solo[1]), "--output", str(compared),
|
||||
], check=True, capture_output=True, text=True)
|
||||
assert stat.S_IMODE(compared.stat().st_mode) == 0o600
|
||||
assert TOKEN not in compared.read_text()
|
||||
sequential = json.loads(compared.read_text())["summary"]
|
||||
assert sequential["pairs"] == 3
|
||||
assert sequential["same_normalized_output"] == 3
|
||||
assert sequential["candidate_quality_passed"] == 3
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
Reference in New Issue
Block a user