#!/usr/bin/env python3 """Dashboard patch (Young's request 2026-11-20 17:12): add a dedicated /train page for run sera-v4-fs1-jedi-l60k with server-generated SVG charts. The main page (/) and /api/status stay 100% untouched. New route: GET /train -> full server-rendered HTML, meta refresh 60s. Data is discovered fresh on every request: - train log: EXP/sera-v4-fs1-jedi-l60k.log (convention of the previous jedi run), else the newest *l60k*.log in EXP or fewshot/ whose name is not a smoke/check/queue/measure/gate/watch/err side log. Parsed incrementally (byte offset kept in memory): metric lines carry "step:N smpl:.. loss:.. lr:.. jedi_dd_task:.." plus an INFO timestamp; eval lines carry "step N: eval_loss=..". - checkpoints: /checkpoints/NNNNNN for the 12 milestones 5k..60k; a milestone counts as done when pretrained_model/ model.safetensors exists; any entry (top level or inside pretrained_model) whose name contains "ema" marks the EMA copy. - test @20k: CPU measure file *l60k*measure*.txt in fewshot/ or the run dir (DD_task / dv_swap, raw vs EMA by line), and the cond-b rollout JSONL fewshot/results/fs1-jedi-l60k20k-cond-b.jsonl (episode/success counts, target 90). If the run has not started, the page renders a "chua khoi chay" state instead of failing. Exact-match asserted replacements; backup at server.py.bak-trainpage-20261120. """ import py_compile import shutil from pathlib import Path P = Path.home() / "sera_v4_dashboard" / "server.py" src = P.read_text() orig = src NEW_CODE = r''' # --- Trang /train: theo doi run l60k (Young yeu cau 2026-11-20 17:12) --- L60K_NAME = "sera-v4-fs1-jedi-l60k" L60K_TOTAL_DEFAULT = 60000 L60K_MILESTONES = list(range(5000, 60001, 5000)) L60K_TEST_STEP = 20000 L60K_ROLLOUT_PATH = os.path.join(FS_RES, "fs1-jedi-l60k20k-cond-b.jsonl") L60K_ROLLOUT_TOTAL = 90 _L60K_EXCLUDE = ("smoke", "check", "queue", "measure", "gate", "watch", "err") _l60k_state = {"path": None, "offset": 0, "loss": [], "dd": [], "lr": [], "ts": [], "eval": [], "total": None} _l60k_lock = threading.Lock() _L60K_STEP_RE = re.compile(r"\bstep:(\d+)\s+smpl:") _L60K_TS_RE = re.compile(r"INFO (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})") _L60K_EVAL_RE = re.compile(r"\bstep (\d+): eval_loss=([0-9.]+)") _L60K_TQDM_RE = re.compile(r"(\d{2,6})/(\d{4,6}) \[") def _vn(x, nd=3): """Format so kieu Viet Nam (dau phay thap phan); None -> '—'.""" if x is None: return "—" try: s = "%.*f" % (nd, float(x)) except Exception: return "—" if "." in s: s = s.rstrip("0").rstrip(".") return s.replace(".", ",") def _num(n): if n is None: return "—" return "{:,}".format(int(n)).replace(",", ".") def _esc(s): return str(s).replace("&", "&").replace("<", "<").replace(">", ">") def _fmt_eta(sec): if sec is None: return "—" sec = int(round(sec)) if sec >= 3600: return "≈ %d giờ %d phút" % (sec // 3600, (sec % 3600) // 60) if sec >= 60: return "≈ %d phút" % (sec // 60) return "≈ %d giây" % sec def _l60k_find_log(): """Tu phat hien log train cua run l60k (uu tien dung quy uoc ten).""" exact = os.path.join(EXP, L60K_NAME + ".log") if os.path.isfile(exact): return exact cands = [] for folder in (EXP, os.path.join(EXP, "fewshot")): try: names = os.listdir(folder) except Exception: continue for fn in names: low = fn.lower() if "l60k" not in low or not low.endswith(".log"): continue if any(k in low for k in _L60K_EXCLUDE): continue cands.append(os.path.join(folder, fn)) if not cands: return None try: return max(cands, key=lambda p: os.path.getmtime(p)) except Exception: return cands[0] def _l60k_ckpt_root(): roots = [] exact = os.path.join(EXP, L60K_NAME) if os.path.isdir(exact): roots.append(exact) try: for fn in os.listdir(EXP): if "l60k" in fn: p = os.path.join(EXP, fn) if os.path.isdir(p) and p not in roots: roots.append(p) except Exception: pass for r in roots: for cand in (os.path.join(r, "checkpoints"), r): try: subs = os.listdir(cand) except Exception: continue if any(s.isdigit() for s in subs): return cand return os.path.join(exact, "checkpoints") def _l60k_parse_chunk(st, text): for m in _L60K_TQDM_RE.finditer(text): try: st["total"] = int(m.group(2)) except Exception: pass for line in text.splitlines(): me = _L60K_EVAL_RE.search(line) if me: try: st["eval"].append((int(me.group(1)), float(me.group(2)))) except Exception: pass continue ms = _L60K_STEP_RE.search(line) if not ms or "loss:" not in line: continue try: step = int(ms.group(1)) except Exception: continue loss = _last_float(r"\bloss:([0-9.eE+-]+)", line) if loss is not None: st["loss"].append((step, loss)) dd = _last_float(r"jedi_dd_task:([0-9.]+)", line) if dd is not None: st["dd"].append((step, dd)) lr = _last_float(r"\blr:([0-9.eE+-]+)", line) if lr is not None: st["lr"].append((step, lr)) mt = _L60K_TS_RE.search(line) if mt: try: ts = time.mktime(time.strptime(mt.group(1), "%Y-%m-%d %H:%M:%S")) st["ts"].append((step, ts)) except Exception: pass def _l60k_series(): """Parse tang dan log train l60k (giu offset trong RAM). None neu chua co log.""" path = _l60k_find_log() if path is None: return None with _l60k_lock: st = _l60k_state try: size = os.path.getsize(path) except Exception: return None if st["path"] != path or size < st["offset"]: st.update({"path": path, "offset": 0, "loss": [], "dd": [], "lr": [], "ts": [], "eval": [], "total": None}) if size > st["offset"]: try: with open(path, "rb") as f: f.seek(st["offset"]) chunk = f.read() except Exception: chunk = b"" cut = chunk.rfind(b"\n") if cut >= 0: st["offset"] += cut + 1 _l60k_parse_chunk( st, chunk[:cut + 1].decode("utf-8", errors="ignore")) try: st["log_age_s"] = round(time.time() - os.path.getmtime(path)) except Exception: st["log_age_s"] = None st["log_file"] = os.path.basename(path) return st def _l60k_speed(st): pts = st["ts"] if len(pts) < 2: return None tail = pts[-300:] (s0, t0), (s1, t1) = tail[0], tail[-1] if t1 - t0 >= 20 and s1 > s0: return (s1 - s0) / float(t1 - t0) return None def _l60k_proc_running(): try: for pid in os.listdir("/proc"): if not pid.isdigit(): continue try: with open(os.path.join("/proc", pid, "cmdline"), "rb") as f: cmd = f.read().decode("utf-8", errors="ignore") except Exception: continue if "l60k" in cmd and ("train.py" in cmd or "lerobot-train" in cmd or "train_v4" in cmd): return True except Exception: pass return False def _l60k_checkpoints(): root = _l60k_ckpt_root() out = [] for m in L60K_MILESTONES: d = os.path.join(root, "%06d" % m) state, ema = "pending", False if os.path.isdir(d): state = "writing" names = [] try: names += os.listdir(d) except Exception: pass sub = [] try: sub = os.listdir(os.path.join(d, "pretrained_model")) except Exception: pass names += sub ema = any("ema" in n.lower() for n in names) if "model.safetensors" in sub: state = "done" out.append({"step": m, "state": state, "ema": ema}) return out def _l60k_measure(): """File do CPU cua test 20k (*l60k*measure*.txt): DD_task + dv_swap, tach tho/EMA theo tung dong.""" cands = [] for folder in (os.path.join(EXP, "fewshot"), os.path.join(EXP, L60K_NAME)): try: names = os.listdir(folder) except Exception: continue for fn in names: low = fn.lower() if "l60k" in low and "measure" in low and low.endswith(".txt"): cands.append(os.path.join(folder, fn)) if not cands: return None try: path = max(cands, key=lambda p: os.path.getmtime(p)) except Exception: path = cands[0] try: with open(path, errors="ignore") as f: text = f.read() except Exception: return None vals = {"dd_raw": None, "dd_ema": None, "dv_raw": None, "dv_ema": None} for line in text.splitlines(): low = line.lower() suf = "_ema" if "ema" in low else "_raw" m = re.search(r"dd_task\s*[:=]\s*([0-9.]+)", low) if m: vals["dd" + suf] = float(m.group(1)) m = re.search(r"(?:dv_swap|delta_v|δv_swap)\s*[:=]\s*([0-9.]+)", low) if m: vals["dv" + suf] = float(m.group(1)) return {"file": os.path.basename(path), "vals": vals} def _l60k_rollout(): path = L60K_ROLLOUT_PATH if not os.path.isfile(path): return None n = succ = 0 try: with open(path, errors="ignore") as f: for line in f: line = line.strip() if not line: continue try: r = json.loads(line) except Exception: continue n += 1 if r.get("success"): succ += 1 except Exception: return None try: age = time.time() - os.path.getmtime(path) except Exception: age = None if n >= L60K_ROLLOUT_TOTAL: status = "DONE" elif age is not None and age < 180: status = "RUNNING" else: status = "PARTIAL" return {"episodes": n, "expected": L60K_ROLLOUT_TOTAL, "success": succ, "success_rate": round(100.0 * succ / n, 1) if n else None, "pct": round(100.0 * n / L60K_ROLLOUT_TOTAL, 1), "status": status} def _thin(points, cap=700): if len(points) <= cap: return points stride = (len(points) + cap - 1) // cap out = points[::stride] if out[-1] != points[-1]: out.append(points[-1]) return out def _svg_line_chart(points, color, x_max, y_lo=None, y_hi=None, hline=None, hline_label=None, markers=None, height=250): """SVG polyline sinh phia server; markers = list (step, value) ve bang cham do (eval_loss).""" if not points and not markers: return "

Chưa có dữ liệu.

" w, h = 1120, height L, R, T, B = 58, 16, 14, 28 iw, ih = w - L - R, h - T - B vals = [v for _, v in points] if markers: vals += [v for _, v in markers] if hline is not None: vals.append(hline) lo = min(vals) if y_lo is None else y_lo hi = max(vals) if y_hi is None else y_hi if hi <= lo: hi = lo + 1.0 pad = 0.08 * (hi - lo) dlo, dhi = lo - pad, hi + pad def X(s): return L + iw * (float(s) / float(x_max)) def Y(v): return T + ih * (1.0 - (v - dlo) / (dhi - dlo)) out = ["" % (w, h)] out.append("" % (L, T, iw, ih)) for s in (0, 20000, 40000, x_max): x = X(s) out.append("" % (x, T, x, T + ih)) lab = "0" if s == 0 else ("%dk" % (s // 1000)) out.append("%s" % (x, T + ih + 18, lab)) out.append("%s" % (L - 6, Y(hi) + 4, _vn(hi, 3))) out.append("%s" % (L - 6, Y(lo) + 4, _vn(lo, 3))) if hline is not None: y = Y(hline) out.append("" % (L, y, L + iw, y)) if hline_label: out.append("%s" % (L + iw - 4, y - 5, hline_label)) if points: pts = " ".join("%.1f,%.1f" % (X(s), Y(v)) for s, v in points) out.append("" % (pts, color)) if markers: for s, v in markers: out.append("step %d · eval_loss %s" % (X(s), Y(v), s, _vn(v, 4))) out.append("") return "".join(out) TRAIN_HEAD = """ Train l60k — sera-v4-fs1-jedi-l60k

Train — sera-v4-fs1-jedi-l60k

JEDI-lite train lại 60.000 bước (dropout 0,1 + EMA 0,999) · test tại mốc 20.000 trên checkpoint EMA · ← Dashboard chính · Trang tự làm mới mỗi 60 giây, số liệu đọc trực tiếp trên máy train

""" def _tkpi(v, k): return ("
%s
" "
%s
" % (v, k)) def render_train_page(): st = _l60k_series() ckpts = _l60k_checkpoints() meas = _l60k_measure() roll = _l60k_rollout() total = L60K_TOTAL_DEFAULT step = None speed = None if st is not None: if st.get("total"): total = st["total"] if st["loss"]: step = st["loss"][-1][0] elif st["eval"]: step = st["eval"][-1][0] speed = _l60k_speed(st) running = _l60k_proc_running() if st is None: status, bcls = "CHƯA KHỞI CHẠY", "idle" elif step is not None and step >= total: status, bcls = "ĐÃ XONG", "done" elif running or (st.get("log_age_s") is not None and st["log_age_s"] < 180): status, bcls = "ĐANG CHẠY", "run" else: status, bcls = "ĐÃ DỪNG", "stopped" pct = round(100.0 * step / total, 1) if step else 0.0 if step is not None and step >= L60K_TEST_STEP: eta20 = "đã qua mốc" elif speed and step is not None: eta20 = _fmt_eta((L60K_TEST_STEP - step) / speed) + " (ước tính)" else: eta20 = "—" if step is not None and step >= total: eta60 = "đã xong" elif speed and step is not None: eta60 = _fmt_eta((total - step) / speed) + " (ước tính)" else: eta60 = "—" b = [TRAIN_HEAD] b.append("

Tổng quan

") b.append(_tkpi("%s" % (bcls, status), "Trạng thái")) b.append(_tkpi("%s / %s" % (_num(step), _num(total)), "Bước hiện tại")) b.append(_tkpi(_vn(pct, 1) + "%", "Tiến độ")) b.append(_tkpi((_vn(speed, 2) + " bước/giây") if speed else "—", "Tốc độ (đo từ log)")) b.append(_tkpi(eta20, "ETA tới mốc test 20.000")) b.append(_tkpi(eta60, "ETA tới 60.000")) b.append("
") mark_pct = 100.0 * L60K_TEST_STEP / float(total) b.append("
" "
" % (_vn(pct, 1).replace(",", "."), mark_pct)) if st is not None: b.append("
Vạch đỏ: mốc test 20.000. " "Log: %s · cập nhật %s giây trước · eval_loss gần nhất: %s
" % (_esc(st.get("log_file") or "—"), _num(st.get("log_age_s")), _vn(st["eval"][-1][1], 4) if st["eval"] else "—")) else: b.append("
Vạch đỏ: mốc test 20.000. " "Chưa tìm thấy log train của run l60k trên máy — trang sẽ tự hiện số liệu khi train khởi chạy.
") b.append("
") loss_pts = _thin(st["loss"]) if st else [] eval_pts = [(s, v) for s, v in (st["eval"] if st else [])] b.append("

Loss train theo bước

") b.append(_svg_line_chart(loss_pts, "#1B6AC9", total, markers=eval_pts)) b.append("

Đường xanh: loss train (mẫu log mỗi 10 bước). " "Chấm đỏ: eval_loss tại các mốc eval trong log.

") dd_pts = _thin(st["dd"]) if st else [] b.append("

jedi_dd_task theo bước

") b.append(_svg_line_chart(dd_pts, "#1E8449", total, y_lo=0, hline=1.5, hline_label="ngưỡng Cổng 0: 1,5")) b.append("

DD_task = lỗi dự đoán keyframe với demo phản thực / demo đúng. " "Trên đường ngưỡng 1,5 là đạt chuẩn Cổng 0 (run 10k đạt 5,91 tại mốc 2.000).

") if st and st["lr"]: b.append("

Tốc độ học (lr) theo bước

") b.append(_svg_line_chart(_thin(st["lr"]), "#D4820A", total, y_lo=0)) b.append("
") b.append("

Checkpoint (mỗi 5.000 bước)

") for c in ckpts: tags = "" if c["ema"]: tags += "EMA" if c["step"] == L60K_TEST_STEP: tags += "MỐC TEST" if c["state"] == "writing": tags += "đang ghi" b.append("
%dk%s
" % (c["state"], c["step"] // 1000, tags)) b.append("

Ô xanh: checkpoint đã ghi xong (có model.safetensors). " "Ô cam: thư mục đã xuất hiện nhưng chưa ghi xong. Nhãn EMA: có bản sao trọng số EMA trong checkpoint.

") b.append("

Test tại mốc 20.000 (checkpoint EMA 020000)

") if meas is None and roll is None: if step is not None and step >= L60K_TEST_STEP: b.append("

Đã qua mốc 20.000 — đang chờ kết quả từ watcher test (đo CPU + rollout cond-b).

") else: b.append("

Chưa tới mốc 20.000. Khi checkpoint EMA 020000 xuất hiện, watcher test sẽ đo " "DD_task + Δv_swap trên CPU và chạy rollout chỉ điều kiện b (demo đúng task): " "90 episode trên 9 task held-out.

") if meas is not None: v = meas["vals"] boxes = [] for label, key in (("DD_task (thô)", "dd_raw"), ("DD_task (EMA)", "dd_ema"), ("Δv_swap (thô)", "dv_raw"), ("Δv_swap (EMA)", "dv_ema")): if v.get(key) is not None: boxes.append("
%s
" "
%s
" % (_vn(v[key], 3), label)) if boxes: b.append("
" + "".join(boxes) + "
") else: b.append("

Đã có file đo nhưng chưa parse được số DD/Δv từ file.

") b.append("

Nguồn: %s · Đối chiếu run 10k: " "DD_task 5,91 (Cổng 0, tại 2k) · Δv_swap 0,896 (Cổng 1, tại 10k).

" % _esc(meas["file"])) if roll is not None: bc = {"RUNNING": "run", "DONE": "done", "PARTIAL": "part"}[roll["status"]] b.append("
Rollout cond-b (demo đúng task) @ EMA 020000" "%d/%d episode · thành công %d (%s%%)" "%s
" "
" % (roll["episodes"], roll["expected"], roll["success"], _vn(roll["success_rate"], 1), bc, roll["status"], "done" if roll["status"] == "DONE" else "", _vn(roll["pct"], 1).replace(",", "."))) b.append("
") b.append("
" "" % (L60K_NAME, time.strftime("%Y-%m-%d %H:%M:%S"))) return "".join(b) ''' ROUTE_OLD = ''' elif self.path == "/" or self.path.startswith("/?"): body = HTML.encode("utf-8")''' ROUTE_NEW = ''' elif self.path == "/train" or self.path.startswith("/train?"): body = render_train_page().encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.send_header("Cache-Control", "no-store") self.end_headers() self.wfile.write(body) elif self.path == "/" or self.path.startswith("/?"): body = HTML.encode("utf-8")''' REPLACEMENTS = [ ("class Handler(BaseHTTPRequestHandler):", NEW_CODE + "\n\nclass Handler(BaseHTTPRequestHandler):"), (ROUTE_OLD, ROUTE_NEW), ] for i, (old, new) in enumerate(REPLACEMENTS): n = src.count(old) assert n == 1, f"replacement {i}: anchor found {n} times (expected 1)" src = src.replace(old, new) assert src != orig shutil.copy(P, P.with_name("server.py.bak-trainpage-20261120")) P.write_text(src) py_compile.compile(str(P), doraise=True) print(f"dashboard server.py train-page patched OK ({len(REPLACEMENTS)} replacements), backup at server.py.bak-trainpage-20261120")