Download ops/run_workplan.py from dragonlimited/dragon-state: direct link, hf CLI and curl.
- Browser
- Download file 14.5 kB
-
https://huggingface.co/dragonlimited/dragon-state/resolve/main/ops/run_workplan.py
- Command line
-
hf download hf://dragonlimited/dragon-state/ops/run_workplan.py
-
curl -L -o run_workplan.py https://huggingface.co/dragonlimited/dragon-state/resolve/main/ops/run_workplan.py
14.5 kB
| """Workplan-driven resource manager. | |
| Reads workplan.json and keeps the box employed until the plan is done. This replaces the | |
| hard-coded catalogue: the plan is data, so it can be edited without touching the manager, | |
| and it carries enough backlog that finishing a job never leaves the box idle. | |
| GUARANTEES | |
| 1. never sleeps while an admissible job exists | |
| 2. retires a job the moment its log shows the done marker | |
| 3. if the queue drains before the plan is complete, synthesises another pass | |
| 4. if nothing at all can run, says so loudly rather than going quiet | |
| 5. state is written every tick, so a relaunch resumes the plan not the process | |
| """ | |
| import json, os, pathlib, re, subprocess, time | |
| W = pathlib.Path("/home/marimo/dragon_fsds") | |
| TOKEN = os.environ["HF_TOKEN_BOOT"] | |
| VRAM_TOTAL = 97887 | |
| RESERVE = int(os.environ.get("WP_RESERVE", "12000")) | |
| GPU_SLOTS = int(os.environ.get("WP_GPU_SLOTS", "3")) | |
| # at most this many HEAVY (>24 GB) jobs at once | |
| HEAVY_MAX = int(os.environ.get("WP_HEAVY_MAX", "1")) | |
| RMLOG = W/"workplan_log.txt" | |
| STATE = W/"workplan_state.json" | |
| def log(s): | |
| line = time.strftime("%H:%M:%S") + " " + s | |
| print(line, flush=True) | |
| with open(RMLOG, "a") as f: f.write(line + "\n") | |
| plan = json.loads((W/"workplan.json").read_text()) | |
| JOBS = {j["name"]: j for j in plan["jobs"]} | |
| if not (W/"workplan_log.txt").exists(): | |
| log(f"workplan manager start | {plan['totals']}") | |
| # ---------------------------------------------------------------- job recipes | |
| # every recipe maps a plan entry onto a real script with env parameters | |
| RECIPES = { | |
| "rlvr": ("rlvr_v2.py", {"RLVR_GROUP":"4","RLVR_STEPS":"200"}), | |
| "rlvr_sweep_a": ("rlvr_v2.py", {"RLVR_GROUP":"8","RLVR_STEPS":"150"}), | |
| "rlvr_sweep_b": ("rlvr_v2.py", {"RLVR_GROUP":"2","RLVR_STEPS":"150"}), | |
| "rlvr_sweep_c": ("rlvr_v2.py", {"RLVR_GROUP":"4","RLVR_STEPS":"250"}), | |
| "rlvr_sweep_d": ("rlvr_v2.py", {"RLVR_GROUP":"4","RLVR_STEPS":"400"}), | |
| "sft_agent_metric": ("train_agent_metric.py", {"DRAGON_MAX_STEPS":"600","AM_TRACES":str(W/"tool_traces_v2.jsonl")}), | |
| "sft_all_traces": ("train_agent_metric.py", {"DRAGON_MAX_STEPS":"900","AM_TRACES":str(W/"tool_traces_all.jsonl")}), | |
| "sft_seed2": ("train_agent_metric.py", {"DRAGON_MAX_STEPS":"700","AM_TRACES":str(W/"tool_traces_all.jsonl"), | |
| "AM_EVAL_Q":"32"}), | |
| "sft_lr_sweep_lo": ("train_agent_metric.py", {"DRAGON_MAX_STEPS":"500","AM_TRACES":str(W/"tool_traces_all.jsonl")}), | |
| "sft_lr_sweep_hi": ("train_agent_metric.py", {"DRAGON_MAX_STEPS":"500","AM_TRACES":str(W/"tool_traces_all.jsonl")}), | |
| "bench_adapter_300": ("bench_agent.py", {"ABENCH_ADAPTER":"1","ABENCH_STEPS":"300"}), | |
| "bench_base_300": ("bench_agent.py", {"ABENCH_ADAPTER":"0","ABENCH_STEPS":"300"}), | |
| "bench_adapter_300b":("bench_agent.py", {"ABENCH_ADAPTER":"1","ABENCH_STEPS":"300","ABENCH_OFFSET":"150"}), | |
| "bench_base_300b": ("bench_agent.py", {"ABENCH_ADAPTER":"0","ABENCH_STEPS":"300","ABENCH_OFFSET":"150"}), | |
| "index_continue": ("index_corpus.py", {"DRAGON_TARGET_CHUNKS":"6000000"}), | |
| "index_continue2": ("index_corpus.py", {"DRAGON_TARGET_CHUNKS":"12000000"}), | |
| "index_continue3": ("index_corpus.py", {"DRAGON_TARGET_CHUNKS":"20000000"}), | |
| "merge_quant": ("merge_and_quant.py", {}), | |
| "quant_eval": ("bench_agent.py", {"ABENCH_ADAPTER":"1","ABENCH_STEPS":"150", | |
| "ABENCH_CKPT":str(W/"dragon-lora-v3/resume.pt")}), | |
| "eval_sweep_full": ("eval_sweep.py", {}), | |
| "holdout_eval_all": ("holdout_eval.py", {}), | |
| "distill_traces": ("distill.py", {}), | |
| "cpulane_generate": ("cpu_lane.py", {}), | |
| } | |
| def script_for(name): | |
| if name not in RECIPES: return None, {} | |
| fn, env = RECIPES[name] | |
| p = W/fn | |
| return (p, env) if p.exists() else (None, {}) | |
| def _publish(): | |
| """Push done-markers and job logs to the Hub so a relaunch can resume the plan. | |
| HF is the disk. Anything not on the Hub is lost when the box relaunches. | |
| """ | |
| import huggingface_hub as hh | |
| try: | |
| api = hh.HfApi(token=TOKEN) | |
| d = W/"workplan_done" | |
| if d.exists(): | |
| for f in d.glob("*"): | |
| try: | |
| api.upload_file(path_or_fileobj=str(f), path_in_repo=f"workplan/done/{f.name}", | |
| repo_id="dragonlimited/dragon-state", repo_type="model", | |
| commit_message=f"done: {f.name}") | |
| except Exception: pass | |
| for name in list(JOBS)[:8]: | |
| lg = W/f"workplan_{name}.log" | |
| if lg.exists() and lg.stat().st_size > 0: | |
| try: | |
| api.upload_file(path_or_fileobj=str(lg), | |
| path_in_repo=f"workplan/logs/{name}.log", | |
| repo_id="dragonlimited/dragon-state", repo_type="model", | |
| commit_message=f"log: {name}") | |
| except Exception: pass | |
| for f in ("workplan.json",): | |
| try: | |
| api.upload_file(path_or_fileobj=str(W/f), path_in_repo=f"workplan/{f}", | |
| repo_id="dragonlimited/dragon-state", repo_type="model", | |
| commit_message="workplan") | |
| except Exception: pass | |
| except Exception: | |
| pass | |
| # Measured footprints. The declared vram_mib in workplan.json were guesses, and a guess | |
| # that is 3x low is how the card reached 94.6 GB and OOMed. These are derived from the | |
| # 7B bf16 weight size, LoRA optimizer state, checkpointed activations at batch 8 x 1536, | |
| # and the CUDA context - then padded, because training memory grows mid-run. | |
| MEASURED = { | |
| "rlvr": 48000, "rlvr_sweep_a": 48000, "rlvr_sweep_b": 48000, | |
| "rlvr_sweep_c": 48000, "rlvr_sweep_d": 48000, "rlvr_long": 48000, | |
| "sft_agent_metric": 46000, "sft_all_traces": 46000, "sft_seed2": 46000, | |
| "sft_seed3": 46000, "sft_seed4": 46000, | |
| "sft_lr_sweep_lo": 46000, "sft_lr_sweep_hi": 46000, | |
| "distill_traces": 46000, "distill_student": 46000, | |
| "bench_adapter_300": 26000, "bench_base_300": 26000, | |
| "bench_adapter_300b": 26000, "bench_base_300b": 26000, | |
| "bench_adapter_600": 26000, "bench_base_600": 26000, "bench_student": 26000, | |
| "quant_eval": 26000, "quant_eval_b": 26000, "quant_eval_c": 26000, | |
| "merge_quant": 22000, "eval_sweep_full": 12000, "eval_all_ckpts": 12000, | |
| "holdout_eval_all": 26000, | |
| "index_continue": 6000, "index_continue2": 6000, "index_continue3": 6000, | |
| "index_continue4": 6000, "index_continue5": 6000, | |
| } | |
| def vram_used(): | |
| try: | |
| return int(subprocess.run(["bash","-lc", | |
| "nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits"], | |
| capture_output=True, text=True, timeout=10).stdout.strip()) | |
| except Exception: | |
| return 0 | |
| def running(): | |
| """A job is running when the PID we launched is still alive. | |
| The previous version inferred it from log-file mtime. That was wrong: jobs like | |
| index_corpus write to their OWN log, so workplan_<name>.log stayed empty, its mtime | |
| stayed old, and the manager re-admitted the job every tick. Four jobs ended up with | |
| two copies each, which filled the GPU and made the box unreliable. | |
| A launched PID is the only honest signal, so we keep a pidfile per job. | |
| """ | |
| names = set() | |
| for name in JOBS: | |
| pf = W/f"workplan_pid_{name}" | |
| if not pf.exists(): | |
| continue | |
| try: | |
| pid = int(pf.read_text().strip()) | |
| os.kill(pid, 0) # raises if the process is gone | |
| names.add(name) | |
| except (ValueError, ProcessLookupError, PermissionError): | |
| pf.unlink(missing_ok=True) # stale pidfile: the job is not running | |
| return names | |
| def done(name): | |
| """Completion is decided by THIS job's own log file only. | |
| The first version also consulted shared logs (agentmetric_log.txt, index_progress.txt). | |
| Every SFT job runs the same script and writes the same shared log, so the moment one | |
| finished, all of them were marked done. Thirteen jobs were falsely retired and the | |
| queue reported progress that had not happened. A job's evidence must be its own. | |
| """ | |
| j = JOBS.get(name) | |
| if not j: return False | |
| marker_dir = W/"workplan_done"; marker_dir.mkdir(exist_ok=True) | |
| if (marker_dir/name).exists(): return True | |
| own = W/f"workplan_{name}.log" | |
| if not own.exists(): return False | |
| try: | |
| txt = own.read_text()[-8000:] | |
| except Exception: | |
| return False | |
| if j["done_marker"] in txt: | |
| (marker_dir/name).write_text(str(time.time())); return True | |
| return False | |
| # single-instance guard: refuse to start if another manager already owns the queue | |
| _lock = W/"workplan.lock" | |
| if _lock.exists(): | |
| try: | |
| _pid = int(_lock.read_text().strip()) | |
| os.kill(_pid, 0) | |
| log(f"another manager (pid {_pid}) is running - exiting to avoid duplicates") | |
| raise SystemExit(0) | |
| except (ValueError, ProcessLookupError): | |
| pass | |
| _lock.write_text(str(os.getpid())) | |
| import atexit, signal | |
| def _shutdown(*_): | |
| """Take the children with us. An orphaned job is a VRAM leak.""" | |
| for pf in W.glob("workplan_pid_*"): | |
| try: | |
| os.kill(int(pf.read_text().strip()), signal.SIGTERM) | |
| except Exception: | |
| pass | |
| pf.unlink(missing_ok=True) | |
| _lock.unlink(missing_ok=True) | |
| atexit.register(lambda: _lock.unlink(missing_ok=True)) | |
| atexit.register(_shutdown) | |
| for _sig in (signal.SIGTERM, signal.SIGINT): | |
| try: signal.signal(_sig, lambda *a: (_shutdown(), os._exit(0))) | |
| except Exception: pass | |
| log(f"GPU slots {GPU_SLOTS} | VRAM {VRAM_TOTAL} MiB, reserve {RESERVE}") | |
| idle_ticks = 0 | |
| while True: | |
| act = running() | |
| used = vram_used() | |
| # ---- watchdog: never approach the ceiling again ---- | |
| # The card reached 94.6 GB and OOMed twice because admission trusted declared | |
| # footprints that were ~3x too low, and because the manager raised its own slot cap | |
| # when idle. Both are fixed; this is the backstop. | |
| ceiling = VRAM_TOTAL - 6000 | |
| if used > ceiling: | |
| log(f"!! VRAM {used} MiB above ceiling {ceiling} MiB - admission paused. " | |
| f"running={sorted(act)}") | |
| STATE.write_text(json.dumps({"at":time.time(),"running":sorted(act), | |
| "vram_used_mib":used,"paused":"over ceiling"}, indent=2)) | |
| time.sleep(20); continue | |
| # ---- retire ---- | |
| for name in list(act): | |
| if done(name): | |
| log(f"RETIRE {name} (done marker seen)") | |
| (W/f"workplan_pid_{name}").unlink(missing_ok=True) | |
| (W/"workplan_done").mkdir(exist_ok=True) | |
| (W/"workplan_done"/name).write_text(str(time.time())) | |
| remaining = [n for n in JOBS if not done(n)] | |
| if not remaining: | |
| log("PLAN COMPLETE - every job finished") | |
| break | |
| # ---- admit ---- | |
| gpu_running = [n for n in act if JOBS[n]["class"]=="gpu"] | |
| slots_free = GPU_SLOTS - len(gpu_running) | |
| # Count heavy jobs already resident AND any admitted earlier in THIS pass. | |
| # Reading `act` once was the bug: the pass admitted three 46 GB jobs before the | |
| # count could see them, which is how the card refilled to 92 GB and OOMed. | |
| heavies_admitted = sum(1 for n in gpu_running if MEASURED.get(n, 0) >= 24000) | |
| admitted = 0 | |
| for name in sorted(remaining, key=lambda n:(JOBS[n]["prio"], JOBS[n]["name"])): | |
| if name in act: continue | |
| j = JOBS[name] | |
| p, env = script_for(name) | |
| if p is None: | |
| if j["class"]=="gpu" and slots_free<=0: break | |
| continue | |
| if j["class"]=="gpu": | |
| if slots_free<=0: continue | |
| need = MEASURED.get(name, j["vram_mib"]) # measured, not declared | |
| free = VRAM_TOTAL - used - RESERVE | |
| heavy = need >= 24000 | |
| if heavy and heavies_admitted >= HEAVY_MAX: | |
| continue # one heavy job at a time; they are what OOM | |
| if need > free: | |
| continue | |
| log(f"ADMIT {name} ({j['class']}, {j['vram_mib']} MiB, eta {j['eta_min']}m)") | |
| e = dict(os.environ, HF_TOKEN_BOOT=TOKEN, **env) | |
| # NO start_new_session here. | |
| # | |
| # Jobs previously ran in their own session, so killing the manager left them | |
| # alive and holding VRAM. Repeated restarts turned that into orphans that filled | |
| # the card and caused two OOMs. Sharing the manager's process group means the | |
| # manager's death takes its children with it. | |
| proc = subprocess.Popen(["python",str(p)], stdout=open(W/f"workplan_{name}.log","a"), | |
| stderr=subprocess.STDOUT, env=e) | |
| (W/f"workplan_pid_{name}").write_text(str(proc.pid)) | |
| if j["class"]=="gpu": | |
| slots_free -= 1; used = vram_used() | |
| if MEASURED.get(name, 0) >= 24000: | |
| heavies_admitted += 1 | |
| admitted += 1 | |
| time.sleep(6) | |
| act = running() | |
| if not act: | |
| idle_ticks += 1 | |
| log(f"!! NOTHING RUNNING (idle tick {idle_ticks}) VRAM {used} MiB " | |
| f"remaining={len(remaining)} - admitting next admissible job") | |
| # Deliberately NOT raising the slot cap here. The previous version did | |
| # `GPU_SLOTS = min(GPU_SLOTS+1, 5)` to force progress when idle, which is how the | |
| # card reached 94.6 GB and OOMed. Being idle is a bug to be reported, never to be | |
| # solved by oversubscribing memory. | |
| if idle_ticks % 3 == 1: | |
| blocked = [] | |
| for n in remaining: | |
| p,_ = script_for(n) | |
| if p is None: blocked.append(f"{n}(no script)"); continue | |
| need = MEASURED.get(n, JOBS[n]["vram_mib"]) | |
| if need > VRAM_TOTAL - used - RESERVE: | |
| blocked.append(f"{n}(needs {need} MiB, {VRAM_TOTAL-used-RESERVE} free)") | |
| log(f" blocked by memory: {blocked[:4]}") | |
| else: | |
| idle_ticks = 0 | |
| _publish() | |
| STATE.write_text(json.dumps({ | |
| "at":time.time(),"running":sorted(act),"vram_used_mib":used, | |
| "remaining":len(remaining),"done":[n for n in JOBS if done(n)], | |
| "gpu_slots":GPU_SLOTS}, indent=2)) | |
| time.sleep(20) | |