Download src/linedet/driver.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 11.6 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/src/linedet/driver.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/src/linedet/driver.py
-
curl -L -o driver.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/src/linedet/driver.py
11.6 kB
| """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() | |