File size: 11,896 Bytes
b5e5fa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
#!/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()