File size: 8,854 Bytes
ae1ed83 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | #!/usr/bin/env python3
"""TRACE-VLA dashboard server.
Serves one static page plus live JSON endpoints read fresh from the
validation workspace on the train machine. Binds 127.0.0.1 only;
external access goes through the cloudflared tunnel started by start.sh.
Endpoints:
/ -> www/index.html
/data/status -> trace_validation/status.json (+ STATUS.md markers)
/data/train -> trace_validation/train_progress.json (may not exist yet)
/data/results -> flattened numeric metrics from trace_validation/results/*.json
/data/machine -> GPU / disk / running train-eval processes (cached 10 s)
"""
import json
import os
import re
import subprocess
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse
HOME = os.path.expanduser("~")
ROOT = os.path.join(HOME, "trace_dashboard")
WWW = os.path.join(ROOT, "www")
VAL = os.path.join(HOME, "sera_v4_experiments", "trace_validation")
STATUS_JSON = os.path.join(VAL, "status.json")
V2_JSON = os.path.join(VAL, "status_v2.json")
TRAIN_JSON = os.path.join(VAL, "train_progress.json")
STATUS_MD = os.path.join(VAL, "STATUS.md")
RESULTS_DIR = os.path.join(VAL, "results")
PORT = 8901
_machine_cache = {"t": 0.0, "data": None}
def fmt_mtime(path):
try:
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(os.path.getmtime(path)))
except OSError:
return None
def load_json(path):
try:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
return None
def status_payload():
data = load_json(STATUS_JSON)
markers = {}
try:
with open(STATUS_MD, "r", encoding="utf-8", errors="replace") as f:
text = f.read()
# e.g. PB1_DONE, PB2_FINAL_DONE, A03_DONE, TESTS26_DONE
for m in re.finditer(r"\b([A-Za-z][A-Za-z0-9\-]{1,20}?)_(FINAL_DONE|RERUN_DONE|DONE|PASS|FAIL)\b", text):
key = m.group(1)
val = "DONE" if m.group(2) != "FAIL" else "FAIL"
if key not in markers or val == "FAIL":
markers[key] = val
gm = re.search(r"Gate\s*A\s*:\s*(PASS|FAIL)", text)
if gm:
markers["GateA_md"] = gm.group(1)
except OSError:
pass
return {
"available": data is not None,
"updated_at": fmt_mtime(STATUS_JSON),
"status_md_updated_at": fmt_mtime(STATUS_MD),
"data": data,
"markers": markers,
}
def v2_payload():
data = load_json(V2_JSON)
return {
"available": data is not None,
"updated_at": fmt_mtime(V2_JSON),
"data": data,
}
def train_payload():
data = load_json(TRAIN_JSON)
return {
"available": data is not None,
"updated_at": fmt_mtime(TRAIN_JSON),
"data": data,
}
def flatten(obj, prefix, out, depth=0):
if depth > 5 or len(out) > 80:
return
if isinstance(obj, dict):
for k, v in obj.items():
flatten(v, f"{prefix}{k}." if prefix else f"{k}.", out, depth + 1)
elif isinstance(obj, list):
scalars = [x for x in obj if isinstance(x, (int, float)) and not isinstance(x, bool)]
if scalars and len(scalars) == len(obj) and len(obj) <= 8:
for i, x in enumerate(obj):
out[f"{prefix[:-1]}[{i}]"] = x
elif isinstance(obj, (int, float)) and not isinstance(obj, bool):
out[prefix[:-1]] = obj
elif isinstance(obj, str) and len(obj) <= 40 and prefix.rstrip(".").lower().endswith(("verdict", "status")):
out[prefix[:-1]] = obj
def results_payload():
files = []
try:
names = sorted(os.listdir(RESULTS_DIR))
except OSError:
names = []
for name in names:
if not name.endswith(".json"):
continue
path = os.path.join(RESULTS_DIR, name)
data = load_json(path)
if data is None:
continue
metrics = {}
flatten(data, "", metrics)
files.append({"file": name, "updated_at": fmt_mtime(path), "metrics": metrics})
return {"available": bool(files), "files": files}
def run_cmd(cmd, timeout=8):
try:
return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout).stdout.strip()
except Exception:
return ""
def machine_payload():
now = time.time()
if _machine_cache["data"] is not None and now - _machine_cache["t"] < 10:
return _machine_cache["data"]
gpu = {}
out = run_cmd(["nvidia-smi", "--query-gpu=name,utilization.gpu,memory.used,memory.total,temperature.gpu",
"--format=csv,noheader,nounits"])
if out:
parts = [p.strip() for p in out.splitlines()[0].split(",")]
if len(parts) == 5:
try:
gpu = {"name": parts[0], "util_pct": float(parts[1]),
"mem_used_mib": float(parts[2]), "mem_total_mib": float(parts[3]),
"temp_c": float(parts[4])}
except ValueError:
gpu = {"name": parts[0]}
disk = {}
out = run_cmd(["df", "-h", HOME])
if out:
lines = out.splitlines()
if len(lines) >= 2:
p = lines[1].split()
if len(p) >= 5:
disk = {"total": p[1], "used": p[2], "avail": p[3], "use_pct": p[4]}
procs = []
out = run_cmd(["ps", "-eo", "pid,etime,pcpu,pmem,args", "--sort=-pcpu"])
for line in out.splitlines()[1:]:
low = line.lower()
if ("trace_validation" in low or "train_pilot" in low or "eval_trace" in low
or "master_chain" in low or "phase_b" in low) and "trace_dashboard" not in low:
procs.append(line.strip()[:220])
if len(procs) >= 8:
break
data = {"available": True, "time": time.strftime("%Y-%m-%d %H:%M:%S"),
"gpu": gpu, "disk": disk, "processes": procs}
_machine_cache["t"] = now
_machine_cache["data"] = data
return data
class Handler(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def send_json(self, obj, code=200):
body = json.dumps(obj, ensure_ascii=False).encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
path = urlparse(self.path).path
try:
if path in ("/", "/index.html"):
fpath = os.path.join(WWW, "index.html")
with open(fpath, "rb") as f:
body = f.read()
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
elif path == "/data/status":
self.send_json(status_payload())
elif path == "/data/v2":
self.send_json(v2_payload())
elif path == "/data/train":
self.send_json(train_payload())
elif path == "/data/results":
self.send_json(results_payload())
elif path == "/data/machine":
self.send_json(machine_payload())
elif path == "/healthz":
self.send_json({"ok": True})
else:
# static assets from www/ (e.g. vendored chart.umd.min.js fallback)
rel = path.lstrip("/")
fpath = os.path.normpath(os.path.join(WWW, rel))
if fpath.startswith(WWW) and os.path.isfile(fpath):
types = {".js": "application/javascript", ".css": "text/css",
".png": "image/png", ".json": "application/json",
".html": "text/html; charset=utf-8"}
with open(fpath, "rb") as f:
body = f.read()
self.send_response(200)
self.send_header("Content-Type", types.get(os.path.splitext(fpath)[1], "application/octet-stream"))
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
else:
self.send_json({"error": "not found"}, 404)
except Exception as e: # keep the server alive on any single-request error
try:
self.send_json({"error": str(e)}, 500)
except Exception:
pass
if __name__ == "__main__":
ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()
|