"""Recompute per-trajectory timing and recorded cumulative token statistics.""" import csv import json import math from collections import Counter from concurrent.futures import ThreadPoolExecutor from pathlib import Path OUT = Path(__file__).resolve().parent ROOT = OUT.parent / "robolab_full_task_1x_empirical_study" TOKEN_FIELDS = ( "inputTokens", "outputTokens", "totalTokens", "cachedInputTokens", "cacheWriteInputTokens", "reasoningOutputTokens", ) def read_usage(path): latest = {} updates = 0 decreases = [] completed_turns = 0 models = set() last_line = 0 with path.open("rb") as stream: for line_number, line in enumerate(stream, 1): # Image payloads make the logs large; decode only relevant events. if not any(marker in line for marker in ( b"thread/tokenUsage/updated", b'"thread/started"', b'"turn/completed"', )): continue row = json.loads(line) if row.get("direction") != "receive": continue event = row.get("event", {}) method = event.get("method") params = event.get("params", {}) if method == "thread/started": models.add(params["thread"].get("model")) elif method == "turn/completed": completed_turns += 1 elif method == "thread/tokenUsage/updated": thread = params["threadId"] usage = params["tokenUsage"]["total"] assert all(type(usage.get(k)) is int and usage[k] >= 0 for k in TOKEN_FIELDS), path assert usage["inputTokens"] + usage["outputTokens"] == usage["totalTokens"], path assert usage["cachedInputTokens"] <= usage["inputTokens"], path assert usage["reasoningOutputTokens"] <= usage["outputTokens"], path if thread in latest and usage["totalTokens"] < latest[thread]["totalTokens"]: decreases.append(line_number) latest[thread] = usage updates += 1 last_line = line_number assert latest, f"No token usage found: {path}" assert not decreases, f"Cumulative token counter decreased: {path}: {decreases}" return { **{key: sum(usage[key] for usage in latest.values()) for key in TOKEN_FIELDS}, "usage_updates": updates, "thread_count": len(latest), "completed_turn_events": completed_turns, "last_usage_line": last_line, "model": ";".join(sorted(m for m in models if m)), "events_path": str(path.relative_to(ROOT)), } def main(): rows = [] result_files = sorted(ROOT.glob("*/episode_results.jsonl")) for path in result_files: for line_number, line in enumerate(path.read_text().splitlines(), 1): episode = json.loads(line) rows.append({ "task_name": episode["task_name"], "run": episode["run"], "env_id": episode["env_id"], "success": episode["success"], "episode_step": episode["episode_step"], **{key: episode["timing"][key] for key in ( "policy_inference_s", "env_step_s", "video_write_s", "wall_total_s", )}, "result_path": str(path.relative_to(ROOT)), "result_line": line_number, }) rows.sort(key=lambda row: (row["task_name"], row["run"], row["env_id"])) assert len(rows) == 1200 assert len({(r["task_name"], r["run"], r["env_id"]) for r in rows}) == 1200 tasks = Counter(r["task_name"] for r in rows) assert len(tasks) == 120 and set(tasks.values()) == {10} assert all(r["env_id"] == 0 for r in rows) paths = [ROOT / "codex_log" / r["task_name"] / f"episode-{r['run'] + 1:04d}" / "events.jsonl" for r in rows] assert set(paths) == set(ROOT.glob("codex_log/*/episode-*/events.jsonl")) print(f"Scanning {len(paths)} event logs ({sum(p.stat().st_size for p in paths) / 1e9:.2f} GB)", flush=True) with ThreadPoolExecutor(max_workers=8) as pool: for index, (row, usage) in enumerate(zip(rows, pool.map(read_usage, paths)), 1): row.update(usage) row["uncachedInputTokens"] = row["inputTokens"] - row["cachedInputTokens"] if index % 100 == 0: print(f"Processed {index}/{len(rows)}", flush=True) summary = { "trajectory_count": len(rows), "task_count": len(tasks), "trajectories_per_task": 10, "result_file_count": len(result_files), "token_log_count": len(paths), "success_count": sum(r["success"] for r in rows), "models": dict(Counter(r["model"] for r in rows)), "thread_count_distribution": dict(Counter(r["thread_count"] for r in rows)), "logs_with_turn_completed": sum(r["completed_turn_events"] > 0 for r in rows), "method": { "harness_time": "episode_results.jsonl: timing.policy_inference_s; cumulative client-side policy-call elapsed time", "total_execution_time": "timing.wall_total_s; sum of timed policy, environment-step and video-writing sections", "tokens": "Latest recorded thread/tokenUsage/updated.params.tokenUsage.total per thread in each trajectory log; do not sum cumulative updates", "cache": "cachedInputTokens is included in inputTokens; reasoningOutputTokens is included in outputTokens", "coverage": "All 1200 trajectories, including successful and unsuccessful results; recorded token snapshots only", }, "metrics": {}, } for key in ("policy_inference_s", "env_step_s", "video_write_s", "wall_total_s", *TOKEN_FIELDS, "uncachedInputTokens"): values = [r[key] for r in rows] total = math.fsum(values) if key.endswith("_s") else sum(values) summary["metrics"][key] = {"total": total, "mean_per_trajectory": total / len(rows)} with (OUT / "per_trajectory.csv").open("w", newline="") as stream: writer = csv.DictWriter(stream, fieldnames=list(rows[0])) writer.writeheader() writer.writerows(rows) (OUT / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n") print(json.dumps(summary, ensure_ascii=False, indent=2)) if __name__ == "__main__": main()