File size: 12,937 Bytes
f10cac2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
#!/usr/bin/env python3
"""Download Albedo eval artifacts (rollouts) for a given eval_run_id.

The public dashboard at albedo.tech lists recent evals and their artifact URLs.
This script looks up that eval, then downloads every artifact the site exposes:

  generated-samples.jsonl   challenger + king rollouts (the main training file)
  scoring-results.jsonl     per-sample judge scores
  verdict.json              win/loss, margins, model URIs
  progress.jsonl            remote generation progress
  remote-logs.txt           remote worker log summary

Usage:
  python pull_eval_rollouts.py 1a23f451-459e-481d-a896-7604220a5d01
  python pull_eval_rollouts.py https://albedo.tech/detail.html?eval_run_id=1a23f451-...
  python pull_eval_rollouts.py 1a23f451-... --out ./evals --sibling-passes
"""

from __future__ import annotations

import argparse
import json
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path

DASHBOARD_URLS = [
    "https://albedo.tech/data/dashboard.json",
]

# Same labels the website uses in website/js/config.js ARTIFACT_TYPES.
ARTIFACT_NAMES = {
    "EVAL_VERDICT": "verdict.json",
    "GENERATED_SAMPLES": "generated-samples.jsonl",
    "SCORING_RESULTS": "scoring-results.jsonl",
    "JUDGE_RESULTS": "judge-results.jsonl",
    "EVAL_TRANSCRIPT": "duel-transcript.jsonl",
    "REMOTE_PROGRESS": "progress.jsonl",
    "REMOTE_LOGS": "remote-logs.txt",
    "SANITY_RESULT": "sanity-result.json",
}

# Miners usually want these first; the rest are still downloaded unless --only is set.
DEFAULT_PRIORITY = (
    "GENERATED_SAMPLES",
    "SCORING_RESULTS",
    "EVAL_VERDICT",
    "REMOTE_PROGRESS",
    "REMOTE_LOGS",
    "JUDGE_RESULTS",
    "EVAL_TRANSCRIPT",
    "SANITY_RESULT",
)

USER_AGENT = "albedo-mining-scripts/1.0 (+https://albedo.tech)"
CHUNK = 1 << 16


def log(message: str) -> None:
    print(message, flush=True)


def parse_eval_run_id(raw: str) -> str:
    value = raw.strip()
    if "eval_run_id=" in value:
        query = urllib.parse.urlparse(value).query
        found = urllib.parse.parse_qs(query).get("eval_run_id", [None])[0]
        if found:
            return found.strip()
    return value


def request(url: str, *, timeout: float = 60) -> urllib.request.Request:
    return urllib.request.Request(url, headers={"User-Agent": USER_AGENT})


def fetch_json(url: str, *, timeout: float = 60) -> dict:
    with urllib.request.urlopen(request(url), timeout=timeout) as resp:
        return json.loads(resp.read().decode("utf-8"))


def load_dashboard(urls: list[str]) -> dict:
    last_error: Exception | None = None
    for base in urls:
        # cache-bust the same way the website does
        url = f"{base}?t={int(time.time() * 1000)}"
        try:
            data = fetch_json(url, timeout=90)
            if isinstance(data, dict) and (
                data.get("eval_runs") is not None or data.get("current_eval") is not None
            ):
                return data
            last_error = RuntimeError(f"unexpected dashboard payload from {base}")
        except Exception as exc:  # noqa: BLE001 — try the next mirror
            last_error = exc
    raise RuntimeError(f"could not load dashboard.json: {last_error}")


def iter_dashboard_records(dashboard: dict) -> list[tuple[str, dict]]:
    records: list[tuple[str, dict]] = []
    for run in dashboard.get("eval_runs") or []:
        records.append(("eval_run", run))
    current = dashboard.get("current_eval")
    if isinstance(current, dict) and current.get("eval_run_id"):
        records.append(("current_eval", current))
    for fail in dashboard.get("fails") or []:
        records.append(("fail", fail))
    return records


def find_record(dashboard: dict, eval_run_id: str) -> tuple[str, dict]:
    for kind, record in iter_dashboard_records(dashboard):
        if record.get("eval_run_id") == eval_run_id:
            return kind, record
    raise KeyError(
        f"eval_run_id {eval_run_id} was not in the public dashboard "
        f"({len(dashboard.get('eval_runs') or [])} recent evals + "
        f"{len(dashboard.get('fails') or [])} fails). "
        "The site only publishes the latest ~200 finished evals."
    )


def sibling_passes(dashboard: dict, record: dict) -> list[dict]:
    submission_id = record.get("submission_id")
    if not submission_id:
        return [record]
    runs = [
        run
        for run in (dashboard.get("eval_runs") or [])
        if run.get("submission_id") == submission_id
    ]
    runs.sort(key=lambda run: str(run.get("finished_at") or ""))
    return runs or [record]


def human_bytes(n: int | None) -> str:
    if n is None:
        return "?"
    size = float(n)
    for unit in ("B", "KB", "MB", "GB"):
        if size < 1024 or unit == "GB":
            return f"{size:.1f} {unit}" if unit != "B" else f"{int(size)} B"
        size /= 1024
    return f"{n} B"


def download_file(url: str, dest: Path, *, retries: int = 3) -> dict:
    dest.parent.mkdir(parents=True, exist_ok=True)
    last_error: Exception | None = None
    for attempt in range(1, retries + 1):
        tmp = dest.with_suffix(dest.suffix + ".part")
        try:
            with urllib.request.urlopen(request(url), timeout=180) as resp:
                total = resp.headers.get("Content-Length")
                expected = int(total) if total and total.isdigit() else None
                if dest.exists() and expected is not None and dest.stat().st_size == expected:
                    return {
                        "path": dest,
                        "bytes": expected,
                        "skipped": True,
                        "url": url,
                    }
                written = 0
                started = time.time()
                with tmp.open("wb") as handle:
                    while True:
                        chunk = resp.read(CHUNK)
                        if not chunk:
                            break
                        handle.write(chunk)
                        written += len(chunk)
                if expected is not None and written != expected:
                    raise IOError(f"size mismatch: got {written}, expected {expected}")
            tmp.replace(dest)
            elapsed = max(time.time() - started, 0.001)
            return {
                "path": dest,
                "bytes": written,
                "skipped": False,
                "url": url,
                "mbps": (written / elapsed) / (1024 * 1024),
            }
        except (urllib.error.URLError, TimeoutError, OSError) as exc:
            last_error = exc
            if tmp.exists():
                tmp.unlink(missing_ok=True)
            if attempt < retries:
                time.sleep(1.5 * attempt)
    raise RuntimeError(f"download failed for {url}: {last_error}")


def count_jsonl(path: Path) -> int:
    if path.suffix != ".jsonl" or not path.exists():
        return 0
    n = 0
    with path.open() as handle:
        for line in handle:
            if line.strip():
                n += 1
    return n


def write_meta(out_dir: Path, kind: str, record: dict, downloads: list[dict]) -> Path:
    meta = {
        "source": "https://albedo.tech/data/dashboard.json",
        "kind": kind,
        "eval_run_id": record.get("eval_run_id"),
        "submission_id": record.get("submission_id"),
        "model_uri": record.get("model_uri"),
        "uid": record.get("uid"),
        "hotkey": record.get("hotkey"),
        "challenger_won": record.get("challenger_won"),
        "score_challenger": record.get("score_challenger"),
        "score_king": record.get("score_king"),
        "win_margin": record.get("win_margin"),
        "required_win_margin": record.get("required_win_margin"),
        "pass_margins": record.get("pass_margins"),
        "finished_at": record.get("finished_at"),
        "scoring_mode": record.get("scoring_mode"),
        "scored_sample_count": record.get("scored_sample_count"),
        "total_turns": record.get("total_turns"),
        "valid_turns": record.get("valid_turns"),
        "king": record.get("king"),
        "artifacts": record.get("artifacts") or {},
        "downloaded": [
            {
                "name": item["name"],
                "path": str(item["path"].name),
                "bytes": item["bytes"],
                "skipped": item.get("skipped", False),
                "url": item["url"],
                "rollout_count": item.get("rollout_count"),
            }
            for item in downloads
        ],
    }
    path = out_dir / "eval-meta.json"
    path.write_text(json.dumps(meta, indent=2, default=str) + "\n", encoding="utf-8")
    return path


def pull_one(
    record: dict,
    kind: str,
    out_root: Path,
    *,
    only: set[str] | None,
    force: bool,
) -> Path:
    eval_run_id = record["eval_run_id"]
    out_dir = out_root / eval_run_id
    artifacts = record.get("artifacts") or {}
    if not artifacts:
        raise RuntimeError(f"{eval_run_id}: no artifacts listed on the dashboard")

    keys = [key for key in DEFAULT_PRIORITY if key in artifacts]
    keys.extend(key for key in artifacts if key not in keys)
    if only:
        keys = [key for key in keys if key in only]
        missing = only - set(artifacts)
        if missing:
            log(f"  warning: dashboard has no {', '.join(sorted(missing))}")

    downloads: list[dict] = []
    for key in keys:
        url = artifacts[key]
        name = ARTIFACT_NAMES.get(key, url.rstrip("/").rsplit("/", 1)[-1])
        dest = out_dir / name
        if force and dest.exists():
            dest.unlink()
        log(f"  {name}")
        result = download_file(url, dest)
        result["name"] = name
        if name == "generated-samples.jsonl":
            result["rollout_count"] = count_jsonl(dest)
        status = "skipped" if result.get("skipped") else f"{human_bytes(result['bytes'])}"
        extra = ""
        if result.get("rollout_count") is not None:
            extra = f" · {result['rollout_count']} rollouts"
        if result.get("mbps") and not result.get("skipped"):
            extra += f" · {result['mbps']:.1f} MB/s"
        log(f"    {status}{extra}")
        downloads.append(result)

    write_meta(out_dir, kind, record, downloads)
    return out_dir


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="Download Albedo eval rollouts for one eval_run_id from albedo.tech."
    )
    parser.add_argument(
        "eval_run_id",
        help="eval run UUID, or a detail.html URL that contains eval_run_id=",
    )
    parser.add_argument(
        "--out",
        type=Path,
        default=Path("evals"),
        help="output directory (default: ./evals/<eval_run_id>/)",
    )
    parser.add_argument(
        "--sibling-passes",
        action="store_true",
        help="also download the other scored pass on the same submission (win-on-both)",
    )
    parser.add_argument(
        "--only",
        metavar="NAME",
        action="append",
        help="download only these artifact keys, e.g. GENERATED_SAMPLES (repeatable)",
    )
    parser.add_argument(
        "--force",
        action="store_true",
        help="re-download files even if they already exist with the same size",
    )
    parser.add_argument(
        "--dashboard-url",
        action="append",
        dest="dashboard_urls",
        help="override dashboard.json URL (repeatable)",
    )
    return parser


def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    eval_run_id = parse_eval_run_id(args.eval_run_id)
    if not eval_run_id:
        log("error: missing eval_run_id")
        return 2

    only = {name.upper() for name in args.only} if args.only else None
    dashboard = load_dashboard(args.dashboard_urls or DASHBOARD_URLS)
    kind, record = find_record(dashboard, eval_run_id)
    targets = sibling_passes(dashboard, record) if args.sibling_passes else [record]

    log(f"eval_run_id  {eval_run_id}")
    log(f"model        {record.get('model_uri') or '—'}")
    log(
        f"result       chal {record.get('score_challenger')}  "
        f"king {record.get('score_king')}  "
        f"margin {record.get('win_margin')}  "
        f"won={record.get('challenger_won')}"
    )
    if len(targets) > 1:
        log(f"sibling passes: {len(targets)} evals on submission {record.get('submission_id')}")

    for target in targets:
        tid = target.get("eval_run_id")
        log(f"\ndownloading {tid}")
        out_dir = pull_one(target, kind, args.out, only=only, force=args.force)
        log(f"  wrote {out_dir}")

    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except KeyError as exc:
        log(f"error: {exc}")
        raise SystemExit(1)
    except Exception as exc:  # noqa: BLE001
        log(f"error: {exc}")
        raise SystemExit(1)