| |
| """Inference via the Codex CLI for GPT-5.x ChatGPT-auth models. |
| |
| The Codex CLI is run with an isolated temporary CODEX_HOME and temporary |
| read-only workdirs so inference calls do not persist sessions into the user's |
| real ~/.codex or the project directory. |
| """ |
|
|
| import argparse |
| import atexit |
| import json |
| import os |
| import shutil |
| import subprocess |
| import tempfile |
| from concurrent.futures import ThreadPoolExecutor, as_completed |
| from pathlib import Path |
| from threading import Lock |
|
|
|
|
| INFER_TASK1 = """You are an expert AI research scientist and a rigorous peer reviewer. Your task is to identify the key ablation research questions that should be investigated to rigorously validate a paper's central methodological claims. |
| |
| <Research_Context> |
| (Paper context with ablation-related content removed) |
| {CONTENT} |
| </Research_Context> |
| |
| **Task Instructions:** |
| 1. Read the paper context carefully and infer the most important research questions that should be addressed by ablation or controlled analysis. |
| 2. Identify which components, mechanisms, or assumptions are most scientifically vulnerable. |
| 3. Consider what causal confounders or alternative explanations a skeptical reviewer would raise. |
| 4. Focus on research questions that are necessary to verify whether the claimed gains truly come from the proposed method. |
| 5. Stay at the level of research questions rather than detailed implementation. |
| |
| **Important Constraints:** |
| - Do not propose full experimental plans, datasets, hyperparameters, or exact protocols. |
| - Prefer mechanistically meaningful and causally informative questions over superficial component toggles. |
| - Identify the 2-6 most critical ablation targets. Prioritize scientific necessity over completeness. |
| |
| **Output Format:** Each bullet represents one atomic ablation target. Output the most scientifically necessary targets (typically 2-6). |
| |
| <Think> |
| [A brief reasoning process explaining the most important scientific vulnerabilities and causal uncertainties.] |
| </Think> |
| |
| <Result> |
| [A list of target modules and their corresponding high-level research questions.] |
| |
| - Target Module: [Name of the component or design choice] |
| - Research Question: [One precise sentence summarizing the exact hypothesis to test] |
| </Result> |
| |
| Output only the <Think> and <Result> blocks. Do not run any commands or tools; just write the research questions.""" |
|
|
|
|
| INFER_TASK2 = """You are an expert AI research scientist specializing in scientific experimental design. Your task is to construct a rigorous and reproducible ablation plan for a given ablation goal, based on the paper's methodology context. |
| |
| <Research_Context> |
| {CONTENT} |
| </Research_Context> |
| |
| <Ablation_Goal> |
| {GOAL} |
| </Ablation_Goal> |
| |
| **Task Instructions:** |
| 1. Design a scientifically rigorous experimental plan that directly tests the given ablation goal. |
| 2. Define a fair baseline. |
| 3. Specify the most important ablation or control variants. |
| 4. Isolate the intended causal factor as cleanly as possible. |
| 5. Keep unrelated components fixed unless a change is explicitly required. |
| 6. Include the critical protocols and evaluation metrics needed for a reproducible comparison. |
| |
| **Important Constraints:** |
| - Focus on causal validity, fairness of comparison, and confounder isolation. |
| - Avoid introducing unnecessary complexity or speculative variants that are not grounded in the methodology context. |
| - If a stronger control is needed to rule out a plausible alternative explanation, include it. |
| - The plan should be specific enough to be executable, but should not invent unsupported details that are absent from the context. |
| |
| **Output Format:** The response should prioritize scientific rigor, reproducibility, and fairness of comparison. |
| |
| <Think> |
| [A brief reasoning process explaining how the ablation goal maps to the key controls, baselines, and confounders.] |
| </Think> |
| |
| <Proposed_Plan> |
| - Objective: [Brief statement of the design goal] |
| - Baseline Setup: [Clear definition of the control condition] |
| - Variants: [The main ablation or control conditions and what each one changes] |
| - Fixed Protocols & Metrics: [Key training constraints, datasets, evaluation settings, and primary metrics in a single paragraph] |
| </Proposed_Plan> |
| |
| Output only the <Think> and <Proposed_Plan> blocks. Do not run any commands or tools; just write the plan.""" |
|
|
|
|
| _write_lock = Lock() |
|
|
|
|
| def _isolated_codex_env() -> dict: |
| real_home = os.path.expanduser("~/.codex") |
| tmp_home = tempfile.mkdtemp(prefix="abforge_codexhome_") |
| for name in ("auth.json", "config.toml"): |
| src = os.path.join(real_home, name) |
| if os.path.isfile(src): |
| shutil.copy2(src, os.path.join(tmp_home, name)) |
| atexit.register(lambda: shutil.rmtree(tmp_home, ignore_errors=True)) |
| return {**os.environ, "CODEX_HOME": tmp_home} |
|
|
|
|
| CODEX_ENV = _isolated_codex_env() |
|
|
|
|
| def load_jsonl(path: Path) -> list[dict]: |
| rows = [] |
| with path.open(encoding="utf-8") as f: |
| for line in f: |
| if line.strip(): |
| rows.append(json.loads(line)) |
| return rows |
|
|
|
|
| def append_jsonl(path: Path, row: dict) -> None: |
| path.parent.mkdir(parents=True, exist_ok=True) |
| with _write_lock: |
| with path.open("a", encoding="utf-8") as f: |
| f.write(json.dumps(row, ensure_ascii=False) + "\n") |
| f.flush() |
|
|
|
|
| def get_title(row: dict) -> str: |
| return ((row.get("meta") or {}).get("title") or "").strip() |
|
|
|
|
| def done_titles(path: Path) -> set[str]: |
| if not path.exists(): |
| return set() |
| return {title for row in load_jsonl(path) if (title := get_title(row))} |
|
|
|
|
| def build_prompt(item: dict, task: str, max_content_chars: int) -> str: |
| content = item.get("Content", "") or "" |
| if max_content_chars > 0: |
| content = content[:max_content_chars] |
| if task == "1": |
| return INFER_TASK1.replace("{CONTENT}", content) |
| return INFER_TASK2.replace("{CONTENT}", content).replace("{GOAL}", item.get("Goal", "") or "") |
|
|
|
|
| def build_output_row(item: dict, task: str, response: str, model: str) -> dict: |
| if task == "1": |
| return { |
| "meta": item.get("meta", {}), |
| "gt_Candidates": item.get("Candidates", ""), |
| "infer_task1_response": response, |
| "codex_model": model, |
| } |
| return { |
| "meta": item.get("meta", {}), |
| "Goal": item.get("Goal", ""), |
| "gt_refined_plan": item.get("refined_standard_plan", ""), |
| "gt_Rubric": item.get("Rubric", ""), |
| "infer_task2_response": response, |
| "codex_model": model, |
| } |
|
|
|
|
| def call_codex(prompt: str, model: str, reasoning: str, timeout: int) -> str: |
| workdir = tempfile.mkdtemp(prefix="abforge_codex_wd_") |
| msg_file = os.path.join(workdir, "_last.txt") |
| cmd = [ |
| "codex", |
| "exec", |
| "--ephemeral", |
| "-m", |
| model, |
| "-s", |
| "read-only", |
| "--skip-git-repo-check", |
| "--color", |
| "never", |
| "-C", |
| workdir, |
| "-o", |
| msg_file, |
| "-c", |
| f'model_reasoning_effort="{reasoning}"', |
| "-", |
| ] |
| try: |
| proc = subprocess.run( |
| cmd, |
| input=prompt, |
| capture_output=True, |
| text=True, |
| timeout=timeout, |
| env=CODEX_ENV, |
| ) |
| if os.path.exists(msg_file): |
| text = Path(msg_file).read_text(encoding="utf-8").strip() |
| if text: |
| return text |
| err = (proc.stderr or proc.stdout or "").strip().replace("\n", " ") |
| raise RuntimeError(f"codex exit {proc.returncode}: {err[:500]}") |
| finally: |
| shutil.rmtree(workdir, ignore_errors=True) |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--task", required=True, choices=["1", "2"]) |
| parser.add_argument("--input", required=True) |
| parser.add_argument("--output", required=True) |
| parser.add_argument("--fail-output", default=None) |
| parser.add_argument("--model", default="gpt-5.4") |
| parser.add_argument("--reasoning", default="medium") |
| parser.add_argument("--max-content-chars", type=int, default=60000) |
| parser.add_argument("--workers", type=int, default=2) |
| parser.add_argument("--timeout", type=int, default=600) |
| args = parser.parse_args() |
|
|
| input_path = Path(args.input) |
| output_path = Path(args.output) |
| fail_path = Path(args.fail_output) if args.fail_output else None |
|
|
| rows = load_jsonl(input_path) |
| done = done_titles(output_path) |
| todo = [row for row in rows if get_title(row) not in done] |
| print( |
| f"{len(rows)} items, {len(done)} done, {len(todo)} to run, " |
| f"task={args.task}, model={args.model} -> {output_path}", |
| flush=True, |
| ) |
|
|
| def work(index_row: tuple[int, dict]) -> bool: |
| index, row = index_row |
| label = get_title(row) or f"item-{index}" |
| try: |
| response = call_codex( |
| build_prompt(row, args.task, args.max_content_chars), |
| args.model, |
| args.reasoning, |
| args.timeout, |
| ) |
| append_jsonl(output_path, build_output_row(row, args.task, response, args.model)) |
| print(f"[ok] {label[:80]}", flush=True) |
| return True |
| except Exception as exc: |
| print(f"[FAIL] {label[:80]}: {exc}", flush=True) |
| if fail_path: |
| append_jsonl( |
| fail_path, |
| {"meta": row.get("meta", {}), "task": args.task, "error": str(exc)}, |
| ) |
| return False |
|
|
| ok = 0 |
| with ThreadPoolExecutor(max_workers=args.workers) as executor: |
| futures = [executor.submit(work, item) for item in enumerate(todo)] |
| for future in as_completed(futures): |
| ok += 1 if future.result() else 0 |
|
|
| out_rows = len(load_jsonl(output_path)) if output_path.exists() else 0 |
| print(f"done: {ok}/{len(todo)} ok; output rows now {out_rows}", flush=True) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|