"""Controlled baseline and C1/C4/C8 concurrency study using SGLang native SSE.""" import argparse import ast import asyncio import hashlib import importlib.metadata import json import math import platform import statistics import subprocess import time import uuid from datetime import datetime, timezone from pathlib import Path import aiohttp from prompts import MODEL, REVISION, digest, load_manifest, strict_json ROOT = Path(__file__).resolve().parent SAMPLING = dict(temperature=0, top_p=1.0, top_k=-1, min_p=0.0, max_new_tokens=64, ignore_eos=True, repetition_penalty=1.0, frequency_penalty=0.0, presence_penalty=0.0, stop=None, stop_token_ids=None, stop_regex=None, sampling_seed=42, stream_interval=1, n=1) TIMEOUT = 120 SCHEDULE = [(1, 1), (4, 1), (8, 1), (8, 2), (1, 2), (4, 2), (4, 3), (8, 3), (1, 3)] def sampling_for_output(target): if type(target) is not int or target not in (1,32,64,128,256): raise ValueError("Output length must be 1 (primer), 32, 64, 128, or 256") return {**SAMPLING, "max_new_tokens":target} def validate_concurrency(value): value = int(value) if value not in (1, 4, 8): raise ValueError("Concurrency must be 1, 4, or 8") return value def make_run_id(mode, concurrency=1, repetition=None): label = f"concurrency_c{concurrency}_r{repetition}" if mode == "concurrency" else mode return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + "-" + label + "-" + uuid.uuid4().hex[:8] async def dispatch(prompts, concurrency, invoke): """FIFO slot acquisition; stop new submissions on failure, drain in-flight work.""" semaphore = asyncio.Semaphore(validate_concurrency(concurrency)) stopped = False async def limited(prompt): nonlocal stopped async with semaphore: if stopped: return None result = await invoke(prompt) # request timer starts only after acquisition if not result["contract_valid"]: stopped = True return result records = await asyncio.gather(*(limited(p) for p in prompts)) return [r for r in records if r is not None] def cross_run_summary(runs): valid = [r for r in runs if r.get("experiment") == "concurrency_scaling" and r.get("status") == "passed" and r.get("primary_comparison_eligible") and all(r.get("aggregates", {}).get(k) == 40 for k in ("attempted", "successful", "contract_success"))] groups = {} for c in (1, 4, 8): group = [r for r in valid if r["concurrency"] == c] if len(group) != 3 or {r["repetition"] for r in group} != {1, 2, 3}: raise ValueError(f"Need exactly three valid distinct repetitions for C{c}") values = {} for key in ("ttft_s", "tpot_s", "e2e_s", "output_throughput_tps", "request_throughput_rps"): individual = [{"run_id": r["run_id"], "value": r["aggregates"][key]["mean"] if key.endswith("_s") else r["aggregates"][key]} for r in group] nums = [v["value"] for v in individual] if not all(math.isfinite(v) for v in nums): raise ValueError("Nonfinite summary metric") values[key] = {"median": statistics.median(nums), "min": min(nums), "max": max(nums), "runs": individual} groups[str(c)] = values return {"schema_version": 1, "method": "median and min/max of three run-level means or throughputs; no request pooling", "concurrency": groups, "excluded_run_ids": [r["run_id"] for r in runs if r not in valid], "individual_runs": [{k:r[k] for k in ("run_id", "concurrency", "repetition", "aggregates")} for r in valid]} class SSEParser: """Incremental byte framing; handles arbitrary transport splits and CRLF.""" def __init__(self): self.buffer = b"" self.data = [] def feed(self, chunk): self.buffer += chunk events = [] while b"\n" in self.buffer: line, self.buffer = self.buffer.split(b"\n", 1) line = line.removesuffix(b"\r") if not line: if self.data: events.append(b"\n".join(self.data).decode("utf-8")) self.data = [] elif line.startswith(b"data:"): self.data.append(line[5:].removeprefix(b" ")) return events def finish(self): if self.buffer or self.data: raise ValueError("Truncated SSE event at EOF") def new_record(run_id, prompt, role="measured"): return dict(schema_version=1, run_id=run_id, request_id=prompt["prompt_id"], prompt_id=prompt["prompt_id"], role=role, submitted_input_tokens=len(prompt["input_ids"]), target_input_tokens=prompt.get("input_tokens", len(prompt["input_ids"])), server_reported_prompt_tokens=None, requested_output_tokens=prompt.get("requested_output_tokens",64), server_reported_output_tokens=None, submitted_at=None, first_output_at=None, last_output_at=None, terminal_at=None, settled_at=None, ttft_s=None, tpot_s=None, e2e_s=None, http_status=None, success=False, contract_valid=False, violation_reasons=[], finish_reason=None, error=None, cached_tokens=None, terminal_kind=None, timing_signal="completion_tokens_growth", stream_events=[]) def observe(record, event, offset): if event == "[DONE]": record["terminal_at"] = offset record["terminal_kind"] = "DONE" return True data = json.loads(event) if "error" in data: raise ValueError(f"Server stream error: {data['error']}") meta = data.get("meta_info", {}) count = meta.get("completion_tokens") if type(count) is not int or count < 0: raise ValueError("Streaming event lacks reliable completion_tokens") previous = record["server_reported_output_tokens"] or 0 if count < previous: raise ValueError("Non-monotonic completion_tokens") prompt_count = meta.get("prompt_tokens") if prompt_count is not None: old = record["server_reported_prompt_tokens"] if old is not None and old != prompt_count: raise ValueError("Changing prompt_tokens") record["server_reported_prompt_tokens"] = prompt_count record["server_reported_output_tokens"] = count record["cached_tokens"] = meta.get("cached_tokens", record["cached_tokens"]) record["finish_reason"] = meta.get("finish_reason", record["finish_reason"]) record["stream_events"].append({"at": offset, "completion_tokens": count, "text_present": bool(data.get("text")), "prompt_tokens": prompt_count, "cached_tokens": meta.get("cached_tokens"), "finish_reason": meta.get("finish_reason")}) if count > previous: if record["first_output_at"] is None: record["first_output_at"] = offset record["last_output_at"] = offset return False def finalize(record, require_cold=False): issues = [] for key in ("ttft_s", "tpot_s", "e2e_s"): record[key] = None start, first, last, terminal = [record[k] for k in ("submitted_at", "first_output_at", "last_output_at", "terminal_at")] if all(t is not None for t in (start, first, last, terminal)): if not start <= first <= last <= terminal: issues.append("timing_order") else: record["ttft_s"] = first - start record["e2e_s"] = terminal - start n = record["server_reported_output_tokens"] record["tpot_s"] = (last - first) / (n - 1) if n and n > 1 else None else: issues.append("missing_output_or_terminal_timing") target = record.get("target_input_tokens", 512) if record["submitted_input_tokens"] != target or record["server_reported_prompt_tokens"] != target: issues.append("prompt_length_mismatch") if record["server_reported_output_tokens"] != record["requested_output_tokens"]: issues.append("output_length_mismatch") if require_cold and record["cached_tokens"] != 0: issues.append("cache_not_verified_zero") finish = record["finish_reason"] record["success"] = bool(record["http_status"] == 200 and record["error"] is None and terminal is not None and isinstance(finish, dict) and finish.get("type") == "length") if not record["success"]: issues.append("unsuccessful_response") record["violation_reasons"] = issues record["contract_valid"] = not issues return record async def request(session, base_url, prompt, run_id, origin, require_cold=False, role="measured"): record = new_record(run_id, prompt, role) parser = SSEParser() payload = {"input_ids": prompt["input_ids"], "sampling_params": sampling_for_output(record["requested_output_tokens"]), "stream": True} record["submitted_at"] = time.perf_counter() - origin try: async with session.post(base_url + "/generate", json=payload) as response: record["http_status"] = response.status if response.status != 200: raise RuntimeError(f"HTTP {response.status}: {(await response.text())[:500]}") if "text/event-stream" not in response.headers.get("Content-Type", ""): raise ValueError("Expected SSE response") done = False async for chunk in response.content.iter_any(): for event in parser.feed(chunk): # Observed complete SSE event time; no fabricated within-chunk token timestamps. if observe(record, event, time.perf_counter() - origin): done = True break if done: break if not done: parser.finish() record["terminal_at"] = time.perf_counter() - origin record["terminal_kind"] = "clean_eof" except Exception as exc: record["error"] = {"type": type(exc).__name__, "message": str(exc)[:1000]} record["settled_at"] = time.perf_counter() - origin return finalize(record, require_cold) def percentile(values, q): """Linear interpolation at (n-1)*q (Hyndman-Fan type 7).""" if not values: return None values = sorted(values) at = (len(values) - 1) * q lo, hi = math.floor(at), math.ceil(at) return values[lo] + (values[hi] - values[lo]) * (at - lo) def aggregate(records, duration): successful = [r for r in records if r["success"]] tokens = sum(r["server_reported_output_tokens"] or 0 for r in successful) result = dict(attempted=len(records), successful=len(successful), failed=len(records)-len(successful), contract_success=sum(r["contract_valid"] for r in records), workload_duration_s=duration, total_output_tokens=tokens, request_throughput_rps=len(successful)/duration if duration > 0 else None, output_throughput_tps=tokens/duration if duration > 0 else None) for key in ("ttft_s", "tpot_s", "e2e_s"): values = [r[key] for r in successful if r[key] is not None] result[key] = {"count": len(values), "mean": statistics.mean(values) if values else None, "median": percentile(values, .5), "p95": percentile(values, .95)} return result def save_json(path, data): path.write_text(strict_json(data) + "\n", encoding="utf-8") async def get_json(session, url): async with session.get(url) as response: response.raise_for_status() return await response.json() async def flush(session, base_url): async with session.post(base_url + "/flush_cache", params={"timeout": 30}) as response: text = await response.text() if response.status != 200 or not text.startswith("Cache flushed."): raise RuntimeError(f"Cache reset not acknowledged: {response.status} {text[:300]}") return {"http_status": response.status, "acknowledgment": text} def environment(): import torch def command(args): p = subprocess.run(args, capture_output=True, text=True, timeout=15) return p.stdout.strip() if p.returncode == 0 else None return {"python": platform.python_version(), "os": platform.platform(), "kernel": platform.release(), "sglang": importlib.metadata.version("sglang"), "aiohttp": aiohttp.__version__, "transformers": importlib.metadata.version("transformers"), "pytorch": torch.__version__, "torch_cuda": torch.version.cuda, "gpu": command(["nvidia-smi", "--query-gpu=name,memory.total,driver_version", "--format=csv,noheader"]), "git_revision": command(["git", "-C", str(ROOT), "rev-parse", "HEAD"]), "source_hashes": {f: hashlib.sha256((ROOT/f).read_bytes()).hexdigest() for f in ("benchmark.py", "prompts.py")}} def resolved_subset(info): keys = ("model_path", "tokenizer_path", "revision", "device", "host", "port", "dtype", "quantization", "random_seed", "mem_fraction_static", "chunked_prefill_size", "max_prefill_tokens", "schedule_policy", "disable_radix_cache", "stream_interval", "attention_backend", "sampling_backend", "sampling_defaults", "skip_server_warmup", "enable_cache_report", "tp_size", "pp_size", "dp_size", "cuda_graph_config") return {key: info.get(key) for key in keys} async def run(mode, base_url, concurrency=1, repetition=None, order=None, study_id=None, input_length=512, output_length=64): validate_concurrency(concurrency) sampling = sampling_for_output(output_length) manifest = load_manifest(input_length) measured = [{**p,"requested_output_tokens":output_length} for p in manifest["prompts"] if p["role"] == "measured"] warmup = [{**p,"requested_output_tokens":output_length} for p in manifest["prompts"] if p["role"] == "warmup"] manifest_path = ROOT/"configs"/("prompt_manifest.json" if input_length == 512 else f"prompt_manifest_{input_length}.json") if manifest_path.exists() and json.loads(manifest_path.read_text()) != manifest: raise RuntimeError("Existing prompt manifest differs; refusing overwrite") if not manifest_path.exists(): save_json(manifest_path, manifest) env = environment() if env["sglang"] != "0.5.19": raise RuntimeError("Requires recovered SGLang 0.5.19") run_id = make_run_id(mode, concurrency, repetition) if mode == "prompt_length": run_id = make_run_id(f"prompt_length_l{input_length}_r{repetition}") if mode == "output_length": run_id = make_run_id(f"output_length_o{output_length}_r{repetition}") output = ROOT/"results/runs"/run_id output.mkdir(parents=True, exist_ok=False) metadata = dict(schema_version=1, run_id=run_id, timestamp_utc=datetime.now(timezone.utc).isoformat(), experiment="output_length_scaling" if mode == "output_length" else ("prompt_length_scaling" if mode == "prompt_length" else ("concurrency_scaling" if mode == "concurrency" else ("canonical_baseline" if mode == "validation" else "protocol_preflight"))), repetition=repetition if mode in ("concurrency", "prompt_length", "output_length") else mode, status="preparing", model=MODEL, tokenizer=MODEL, revision=REVISION, environment=env, endpoint=base_url+"/generate", concurrency=concurrency, measured_requests=0 if mode=="preflight" else 40, execution_order=order, study_id=study_id, prompt_order=[p["prompt_id"] for p in measured], input_tokens=input_length, requested_output_tokens=output_length, sampling=sampling, prompt_manifest_sha256=hashlib.sha256(manifest_path.read_bytes()).hexdigest(), prompt_manifest_path=str(manifest_path.relative_to(ROOT)), timeout_s=TIMEOUT, cache_policy="idle flush acknowledged; distinct first IDs; measured cached_tokens must be zero", warmup_policy=f"8 separate {input_length}/{output_length} C{concurrency} requests, excluded; flush after completion", percentile_method="linear interpolation (n-1)*q, type 7", server_command=None) save_json(output/"run.json", metadata) try: async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=TIMEOUT), trust_env=False) as session: info = await get_json(session, base_url+"/get_model_info") if info.get("model_path") != MODEL: raise RuntimeError("Unexpected server model") server = await get_json(session, base_url+"/server_info") if server.get("version") != "0.5.19": raise RuntimeError("Unexpected server version") if server.get("revision") != REVISION or server.get("tokenizer_path") != MODEL: raise RuntimeError("Server/tokenizer revision does not match pinned workload") if server.get("random_seed") != 42 or server.get("disable_radix_cache") is not False: raise RuntimeError("Unexpected seed or radix-cache configuration") metadata["resolved_server_config"] = resolved_subset(server) metadata["server_version"] = server.get("version") # Optional operator-supplied launch provenance, not inferred from defaults. provenance = ROOT/"configs"/("output_length_server.json" if mode == "output_length" else ("prompt_length_server.json" if mode == "prompt_length" else ("concurrency_server.json" if mode == "concurrency" else "validation_server.json"))) if provenance.exists(): metadata["server_launch"] = json.loads(provenance.read_text()) metadata["server_command"] = metadata["server_launch"]["command"] metadata["server_session_id"] = metadata["server_launch"].get("server_session_id") if mode in ("concurrency", "prompt_length", "output_length"): expected = metadata["server_launch"] pid = expected["pid"] proc = Path(f"/proc/{pid}/stat") if not proc.exists() or proc.read_text().split()[21] != expected["proc_start_ticks"]: raise RuntimeError("Server session process changed") if metadata["resolved_server_config"] != expected["resolved_server_config"]: raise RuntimeError("Server configuration changed from session preflight") if mode == "preflight": metadata["preflight_flush"] = await flush(session, base_url) r = await request(session, base_url, measured[0], run_id, time.perf_counter(), True, "preflight") save_json(output/"protocol_record.json", r) if not r["contract_valid"]: raise RuntimeError(f"Preflight contract failed: {r['violation_reasons']}; {r['error']}") metadata["status"] = "passed" else: # Require a preserved successful protocol check before the one validation workload. passed = [] for p in sorted((ROOT/"results/runs").glob("*-preflight-*/run.json")): prior = json.loads(p.read_text()) if (prior.get("status") == "passed" and prior.get("revision") == REVISION and prior.get("endpoint") == metadata["endpoint"] and prior.get("prompt_manifest_sha256") == hashlib.sha256((ROOT/"configs/prompt_manifest.json").read_bytes()).hexdigest()): passed.append(p) if not passed: raise RuntimeError("Run protocol preflight before validation") metadata["protocol_preflight"] = str(passed[-1].parent.relative_to(ROOT)) warm_origin = time.perf_counter() warm_records = await dispatch(warmup, concurrency, lambda p: request(session, base_url, p, run_id, warm_origin, role="warmup")) save_json(output/"warmup.json", warm_records) if len(warm_records) != 8 or not all(r["contract_valid"] for r in warm_records): raise RuntimeError("Warmup contract failed") metadata["cache_flush"] = await flush(session, base_url) records = [] # No file writes, metadata HTTP calls, or warmup inside this boundary. origin = time.perf_counter() records = await dispatch(measured, concurrency, lambda p: request(session, base_url, p, run_id, origin, True)) duration = time.perf_counter() - origin with (output/"requests.jsonl").open("x", encoding="utf-8") as f: for r in records: f.write(strict_json(r)+"\n") metadata["aggregates"] = aggregate(records, duration) metadata["status"] = "passed" if len(records)==40 and all(r["contract_valid"] for r in records) else "failed" metadata["primary_comparison_eligible"] = mode in ("concurrency", "prompt_length", "output_length") and metadata["status"] == "passed" reread = [json.loads(line) for line in (output/"requests.jsonl").read_text().splitlines()] if aggregate(reread, duration) != metadata["aggregates"]: raise RuntimeError("Raw aggregate roundtrip mismatch") if metadata["status"] != "passed": raise RuntimeError("Measured workload stopped on a contract violation; inspect raw records") except Exception as exc: metadata["status"] = "failed" metadata["primary_comparison_eligible"] = False metadata["error"] = {"type": type(exc).__name__, "message": str(exc)} raise finally: save_json(output/"run.json", metadata) print(strict_json({"output": str(output), "status": metadata["status"], "aggregates": metadata.get("aggregates")})) return metadata async def concurrency_study(base_url): study_id = make_run_id("concurrency-study") directory = ROOT/"results"/study_id directory.mkdir(exist_ok=False) schedule = {"study_id": study_id, "schedule": [{"order": i, "concurrency": c, "repetition": r} for i, (c, r) in enumerate(SCHEDULE, 1)], "completed_run_ids": [], "status": "running"} save_json(directory/"schedule.json", schedule) runs = [] try: for i, (c, rep) in enumerate(SCHEDULE, 1): result = await run("concurrency", base_url, c, rep, i, study_id) runs.append(result) schedule["completed_run_ids"].append(result["run_id"]) save_json(directory/"schedule.json", schedule) summary = cross_run_summary(runs) summary["study_id"] = study_id save_json(directory/"summary.json", summary) schedule["status"] = "passed" except Exception as exc: schedule["status"] = "failed" schedule["error"] = str(exc) raise finally: save_json(directory/"schedule.json", schedule) print(strict_json({"study": str(directory), "status": "passed"})) def compatible_baselines(): """Audit existing evidence, never modify/copy it; source extension approved by user.""" old_source = (ROOT/"provenance/reference_code/efdfe3a-benchmark.py").read_bytes() old_prompt_source = (ROOT/"provenance/reference_code/efdfe3a-prompts.py").read_bytes() def nodes(source): return {n.name:ast.dump(n, include_attributes=False) for n in ast.parse(source).body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))} old, new = nodes(old_source), nodes((ROOT/"benchmark.py").read_text()) unchanged = ["SSEParser", "observe", "dispatch", "aggregate", "percentile"] if any(old[n] != new[n] for n in unchanged): raise RuntimeError("Measurement implementation changed: baseline reuse requires review") # At O64 the only request-function change is an equal sampling dictionary. normalized=(ROOT/"benchmark.py").read_text().replace('sampling_for_output(record["requested_output_tokens"])','SAMPLING') if nodes(normalized)["request"] != old["request"] or sampling_for_output(64) != SAMPLING: raise RuntimeError("Request timing/parser behavior changed beyond sampling parameterization") manifest_path = ROOT/"configs/prompt_manifest.json" manifest = json.loads(manifest_path.read_text()) if manifest != load_manifest(512): raise RuntimeError("512 prompt family differs from Step 4") ids = [p["prompt_id"] for p in manifest["prompts"] if p["role"] == "measured"] runs = [] for path in sorted((ROOT/"results/runs").glob("*-concurrency_c1_r*/run.json")): m = json.loads(path.read_text()) if not (m["status"] == "passed" and m["primary_comparison_eligible"]): continue expected = {"concurrency":1,"input_tokens":512,"requested_output_tokens":64, "measured_requests":40,"sampling":SAMPLING,"prompt_order":ids, "warmup_policy":"8 separate 512/64 C1 requests, excluded; flush after completion", "cache_policy":"idle flush acknowledged; distinct first IDs; measured cached_tokens must be zero", "percentile_method":"linear interpolation (n-1)*q, type 7"} if any(m.get(k)!=v for k,v in expected.items()): raise RuntimeError("Baseline contract differs") if m["prompt_manifest_sha256"] != hashlib.sha256(manifest_path.read_bytes()).hexdigest(): raise RuntimeError("Baseline manifest hash differs") for name, content in [("benchmark.py",old_source),("prompts.py",old_prompt_source)]: if m["environment"]["source_hashes"][name] != hashlib.sha256(content).hexdigest(): raise RuntimeError("Baseline code not the audited Step 4 implementation") rows=[json.loads(l) for l in (path.parent/"requests.jsonl").read_text().splitlines()] if len(rows)!=40 or [r["prompt_id"] for r in rows]!=ids: raise RuntimeError("Baseline records differ") for r in rows: revised=finalize(dict(r),True) if not revised["contract_valid"] or any(revised[k]!=r[k] for k in ("ttft_s","tpot_s","e2e_s")): raise RuntimeError("Baseline validation/metric behavior differs") if aggregate(rows,m["aggregates"]["workload_duration_s"])!=m["aggregates"]: raise RuntimeError("Baseline aggregation mismatch") runs.append(m) if len(runs)!=3 or {r["repetition"] for r in runs}!={1,2,3}: raise RuntimeError("Need three compatible Step 4 C1 runs") return runs, {"status":"compatible", "reused_run_ids":[r["run_id"] for r in runs], "previous_sessions":sorted({r["server_session_id"] for r in runs}), "unchanged_measurement_functions":unchanged, "request_equivalence":"AST identical after normalizing only sampling_for_output(record[requested_output_tokens]) to SAMPLING; O64 dictionaries identical", "source_revision_policy":"User approved tested behavioral equivalence at 512; source hashes differ and are retained", "validation_extension":"Target input/output lengths replace hard-coded 512/64; four-point timing and percentile formulas unchanged", "prompt_family":"512 manifest object and bytes unchanged; other lengths prefix the extended source sequences"} def prompt_length_summary(runs, reused_ids): valid=[r for r in runs if r.get("status")=="passed" and r.get("primary_comparison_eligible") and r.get("concurrency")==1 and r.get("requested_output_tokens")==64 and all(r.get("aggregates",{}).get(k)==40 for k in ("attempted","successful","contract_success")) and (r.get("experiment")=="prompt_length_scaling" or r["run_id"] in reused_ids)] groups={} for length in (128,512,1024,2048): group=[r for r in valid if r["input_tokens"]==length] if len(group)!=3 or {r["repetition"] for r in group}!={1,2,3}: raise ValueError(f"Need three distinct valid repetitions for length {length}") groups[str(length)]={} for key in ("ttft_s","tpot_s","e2e_s","output_throughput_tps","request_throughput_rps"): vals=[{"run_id":r["run_id"],"value":r["aggregates"][key]["mean"] if key.endswith("_s") else r["aggregates"][key]} for r in group] nums=[v["value"] for v in vals] if not all(math.isfinite(v) for v in nums):raise ValueError("Nonfinite summary") groups[str(length)][key]={"median":statistics.median(nums),"min":min(nums),"max":max(nums),"runs":vals} return {"schema_version":1,"method":"median/min/max of three run-level means or throughputs, no request pooling", "input_lengths":groups,"referenced_step4_run_ids":reused_ids, "individual_runs":[{**{k:r[k] for k in ("run_id","input_tokens","repetition","server_session_id","aggregates")}, "evidence_origin":"referenced_step4" if r["run_id"] in reused_ids else "new_step5"} for r in valid], "excluded_run_ids":[r["run_id"] for r in runs if r not in valid]} async def prompt_length_study(base_url): baselines,audit=compatible_baselines() launch=json.loads((ROOT/"configs/prompt_length_server.json").read_text()) if any(r["resolved_server_config"]!=launch["resolved_server_config"] for r in baselines): raise RuntimeError("New session configuration differs from reused baseline") for length in (128,512,1024,2048): manifest=load_manifest(length) full=load_manifest(2048) for p,source in zip(manifest["prompts"],full["prompts"]): if p["input_ids"]!=source["input_ids"][:length]:raise RuntimeError("Prefix family mismatch") study_id=make_run_id("prompt-length-study") directory=ROOT/"results"/study_id;directory.mkdir(exist_ok=False) save_json(directory/"baseline_compatibility.json",audit) order=[(128,1),(1024,1),(2048,1),(2048,2),(128,2),(1024,2),(1024,3),(2048,3),(128,3)] schedule={"study_id":study_id,"schedule":[{"order":i,"input_tokens":n,"repetition":r} for i,(n,r) in enumerate(order,1)], "referenced_step4_run_ids":audit["reused_run_ids"],"completed_run_ids":[],"status":"running"} save_json(directory/"schedule.json",schedule) runs=list(baselines) try: for i,(length,rep) in enumerate(order,1): m=await run("prompt_length",base_url,1,rep,i,study_id,length) runs.append(m);schedule["completed_run_ids"].append(m["run_id"]) save_json(directory/"schedule.json",schedule) summary=prompt_length_summary(runs,audit["reused_run_ids"]);summary["study_id"]=study_id save_json(directory/"summary.json",summary);schedule["status"]="passed" except Exception as exc: schedule["status"]="failed";schedule["error"]=str(exc);raise finally:save_json(directory/"schedule.json",schedule) print(strict_json({"study":str(directory),"status":schedule["status"]})) def decode_analysis(records): valid=[r for r in records if r["success"] and r["contract_valid"]] windows=[r["last_output_at"]-r["first_output_at"] for r in valid] tails=[r["terminal_at"]-r["last_output_at"] for r in valid] ttfts=[r["ttft_s"] for r in valid];e2es=[r["e2e_s"] for r in valid] return {"mean_decode_window_s":statistics.mean(windows) if windows else None, "median_decode_window_s":statistics.median(windows) if windows else None, "mean_terminal_overhead_s":statistics.mean(tails) if tails else None, "ttft_share_of_e2e":statistics.mean(ttfts)/statistics.mean(e2es) if e2es and statistics.mean(e2es)>0 else None} def output_length_summary(runs,reused_ids,derived): valid=[r for r in runs if r.get("status")=="passed" and r.get("primary_comparison_eligible") and r.get("concurrency")==1 and r.get("input_tokens")==512 and all(r.get("aggregates",{}).get(k)==40 for k in ("attempted","successful","contract_success")) and (r.get("experiment")=="output_length_scaling" or r["run_id"] in reused_ids)] groups={} for length in (32,64,128,256): group=[r for r in valid if r["requested_output_tokens"]==length] if len(group)!=3 or {r["repetition"] for r in group}!={1,2,3}: raise ValueError(f"Need three distinct valid repetitions for output {length}") groups[str(length)]={} for key in ("ttft_s","tpot_s","e2e_s","output_throughput_tps","request_throughput_rps"): vals=[{"run_id":r["run_id"],"value":r["aggregates"][key]["mean"] if key.endswith("_s") else r["aggregates"][key]} for r in group] nums=[v["value"] for v in vals] if not all(math.isfinite(v) for v in nums):raise ValueError("Nonfinite summary") groups[str(length)][key]={"median":statistics.median(nums),"min":min(nums),"max":max(nums),"runs":vals} return {"schema_version":1,"method":"median/min/max of three run-level means or throughputs; no pooling", "output_lengths":groups,"referenced_step4_run_ids":reused_ids, "individual_runs":[{**{k:r[k] for k in ("run_id","requested_output_tokens","repetition","server_session_id","aggregates")}, "evidence_origin":"referenced_step4" if r["run_id"] in reused_ids else "new_step6", "derived":derived[r["run_id"]]} for r in valid], "excluded_run_ids":[r["run_id"] for r in runs if r not in valid]} async def output_length_study(base_url): baselines,audit=compatible_baselines() launch=json.loads((ROOT/"configs/output_length_server.json").read_text()) if any(r["resolved_server_config"]!=launch["resolved_server_config"] for r in baselines): raise RuntimeError("New session configuration differs from O64 baseline") study_id=make_run_id("output-length-study");directory=ROOT/"results"/study_id;directory.mkdir(exist_ok=False) save_json(directory/"baseline_compatibility.json",audit) order=[(32,1),(128,1),(256,1),(256,2),(32,2),(128,2),(128,3),(256,3),(32,3)] schedule={"study_id":study_id,"schedule":[{"order":i,"output_tokens":n,"repetition":r} for i,(n,r) in enumerate(order,1)], "referenced_step4_run_ids":audit["reused_run_ids"],"completed_run_ids":[],"status":"running"} save_json(directory/"schedule.json",schedule);runs=list(baselines) try: for i,(length,rep) in enumerate(order,1): m=await run("output_length",base_url,1,rep,i,study_id,512,length) runs.append(m);schedule["completed_run_ids"].append(m["run_id"]);save_json(directory/"schedule.json",schedule) derived={} for r in runs: records=[json.loads(l) for l in (ROOT/"results/runs"/r["run_id"]/"requests.jsonl").read_text().splitlines()] derived[r["run_id"]]=decode_analysis(records) summary=output_length_summary(runs,audit["reused_run_ids"],derived);summary["study_id"]=study_id save_json(directory/"summary.json",summary);schedule["status"]="passed" except Exception as exc: schedule["status"]="failed";schedule["error"]=str(exc);raise finally:save_json(directory/"schedule.json",schedule) print(strict_json({"study":str(directory),"status":schedule["status"]})) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("mode", choices=["preflight", "validation", "concurrency-study", "prompt-length-study", "output-length-study"]) parser.add_argument("--base-url", default="http://127.0.0.1:30000") args = parser.parse_args() asyncio.run(output_length_study(args.base_url.rstrip("/")) if args.mode == "output-length-study" else prompt_length_study(args.base_url.rstrip("/")) if args.mode == "prompt-length-study" else concurrency_study(args.base_url.rstrip("/")) if args.mode == "concurrency-study" else run(args.mode, args.base_url.rstrip("/")))