Download executor_entrypoint.py from Neurips-2026-MLIntern-Repro/attention-closes-executor: direct link, hf CLI and curl.
- Browser
- Download file 11.9 kB
-
https://huggingface.co/spaces/Neurips-2026-MLIntern-Repro/attention-closes-executor/resolve/main/executor_entrypoint.py
- Command line
-
hf download hf://spaces/Neurips-2026-MLIntern-Repro/attention-closes-executor/executor_entrypoint.py
-
curl -L -o executor_entrypoint.py https://huggingface.co/spaces/Neurips-2026-MLIntern-Repro/attention-closes-executor/resolve/main/executor_entrypoint.py
11.9 kB
| #!/usr/bin/env python3 | |
| """One-shot stage executor for the "When Attention Closes" reproduction | |
| (arXiv:2605.12922v2, Mistral-7B Table 1 cells: 5-fact & 20-fact retention, | |
| default attention vs forced sliding-window W=4096). | |
| Runs the stage named in ./stage.txt on Space startup, pushes results to the | |
| bundle dataset repos, then serves a status page on $APP_PORT. | |
| Stages: | |
| mirror verify file parity with the org Space; executes nothing | |
| smoke mask unit check + 2-episode full 50-turn task2 under SW and default | |
| run-default task1 default (100 eps) then task2 default (100 eps), resumable | |
| run-sw task1 SW=4096 (50 eps) then task2 SW=4096 (50 eps), resumable | |
| aggregate download cell outputs from the mirror repo, aggregate r50 / | |
| post-crossover recall with Wilson CIs, push summary | |
| This file is byte-identical in the private Gradio executor Space | |
| (Frame17/attention-closes-executor-private) and the public Docker mirror | |
| (Neurips-2026-MLIntern-Repro/attention-closes-executor). | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import os | |
| import shutil | |
| import subprocess | |
| import sys | |
| import threading | |
| import time | |
| import traceback | |
| from datetime import datetime, timezone | |
| from http.server import BaseHTTPRequestHandler, HTTPServer | |
| from pathlib import Path | |
| from huggingface_hub import HfApi | |
| ORG_SPACE_ID = "Neurips-2026-MLIntern-Repro/attention-closes-executor" | |
| DEST_MIRROR = "Frame17/attention-closes-repro" # user-owned: direct write | |
| DEST_PUBLIC = "Neurips-2026-MLIntern-Repro/attention-closes-repro" # PR best-effort | |
| SHARED_FILES = ["executor_entrypoint.py", "stage.txt", "runner.py", "tasks.json"] | |
| WORK = Path("/tmp/work") | |
| MODEL_ID = "mistralai/Mistral-7B-Instruct-v0.3" | |
| STATUS_HTML = Path("/tmp/status.html") | |
| BATCH = 8 | |
| SEED_BASE = 0 | |
| CELLS = { | |
| "smoke": [("task2", "sw4096", 2, 50), ("task2", "default", 2, 50)], | |
| "run-default": [("task1", "default", 100, 50), ("task2", "default", 100, 50)], | |
| "run-sw": [("task1", "sw4096", 50, 50), ("task2", "sw4096", 50, 50)], | |
| } | |
| OUT_NAME = lambda task, cond: f"out_{task}_{cond}.jsonl" | |
| def read_stage() -> str: | |
| path = Path(__file__).parent / "stage.txt" | |
| if not path.exists(): | |
| return "idle" | |
| lines = [line.strip() for line in path.read_text(encoding="utf-8").splitlines()] | |
| lines = [line for line in lines if line and not line.startswith("#")] | |
| return lines[0] if lines else "idle" | |
| def hf_api() -> HfApi: | |
| token = os.environ.get("HF_TOKEN") | |
| if not token: | |
| raise RuntimeError( | |
| "HF_TOKEN Space secret is not set. Add it in Space settings " | |
| "(Settings > Variables and secrets > New secret > HF_TOKEN).") | |
| return HfApi(token=token) | |
| def push_file(name: str, data: bytes, public: bool = True) -> dict: | |
| """Push to the user-owned mirror repo directly (overwrite at a fixed path), | |
| and best-effort as a timestamped PR to the public bundle repo.""" | |
| ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") | |
| fixed = f"logs/{name}" | |
| stamped = f"logs/{ts}_{name}" | |
| api = hf_api() | |
| outcomes: dict = {} | |
| try: | |
| api.upload_file(path_or_fileobj=data, path_in_repo=fixed, | |
| repo_id=DEST_MIRROR, repo_type="dataset") | |
| api.upload_file(path_or_fileobj=data, path_in_repo=stamped, | |
| repo_id=DEST_MIRROR, repo_type="dataset") | |
| outcomes[DEST_MIRROR] = ["ok"] | |
| except Exception as exc: | |
| outcomes[DEST_MIRROR] = [f"error: {str(exc)[:250]}"] | |
| if public: | |
| for path_in_repo in (fixed, stamped): | |
| try: | |
| api.upload_file(path_or_fileobj=data, path_in_repo=path_in_repo, | |
| repo_id=DEST_PUBLIC, repo_type="dataset", create_pr=True) | |
| outcomes.setdefault(DEST_PUBLIC, []).append("ok") | |
| except Exception as exc: | |
| outcomes.setdefault(DEST_PUBLIC, []).append(f"error: {str(exc)[:250]}") | |
| return {"fixed_path": fixed, "stamped_path": stamped, "destinations": outcomes} | |
| def push_result(stage: str, payload: dict) -> dict: | |
| payload = dict(payload, stage=stage) | |
| try: | |
| payload["result_url"] = push_file( | |
| f"payload_{stage}.json", | |
| json.dumps(payload, indent=2, ensure_ascii=False).encode("utf-8")) | |
| except Exception as exc: | |
| payload["push_error"] = f"{exc}" | |
| return payload | |
| def run(cmd: list[str], **kw) -> subprocess.CompletedProcess: | |
| proc = subprocess.run(cmd, capture_output=True, text=True, **kw) | |
| if proc.returncode != 0: | |
| tail = (proc.stdout[-1500:] + "\n" + proc.stderr[-2500:]) | |
| raise RuntimeError(f"command failed ({' '.join(map(str, cmd[:4]))}...):\n{tail}") | |
| return proc | |
| def ensure_deps() -> dict: | |
| """torch/transformers/accelerate are preinstalled in the private Space via | |
| requirements.txt; bootstrap them here for Docker failover.""" | |
| pins = {"torch": "torch", "transformers": "transformers==5.25.1", "accelerate": "accelerate"} | |
| done = [] | |
| for mod, pin in pins.items(): | |
| try: | |
| __import__(mod) | |
| except ImportError: | |
| run([sys.executable, "-m", "pip", "install", "--no-cache-dir", pin]) | |
| done.append(pin) | |
| return {"bootstrapped": done} | |
| def fetch_latest_out(name: str) -> bool: | |
| """Restore a previous cell's output file into WORK so the runner resumes.""" | |
| api = hf_api() | |
| files = api.list_repo_files(repo_id=DEST_MIRROR, repo_type="dataset") | |
| stamps = sorted(f for f in files if f.startswith("logs/") and f.endswith(f"_{name}")) | |
| if not stamps: | |
| return False | |
| local = api.hf_hub_download(repo_id=DEST_MIRROR, repo_type="dataset", filename=stamps[-1]) | |
| WORK.mkdir(parents=True, exist_ok=True) | |
| shutil.copyfile(local, WORK / name) | |
| return True | |
| def _partial_pusher(out_path: Path, name: str, stop: threading.Event) -> None: | |
| while not stop.wait(180): | |
| if out_path.exists(): | |
| try: | |
| push_file(name, out_path.read_bytes(), public=False) | |
| except Exception: | |
| pass | |
| def mask_check() -> dict: | |
| """Unit check: a fact stated >W tokens back must be retrievable under | |
| default attention and unretrievable under SW=4096 (greedy).""" | |
| proc = run([sys.executable, "runner.py", "--mask-check"]) | |
| tail = proc.stdout[-1500:] | |
| ok = "PASS" in proc.stdout | |
| if not ok: | |
| raise RuntimeError(f"mask check failed:\n{tail}") | |
| return {"mask_check": "PASS", "tail": tail} | |
| def stage_run(stage: str) -> dict: | |
| ensure_deps() | |
| WORK.mkdir(parents=True, exist_ok=True) | |
| here = Path(__file__).parent | |
| for f in ("runner.py", "tasks.json", "aggregate.py"): | |
| if (here / f).exists(): | |
| shutil.copyfile(here / f, WORK / f) | |
| check = mask_check() | |
| cells = [] | |
| for task, cond, episodes, max_turns in CELLS[stage]: | |
| name = OUT_NAME(task, cond) | |
| out_path = WORK / name | |
| if out_path.exists(): | |
| out_path.unlink() | |
| restored = fetch_latest_out(name) | |
| cmd = [sys.executable, "runner.py", "--task", task, "--condition", cond, | |
| "--episodes", str(episodes), "--batch", str(BATCH), | |
| "--max-turns", str(max_turns), "--seed-base", str(SEED_BASE), | |
| "--out", str(out_path)] | |
| stop = threading.Event() | |
| watchdog = threading.Thread(target=_partial_pusher, args=(out_path, name, stop), daemon=True) | |
| watchdog.start() | |
| try: | |
| proc = run(cmd) | |
| finally: | |
| stop.set() | |
| cells.append({"task": task, "condition": cond, "episodes": episodes, | |
| "resumed_from_mirror": restored, | |
| "tail": proc.stdout[-3000:], | |
| "push": push_file(name, out_path.read_bytes())}) | |
| return {"mask_check": check["mask_check"], "cells": cells} | |
| def stage_smoke() -> dict: | |
| return stage_run("smoke") | |
| def stage_aggregate() -> dict: | |
| ensure_deps() | |
| WORK.mkdir(parents=True, exist_ok=True) | |
| here = Path(__file__).parent | |
| for f in ("aggregate.py", "tasks.json"): | |
| shutil.copyfile(here / f, WORK / f) | |
| paths = [] | |
| for task in ("task1", "task2"): | |
| for cond in ("default", "sw4096"): | |
| name = OUT_NAME(task, cond) | |
| if fetch_latest_out(name): | |
| paths.append(str(WORK / name)) | |
| else: | |
| paths.append(f"MISSING:{name}") | |
| present = [p for p in paths if not p.startswith("MISSING:")] | |
| if not present: | |
| raise RuntimeError("no cell outputs found in the mirror repo — run a cell stage first") | |
| proc = run([sys.executable, "aggregate.py", *present]) | |
| summary = json.loads(proc.stdout.strip().splitlines()[-1]) | |
| push = push_file("summary.json", json.dumps(summary, indent=2).encode("utf-8")) | |
| return {"summary": summary, "push": push, "missing": [p for p in paths if p.startswith("MISSING:")]} | |
| def stage_mirror() -> dict: | |
| """Mirror mode: execute nothing; verify file parity with the org Space.""" | |
| api = HfApi() | |
| parity = {} | |
| for name in SHARED_FILES: | |
| try: | |
| local = (Path(__file__).parent / name).read_bytes() | |
| except OSError as exc: | |
| parity[name] = f"local-missing: {exc}" | |
| continue | |
| try: | |
| remote = Path(api.hf_hub_download( | |
| repo_id=ORG_SPACE_ID, repo_type="space", filename=name)).read_bytes() | |
| parity[name] = "match" if local == remote else "DIFFER" | |
| except Exception as exc: | |
| parity[name] = f"org-read-error: {exc}" | |
| try: | |
| org_stage = Path(api.hf_hub_download( | |
| repo_id=ORG_SPACE_ID, repo_type="space", filename="stage.txt")).read_text().strip() | |
| except Exception as exc: | |
| org_stage = f"org-read-error: {exc}" | |
| differ = [k for k, v in parity.items() if v != "match"] | |
| return {"mode": "mirror", "parity": parity, "org_stage": org_stage, | |
| "note": "mirror executes no stages; set stage.txt to a real stage here " | |
| "to make this Space the compute engine (failover)", | |
| "parity_ok": not differ} | |
| STAGES = {"mirror": stage_mirror, "smoke": stage_smoke, | |
| "run-default": stage_run, "run-sw": stage_run, | |
| "aggregate": stage_aggregate} | |
| def run_stage(stage: str) -> dict: | |
| started = datetime.now(timezone.utc).isoformat() | |
| try: | |
| payload = STAGES[stage]() if stage in STAGES else {"error": f"unknown stage {stage!r}"} | |
| except Exception as exc: | |
| payload = {"error": f"{exc}", "traceback": traceback.format_exc()[-3000:]} | |
| payload["started_at"] = started | |
| payload["finished_at"] = datetime.now(timezone.utc).isoformat() | |
| return push_result(stage, payload) | |
| def write_status(payload: dict) -> None: | |
| STATUS_HTML.parent.mkdir(parents=True, exist_ok=True) | |
| STATUS_HTML.write_text( | |
| "<html><body><h1>attention-closes executor</h1><pre>" | |
| + json.dumps(payload, indent=2, ensure_ascii=False) | |
| + "</pre></body></html>", encoding="utf-8") | |
| def serve() -> None: | |
| port = int(os.environ.get("APP_PORT") or 7860) | |
| class Handler(BaseHTTPRequestHandler): | |
| def do_GET(self) -> None: | |
| body = STATUS_HTML.read_bytes() if STATUS_HTML.exists() else b"starting..." | |
| self.send_response(200) | |
| self.send_header("Content-Type", "text/html; charset=utf-8") | |
| self.send_header("Content-Length", str(len(body))) | |
| self.end_headers() | |
| self.wfile.write(body) | |
| def log_message(self, *args) -> None: | |
| pass | |
| HTTPServer(("0.0.0.0", port), Handler).serve_forever() | |
| def main() -> None: | |
| stage = read_stage() | |
| threading.Thread(target=serve, daemon=True).start() | |
| payload = run_stage(stage) | |
| write_status(payload) | |
| print(json.dumps(payload, indent=2, ensure_ascii=False), flush=True) | |
| while True: | |
| time.sleep(60) | |
| if __name__ == "__main__": | |
| main() | |