File size: 8,935 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
"""One Kaggle session: pick a runnable job, hold its lease, run it until done or out of time.



    python -m pocket_math.runner --job auto --ops-repo ORG/pocket-math-ops



Friends never pass anything but the job id. Everything else comes from the queue and the

job's own repo, so any account can continue any job.

"""

from __future__ import annotations

import argparse
import os
import shutil
import subprocess
import sys
import time
import traceback
import uuid
from pathlib import Path

from .config import PROJECT_DIR, resolve_job_config
from .context import JobContext, OutOfTime, Session, secret_values
from .hub import Heartbeat, JobHandle, Lease, LeaseLost, make_store, use_http_timeouts
from .queue import DONE, FAILED, JobView, QueueEntry, job_repo, parse_queue, runnable

LEASE_TTL = 45 * 60
HEARTBEAT_EVERY = 10 * 60
MAX_FAILS = 2
MIN_MINUTES_TO_START = 25


def detect_gpus() -> int:
    if shutil.which("nvidia-smi") is None:
        return 0
    out = subprocess.run(["nvidia-smi", "-L"], capture_output=True, text=True).stdout
    return sum(1 for line in out.splitlines() if line.startswith("GPU "))


def code_sha() -> str:
    if os.environ.get("PM_CODE_SHA"):
        return os.environ["PM_CODE_SHA"]
    marker = PROJECT_DIR / "CODE_SHA"
    if marker.exists():
        return marker.read_text().strip()
    try:
        return subprocess.run(["git", "-C", str(PROJECT_DIR), "rev-parse", "HEAD"], capture_output=True,
                              text=True, timeout=20).stdout.strip() or "unknown"
    except (OSError, subprocess.SubprocessError):
        return "unknown"


def whoami(hub: str) -> str:
    if hub != "hf":
        return os.environ.get("USER") or os.environ.get("USERNAME") or "local"
    try:
        from huggingface_hub import HfApi

        return HfApi(token=os.environ.get("HF_TOKEN")).whoami()["name"]
    except Exception:  # noqa: BLE001 - attribution only
        return "unknown"


def job_views(entries: list[QueueEntry], ops_repo: str, hub: str) -> dict[str, JobView]:
    views = {}
    for e in entries:
        store = make_store(job_repo(ops_repo, e.id), hub)
        head = store.head()
        if head is None:
            views[e.id] = JobView(None, None)
            continue
        state_text = store.read_text("state.json", revision=head)
        import json

        status = json.loads(state_text).get("status") if state_text else None
        views[e.id] = JobView(status, Lease.parse(store.read_text("lease.json", revision=head)))
    return views


def run_job(entry: QueueEntry, handle: JobHandle, session: Session) -> str:
    """Returns "done", "paused", "failed" or "lost"."""
    from .jobs import HANDLERS

    beat = Heartbeat(handle, HEARTBEAT_EVERY)
    beat.start()
    ctx: JobContext | None = None
    try:
        config = handle.read_json("config.json") or resolve_job_config(entry.config, entry.overrides,
                                                                       org=session.ops_repo.split("/")[0])
        state = handle.read_json("state.json", {}) or {"status": "new", "fails": 0, "sessions": []}
        ctx = JobContext(entry.id, config, handle, session, state)
        sessions = [*state.get("sessions", []), {"id": session.id, "user": session.user, "start": time.time()}]
        ctx.commit({"config.json": config}, "session start", state={"status": "running", "sessions": sessions[-50:]})
        handler = HANDLERS[config["kind"]]
        try:
            outcome = handler(ctx)
        except OutOfTime as e:
            ctx.log(f"pausing: {e}")
            outcome = "paused"
        ctx.commit({}, f"session end: {outcome}", state={"status": DONE if outcome == "done" else "paused",
                                                         "fails": 0})
        return outcome
    except LeaseLost:
        print(f"lease on {entry.id} was taken over; this session stops writing", flush=True)
        return "lost"
    except Exception as e:  # noqa: BLE001 - record the failure in the job repo, then let the next job run
        tb = traceback.format_exc()
        message = f"{type(e).__name__}: {str(e)[:500]}"
        for secret in secret_values():
            tb, message = tb.replace(secret, "***"), message.replace(secret, "***")
        print(tb, flush=True)
        if ctx is None or handle.lost.is_set():
            return "failed"
        fails = int(ctx.state.get("fails", 0)) + 1
        status = FAILED if fails >= MAX_FAILS else "paused"
        try:
            ctx.commit({"logs/last_error.txt": tb[-6000:]}, f"error: {type(e).__name__}",
                       state={"status": status, "fails": fails, "last_error": message})
        except LeaseLost:
            return "lost"
        return "failed"
    finally:
        beat.stop()
        beat.join(timeout=900)
        if not handle.lost.is_set():
            try:
                handle.commit({}, "release", released=True)
            except Exception as e:  # noqa: BLE001 - an unreleased lease expires on its own after LEASE_TTL
                print(f"lease release failed ({type(e).__name__}); it expires in {LEASE_TTL // 60} min", flush=True)


def main(argv: list[str] | None = None) -> int:
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--job", default="auto", help="a job id from the queue, or 'auto' for the first runnable job")
    p.add_argument("--ops-repo", default=os.environ.get("PM_OPS_REPO"), required=not os.environ.get("PM_OPS_REPO"))
    p.add_argument("--hub", default=os.environ.get("PM_HUB", "hf"), help="'hf' or 'local:<dir>' (tests)")
    p.add_argument("--work", default=os.environ.get("PM_WORK", "/tmp/pm-work"))
    p.add_argument("--budget-hours", type=float, default=float(os.environ.get("PM_BUDGET_HOURS", "11.25")))
    p.add_argument("--gen-python", default=os.environ.get("PM_GEN_PYTHON", sys.executable),
                   help="the Python of the vLLM venv")
    p.add_argument("--env-dir", default=os.environ.get("PM_ENV_DIR"), help="session environment files to record")
    a = p.parse_args(argv)

    if a.hub == "hf":
        use_http_timeouts()
    start = float(os.environ.get("PM_SESSION_START", time.time()))
    session = Session(id=time.strftime("%Y%m%d-%H%M%S-") + uuid.uuid4().hex[:6], user=whoami(a.hub),
                      start=start, deadline=start + a.budget_hours * 3600, hub=a.hub, ops_repo=a.ops_repo,
                      work=Path(a.work), gen_python=a.gen_python, n_gpus=detect_gpus(), code_sha=code_sha(),
                      env_dir=Path(a.env_dir) if a.env_dir else None)
    print(f"session {session.id} user={session.user} gpus={session.n_gpus} code={session.code_sha[:12]} "
          f"budget={a.budget_hours} h", flush=True)

    ops = make_store(a.ops_repo, a.hub, repo_type="dataset")
    entries = parse_queue(ops.read_text("queue.yaml"))
    by_id = {e.id: e for e in entries}
    if a.job != "auto" and a.job not in by_id:
        print(f"job {a.job!r} is not in queue.yaml; known: {sorted(by_id)}", flush=True)
        return 2
    if a.job != "auto":
        views = job_views(entries, a.ops_repo, a.hub)
        if views[a.job].status in (DONE, FAILED):
            print(f"job {a.job} is {views[a.job].status}; nothing to run", flush=True)
            return 0
        waiting = [n for n in by_id[a.job].needs if views.get(n, JobView(None, None)).status != DONE]
        if waiting:
            print(f"job {a.job} waits for {waiting}", flush=True)
            return 0

    tried: set[str] = set()
    while session.time_left() > MIN_MINUTES_TO_START * 60:
        if a.job == "auto":
            views = job_views(entries, a.ops_repo, a.hub)
            candidates = [j for j in runnable(entries, views, session.id, time.time(), LEASE_TTL) if j not in tried]
        else:
            candidates = [a.job] if a.job not in tried else []
        claimed = None
        for job_id in candidates:
            handle = JobHandle(make_store(job_repo(a.ops_repo, job_id), a.hub), session.id, session.user, LEASE_TTL)
            if handle.try_claim():
                claimed = (by_id[job_id], handle)
                break
            print(f"{job_id}: another session holds it", flush=True)
            tried.add(job_id)
        if claimed is None:
            print("no runnable job for this session", flush=True)
            break
        entry, handle = claimed
        tried.add(entry.id)
        print(f"running {entry.id} ({entry.config})", flush=True)
        outcome = run_job(entry, handle, session)
        print(f"{entry.id}: {outcome}", flush=True)
        if outcome == "paused" or a.job != "auto":
            break
    return 0


if __name__ == "__main__":
    sys.exit(main())