"""Targeted extra cells for revision experiments. Reuses the exact runner scoring path and record schema so results merge into the standard analyses. Modes: screps single topology, replications 3..6 at tau=0.7, all families, 16 instances, 7 models (token-matched self-consistency ladder) greedy2 all 5 topologies, layout+intervention, 16 instances, second greedy pass (rep=1) to measure greedy-decoding TCI layoutext layout instances 16..39 (the frozen full-grid extension), all 5 topologies, replications 0..2 at tau=0.7 promptvar critique+debate, layout+intervention, instances 0..7, greedy, under an alternative orchestration-prompt set (--prompts-dir) python3 src/extra_cells.py --mode screps [--run-id auto] [--concurrency 8] """ from __future__ import annotations import argparse import json import os import sys import threading import time from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from client import LLMClient # noqa: E402 from runner import build_instances, load_config, cell_key # noqa: E402 from tasks import FAMILIES # noqa: E402 import topologies as T # noqa: E402 import metrics as M # noqa: E402 MODELS = ["gemma-4-31b", "gptoss-120b", "gptoss-20b", "leanstral-2603", "qwen3-30b-a3b-instruct-fp8", "qwen3.5-9b", "qwen3.6-27b-fp8"] CANON = ["menu", "layout", "klm", "intervention"] def spec(mode: str): # families SELECT which families run; instance generation always uses the # canonical family order so per-family rng streams align with the main run if mode == "screps": return dict(families=CANON, n_inst=16, idx_lo=0, topos=["single"], reps=[3, 4, 5, 6], greedy=False) if mode == "greedy2": return dict(families=["layout", "intervention"], n_inst=16, idx_lo=0, topos=["single", "chain", "critique", "debate", "hierarchical"], reps=[1], greedy=True) if mode == "layoutext": return dict(families=["layout"], n_inst=40, idx_lo=16, topos=["single", "chain", "critique", "debate", "hierarchical"], reps=[0, 1, 2], greedy=False) if mode == "promptvar": return dict(families=["layout", "intervention"], n_inst=8, idx_lo=0, topos=["critique", "debate"], reps=[0], greedy=True) if mode == "promptvar2": return dict(families=["layout", "intervention"], n_inst=8, idx_lo=0, topos=["chain", "hierarchical"], reps=[0], greedy=True) raise ValueError(mode) def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--mode", required=True) ap.add_argument("--run-id", default=None) ap.add_argument("--prompts-dir", default="prompts") ap.add_argument("--concurrency", type=int, default=8) args = ap.parse_args() s = spec(args.mode) run_id = args.run_id or ("ext_" + args.mode + ("" if args.prompts_dir == "prompts" else "_" + os.path.basename(args.prompts_dir))) T.PROMPTS_DIR = args.prompts_dir cfg = load_config("config/experiment.yaml") grid = dict(cfg["design"]["grids"][cfg["design"]["active_grid"]]) grid["families"] = CANON grid["instances_per_family"] = s["n_inst"] instances = [r for r in build_instances(cfg, grid, cfg["paths"]["cache_dir"]) if r["family"] in s["families"] and r["idx"] >= s["idx_lo"]] run_dir = os.path.join(cfg["paths"]["results_dir"], run_id) os.makedirs(os.path.join(run_dir, "traces"), exist_ok=True) records_path = os.path.join(run_dir, "records.jsonl") done = set() if os.path.exists(records_path): for line in open(records_path): try: done.add(json.loads(line)["key"]) except Exception: pass client = LLMClient(base_url=cfg["server"]["base_url"], api_key=cfg["server"]["api_key"], timeout_s=cfg["server"]["timeout_s"], max_retries=cfg["server"]["max_retries"], max_concurrency=args.concurrency) cond_name = ("greedy" if s["greedy"] else "replication") jobs = [] for rec in instances: for topo in s["topos"]: for model in MODELS: for rep in s["reps"]: key = cell_key(family=rec["family"], idx=rec["idx"], topology=topo, model=model, cond=cond_name + "_" + args.mode, rep=rep, para=None) if key not in done: jobs.append((key, rec, topo, model, rep)) print(f"[info] {run_id}: {len(jobs)} cells to run", flush=True) lock = threading.Lock() def work(job): key, rec, topo, model, rep = job inst, oracle = rec["inst"], rec["oracle"] task_cls = FAMILIES[rec["family"]] dec = dict(cfg["decoding"]) if s["greedy"]: dec["temperature"] = 0.0 rng = np.random.default_rng( (inst.seed * 1_000_003 + hash((topo, model, args.mode, rep, args.prompts_dir))) % (2**31)) t0 = time.monotonic() trace = T.TOPOLOGIES[topo](client, model, inst, task_cls, dec, {}, rng, inst.data["description"]) wall = time.monotonic() - t0 parsed = task_cls.parse(inst, trace.final_text) \ if trace.final_text else None action, penalty = task_cls.penalized(inst, parsed) c_hat = task_cls.cost(inst, action) + penalty committee = [] for txt in trace.committee_texts: p = task_cls.parse(inst, txt) if txt else None a2, pen2 = task_cls.penalized(inst, p) committee.append(M.normalized_regret( task_cls.cost(inst, a2) + pen2, oracle["c_star"], oracle["c_rand"])) return {"key": key, "ts": time.time(), "family": rec["family"], "instance_idx": rec["idx"], "instance_seed": inst.seed, "topology": topo, "model": model, "condition": cond_name, "rep": rep, "paraphrase": None, "parsed_ok": parsed is not None, "penalty": penalty, "cost": c_hat, "c_star": oracle["c_star"], "c_rand": oracle["c_rand"], "normalized_regret": M.normalized_regret( c_hat, oracle["c_star"], oracle["c_rand"]), "committee_regrets": committee, "committee_divergence": (M.committee_divergence( committee, M.normalized_regret( c_hat, oracle["c_star"], oracle["c_rand"])) if committee else None), "wall_latency_s": wall, "sum_call_latency_s": trace.total_latency_s, "prompt_tokens": trace.total_prompt_tokens, "completion_tokens": trace.total_completion_tokens, "role_failures": trace.role_failures, "action": action} n = 0 with ThreadPoolExecutor(max_workers=args.concurrency) as ex: futs = {ex.submit(work, j): j for j in jobs} for fut in as_completed(futs): try: r = fut.result() except Exception as e: r = {"key": futs[fut][0], "error": str(e), "role_failures": 1} with lock: with open(records_path, "a") as f: f.write(json.dumps(r) + "\n") n += 1 if n % 50 == 0: print(f"[{run_id} {n}/{len(jobs)}]", flush=True) print(f"[info] {run_id} complete", flush=True) if __name__ == "__main__": main()