File size: 11,644 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Task driver for the one GPU job of stage LINEDET.

Reads a task list (JSON, re-read every loop, so tasks can be added while the job waits in the queue or runs). A task starts
when every file in its `requires` exists and every task in `after` has finished. Tasks run as separate subprocesses, so a
crash only fails that task. At the stop time every running task gets SIGTERM (training saves resume.pt and exits), then
SIGKILL after a grace period. The state of every task is written to the status file after each change.

Task fields: name, cmd (list of strings; {PY} and {REMAIN} are replaced), requires (list), after (list), env (dict),
kind ("local" = subprocess, "sbatch" = submit a batch script and treat it as done).
"""
import argparse
import datetime
import json
import os
import signal
import subprocess
import sys
import time

CODE = "/path/to/TURKIC_OCR_CODE"
DATA = "/path/to/TURKIC_OCR_DATA"
PY = CODE + "/.venv_kraken/bin/python"


def now_s():
    return time.time()


def iso(ts):
    return datetime.datetime.fromtimestamp(ts, datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def parse_iso(s):
    return datetime.datetime.strptime(s, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=datetime.timezone.utc).timestamp()


def normalize_task(t):
    """Accept the task layout of other stages. Keys: name (or id); cmd or command (list, or a string that is split like a shell line);
    venv (a directory; {VENV} in the command is replaced by it); requires, after (lists); env (mapping); max_runtime_s or max_hours;
    reserve_s (seconds before the job stop at which {REMAIN} ends); retry_args; cwd; kind."""
    import shlex
    name = t.get("name") or t.get("id")
    cmd = t.get("cmd") or t.get("command")
    if not name or not cmd:
        return None
    if isinstance(cmd, str):
        cmd = shlex.split(cmd)
    venv = t.get("venv")
    if venv:
        cmd = [c.replace("{VENV}", venv) for c in cmd]
    mr = t.get("max_runtime_s") or (float(t["max_hours"]) * 3600 if t.get("max_hours") else None)
    nt = {"name": str(name), "cmd": [str(c) for c in cmd], "requires": list(t.get("requires", [])), "after": list(t.get("after", [])), "env": dict(t.get("env", {}))}
    if mr:
        nt["max_runtime_s"] = mr
    for k in ("reserve_s", "retry_args", "cwd", "kind", "skip_if_missing_after_done", "gpu_mem_gb", "host_ram_gb", "cpus"):
        if k in t:
            nt[k] = t[k]
    return nt


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--tasks", required=True)
    ap.add_argument("--status", required=True)
    ap.add_argument("--logdir", required=True)
    ap.add_argument("--poll", type=float, default=20)
    ap.add_argument("--gpu_budget_gb", type=float, default=0, help="admit tasks only while the sum of their gpu_mem_gb estimates stays within this (0 = no limit)")
    ap.add_argument("--ram_budget_gb", type=float, default=0, help="same for host_ram_gb")
    ap.add_argument("--cpu_budget", type=float, default=0, help="same for cpus")
    ap.add_argument("--grace", type=float, default=240, help="seconds between SIGTERM and SIGKILL at the stop time")
    ap.add_argument("--max_seconds", type=float, default=0, help="the stop time is the earlier of stop_utc and the job start plus this many seconds")
    a = ap.parse_args()
    os.makedirs(a.logdir, exist_ok=True)
    state = {}   # name -> dict(status, pid, start, end, rc)
    procs = {}
    t_job0 = now_s()
    stop_signalled = False

    last_spec = {}

    def load_spec():
        for _ in range(5):
            try:
                last_spec.clear()
                last_spec.update(json.load(open(a.tasks)))
                break
            except Exception:
                time.sleep(1)
        spec = dict(last_spec)
        spec["tasks"] = list(spec.get("tasks", []))
        names = {x["name"] for x in spec["tasks"]}
        for inc in spec.get("include", []):          # task files written by other stages (stage REF: records/R5/REF/gpu_tasks.json copy)
            try:
                d = json.load(open(inc))
            except Exception:
                continue
            for t in (d["tasks"] if isinstance(d, dict) and "tasks" in d else d):
                nt = normalize_task(t)
                if nt and nt["name"] not in names:
                    spec["tasks"].append(nt)
                    names.add(nt["name"])
        return spec

    def write_status(note=""):
        spec = load_spec()
        out = {"updated": iso(now_s()), "job_id": os.environ.get("SLURM_JOB_ID"), "node": os.uname().nodename,
               "job_started": iso(t_job0), "stop_at": spec["stop_utc"], "hard_deadline": spec.get("deadline_utc"), "note": note, "tasks": state}
        tmp = a.status + ".tmp"
        json.dump(out, open(tmp, "w"), indent=1)
        os.replace(tmp, a.status)

    last_waiting = {}
    write_status("driver started")
    while True:
        spec = load_spec()
        stop_ts = parse_iso(spec["stop_utc"])
        if a.max_seconds:
            stop_ts = min(stop_ts, t_job0 + a.max_seconds)
        t = now_s()
        # reap
        tasks_by_name = {x["name"]: x for x in spec["tasks"]}
        for name, p in list(procs.items()):
            rc = p.poll()
            tk = tasks_by_name.get(name, {})
            if rc is None and tk.get("max_runtime_s") and t - parse_iso(state[name]["start"]) > tk["max_runtime_s"] and not state[name].get("timeout_sent"):
                state[name]["timeout_sent"] = True
                p.send_signal(signal.SIGTERM)
                state[name]["timeout_at"] = iso(t)
            if rc is None and state[name].get("timeout_sent") and t - parse_iso(state[name]["timeout_at"]) > 120:
                p.kill()
            if rc is not None:
                if rc != 0 and tk.get("retry_args") and not state[name].get("retried") and not state[name].get("timeout_sent"):
                    # one retry with extra arguments (for example --no_amp); the training resumes from resume.pt if one exists
                    remain = max(60, int(stop_ts - t - tk.get("reserve_s", 60)))
                    cmd = [c.replace("{PY}", PY).replace("{REMAIN}", str(remain)) for c in tk["cmd"]] + tk["retry_args"]
                    log = open(os.path.join(a.logdir, name + ".log"), "a")
                    log.write("\n=== RETRY with %s after rc=%s\n" % (tk["retry_args"], rc))
                    log.flush()
                    env = dict(os.environ)
                    for k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
                        env.pop(k, None)
                    env.update(tk.get("env", {}))
                    p2 = subprocess.Popen(cmd, stdout=log, stderr=subprocess.STDOUT, env=env, cwd=tk.get("cwd", DATA))
                    procs[name] = p2
                    state[name].update({"status": "running", "pid": p2.pid, "retried": True, "first_rc": rc, "cmd": cmd})
                    write_status()
                    continue
                state[name].update({"status": "done" if rc == 0 else "failed", "rc": rc, "end": iso(t)})
                del procs[name]
                write_status()
        if t >= stop_ts and not stop_signalled:
            stop_signalled = True
            for name, p in procs.items():
                state[name]["status"] = "terminating"
                p.send_signal(signal.SIGTERM)
            write_status("stop time reached, SIGTERM sent")
            grace_end = t + spec.get("grace_s", a.grace)
        if stop_signalled:
            if not procs or t > grace_end:
                for name, p in list(procs.items()):
                    p.kill()
                    state[name].update({"status": "killed", "end": iso(now_s())})
                write_status("stopped")
                break
            time.sleep(5)
            continue
        # start tasks: eligible ones are sorted by priority_order (name prefixes of the task file) and admitted by the resource budgets
        tbn = {x["name"]: x for x in spec["tasks"]}
        prio_order = spec.get("priority_order", [])

        def prio(task, pos):
            for i, pre in enumerate(prio_order):
                if task["name"].startswith(pre):
                    return (i, pos)
            return (len(prio_order), pos)
        used = {"gpu_mem_gb": 0.0, "host_ram_gb": 0.0, "cpus": 0.0}
        for n in procs:
            for k in used:
                used[k] += float(tbn.get(n, {}).get(k, 0) or 0)
        elig = []
        for pos, task in enumerate(spec["tasks"]):
            name = task["name"]
            if name in state:
                continue
            after_done = all(state.get(x, {}).get("status") in ("done", "failed", "killed", "submitted", "skipped") for x in task.get("after", []))
            if any(not os.path.exists(r) for r in task.get("requires", [])):
                if task.get("skip_if_missing_after_done") and task.get("after") and after_done:
                    state[name] = {"status": "skipped", "note": "required file never appeared and the tasks it waited for are done", "end": iso(t)}
                    write_status()
                continue
            if not after_done:
                continue
            elig.append((prio(task, pos), task))
        elig.sort(key=lambda x: x[0])
        budgets = {"gpu_mem_gb": spec.get("gpu_budget_gb", a.gpu_budget_gb), "host_ram_gb": spec.get("ram_budget_gb", a.ram_budget_gb), "cpus": spec.get("cpu_budget", a.cpu_budget)}
        blocked_big = False
        waiting = []
        for _, task in elig:
            name = task["name"]
            need = {k: float(task.get(k, 0) or 0) for k in used}
            nothing_running = not any(used.values())
            fits = all((not budgets[k]) or used[k] + need[k] <= budgets[k] + 1e-9 or (nothing_running and need[k] > budgets[k]) for k in used)
            big = need["gpu_mem_gb"] > 4
            if not fits or (big and blocked_big):
                if big and not fits:
                    blocked_big = True       # first-in-line: no later large task may overtake it
                waiting.append(name)
                continue
            for k in used:
                used[k] += need[k]
            remain = max(60, int(stop_ts - t - task.get("reserve_s", 60)))
            cmd = [c.replace("{PY}", PY).replace("{REMAIN}", str(remain)) for c in task["cmd"]]
            env = dict(os.environ)
            for k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
                env.pop(k, None)
            env.update(task.get("env", {}))
            log = open(os.path.join(a.logdir, name + ".log"), "a")
            res = {k: need[k] for k in need if need[k]}
            if task.get("kind") == "sbatch":
                r = subprocess.run(cmd, stdout=log, stderr=subprocess.STDOUT, env=env)
                state[name] = {"status": "submitted" if r.returncode == 0 else "failed", "start": iso(t), "rc": r.returncode, "cmd": cmd}
            else:
                p = subprocess.Popen(cmd, stdout=log, stderr=subprocess.STDOUT, env=env, cwd=task.get("cwd", DATA))
                procs[name] = p
                state[name] = {"status": "running", "pid": p.pid, "start": iso(t), "cmd": cmd, "admitted_resources": res, "remain_s_given": remain}
            write_status()
        if waiting != last_waiting.get("w"):
            last_waiting["w"] = waiting
            write_status("waiting for resources or order: %s" % ", ".join(waiting[:12]))
        # finished?
        names = [x["name"] for x in spec["tasks"]]
        if not procs and all(n in state for n in names):
            write_status("all tasks finished")
            break
        time.sleep(a.poll)


if __name__ == "__main__":
    main()