andersoncliffb commited on
Commit
ceb0fdb
·
verified ·
1 Parent(s): 5591f49

Initial commit of track.py

Browse files
Files changed (1) hide show
  1. track.py +140 -0
track.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = ["huggingface-hub>=2.2", "wandb", "mlflow-skinny"]
4
+ # ///
5
+ r"""Track a Hugging Face Job in Weights & Biases (--wandb) and/or MLflow (--mlflow) from your own machine,
6
+ whoever wrote the script it runs. Give it the `hf jobs` command that starts the job:
7
+
8
+ uv run track.py --wandb -- hf jobs uv run -s HF_TOKEN \
9
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py INPUT OUTPUT
10
+
11
+ or NAMESPACE/JOB_ID, to follow a job that's already running (e.g. to pick it up again after Ctrl-C):
12
+
13
+ uv run track.py --wandb divinity-library/JOB_ID
14
+
15
+ The run records the script and its arguments, the job's image, hardware and outcome, everything the job
16
+ prints, and the CPU, GPU, memory and network use Hugging Face reports for it. It sees nothing inside the
17
+ script beyond what the script prints. W&B and MLflow are set up as usual on this machine (wandb login,
18
+ WANDB_PROJECT, MLFLOW_TRACKING_URI, ...; project and experiment default to hf-jobs), so no tracking
19
+ credentials go into the job, and an MLflow server only has to be reachable from here.
20
+ """
21
+
22
+ import argparse
23
+ import json
24
+ import os
25
+ import re
26
+ import subprocess
27
+ import sys
28
+ import threading
29
+ from datetime import datetime, timezone
30
+
31
+ from huggingface_hub import HfApi
32
+
33
+ SAMPLE_SECONDS = 15 # how often to record the job's resource use
34
+
35
+
36
+ def launch(command: list[str]) -> tuple[str, str]:
37
+ """Start an `hf jobs run` / `hf jobs uv run` command detached. Returns NAMESPACE/JOB_ID and the launch
38
+ configuration it printed (secrets redacted by `hf`)."""
39
+ i = command.index("run") + 1 # that subcommand's options can go anywhere before its script or image
40
+ proc = subprocess.run([*command[:i], "--detach", "--json", *command[i:]], capture_output=True, text=True)
41
+ sys.stderr.write(proc.stderr)
42
+ if proc.returncode:
43
+ sys.exit(proc.returncode)
44
+ url = json.loads(proc.stdout.strip().splitlines()[-1])["url"] # https://huggingface.co/jobs/NAMESPACE/JOB_ID
45
+ printed = "\n".join(line for line in proc.stderr.splitlines() if not line.startswith("Hint:"))
46
+ return "/".join(url.split("/")[-2:]), printed
47
+
48
+
49
+ def main() -> None:
50
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
51
+ parser.add_argument("--wandb", action="store_true", help="log to Weights & Biases")
52
+ parser.add_argument("--mlflow", action="store_true", help="log to MLflow")
53
+ parser.add_argument("job", nargs=argparse.REMAINDER, help="an `hf jobs ...` command, or NAMESPACE/JOB_ID")
54
+ args = parser.parse_args()
55
+ job_args = args.job[1:] if args.job[:1] == ["--"] else args.job
56
+ if not job_args or not (args.wandb or args.mlflow):
57
+ parser.error("pass --wandb and/or --mlflow, then an `hf jobs` command or NAMESPACE/JOB_ID")
58
+
59
+ ref, launched = launch(job_args) if job_args[0] == "hf" else (job_args[0], "")
60
+ namespace, _, job_id = ref.rpartition("/")
61
+ api = HfApi()
62
+ job = api.inspect_job(job_id=job_id, namespace=namespace or None)
63
+ namespace, ref = job.owner.name, f"{job.owner.name}/{job.id}"
64
+ flags = " ".join(flag for flag in ("--wandb", "--mlflow") if getattr(args, flag[2:]))
65
+ print(f"Tracking {job.url}\nCtrl-C stops the tracking, not the job. To pick it up again: "
66
+ f"uv run track.py {flags} {ref}", flush=True)
67
+
68
+ config = {"url": job.url, "image": job.docker_image or job.space_id, "flavor": job.flavor,
69
+ **dict(re.findall(r"^ (script|args)\s+(.+)$", launched, re.M))}
70
+ if "script" not in config: # following a job started elsewhere: record what it runs
71
+ config["command"] = " ".join([*(job.command or []), *(job.arguments or [])])
72
+ config = {key: value for key, value in config.items() if value}
73
+ name = (job.labels or {}).get("name") or job.id
74
+ loggers, output = [], [launched] if launched else []
75
+ if args.wandb:
76
+ import wandb
77
+
78
+ run = wandb.init(project=os.environ.get("WANDB_PROJECT", "hf-jobs"), id=job.id, name=name, config=config,
79
+ resume="allow", # the same job always goes to the same run
80
+ settings=wandb.Settings(x_disable_stats=True, x_disable_meta=True)) # not this machine's
81
+ loggers.append(run.log)
82
+ if args.mlflow:
83
+ import mlflow
84
+
85
+ mlflow.set_experiment(os.environ.get("MLFLOW_EXPERIMENT_NAME", "hf-jobs"))
86
+ found = mlflow.search_runs(filter_string=f"tags.hf_job = '{ref}'", output_format="list")
87
+ run_id = mlflow.start_run(run_id=found[0].info.run_id if found else None, run_name=name,
88
+ tags={"hf_job": ref}).info.run_id
89
+ mlflow.log_params(config)
90
+ loggers.append(lambda metrics, step: mlflow.log_metrics(metrics, step=step, run_id=run_id))
91
+
92
+ lock, finished = threading.Lock(), threading.Event()
93
+
94
+ def sample_resources() -> None:
95
+ """Log the job's resource use every SAMPLE_SECONDS, against seconds since the job was created."""
96
+ last = -SAMPLE_SECONDS
97
+ try:
98
+ for sample in api.fetch_job_metrics(job_id=job.id, namespace=namespace, follow=True):
99
+ step = int((datetime.now(timezone.utc) - job.created_at).total_seconds())
100
+ if step - last < SAMPLE_SECONDS:
101
+ continue
102
+ last = step
103
+ metrics = {"cpu_pct": sample.get("cpu_usage_pct"), "rx_bps": sample.get("rx_bps"),
104
+ "tx_bps": sample.get("tx_bps"), "memory_gb": sample.get("memory_used_bytes", 0) / 1e9}
105
+ for i, gpu in enumerate((sample.get("gpus") or {}).values()):
106
+ metrics[f"gpu{i}_pct"] = gpu.get("utilization")
107
+ metrics[f"gpu{i}_memory_gb"] = gpu.get("memory_used_bytes", 0) / 1e9
108
+ with lock:
109
+ if finished.is_set():
110
+ return
111
+ for log in loggers:
112
+ log({key: value for key, value in metrics.items() if value is not None}, step=step)
113
+ except Exception as e: # resource use is a bonus: never let it stop the tracking
114
+ print(f"(stopped recording resource use: {e})", file=sys.stderr)
115
+
116
+ threading.Thread(target=sample_resources, daemon=True).start()
117
+ for line in api.fetch_job_logs(job_id=job.id, namespace=namespace, follow=True):
118
+ print(line, flush=True) # W&B records the console
119
+ output.append(line)
120
+ job = api.wait_for_job(job.id, namespace=namespace)
121
+
122
+ stage = getattr(job.status.stage, "value", job.status.stage) # COMPLETED, ERROR, CANCELED or DELETED
123
+ minutes = (job.finished_at - job.started_at).total_seconds() / 60 if job.started_at and job.finished_at else None
124
+ print(f"Job {stage}" + (f" after {minutes:.1f} min" if minutes else "") + f": {job.url}", flush=True)
125
+ with lock:
126
+ finished.set()
127
+ if args.wandb:
128
+ run.summary.update({"stage": stage, "minutes": minutes, "message": job.status.message})
129
+ run.finish(exit_code=0 if stage == "COMPLETED" else 1)
130
+ if args.mlflow:
131
+ mlflow.set_tags({"stage": stage, "message": job.status.message or ""})
132
+ if minutes is not None:
133
+ mlflow.log_metric("minutes", minutes)
134
+ mlflow.log_text("\n".join(output), "job.log")
135
+ mlflow.end_run({"COMPLETED": "FINISHED", "ERROR": "FAILED"}.get(stage, "KILLED"))
136
+ sys.exit(0 if stage == "COMPLETED" else 1)
137
+
138
+
139
+ if __name__ == "__main__":
140
+ main()