121 lines
5.7 KiB
Python
121 lines
5.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Agent-shaped replay for the laptop engine: one conversation that starts big and then grows by small agent turns.
|
|
|
|
Turn 1 is a cold prompt of --first-tokens tokens of real Rust source (the repository's crates/ directory, in a fixed file order,
|
|
corpus digest recorded); every following turn appends --followup-tokens more source plus a question, so the prefix cache serves the
|
|
earlier turns the way a coding agent's session does. Per turn it records the input / cached / new tokens, TTFT, wall time, decode
|
|
tok/s (output tokens over the stream time after the first token) and prefill tok/s (new tokens over TTFT, which includes the
|
|
first token's own step). The reply text is never stored, only its hash.
|
|
|
|
lap_replay.py --label A-30k --first-tokens 30000 --followups 3 --out RESULTS.jsonl
|
|
E2E_BASE_URL (default http://127.0.0.1:8081), E2E_API_KEY or --key-file, E2E_MODEL (default: the first /v1/models id)
|
|
|
|
Test tooling: it reuses the streaming client of scripts/e2e/long_session.py.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import sys
|
|
import urllib.request
|
|
|
|
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent / "e2e"))
|
|
import long_session as ls # noqa: E402
|
|
|
|
CHARS_PER_TOKEN = 3.3
|
|
|
|
|
|
def model_id(base, key):
|
|
request = urllib.request.Request(base + "/v1/models", headers={"Authorization": "Bearer " + key})
|
|
with urllib.request.urlopen(request, timeout=30) as response:
|
|
return json.load(response)["data"][0]["id"]
|
|
|
|
|
|
def corpus_digest(files, src):
|
|
digest = hashlib.sha256()
|
|
for path in files:
|
|
data = pathlib.Path(path).read_bytes()
|
|
digest.update(os.path.relpath(path, src).replace("\\", "/").encode() + b"\0" + hashlib.sha256(data).digest())
|
|
return digest.hexdigest()
|
|
|
|
|
|
def build_turns(files, first_tokens, followups, followup_tokens):
|
|
"""The user texts of every turn (source chunks + a question), sized with the fixed 3.3 characters per token estimate."""
|
|
sizes = [first_tokens] + [followup_tokens] * followups
|
|
texts, position = [], 0
|
|
for turn, tokens in enumerate(sizes):
|
|
chunk, position = ls.take(files, position, int(tokens * CHARS_PER_TOKEN))
|
|
texts.append(chunk + "\n\n" + ls.QUESTIONS[turn % len(ls.QUESTIONS)])
|
|
return texts
|
|
|
|
|
|
def one_turn(args, base, key, model, items):
|
|
info, reply = ls.stream(base, key, model, items, args.max_output)
|
|
new_tokens = (info.get("input_tokens") or 0) - (info.get("cached_tokens") or 0)
|
|
if info.get("ttft_s") and new_tokens > 0:
|
|
info["new_tokens"] = new_tokens
|
|
info["prefill_tok_s"] = round(new_tokens / info["ttft_s"], 1)
|
|
return info, reply
|
|
|
|
|
|
def ladder(args, base, key, model, files):
|
|
"""Cold prompts of growing size (--ladder 4096,8192,...), each on its own part of the corpus so that no prefix is shared; stops at the first failure."""
|
|
position, results = 0, []
|
|
for rung, tokens in enumerate(int(t) for t in args.ladder.split(",")):
|
|
chunk, position = ls.take(files, position, int(tokens * CHARS_PER_TOKEN))
|
|
items = [{"role": "user", "content": [{"type": "input_text", "text": chunk + "\n\n" + ls.QUESTIONS[rung % len(ls.QUESTIONS)]}]}]
|
|
info, _ = one_turn(args, base, key, model, items)
|
|
info.update(label=args.label, rung=rung, target_tokens=tokens)
|
|
print(json.dumps(info), flush=True)
|
|
results.append(info)
|
|
if "error" in info or info.get("status") not in ("completed", "incomplete"):
|
|
break
|
|
return results
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--ladder", help="comma separated prompt sizes: cold prompts of growing size instead of one conversation")
|
|
parser.add_argument("--label", required=True)
|
|
parser.add_argument("--src", default=str(pathlib.Path(__file__).resolve().parents[2] / "crates"))
|
|
parser.add_argument("--first-tokens", type=int, default=30000)
|
|
parser.add_argument("--followups", type=int, default=3)
|
|
parser.add_argument("--followup-tokens", type=int, default=1500)
|
|
parser.add_argument("--max-output", type=int, default=200)
|
|
parser.add_argument("--key-file")
|
|
parser.add_argument("--out", required=True)
|
|
args = parser.parse_args()
|
|
base = os.environ.get("E2E_BASE_URL", "http://127.0.0.1:8081")
|
|
key = os.environ.get("E2E_API_KEY") or pathlib.Path(args.key_file).read_text().strip()
|
|
model = os.environ.get("E2E_MODEL") or model_id(base, key)
|
|
files = ls.collect(args.src)
|
|
if not files:
|
|
print("lap_replay: no .rs file under " + args.src, file=sys.stderr)
|
|
return 2
|
|
if args.ladder:
|
|
results = ladder(args, base, key, model, files)
|
|
with open(args.out, "a", encoding="utf-8") as out:
|
|
out.writelines(json.dumps(r) + "\n" for r in results)
|
|
return 0 if all(r.get("status") in ("completed", "incomplete") for r in results) else 1
|
|
header = {"label": args.label, "corpus_sha256": corpus_digest(files, args.src), "files": len(files), "model": model}
|
|
items, failed = [], False
|
|
with open(args.out, "a", encoding="utf-8") as out:
|
|
out.write(json.dumps(header) + "\n")
|
|
for turn, text in enumerate(build_turns(files, args.first_tokens, args.followups, args.followup_tokens), 1):
|
|
items.append({"role": "user", "content": [{"type": "input_text", "text": text}]})
|
|
info, reply = one_turn(args, base, key, model, items)
|
|
info.update(label=args.label, turn=turn)
|
|
out.write(json.dumps(info) + "\n")
|
|
out.flush()
|
|
print(json.dumps(info), flush=True)
|
|
if "error" in info:
|
|
failed = True
|
|
break
|
|
items.append({"role": "assistant", "content": [{"type": "output_text", "text": reply}]})
|
|
return 1 if failed else 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|