Spaces:
Running on Zero
Running on Zero
Shared stage executor
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276#!/usr/bin/env python3"""One-shot stage executor for the TrajWiki Table 10 reproduction.
Runs the stage named in ./stage.txt on Space startup, pushes its result to thebundle dataset repo, then serves a status page on $APP_PORT.
Stages: idle no-op router-test verify HF router serves gpt-4o-mini and claude-sonnet-4-6 data download official LoCoMo, convert to adapter layout, upload category files + integrity report setup clone TrajWiki @ pinned commit, install package, verify CLI flags, run mock-provider smoke test, upload logs"""from __future__ import annotations
import ioimport jsonimport osimport shutilimport subprocessimport sysimport tarfileimport threadingimport timeimport tracebackimport urllib.requestimport zipfilefrom datetime import datetime, timezonefrom http.server import BaseHTTPRequestHandler, HTTPServerfrom pathlib import Path
from huggingface_hub import HfApi
REPO_ID = "Neurips-2026-MLIntern-Repro/trajwiki-table10-repro"SPACE_ID = "Neurips-2026-MLIntern-Repro/trajwiki-executor"MIRROR_ID = "Frame17/trajwiki-executor-private"SHARED_FILES = ["Dockerfile", "executor_entrypoint.py"]WORK = Path("/tmp/work")PINNED_COMMIT = "79b5b51043b3475308130725125eea9f0c442a0b"TARBALL_URL = ( "https://codeload.github.com/JingyuSunUOE/TrajWiki/tar.gz/" + PINNED_COMMIT)LOCOMO_URL = ( "https://raw.githubusercontent.com/snap-research/LoCoMo/main/data/locomo10.json")CLAIM_FLAGS = [ "--sample-size", "--variants", "--sampling-profile", "--sample-seed", "--max-total-tokens", "--max-output-tokens", "--token-counter", "--independent-judge-provider-kind", "--independent-judge-model",]STATUS_HTML = Path("/tmp/status.html")
def read_stage() -> str: path = Path(__file__).parent / "stage.txt" return path.read_text(encoding="utf-8").strip() if path.exists() 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) -> str: ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") path_in_repo = f"logs/{ts}_{name}" hf_api().upload_file( path_or_fileobj=data, path_in_repo=path_in_repo, repo_id=REPO_ID, repo_type="dataset", ) return f"https://huggingface.co/datasets/{REPO_ID}/blob/main/{path_in_repo}"
def push_result(stage: str, payload: dict) -> dict: payload = dict(payload, stage=stage) try: payload["result_url"] = push_file( stage, json.dumps(payload, indent=2, ensure_ascii=False).encode("utf-8")) except Exception as exc: # noqa: BLE001 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 download(url: str, dest: Path) -> None: dest.parent.mkdir(parents=True, exist_ok=True) with urllib.request.urlopen(url, timeout=120) as resp, dest.open("wb") as out: shutil.copyfileobj(resp, out)
# ---------------------------------------------------------------- stage: datadef stage_data() -> dict: download(LOCOMO_URL, WORK / "locomo10.json") conv = run([sys.executable, "convert_locomo.py", "--source", str(WORK / "locomo10.json"), "--out-dir", str(WORK / "locomo")]) report = json.loads(conv.stdout.strip().splitlines()[-1]) uploaded = [] for name in sorted(p.name for p in (WORK / "locomo").glob("category_*.jsonl")): data = (WORK / "locomo" / name).read_bytes() uploaded.append(push_file(f"data_{name}", data)) # multi-hop row count is the one the claim depends on multi = report["rows_per_category"].get("category_1_multi_hop.jsonl", {}) return {"report": report, "uploaded": uploaded, "multi_hop_queries": multi.get("queries"), "multi_hop_conversations": multi.get("conversations")}
# --------------------------------------------------------------- stage: setupdef stage_setup() -> dict: api = hf_api() name = "category_1_multi_hop.jsonl" data_dir = WORK / "locomo" data_dir.mkdir(parents=True, exist_ok=True) files = api.list_repo_files(repo_id=REPO_ID, repo_type="dataset") match = [f for f in files if f.startswith("logs/") and f.endswith(".jsonl") and "category_1_multi_hop" in f and "data_" in f] if not match: raise RuntimeError("data-stage output not found in bundle repo — run the 'data' stage first") local = api.hf_hub_download(repo_id=REPO_ID, repo_type="dataset", filename=sorted(match)[-1]) (data_dir / name).write_bytes(Path(local).read_bytes())
repo_dir = WORK / "TrajWiki" with urllib.request.urlopen(TARBALL_URL, timeout=120) as resp: with tarfile.open(fileobj=io.BytesIO(resp.read()), mode="r:gz") as tar: tar.extractall(WORK) extracted = list(WORK.glob("TrajWiki-*")) if len(extracted) != 1: raise RuntimeError(f"expected one extracted dir, found {[p.name for p in extracted]}") extracted[0].rename(repo_dir) commit_file = (repo_dir / ".git_commit.txt") commit_file.write_text(PINNED_COMMIT)
env = {**os.environ, "PYTHONPATH": str(repo_dir / "src"), "PATH": os.environ["PATH"]} run([sys.executable, "-m", "pip", "install", "--no-cache-dir", "-e", str(repo_dir)], env=env) help_text = run([sys.executable, "-m", "trajpatch", "run-answer-ablation", "--help"], env=env).stdout missing = [f for f in CLAIM_FLAGS if f not in help_text] if missing: raise RuntimeError(f"claim-critical flags missing at pinned commit: {missing}") smoke = run([sys.executable, "-m", "trajpatch", "benchmark-locomo", "--dataset-path", str(data_dir), "--subset", "multi_hop", "--backbone-provider-kind", "mock", "--judge-provider-kind", "mock", "--embedding-model", "hash-embedding", "--max-samples", "1", "--output-dir", str(WORK / "smoke")], env=env) return { "pinned_commit": PINNED_COMMIT, "claim_flags_verified": CLAIM_FLAGS, "smoke_tail": smoke.stdout[-2500:], }
# ----------------------------------------------------------- stage: router testdef stage_router_test() -> dict: from openai import OpenAI
router = OpenAI(base_url="https://router.huggingface.co/v1", api_key=os.environ["HF_TOKEN"]) results = {} for model in ["openai/gpt-4o-mini", "anthropic/claude-sonnet-4-6"]: try: r = router.chat.completions.create( model=model, messages=[{"role": "user", "content": "Reply with exactly: OK"}], max_tokens=8, ) results[model] = {"ok": True, "content": r.choices[0].message.content, "prompt_tokens": r.usage.prompt_tokens, "completion_tokens": r.usage.completion_tokens} except Exception as exc: # noqa: BLE001 results[model] = {"ok": False, "error": repr(exc)[:500]} return {"results": results}
def stage_mirror() -> dict: """Mirror mode: execute nothing; verify file parity with the org Space. Runs on the private Frame17 mirror Space. Reads are public-only (no token needed), and local files are compared against the org Space's files. """ api = HfApi() parity = {} for name in SHARED_FILES + ["stage.txt"]: 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=SPACE_ID, repo_type="space", filename=name)).read_bytes() parity[name] = "match" if local == remote else "DIFFER" except Exception as exc: # noqa: BLE001 parity[name] = f"org-read-error: {exc}" try: org_stage = Path(api.hf_hub_download( repo_id=SPACE_ID, repo_type="space", filename="stage.txt" )).read_text(encoding="utf-8").strip() except Exception as exc: # noqa: BLE001 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 = {"router-test": stage_router_test, "data": stage_data, "setup": stage_setup, "mirror": stage_mirror}
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: # noqa: BLE001 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>TrajWiki 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: # noqa: N802 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()executor_entrypoint.pyAdded+276