#!/usr/bin/env python3 """modgrad pipe: stream a training script's output into a modgrad run. python3 modgrad_pipe.py [--every SECONDS] -- python -u train.py (wrap) python -u train.py 2>&1 | python3 modgrad_pipe.py [--every SECONDS] (pipe) Echoes every line unchanged, POSTs new lines to $MODGRAD_URL/api/v1/runs//text every few seconds (the server parses metric lines such as "step 10 loss 0.52"), and finishes the run at the end. Wrap runs the command itself (stdout and stderr), records its exit code in the run summary (exit_code) and exits with it; pipe cannot see the exit code. Environment: MODGRAD_URL (default https://app.modgrad.com), MODGRAD_TOKEN (a project token from POST /api/v1/projects). Stdlib only. Logging never stops training: a failed send is reported on stderr and its lines are retried with the next. Note: a line without a step takes the last step seen in the same batch, so print the step on each metric line ("step 10 val_loss 0.4"). """ import json, os, signal, subprocess, sys, threading, time, urllib.parse, urllib.request URL = os.environ.get("MODGRAD_URL", "https://app.modgrad.com").rstrip("/") TOKEN = os.environ.get("MODGRAD_TOKEN", "") MAX_BATCH = 1 << 20 # bytes per POST (the server takes up to 2 MiB) def say(msg): print(f"modgrad: {msg}", file=sys.stderr, flush=True) def main(): args, cmd = sys.argv[1:], None if "--" in args: i = args.index("--") args, cmd = args[:i], args[i + 1:] if not cmd: sys.exit("modgrad: nothing to run after --, e.g. -- python -u train.py") every = 5.0 if "--every" in args: i = args.index("--every") try: every = max(0.5, float(args[i + 1])) except (IndexError, ValueError): sys.exit("modgrad: --every takes seconds, e.g. --every 5") del args[i:i + 2] if len(args) != 1: sys.exit(__doc__) run = args[0] path = "/".join(urllib.parse.quote(p, safe="") for p in run.split("/")) child = None if cmd: env = dict(os.environ, PYTHONUNBUFFERED="1") # a Python child streams instead of buffering try: child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env) except OSError as e: sys.exit(f"modgrad: cannot run {cmd[0]!r}: {e}") # Ctrl-C reaches the child too (same process group); wait for it to end signal.signal(signal.SIGINT, signal.SIG_IGN) source = child.stdout else: source = sys.stdin.buffer buf, lock, done = [], threading.Lock(), threading.Event() def read(): out = sys.stdout.buffer for line in source: out.write(line) out.flush() with lock: buf.append(line) done.set() def request(url, data, ctype): req = urllib.request.Request(url, data=data, method="POST") req.add_header("Content-Type", ctype) if TOKEN: req.add_header("Authorization", f"Bearer {TOKEN}") with urllib.request.urlopen(req, timeout=15) as r: return json.load(r) def exit_code(): if child is None: return None rc = child.wait() return 128 - rc if rc < 0 else rc # killed by signal N -> 128+N, as shells report it def post(data, last): at = f"{URL}/api/v1/runs/{path}" if not last: return request(f"{at}/text", data, "text/plain; charset=utf-8") if child is None: return request(f"{at}/text?finish=1", data, "text/plain; charset=utf-8") r = request(f"{at}/text", data, "text/plain; charset=utf-8") request(f"{at}/finish", json.dumps({"exit_code": exit_code()}).encode(), "application/json") return r threading.Thread(target=read, daemon=True).start() pending, failures, first = [], 0, True # pending: lines the server has not accepted yet while True: eof = done.wait(every) with lock: pending += buf buf.clear() while len(pending) > 200_000: # server down for long: keep the newest lines del pending[:len(pending) - 200_000] while pending or eof: n, size = 0, 0 while n < len(pending) and (n == 0 or size + len(pending[n]) <= MAX_BATCH): size += len(pending[n]) n += 1 last = eof and n == len(pending) try: r = post(b"".join(pending[:n]), last) except Exception as e: code = getattr(e, "code", None) if code and 400 <= code < 500 and code not in (408, 429): # will not fix itself try: why = json.load(e).get("message", "") except Exception: why = "" say(f"the server refused the lines (HTTP {code} from {getattr(e, 'filename', '?')}); not sending more. {why}") done.wait() # keep echoing the output until it ends return exit_code() failures += 1 # server down or busy: keep the lines, try again say(f"send failed ({e}); will retry") if eof and failures >= 5: say(f"giving up; {len(pending)} lines not sent, run not finished") return exit_code() if eof: time.sleep(2) continue break failures = 0 del pending[:n] if first: say(f"run {r.get('run')} -> {r.get('dashboard')}") first = False if last: rc = exit_code() say("run finished" + ("" if rc is None else f" (exit code {rc})")) return rc if __name__ == "__main__": sys.exit(main() or 0)