File size: 12,370 Bytes
b16b327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Operator commands, run from a laptop with an HF token that can write to the org.



    python -m pocket_math ops init --org ORG

    python -m pocket_math ops publish-code --ops-repo ORG/pocket-math-ops

    python -m pocket_math ops add smoke smoke.yaml --ops-repo ORG/pocket-math-ops

    python -m pocket_math ops add opd-8k opd-8k.yaml --needs smoke --set rounds=120

    python -m pocket_math ops status

    python -m pocket_math ops reset opd-8k            # failed -> paused, after fixing the cause

    python -m pocket_math ops set opd-8k optim.lr=3e-5   # only while no session holds the job

    python -m pocket_math ops compare eval-a eval-b --cap 32768

    python -m pocket_math ops upload-data data_out/dev.jsonl data_out/pool.jsonl ...

    python -m pocket_math ops label data_out/pool.jsonl label-0 label-1 --cap 16384 --out data_out/pool.jsonl

"""

from __future__ import annotations

import argparse
import json
import os
import subprocess
import tempfile
import time
from pathlib import Path
from typing import Any

import yaml

from .config import PROJECT_DIR, resolve_job_config, set_dotted
from .hub import Lease, make_store
from .queue import QueueEntry, dump_queue, job_repo, parse_queue

CODE_PATHS = ("pocket_math", "configs", "kaggle", "pyproject.toml", "README.md")


def _parse_sets(pairs: list[str] | None) -> dict[str, Any]:
    out = {}
    for item in pairs or []:
        key, _, raw = item.partition("=")
        value = yaml.safe_load(raw)
        if isinstance(value, str):
            try:
                value = float(value)
            except ValueError:
                pass
        out[key] = value
    return out


def _ops(a) -> Any:
    return make_store(a.ops_repo, a.hub, repo_type="dataset")


def _write_queue(ops, entries: list[QueueEntry], message: str) -> None:
    ops.commit({"queue.yaml": dump_queue(entries).encode()}, [], message, parent=ops.head())


def cmd_init(a) -> None:
    ops = make_store(f"{a.org}/pocket-math-ops", a.hub, repo_type="dataset")
    ops.ensure()
    if ops.read_text("queue.yaml") is None:
        ops.commit({"queue.yaml": b"jobs: []\n"}, [], "create queue", parent=None)
    make_store(f"{a.org}/pocket-math-data", a.hub, repo_type="dataset").ensure()
    print(f"ops repo {a.org}/pocket-math-ops and data repo {a.org}/pocket-math-data are ready")


def _git_sha() -> tuple[str, bool]:
    sha = subprocess.run(["git", "-C", str(PROJECT_DIR), "rev-parse", "HEAD"], capture_output=True,
                         text=True).stdout.strip()
    dirty = bool(subprocess.run(["git", "-C", str(PROJECT_DIR), "status", "--porcelain", "--", "."],
                                capture_output=True, text=True).stdout.strip())
    return sha, dirty


def cmd_publish_code(a) -> None:
    sha, dirty = _git_sha()
    if dirty and not a.allow_dirty:
        raise SystemExit("projects/pocket-math has uncommitted changes; commit first (or --allow-dirty)")
    files: dict[str, Path | bytes] = {}
    for rel in CODE_PATHS:
        p = PROJECT_DIR / rel
        paths = [p] if p.is_file() else [x for x in p.rglob("*") if x.is_file()]
        for f in paths:
            if "__pycache__" in f.parts or f.suffix in (".pyc", ".tmp"):
                continue
            files[f"code/{f.relative_to(PROJECT_DIR).as_posix()}"] = f
    files["code/CODE_SHA"] = (sha + ("-dirty" if dirty else "")).encode()
    ops = _ops(a)
    stale = ["code/"] if any(f.startswith("code/") for f in ops.list_files()) else []
    ops.commit(files, stale, f"code {sha[:12]}", parent=ops.head())
    remote = {f for f in ops.list_files() if f.startswith("code/")}
    if remote != set(files):
        raise SystemExit(f"the published snapshot differs from the local code: missing "
                         f"{sorted(set(files) - remote)[:10]}, extra {sorted(remote - set(files))[:10]}")
    print(f"published {len(files)} files at {sha[:12]} to {a.ops_repo}/code (all present on the store)")


def cmd_add(a) -> None:
    ops = _ops(a)
    entries = parse_queue(ops.read_text("queue.yaml"))
    if any(e.id == a.id for e in entries):
        raise SystemExit(f"{a.id} is already queued")
    overrides = _parse_sets(a.set)
    resolve_job_config(a.config, overrides, org=a.ops_repo.split("/")[0])
    entry = QueueEntry(a.id, a.config, overrides, tuple(x for x in (a.needs or "").split(",") if x))
    entries.append(entry)
    parse_queue(dump_queue(entries))
    make_store(job_repo(a.ops_repo, a.id), a.hub).ensure()
    _write_queue(ops, entries, f"add {a.id}")
    print(f"queued {a.id} ({a.config}); repo {job_repo(a.ops_repo, a.id)}")


def cmd_remove(a) -> None:
    ops = _ops(a)
    entries = [e for e in parse_queue(ops.read_text("queue.yaml")) if e.id != a.id]
    _write_queue(ops, entries, f"remove {a.id}")


def _job_files(a, job_id: str) -> tuple[Any, dict, Lease | None]:
    store = make_store(job_repo(a.ops_repo, job_id), a.hub)
    head = store.head()
    state = json.loads(store.read_text("state.json", head) or "{}") if head else {}
    lease = Lease.parse(store.read_text("lease.json", head)) if head else None
    return store, state, lease


def cmd_status(a) -> None:
    entries = parse_queue(_ops(a).read_text("queue.yaml"))
    now = time.time()
    print(f"{'job':24} {'status':9} {'progress':12} {'held by':18} {'beat':>6}  notes")
    for e in entries:
        _, st, lease = _job_files(a, e.id)
        progress = (f"round {st['round']}" if "round" in st else f"chunk {st['chunks']}" if "chunks" in st else "")
        holder = beat = ""
        if lease and not lease.released and now - lease.heartbeat < 2700:
            holder, beat = lease.user[:18], f"{(now - lease.heartbeat) / 60:.0f}m"
        notes = st.get("last_error") or st.get("stopped") or json.dumps(st.get("summary", ""))[:60]
        print(f"{e.id:24} {st.get('status', 'new'):9} {progress:12} {holder:18} {beat:>6}  {notes}")


def _write_job(a, job_id: str, mutate) -> None:
    store, state, lease = _job_files(a, job_id)
    if lease and lease.held_by_other("ops", time.time(), 2700) and not a.force:
        raise SystemExit(f"{job_id} is held by {lease.user}; wait for its session to end (or --force, which "
                         "makes that session stop at its next commit)")
    files = mutate(store, state)
    # Writing the lease as well makes a session that still holds this job fail its next commit and
    # stop, instead of carrying on with the old config.
    files["lease.json"] = {"session": "ops", "user": "ops", "seq": 0, "heartbeat": time.time(), "released": True}
    store.commit({k: json.dumps(v, indent=2).encode() for k, v in files.items()}, [], f"ops: {a.cmd} {job_id}",
                 parent=store.head())


def cmd_reset(a) -> None:
    def mutate(store, state):
        return {"state.json": {**state, "status": "paused", "fails": 0, "last_error": None}}

    _write_job(a, a.id, mutate)
    print(f"{a.id} reset to paused")


def cmd_set(a) -> None:
    def mutate(store, state):
        cfg = json.loads(store.read_text("config.json") or "null")
        if cfg is None:
            raise SystemExit(f"{a.id} has not started; change its queue entry instead")
        for k, v in _parse_sets(a.pairs).items():
            set_dotted(cfg, k, v)
        notes = [*state.get("config_changes", []), {"time": time.time(), "set": a.pairs}]
        return {"config.json": cfg, "state.json": {**state, "config_changes": notes}}

    _write_job(a, a.id, mutate)
    print(f"{a.id}: set {a.pairs}")


def _results(a, job_id: str) -> tuple[list[dict], dict]:
    store = make_store(job_repo(a.ops_repo, job_id), a.hub)
    with tempfile.TemporaryDirectory() as d:
        store.download(["results/results.jsonl", "config.json"], Path(d))
        rows = [json.loads(x) for x in (Path(d) / "results/results.jsonl").read_text().splitlines() if x.strip()]
        cfg = json.loads((Path(d) / "config.json").read_text())
    return rows, cfg


def cmd_compare(a) -> None:
    from .evaluate import correct_at
    from .stats import mde, paired_bootstrap, pass_at_1

    (ra, ca), (rb, cb) = _results(a, a.a), _results(a, a.b)
    cap = a.cap or min(int(ca.get("max_new_tokens") or 10 ** 9), int(cb.get("max_new_tokens") or 10 ** 9))

    def to_results(rows):
        out: dict[str, list[bool]] = {}
        for r in rows:
            out.setdefault(r["uid"], []).append(correct_at(r, cap))
        return out

    A, B = to_results(ra), to_results(rb)
    c = paired_bootstrap(A, B)
    print(f"cap {cap}: {a.a} {100 * pass_at_1(A):.2f}  vs  {a.b} {100 * pass_at_1(B):.2f}  on {c.n_problems} shared problems")
    print(f"difference {100 * c.diff:+.2f} points, 95% CI [{100 * c.lo:+.2f}, {100 * c.hi:+.2f}], p={c.p_value:.4f}")
    print(f"minimum detectable effect on these problems: {100 * mde(A, B):.2f} points")


def cmd_upload_data(a) -> None:
    from .io import sha256_file

    org = a.ops_repo.split("/")[0]
    store = make_store(f"{org}/pocket-math-data", a.hub, repo_type="dataset")
    store.ensure()
    files = {f"{a.prefix}{Path(f).name}": Path(f) for f in a.files}
    sums = {name: sha256_file(path) for name, path in files.items()}
    store.commit(files, [], "data: " + ", ".join(sorted(files)), parent=store.head())
    for name, digest in sorted(sums.items()):
        print(f"{org}/pocket-math-data:{name}  sha256 {digest}")


def cmd_label(a) -> None:
    """Write each pool problem's pass rate (from eval jobs run on the pool) into meta.pass_rate."""
    from .evaluate import correct_at
    from .io import read_jsonl, write_jsonl

    hits: dict[str, list[bool]] = {}
    for job_id in a.jobs:
        rows, cfg = _results(a, job_id)
        cap = a.cap or int(cfg.get("max_new_tokens") or 10 ** 9)
        for r in rows:
            hits.setdefault(r["uid"], []).append(correct_at(r, cap))
    pool = list(read_jsonl(a.pool))
    labelled = 0
    for row in pool:
        if row["uid"] in hits:
            h = hits[row["uid"]]
            row.setdefault("meta", {})["pass_rate"] = sum(h) / len(h)
            labelled += 1
    write_jsonl(a.out, pool)
    print(f"labelled {labelled}/{len(pool)} problems from {len(a.jobs)} eval jobs -> {a.out}")


def main(argv: list[str] | None = None) -> int:
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--ops-repo", default=os.environ.get("PM_OPS_REPO"))
    p.add_argument("--hub", default=os.environ.get("PM_HUB", "hf"))
    sub = p.add_subparsers(dest="cmd", required=True)
    s = sub.add_parser("init")
    s.add_argument("--org", required=True)
    s = sub.add_parser("publish-code")
    s.add_argument("--allow-dirty", action="store_true")
    s = sub.add_parser("add")
    s.add_argument("id")
    s.add_argument("config")
    s.add_argument("--set", action="append", help="dotted.key=value, e.g. rounds=40")
    s.add_argument("--needs", help="comma-separated job ids that must be done first")
    s = sub.add_parser("remove")
    s.add_argument("id")
    sub.add_parser("status")
    for name in ("reset", "set"):
        s = sub.add_parser(name)
        s.add_argument("id")
        s.add_argument("--force", action="store_true")
        if name == "set":
            s.add_argument("pairs", nargs="+")
    s = sub.add_parser("compare")
    s.add_argument("a")
    s.add_argument("b")
    s.add_argument("--cap", type=int)
    s = sub.add_parser("upload-data")
    s.add_argument("files", nargs="+")
    s.add_argument("--prefix", default="", help="folder in the data repo, e.g. sft/")
    s = sub.add_parser("label")
    s.add_argument("pool")
    s.add_argument("jobs", nargs="+")
    s.add_argument("--cap", type=int)
    s.add_argument("--out", required=True)
    a = p.parse_args(argv)
    if a.cmd != "init" and not a.ops_repo:
        raise SystemExit("set --ops-repo or PM_OPS_REPO")
    {"init": cmd_init, "publish-code": cmd_publish_code, "add": cmd_add, "remove": cmd_remove, "status": cmd_status,
     "reset": cmd_reset, "set": cmd_set, "compare": cmd_compare, "upload-data": cmd_upload_data,
     "label": cmd_label}[a.cmd](a)
    return 0