File size: 25,979 Bytes
b4396f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
#!/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: <run dir>/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("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")


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 "<p class='mut'>Chưa có dữ liệu.</p>"
    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 = ["<svg viewBox='0 0 %d %d' style='width:100%%;height:auto;display:block' role='img'>" % (w, h)]
    out.append("<rect x='%d' y='%d' width='%d' height='%d' fill='#fbfdff' stroke='#c9d5e0'/>" % (L, T, iw, ih))
    for s in (0, 20000, 40000, x_max):
        x = X(s)
        out.append("<line x1='%.1f' y1='%d' x2='%.1f' y2='%d' stroke='#e3ebf2'/>" % (x, T, x, T + ih))
        lab = "0" if s == 0 else ("%dk" % (s // 1000))
        out.append("<text x='%.1f' y='%d' font-size='11' fill='#5a6b7a' text-anchor='middle'>%s</text>" % (x, T + ih + 18, lab))
    out.append("<text x='%d' y='%.1f' font-size='11' fill='#5a6b7a' text-anchor='end'>%s</text>" % (L - 6, Y(hi) + 4, _vn(hi, 3)))
    out.append("<text x='%d' y='%.1f' font-size='11' fill='#5a6b7a' text-anchor='end'>%s</text>" % (L - 6, Y(lo) + 4, _vn(lo, 3)))
    if hline is not None:
        y = Y(hline)
        out.append("<line x1='%d' y1='%.1f' x2='%d' y2='%.1f' stroke='#C0392B' stroke-width='1.4' stroke-dasharray='6 4'/>" % (L, y, L + iw, y))
        if hline_label:
            out.append("<text x='%d' y='%.1f' font-size='11.5' fill='#C0392B' text-anchor='end'>%s</text>" % (L + iw - 4, y - 5, hline_label))
    if points:
        pts = " ".join("%.1f,%.1f" % (X(s), Y(v)) for s, v in points)
        out.append("<polyline points='%s' fill='none' stroke='%s' stroke-width='1.8'/>" % (pts, color))
    if markers:
        for s, v in markers:
            out.append("<circle cx='%.1f' cy='%.1f' r='4.5' fill='#C0392B'><title>step %d · eval_loss %s</title></circle>" % (X(s), Y(v), s, _vn(v, 4)))
    out.append("</svg>")
    return "".join(out)


TRAIN_HEAD = """<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="60">
<title>Train l60k — sera-v4-fs1-jedi-l60k</title>
<style>
  :root{--navy:#002147;--bg:#F9FCFF;--ink:#1a2a3a;--mut:#5a6b7a;--line:#c9d5e0;
        --acc:#1B6AC9;--red:#C0392B;--green:#1E8449;--orange:#D4820A;--card:#fff}
  *{box-sizing:border-box}
  body{margin:0;background:var(--bg);color:var(--ink);
       font-family:"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif}
  header{background:var(--navy);color:#fff;padding:18px 22px}
  header h1{margin:0;font-size:22px;letter-spacing:.2px}
  header p{margin:6px 0 0;font-size:13.5px;opacity:.88}
  header a{color:#fff}
  main{max-width:1180px;margin:0 auto;padding:16px}
  section{background:var(--card);border:1px solid var(--line);padding:14px 16px;margin-bottom:14px}
  h2{margin:0 0 10px;font-size:15.5px;color:var(--navy);text-transform:uppercase;letter-spacing:.4px}
  .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px}
  .kpi{border:1px solid var(--line);padding:10px;background:#fbfdff}
  .kpi .v{font-size:21px;font-weight:700;color:var(--navy)}
  .kpi .k{font-size:12px;color:var(--mut);margin-top:2px}
  .bar{height:14px;background:#e6edf3;position:relative;margin:8px 0 4px}
  .bar>i{position:absolute;left:0;top:0;bottom:0;background:var(--acc)}
  .mut{color:var(--mut)}
  .badge{display:inline-block;padding:1px 8px;font-size:11.5px;font-weight:700;color:#fff;background:var(--acc)}
  .badge.run{background:var(--orange)} .badge.done{background:var(--green)} .badge.idle{background:#8a97a5}
  .badge.fail{background:var(--red)} .badge.pass{background:var(--green)} .badge.stopped{background:#5a6b7a} .badge.cancel{background:#8a97a5}
  .badge.part{background:var(--orange)} .badge.unk{background:#8a97a5}
  .pbar{background:#e8edf1;border-radius:6px;height:14px;overflow:hidden;margin:5px 0 12px}
  .pfill{background:var(--orange);height:100%;border-radius:6px;transition:width .6s ease}
  .pfill.done{background:var(--green)} .pfill.part{background:#8a97a5}
  .runrow{margin:0 0 6px}
  .runhead{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
  .ckstrip{display:flex;gap:6px;flex-wrap:wrap}
  .ck{flex:1 1 58px;border:1px solid var(--line);padding:8px 4px;text-align:center;font-size:12.5px;background:#fbfdff;color:var(--mut)}
  .ck.done{background:var(--green);border-color:var(--green);color:#fff;font-weight:700}
  .ck.writing{background:#fdf3e3;border-color:var(--orange);color:var(--ink);font-weight:700}
  .ck .tag{display:block;font-size:10.5px;font-weight:700;margin-top:2px}
  .bignum{font-size:29px;font-weight:700;color:var(--navy)}
  .markwrap{position:relative}
  .mark{position:absolute;top:-2px;bottom:-2px;width:2px;background:var(--red)}
  footer{color:var(--mut);font-size:12px;padding:0 16px 20px;max-width:1180px;margin:0 auto}
  @media(max-width:640px){header h1{font-size:18px}}
</style>
</head>
<body>
<header>
  <h1>Train — sera-v4-fs1-jedi-l60k</h1>
  <p>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
     · <a href="/">← Dashboard chính</a> · Trang tự làm mới mỗi 60 giây, số liệu đọc trực tiếp trên máy train</p>
</header>
<main>
"""


def _tkpi(v, k):
    return ("<div class='kpi'><div class='v'>%s</div>"
            "<div class='k'>%s</div></div>" % (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("<section><h2>Tổng quan</h2><div class='grid'>")
    b.append(_tkpi("<span class='badge %s'>%s</span>" % (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("</div>")
    mark_pct = 100.0 * L60K_TEST_STEP / float(total)
    b.append("<div class='markwrap'><div class='bar'><i style='width:%s%%'></i></div>"
             "<div class='mark' style='left:%.1f%%'></div></div>"
             % (_vn(pct, 1).replace(",", "."), mark_pct))
    if st is not None:
        b.append("<div class='mut' style='font-size:12px'>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</div>"
                 % (_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("<div class='mut' style='font-size:12px'>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.</div>")
    b.append("</section>")

    loss_pts = _thin(st["loss"]) if st else []
    eval_pts = [(s, v) for s, v in (st["eval"] if st else [])]
    b.append("<section><h2>Loss train theo bước</h2>")
    b.append(_svg_line_chart(loss_pts, "#1B6AC9", total, markers=eval_pts))
    b.append("<p class='mut' style='font-size:12px;margin:6px 0 0'>Đườ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.</p></section>")

    dd_pts = _thin(st["dd"]) if st else []
    b.append("<section><h2>jedi_dd_task theo bước</h2>")
    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("<p class='mut' style='font-size:12px;margin:6px 0 0'>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).</p></section>")

    if st and st["lr"]:
        b.append("<section><h2>Tốc độ học (lr) theo bước</h2>")
        b.append(_svg_line_chart(_thin(st["lr"]), "#D4820A", total, y_lo=0))
        b.append("</section>")

    b.append("<section><h2>Checkpoint (mỗi 5.000 bước)</h2><div class='ckstrip'>")
    for c in ckpts:
        tags = ""
        if c["ema"]:
            tags += "<span class='tag'>EMA</span>"
        if c["step"] == L60K_TEST_STEP:
            tags += "<span class='tag'>MỐC TEST</span>"
        if c["state"] == "writing":
            tags += "<span class='tag'>đang ghi</span>"
        b.append("<div class='ck %s'>%dk%s</div>"
                 % (c["state"], c["step"] // 1000, tags))
    b.append("</div><p class='mut' style='font-size:12px;margin:8px 0 0'>Ô 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.</p></section>")

    b.append("<section><h2>Test tại mốc 20.000 (checkpoint EMA 020000)</h2>")
    if meas is None and roll is None:
        if step is not None and step >= L60K_TEST_STEP:
            b.append("<p>Đã qua mốc 20.000 — đang chờ kết quả từ watcher test (đo CPU + rollout cond-b).</p>")
        else:
            b.append("<p class='mut'>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.</p>")
    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("<div class='kpi'><div class='bignum'>%s</div>"
                             "<div class='k'>%s</div></div>" % (_vn(v[key], 3), label))
        if boxes:
            b.append("<div class='grid'>" + "".join(boxes) + "</div>")
        else:
            b.append("<p class='mut'>Đã có file đo nhưng chưa parse được số DD/Δv từ file.</p>")
        b.append("<p class='mut' style='font-size:12px;margin:8px 0 0'>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).</p>"
                 % _esc(meas["file"]))
    if roll is not None:
        bc = {"RUNNING": "run", "DONE": "done", "PARTIAL": "part"}[roll["status"]]
        b.append("<div class='runrow'><div class='runhead'><b>Rollout cond-b (demo đúng task) @ EMA 020000</b>"
                 "<span>%d/%d episode · thành công %d (%s%%)</span>"
                 "<span style='margin-left:auto'><span class='badge %s'>%s</span></span></div>"
                 "<div class='pbar'><div class='pfill %s' style='width:%s%%'></div></div></div>"
                 % (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("</section>")
    b.append("</main><footer>Nguồn dữ liệu: log train + checkpoint của run %s và kết quả test 20k trong "
             "~/sera_v4_experiments trên chính máy train này · Cập nhật: %s · Trang tự làm mới mỗi 60 giây.</footer>"
             "</body></html>"
             % (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")