#!/usr/bin/env python3 """Send a fixed prompt set to an OpenAI-compatible server, greedy, and record every completion. Used by session-det.sh for the "Same request, different answer" article. Each request carries a cache_salt (vLLM) so that runs never reuse each other's prefix cache unless the run asks for it: --salt run one salt per run: requests of this run may share cached blocks with each other only --salt request one salt per request: every request misses the prefix cache (cold) --salt shared a fixed salt (--salt-value): requests hit blocks cached by an earlier run (warm) Output: one JSON line per prompt (id, text, tokens, finish, latency) plus a meta line first. """ import argparse, asyncio, json, random, time, uuid import aiohttp async def one(session, url, model, item, args, salt): msgs = [] if args.prefix: msgs.append({"role": "system", "content": args.prefix}) msgs.append({"role": "user", "content": item["prompt"]}) body = { "model": model, "messages": msgs, "temperature": 0.0, "max_tokens": args.max_tokens, "seed": 0, "logprobs": True, "top_logprobs": 1, "chat_template_kwargs": {"enable_thinking": False}, } if args.ignore_eos: body["ignore_eos"] = True if salt is not None: body["cache_salt"] = salt t0 = time.time() async with session.post(url + "/v1/chat/completions", json=body) as r: txt = await r.text() if r.status != 200: return {"id": item["id"], "error": f"{r.status} {txt[:300]}"} d = json.loads(txt) ch = d["choices"][0] toks = [t["token"] for t in (ch.get("logprobs") or {}).get("content", [])] return {"id": item["id"], "text": ch["message"]["content"], "tokens": toks, "finish": ch.get("finish_reason"), "latency": time.time() - t0, "usage": d.get("usage")} async def main(): ap = argparse.ArgumentParser() ap.add_argument("--url", default="http://127.0.0.1:8011") ap.add_argument("--model", required=True) ap.add_argument("--prompts", required=True) ap.add_argument("--prefix-file") ap.add_argument("--limit", type=int, default=0) ap.add_argument("--concurrency", type=int, default=1) ap.add_argument("--max-tokens", type=int, default=200) ap.add_argument("--ignore-eos", action="store_true") ap.add_argument("--salt", choices=["run", "request", "shared", "none"], default="run") ap.add_argument("--salt-value", default="warm") ap.add_argument("--shuffle", type=int, default=-1, help="seed for the send order; -1 keeps file order") ap.add_argument("--out", required=True) args = ap.parse_args() args.prefix = open(args.prefix_file).read() if args.prefix_file else None items = [json.loads(l) for l in open(args.prompts)] if args.limit: items = items[: args.limit] order = list(items) if args.shuffle >= 0: random.Random(args.shuffle).shuffle(order) run_salt = uuid.uuid4().hex sem = asyncio.Semaphore(args.concurrency) results = {} timeout = aiohttp.ClientTimeout(total=3600) async with aiohttp.ClientSession(timeout=timeout) as s: async def guarded(it): async with sem: salt = {"run": run_salt, "request": uuid.uuid4().hex, "shared": args.salt_value, "none": None}[args.salt] results[it["id"]] = await one(s, args.url, args.model, it, args, salt) t0 = time.time() await asyncio.gather(*(guarded(it) for it in order)) wall = time.time() - t0 errors = sum(1 for r in results.values() if "error" in r) with open(args.out, "w") as f: f.write(json.dumps({"meta": {k: v for k, v in vars(args).items() if k != "prefix"}, "prefix_chars": len(args.prefix or ""), "wall": wall, "errors": errors, "n": len(items), "at": time.strftime("%F %T")}) + "\n") for it in items: f.write(json.dumps(results[it["id"]]) + "\n") print(f"{args.out}: n={len(items)} errors={errors} wall={wall:.1f}s") if __name__ == "__main__": asyncio.run(main())