scripts / track.py
andersoncliffb's picture
Initial commit of track.py
ceb0fdb verified
Raw History Blame Contribute Delete
7.46 kB
# /// script
# requires-python = ">=3.10"
# dependencies = ["huggingface-hub>=2.2", "wandb", "mlflow-skinny"]
# ///
r"""Track a Hugging Face Job in Weights & Biases (--wandb) and/or MLflow (--mlflow) from your own machine,
whoever wrote the script it runs. Give it the `hf jobs` command that starts the job:
uv run track.py --wandb -- hf jobs uv run -s HF_TOKEN \
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py INPUT OUTPUT
or NAMESPACE/JOB_ID, to follow a job that's already running (e.g. to pick it up again after Ctrl-C):
uv run track.py --wandb divinity-library/JOB_ID
The run records the script and its arguments, the job's image, hardware and outcome, everything the job
prints, and the CPU, GPU, memory and network use Hugging Face reports for it. It sees nothing inside the
script beyond what the script prints. W&B and MLflow are set up as usual on this machine (wandb login,
WANDB_PROJECT, MLFLOW_TRACKING_URI, ...; project and experiment default to hf-jobs), so no tracking
credentials go into the job, and an MLflow server only has to be reachable from here.
"""
import argparse
import json
import os
import re
import subprocess
import sys
import threading
from datetime import datetime, timezone
from huggingface_hub import HfApi
SAMPLE_SECONDS = 15 # how often to record the job's resource use
def launch(command: list[str]) -> tuple[str, str]:
"""Start an `hf jobs run` / `hf jobs uv run` command detached. Returns NAMESPACE/JOB_ID and the launch
configuration it printed (secrets redacted by `hf`)."""
i = command.index("run") + 1 # that subcommand's options can go anywhere before its script or image
proc = subprocess.run([*command[:i], "--detach", "--json", *command[i:]], capture_output=True, text=True)
sys.stderr.write(proc.stderr)
if proc.returncode:
sys.exit(proc.returncode)
url = json.loads(proc.stdout.strip().splitlines()[-1])["url"] # https://huggingface.co/jobs/NAMESPACE/JOB_ID
printed = "\n".join(line for line in proc.stderr.splitlines() if not line.startswith("Hint:"))
return "/".join(url.split("/")[-2:]), printed
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--wandb", action="store_true", help="log to Weights & Biases")
parser.add_argument("--mlflow", action="store_true", help="log to MLflow")
parser.add_argument("job", nargs=argparse.REMAINDER, help="an `hf jobs ...` command, or NAMESPACE/JOB_ID")
args = parser.parse_args()
job_args = args.job[1:] if args.job[:1] == ["--"] else args.job
if not job_args or not (args.wandb or args.mlflow):
parser.error("pass --wandb and/or --mlflow, then an `hf jobs` command or NAMESPACE/JOB_ID")
ref, launched = launch(job_args) if job_args[0] == "hf" else (job_args[0], "")
namespace, _, job_id = ref.rpartition("/")
api = HfApi()
job = api.inspect_job(job_id=job_id, namespace=namespace or None)
namespace, ref = job.owner.name, f"{job.owner.name}/{job.id}"
flags = " ".join(flag for flag in ("--wandb", "--mlflow") if getattr(args, flag[2:]))
print(f"Tracking {job.url}\nCtrl-C stops the tracking, not the job. To pick it up again: "
f"uv run track.py {flags} {ref}", flush=True)
config = {"url": job.url, "image": job.docker_image or job.space_id, "flavor": job.flavor,
**dict(re.findall(r"^ (script|args)\s+(.+)$", launched, re.M))}
if "script" not in config: # following a job started elsewhere: record what it runs
config["command"] = " ".join([*(job.command or []), *(job.arguments or [])])
config = {key: value for key, value in config.items() if value}
name = (job.labels or {}).get("name") or job.id
loggers, output = [], [launched] if launched else []
if args.wandb:
import wandb
run = wandb.init(project=os.environ.get("WANDB_PROJECT", "hf-jobs"), id=job.id, name=name, config=config,
resume="allow", # the same job always goes to the same run
settings=wandb.Settings(x_disable_stats=True, x_disable_meta=True)) # not this machine's
loggers.append(run.log)
if args.mlflow:
import mlflow
mlflow.set_experiment(os.environ.get("MLFLOW_EXPERIMENT_NAME", "hf-jobs"))
found = mlflow.search_runs(filter_string=f"tags.hf_job = '{ref}'", output_format="list")
run_id = mlflow.start_run(run_id=found[0].info.run_id if found else None, run_name=name,
tags={"hf_job": ref}).info.run_id
mlflow.log_params(config)
loggers.append(lambda metrics, step: mlflow.log_metrics(metrics, step=step, run_id=run_id))
lock, finished = threading.Lock(), threading.Event()
def sample_resources() -> None:
"""Log the job's resource use every SAMPLE_SECONDS, against seconds since the job was created."""
last = -SAMPLE_SECONDS
try:
for sample in api.fetch_job_metrics(job_id=job.id, namespace=namespace, follow=True):
step = int((datetime.now(timezone.utc) - job.created_at).total_seconds())
if step - last < SAMPLE_SECONDS:
continue
last = step
metrics = {"cpu_pct": sample.get("cpu_usage_pct"), "rx_bps": sample.get("rx_bps"),
"tx_bps": sample.get("tx_bps"), "memory_gb": sample.get("memory_used_bytes", 0) / 1e9}
for i, gpu in enumerate((sample.get("gpus") or {}).values()):
metrics[f"gpu{i}_pct"] = gpu.get("utilization")
metrics[f"gpu{i}_memory_gb"] = gpu.get("memory_used_bytes", 0) / 1e9
with lock:
if finished.is_set():
return
for log in loggers:
log({key: value for key, value in metrics.items() if value is not None}, step=step)
except Exception as e: # resource use is a bonus: never let it stop the tracking
print(f"(stopped recording resource use: {e})", file=sys.stderr)
threading.Thread(target=sample_resources, daemon=True).start()
for line in api.fetch_job_logs(job_id=job.id, namespace=namespace, follow=True):
print(line, flush=True) # W&B records the console
output.append(line)
job = api.wait_for_job(job.id, namespace=namespace)
stage = getattr(job.status.stage, "value", job.status.stage) # COMPLETED, ERROR, CANCELED or DELETED
minutes = (job.finished_at - job.started_at).total_seconds() / 60 if job.started_at and job.finished_at else None
print(f"Job {stage}" + (f" after {minutes:.1f} min" if minutes else "") + f": {job.url}", flush=True)
with lock:
finished.set()
if args.wandb:
run.summary.update({"stage": stage, "minutes": minutes, "message": job.status.message})
run.finish(exit_code=0 if stage == "COMPLETED" else 1)
if args.mlflow:
mlflow.set_tags({"stage": stage, "message": job.status.message or ""})
if minutes is not None:
mlflow.log_metric("minutes", minutes)
mlflow.log_text("\n".join(output), "job.log")
mlflow.end_run({"COMPLETED": "FINISHED", "ERROR": "FAILED"}.get(stage, "KILLED"))
sys.exit(0 if stage == "COMPLETED" else 1)
if __name__ == "__main__":
main()