Spaces:
Paused
Paused
fix: switch trainer Space to vanilla GRPO path
Browse files- space/training/app.py +747 -673
space/training/app.py
CHANGED
|
@@ -1,673 +1,747 @@
|
|
| 1 |
-
"""FastAPI control panel for the CERNenv trainer Space.
|
| 2 |
-
|
| 3 |
-
Endpoints:
|
| 4 |
-
GET / → status page (HTML)
|
| 5 |
-
GET /status → JSON status of the current training run
|
| 6 |
-
GET /metrics → JSON snapshot of reward / success rate
|
| 7 |
-
GET /logs → tail of the training log
|
| 8 |
-
POST /train → start (or restart) a training run
|
| 9 |
-
GET /health → liveness probe
|
| 10 |
-
|
| 11 |
-
Designed to run on a Hugging Face Space with `sdk: docker`. Heavy training
|
| 12 |
-
work runs in a background thread so the HTTP server stays responsive.
|
| 13 |
-
"""
|
| 14 |
-
|
| 15 |
-
from __future__ import annotations
|
| 16 |
-
|
| 17 |
-
import json
|
| 18 |
-
import logging
|
| 19 |
-
import os
|
| 20 |
-
import subprocess
|
| 21 |
-
import sys
|
| 22 |
-
import threading
|
| 23 |
-
import time
|
| 24 |
-
from datetime import datetime, timezone
|
| 25 |
-
from pathlib import Path
|
| 26 |
-
from typing import Any, Dict, Optional
|
| 27 |
-
|
| 28 |
-
from fastapi import FastAPI, HTTPException
|
| 29 |
-
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, PlainTextResponse
|
| 30 |
-
from fastapi.staticfiles import StaticFiles
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
|
| 34 |
-
logger = logging.getLogger(__name__)
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
def _resolve_repo_root() -> Path:
|
| 38 |
-
env_root = os.environ.get("CERNENV_ROOT")
|
| 39 |
-
candidates = []
|
| 40 |
-
if env_root:
|
| 41 |
-
candidates.append(Path(env_root))
|
| 42 |
-
candidates.extend([
|
| 43 |
-
Path("/home/user/app"),
|
| 44 |
-
Path(__file__).resolve().parent.parent.parent,
|
| 45 |
-
])
|
| 46 |
-
for p in candidates:
|
| 47 |
-
try:
|
| 48 |
-
if p.exists():
|
| 49 |
-
return p.resolve()
|
| 50 |
-
except OSError:
|
| 51 |
-
continue
|
| 52 |
-
return candidates[-1].resolve()
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
REPO_ROOT = _resolve_repo_root()
|
| 56 |
-
LOG_DIR = REPO_ROOT / "training" / "runs"
|
| 57 |
-
try:
|
| 58 |
-
LOG_DIR.mkdir(parents=True, exist_ok=True)
|
| 59 |
-
except OSError as exc: # pragma: no cover - read-only filesystem fallback
|
| 60 |
-
logger.warning("could not create %s (%s); using /tmp", LOG_DIR, exc)
|
| 61 |
-
LOG_DIR = Path("/tmp/cernenv-runs")
|
| 62 |
-
LOG_DIR.mkdir(parents=True, exist_ok=True)
|
| 63 |
-
LOG_FILE = LOG_DIR / "training.log"
|
| 64 |
-
EVIDENCE_DIR = REPO_ROOT / "evidence"
|
| 65 |
-
try:
|
| 66 |
-
EVIDENCE_DIR.mkdir(parents=True, exist_ok=True)
|
| 67 |
-
except OSError: # pragma: no cover
|
| 68 |
-
EVIDENCE_DIR = Path("/tmp/cernenv-evidence")
|
| 69 |
-
EVIDENCE_DIR.mkdir(parents=True, exist_ok=True)
|
| 70 |
-
METRICS_FILE = EVIDENCE_DIR / "before_after_metrics.json"
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
def _env(name: str, default: str) -> str:
|
| 74 |
-
return os.environ.get(name, default)
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
def _detect_gpus() -> int:
|
| 78 |
-
try:
|
| 79 |
-
import torch # type: ignore
|
| 80 |
-
if torch.cuda.is_available():
|
| 81 |
-
return torch.cuda.device_count()
|
| 82 |
-
except Exception:
|
| 83 |
-
pass
|
| 84 |
-
try:
|
| 85 |
-
out = subprocess.run(
|
| 86 |
-
["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],
|
| 87 |
-
capture_output=True, text=True, timeout=5,
|
| 88 |
-
)
|
| 89 |
-
return len([l for l in out.stdout.splitlines() if l.strip()])
|
| 90 |
-
except Exception:
|
| 91 |
-
return 0
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
_NUM_GPUS = _detect_gpus()
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
CONFIG = {
|
| 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 |
-
self.
|
| 128 |
-
self.
|
| 129 |
-
self.
|
| 130 |
-
self.
|
| 131 |
-
self.
|
| 132 |
-
self.
|
| 133 |
-
self.
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
"
|
| 140 |
-
"
|
| 141 |
-
"
|
| 142 |
-
"
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
log_handle.
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
log_handle.
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
log_handle.
|
| 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 |
-
log.
|
| 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 |
-
log
|
| 380 |
-
|
| 381 |
-
if
|
| 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 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FastAPI control panel for the CERNenv trainer Space.
|
| 2 |
+
|
| 3 |
+
Endpoints:
|
| 4 |
+
GET / → status page (HTML)
|
| 5 |
+
GET /status → JSON status of the current training run
|
| 6 |
+
GET /metrics → JSON snapshot of reward / success rate
|
| 7 |
+
GET /logs → tail of the training log
|
| 8 |
+
POST /train → start (or restart) a training run
|
| 9 |
+
GET /health → liveness probe
|
| 10 |
+
|
| 11 |
+
Designed to run on a Hugging Face Space with `sdk: docker`. Heavy training
|
| 12 |
+
work runs in a background thread so the HTTP server stays responsive.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import logging
|
| 19 |
+
import os
|
| 20 |
+
import subprocess
|
| 21 |
+
import sys
|
| 22 |
+
import threading
|
| 23 |
+
import time
|
| 24 |
+
from datetime import datetime, timezone
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
from typing import Any, Dict, Optional
|
| 27 |
+
|
| 28 |
+
from fastapi import FastAPI, HTTPException
|
| 29 |
+
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, PlainTextResponse
|
| 30 |
+
from fastapi.staticfiles import StaticFiles
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
|
| 34 |
+
logger = logging.getLogger(__name__)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _resolve_repo_root() -> Path:
|
| 38 |
+
env_root = os.environ.get("CERNENV_ROOT")
|
| 39 |
+
candidates = []
|
| 40 |
+
if env_root:
|
| 41 |
+
candidates.append(Path(env_root))
|
| 42 |
+
candidates.extend([
|
| 43 |
+
Path("/home/user/app"),
|
| 44 |
+
Path(__file__).resolve().parent.parent.parent,
|
| 45 |
+
])
|
| 46 |
+
for p in candidates:
|
| 47 |
+
try:
|
| 48 |
+
if p.exists():
|
| 49 |
+
return p.resolve()
|
| 50 |
+
except OSError:
|
| 51 |
+
continue
|
| 52 |
+
return candidates[-1].resolve()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
REPO_ROOT = _resolve_repo_root()
|
| 56 |
+
LOG_DIR = REPO_ROOT / "training" / "runs"
|
| 57 |
+
try:
|
| 58 |
+
LOG_DIR.mkdir(parents=True, exist_ok=True)
|
| 59 |
+
except OSError as exc: # pragma: no cover - read-only filesystem fallback
|
| 60 |
+
logger.warning("could not create %s (%s); using /tmp", LOG_DIR, exc)
|
| 61 |
+
LOG_DIR = Path("/tmp/cernenv-runs")
|
| 62 |
+
LOG_DIR.mkdir(parents=True, exist_ok=True)
|
| 63 |
+
LOG_FILE = LOG_DIR / "training.log"
|
| 64 |
+
EVIDENCE_DIR = REPO_ROOT / "evidence"
|
| 65 |
+
try:
|
| 66 |
+
EVIDENCE_DIR.mkdir(parents=True, exist_ok=True)
|
| 67 |
+
except OSError: # pragma: no cover
|
| 68 |
+
EVIDENCE_DIR = Path("/tmp/cernenv-evidence")
|
| 69 |
+
EVIDENCE_DIR.mkdir(parents=True, exist_ok=True)
|
| 70 |
+
METRICS_FILE = EVIDENCE_DIR / "before_after_metrics.json"
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _env(name: str, default: str) -> str:
|
| 74 |
+
return os.environ.get(name, default)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _detect_gpus() -> int:
|
| 78 |
+
try:
|
| 79 |
+
import torch # type: ignore
|
| 80 |
+
if torch.cuda.is_available():
|
| 81 |
+
return torch.cuda.device_count()
|
| 82 |
+
except Exception:
|
| 83 |
+
pass
|
| 84 |
+
try:
|
| 85 |
+
out = subprocess.run(
|
| 86 |
+
["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],
|
| 87 |
+
capture_output=True, text=True, timeout=5,
|
| 88 |
+
)
|
| 89 |
+
return len([l for l in out.stdout.splitlines() if l.strip()])
|
| 90 |
+
except Exception:
|
| 91 |
+
return 0
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
_NUM_GPUS = _detect_gpus()
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
CONFIG = {
|
| 98 |
+
"training_backend": _env("TRAINING_BACKEND", "vanilla"),
|
| 99 |
+
"model_name": _env("MODEL_NAME", "HuggingFaceTB/SmolLM2-360M-Instruct"),
|
| 100 |
+
"difficulty": _env("DIFFICULTY", "easy"),
|
| 101 |
+
"curriculum": _env("CURRICULUM", "0") == "1",
|
| 102 |
+
"curriculum_promote": float(_env("CURRICULUM_PROMOTE", "0.55")),
|
| 103 |
+
"curriculum_demote": float(_env("CURRICULUM_DEMOTE", "0.10")),
|
| 104 |
+
"total_episodes": int(_env("TOTAL_EPISODES", "120")),
|
| 105 |
+
"max_steps": int(_env("MAX_STEPS", "12")),
|
| 106 |
+
"num_generations": int(_env("NUM_GENERATIONS", "4")),
|
| 107 |
+
"checkpoint_eval_steps": int(_env("CHECKPOINT_EVAL_STEPS", "25")),
|
| 108 |
+
"checkpoint_eval_episodes": int(_env("CHECKPOINT_EVAL_EPISODES", "8")),
|
| 109 |
+
"eval_episodes": int(_env("EVAL_EPISODES", "8")),
|
| 110 |
+
"output_dir": _env("OUTPUT_DIR", "runs/vanilla-grpo"),
|
| 111 |
+
"evidence_dir": _env("EVIDENCE_DIR", "evidence"),
|
| 112 |
+
"num_gpus": int(_env("NUM_GPUS", "1")),
|
| 113 |
+
"hf_username": _env("HF_USERNAME", "anugrahhu"),
|
| 114 |
+
"push_repo": _env(
|
| 115 |
+
"PUSH_REPO",
|
| 116 |
+
f"{_env('HF_USERNAME', 'anugrahhu')}/cernenv-grpo-smollm2-360m",
|
| 117 |
+
),
|
| 118 |
+
"autostart": _env("AUTOSTART", "0") == "1",
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
# ── Run state ────────────────────────────────────────────────────────────
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class RunState:
|
| 126 |
+
def __init__(self) -> None:
|
| 127 |
+
self.lock = threading.Lock()
|
| 128 |
+
self.thread: Optional[threading.Thread] = None
|
| 129 |
+
self.process: Optional[subprocess.Popen] = None
|
| 130 |
+
self.status: str = "idle" # idle | running | finished | failed
|
| 131 |
+
self.started_at: Optional[str] = None
|
| 132 |
+
self.finished_at: Optional[str] = None
|
| 133 |
+
self.last_error: Optional[str] = None
|
| 134 |
+
self.last_config: Dict[str, Any] = {}
|
| 135 |
+
|
| 136 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 137 |
+
with self.lock:
|
| 138 |
+
return {
|
| 139 |
+
"status": self.status,
|
| 140 |
+
"started_at": self.started_at,
|
| 141 |
+
"finished_at": self.finished_at,
|
| 142 |
+
"last_error": self.last_error,
|
| 143 |
+
"last_config": self.last_config,
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
STATE = RunState()
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
# ── Training pipeline ────────────────────────────────────────────────────
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def _stream_subprocess(cmd: list[str], log_handle) -> int:
|
| 154 |
+
log_handle.write(f"\n$ {' '.join(cmd)}\n")
|
| 155 |
+
log_handle.flush()
|
| 156 |
+
proc = subprocess.Popen(
|
| 157 |
+
cmd,
|
| 158 |
+
cwd=str(REPO_ROOT),
|
| 159 |
+
stdout=subprocess.PIPE,
|
| 160 |
+
stderr=subprocess.STDOUT,
|
| 161 |
+
bufsize=1,
|
| 162 |
+
universal_newlines=True,
|
| 163 |
+
env={**os.environ, "PYTHONPATH": str(REPO_ROOT)},
|
| 164 |
+
)
|
| 165 |
+
STATE.process = proc
|
| 166 |
+
assert proc.stdout is not None
|
| 167 |
+
for line in proc.stdout:
|
| 168 |
+
log_handle.write(line)
|
| 169 |
+
log_handle.flush()
|
| 170 |
+
rc = proc.wait()
|
| 171 |
+
log_handle.write(f"[exit code {rc}]\n")
|
| 172 |
+
log_handle.flush()
|
| 173 |
+
STATE.process = None
|
| 174 |
+
return rc
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _build_training_cmd(config: Dict[str, Any]) -> list[str]:
|
| 178 |
+
"""Compose the selected training launcher."""
|
| 179 |
+
backend = str(config.get("training_backend", "vanilla")).lower()
|
| 180 |
+
if backend == "vanilla":
|
| 181 |
+
python_bin = "/usr/local/bin/python" if Path("/usr/local/bin/python").exists() else sys.executable
|
| 182 |
+
return [
|
| 183 |
+
python_bin, "-m", "training.training_script",
|
| 184 |
+
"--model_name", config["model_name"],
|
| 185 |
+
"--difficulty", config["difficulty"],
|
| 186 |
+
"--total_episodes", str(config["total_episodes"]),
|
| 187 |
+
"--max_steps", str(config["max_steps"]),
|
| 188 |
+
"--num_generations", str(config["num_generations"]),
|
| 189 |
+
"--output_dir", config["output_dir"],
|
| 190 |
+
]
|
| 191 |
+
|
| 192 |
+
if backend != "unsloth":
|
| 193 |
+
raise ValueError(f"unknown TRAINING_BACKEND={backend!r}")
|
| 194 |
+
|
| 195 |
+
base = [
|
| 196 |
+
"-m", "training.training_unsloth",
|
| 197 |
+
"--model_name", config["model_name"],
|
| 198 |
+
"--difficulty", config["difficulty"],
|
| 199 |
+
"--total_episodes", str(config["total_episodes"]),
|
| 200 |
+
"--max_steps", str(config["max_steps"]),
|
| 201 |
+
"--num_generations", str(config["num_generations"]),
|
| 202 |
+
"--checkpoint_eval_steps", str(config["checkpoint_eval_steps"]),
|
| 203 |
+
"--checkpoint_eval_episodes", str(config["checkpoint_eval_episodes"]),
|
| 204 |
+
"--output_dir", config["output_dir"],
|
| 205 |
+
"--evidence_dir", config["evidence_dir"],
|
| 206 |
+
]
|
| 207 |
+
if config.get("curriculum"):
|
| 208 |
+
base.extend([
|
| 209 |
+
"--curriculum",
|
| 210 |
+
"--curriculum_promote", str(config["curriculum_promote"]),
|
| 211 |
+
"--curriculum_demote", str(config["curriculum_demote"]),
|
| 212 |
+
])
|
| 213 |
+
n = max(int(config.get("num_gpus", 1)), 1)
|
| 214 |
+
if n > 1:
|
| 215 |
+
return ["accelerate", "launch", "--num_processes", str(n), "--mixed_precision", "bf16"] + base
|
| 216 |
+
return [sys.executable] + base
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def _build_eval_cmd(
|
| 220 |
+
*,
|
| 221 |
+
model_name: str,
|
| 222 |
+
difficulty: str,
|
| 223 |
+
episodes: str,
|
| 224 |
+
max_steps: str,
|
| 225 |
+
tag: str,
|
| 226 |
+
out: str,
|
| 227 |
+
backend: str,
|
| 228 |
+
adapter_dir: Optional[str] = None,
|
| 229 |
+
) -> list[str]:
|
| 230 |
+
cmd = [
|
| 231 |
+
sys.executable, "-m", "training.evaluate",
|
| 232 |
+
"--model_name", model_name,
|
| 233 |
+
"--difficulty", difficulty,
|
| 234 |
+
"--episodes", episodes,
|
| 235 |
+
"--max_steps", max_steps,
|
| 236 |
+
"--tag", tag,
|
| 237 |
+
"--out", out,
|
| 238 |
+
]
|
| 239 |
+
if adapter_dir:
|
| 240 |
+
cmd.extend(["--adapter_dir", adapter_dir])
|
| 241 |
+
if backend == "vanilla":
|
| 242 |
+
cmd.append("--no_unsloth")
|
| 243 |
+
return cmd
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def _push_model_folder_to_hub(*, output_dir: Path, repo_id: str, base_model: str, log) -> None:
|
| 247 |
+
"""Upload a vanilla transformers model directory to the Hub."""
|
| 248 |
+
token = os.environ.get("HF_TOKEN")
|
| 249 |
+
if not token:
|
| 250 |
+
log.write("\n[skip] HF_TOKEN not set — model not pushed\n")
|
| 251 |
+
log.flush()
|
| 252 |
+
return
|
| 253 |
+
try:
|
| 254 |
+
from huggingface_hub import HfApi
|
| 255 |
+
api = HfApi(token=token)
|
| 256 |
+
api.create_repo(repo_id=repo_id, repo_type="model", exist_ok=True)
|
| 257 |
+
api.upload_folder(
|
| 258 |
+
folder_path=str(output_dir),
|
| 259 |
+
repo_id=repo_id,
|
| 260 |
+
repo_type="model",
|
| 261 |
+
commit_message=f"Upload vanilla GRPO model based on {base_model}",
|
| 262 |
+
)
|
| 263 |
+
log.write(f"\n[ok] uploaded model → https://huggingface.co/{repo_id}\n")
|
| 264 |
+
log.flush()
|
| 265 |
+
except Exception as exc:
|
| 266 |
+
log.write(f"\n[warn] model push failed: {exc}\n")
|
| 267 |
+
log.flush()
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def _push_evidence_to_hub(*, evidence_dir: Path, repo_id: str, log) -> None:
|
| 271 |
+
"""Upload the entire evidence/ directory to the model repo."""
|
| 272 |
+
token = os.environ.get("HF_TOKEN")
|
| 273 |
+
if not token:
|
| 274 |
+
log.write("\n[skip] HF_TOKEN not set — evidence not pushed\n")
|
| 275 |
+
log.flush()
|
| 276 |
+
return
|
| 277 |
+
try:
|
| 278 |
+
from huggingface_hub import HfApi
|
| 279 |
+
api = HfApi(token=token)
|
| 280 |
+
api.upload_folder(
|
| 281 |
+
folder_path=str(evidence_dir),
|
| 282 |
+
repo_id=repo_id,
|
| 283 |
+
repo_type="model",
|
| 284 |
+
path_in_repo="evidence",
|
| 285 |
+
commit_message="Upload CERNenv training evidence (curves, evals, plots)",
|
| 286 |
+
)
|
| 287 |
+
log.write(f"\n[ok] uploaded evidence/ → https://huggingface.co/{repo_id}/tree/main/evidence\n")
|
| 288 |
+
log.flush()
|
| 289 |
+
except Exception as exc:
|
| 290 |
+
log.write(f"\n[warn] evidence push failed: {exc}\n")
|
| 291 |
+
log.flush()
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def _training_pipeline(config: Dict[str, Any]) -> None:
|
| 295 |
+
started = datetime.now(timezone.utc).isoformat()
|
| 296 |
+
with STATE.lock:
|
| 297 |
+
STATE.status = "running"
|
| 298 |
+
STATE.started_at = started
|
| 299 |
+
STATE.finished_at = None
|
| 300 |
+
STATE.last_error = None
|
| 301 |
+
STATE.last_config = dict(config)
|
| 302 |
+
|
| 303 |
+
evidence_dir = Path(config["evidence_dir"]).resolve()
|
| 304 |
+
evidence_dir.mkdir(parents=True, exist_ok=True)
|
| 305 |
+
|
| 306 |
+
LOG_FILE.parent.mkdir(parents=True, exist_ok=True)
|
| 307 |
+
with open(LOG_FILE, "a") as log:
|
| 308 |
+
log.write(f"\n=== Training started {started} ===\n")
|
| 309 |
+
log.write(json.dumps(config, indent=2) + "\n")
|
| 310 |
+
log.flush()
|
| 311 |
+
try:
|
| 312 |
+
output_dir = config["output_dir"]
|
| 313 |
+
difficulty = config["difficulty"]
|
| 314 |
+
max_steps = str(config["max_steps"])
|
| 315 |
+
eval_episodes = str(config["eval_episodes"])
|
| 316 |
+
model_name = config["model_name"]
|
| 317 |
+
push_repo = config["push_repo"]
|
| 318 |
+
evidence_str = config["evidence_dir"]
|
| 319 |
+
backend = str(config.get("training_backend", "vanilla")).lower()
|
| 320 |
+
pre_jsonl = f"{evidence_str}/pre_eval.jsonl"
|
| 321 |
+
post_jsonl = f"{evidence_str}/post_eval.jsonl"
|
| 322 |
+
|
| 323 |
+
log.write("\n--- baseline sanity check (random / heuristic / oracle) ---\n")
|
| 324 |
+
log.flush()
|
| 325 |
+
for agent in ("random", "heuristic", "oracle"):
|
| 326 |
+
_stream_subprocess(
|
| 327 |
+
[
|
| 328 |
+
sys.executable, "-m", "scripts.run_agent",
|
| 329 |
+
"--agent", agent, "--difficulty", difficulty,
|
| 330 |
+
"--episodes", "3", "--quiet",
|
| 331 |
+
],
|
| 332 |
+
log,
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
log.write(f"\n--- pre-train evaluation ({eval_episodes} eps) ---\n")
|
| 336 |
+
log.flush()
|
| 337 |
+
rc = _stream_subprocess(
|
| 338 |
+
_build_eval_cmd(
|
| 339 |
+
model_name=model_name,
|
| 340 |
+
difficulty=difficulty,
|
| 341 |
+
episodes=eval_episodes,
|
| 342 |
+
max_steps=max_steps,
|
| 343 |
+
tag="pre_train",
|
| 344 |
+
out=pre_jsonl,
|
| 345 |
+
backend=backend,
|
| 346 |
+
),
|
| 347 |
+
log,
|
| 348 |
+
)
|
| 349 |
+
if rc != 0:
|
| 350 |
+
# don't abort — we still want training + post-eval evidence.
|
| 351 |
+
log.write(f"\n[warn] pre-train eval failed (rc={rc}); continuing without baseline\n")
|
| 352 |
+
log.flush()
|
| 353 |
+
|
| 354 |
+
log.write(f"\n--- GRPO training ({backend}, {config['num_gpus']} GPU process(es)) ---\n")
|
| 355 |
+
log.flush()
|
| 356 |
+
rc = _stream_subprocess(_build_training_cmd(config), log)
|
| 357 |
+
if rc != 0:
|
| 358 |
+
raise RuntimeError(f"training failed (rc={rc})")
|
| 359 |
+
|
| 360 |
+
# Cold-load the trained artifact before burning time on post-eval.
|
| 361 |
+
log.write(
|
| 362 |
+
f"\n--- trained artifact smoke test "
|
| 363 |
+
f"(loading {output_dir} cold-start, 2 eps) ---\n"
|
| 364 |
+
)
|
| 365 |
+
log.flush()
|
| 366 |
+
smoke_model = output_dir if backend == "vanilla" else model_name
|
| 367 |
+
smoke_adapter = None if backend == "vanilla" else output_dir
|
| 368 |
+
rc = _stream_subprocess(
|
| 369 |
+
_build_eval_cmd(
|
| 370 |
+
model_name=smoke_model,
|
| 371 |
+
adapter_dir=smoke_adapter,
|
| 372 |
+
difficulty=difficulty,
|
| 373 |
+
episodes="2",
|
| 374 |
+
max_steps=max_steps,
|
| 375 |
+
tag="smoke",
|
| 376 |
+
out=f"{evidence_str}/smoke_eval.jsonl",
|
| 377 |
+
backend=backend,
|
| 378 |
+
),
|
| 379 |
+
log,
|
| 380 |
+
)
|
| 381 |
+
if rc != 0:
|
| 382 |
+
raise RuntimeError(
|
| 383 |
+
f"trained artifact smoke test failed (rc={rc}); refusing to push "
|
| 384 |
+
f"unloadable output to the Hub. Inspect {output_dir}."
|
| 385 |
+
)
|
| 386 |
+
|
| 387 |
+
log.write(f"\n--- post-train evaluation ({eval_episodes} eps) ---\n")
|
| 388 |
+
log.flush()
|
| 389 |
+
post_model = output_dir if backend == "vanilla" else model_name
|
| 390 |
+
post_adapter = None if backend == "vanilla" else output_dir
|
| 391 |
+
rc = _stream_subprocess(
|
| 392 |
+
_build_eval_cmd(
|
| 393 |
+
model_name=post_model,
|
| 394 |
+
adapter_dir=post_adapter,
|
| 395 |
+
difficulty=difficulty,
|
| 396 |
+
episodes=eval_episodes,
|
| 397 |
+
max_steps=max_steps,
|
| 398 |
+
tag="post_train",
|
| 399 |
+
out=post_jsonl,
|
| 400 |
+
backend=backend,
|
| 401 |
+
),
|
| 402 |
+
log,
|
| 403 |
+
)
|
| 404 |
+
if rc != 0:
|
| 405 |
+
log.write(f"\n[warn] post-train eval failed (rc={rc}); evidence will be partial\n")
|
| 406 |
+
log.flush()
|
| 407 |
+
|
| 408 |
+
log.write("\n--- evidence: before/after summary, distribution, trajectories ---\n")
|
| 409 |
+
log.flush()
|
| 410 |
+
try:
|
| 411 |
+
from training.evidence import (
|
| 412 |
+
EvidencePaths,
|
| 413 |
+
render_before_after,
|
| 414 |
+
render_sample_trajectories,
|
| 415 |
+
render_training_curve,
|
| 416 |
+
render_reward_components,
|
| 417 |
+
render_checkpoint_progression,
|
| 418 |
+
)
|
| 419 |
+
paths = EvidencePaths(root=Path(evidence_str))
|
| 420 |
+
paths.ensure()
|
| 421 |
+
metrics = render_before_after(
|
| 422 |
+
pre_jsonl=Path(pre_jsonl),
|
| 423 |
+
post_jsonl=Path(post_jsonl),
|
| 424 |
+
summary_png=paths.before_after_summary_png,
|
| 425 |
+
distribution_png=paths.reward_distribution_png,
|
| 426 |
+
metrics_json=paths.before_after_metrics_json,
|
| 427 |
+
)
|
| 428 |
+
render_sample_trajectories(
|
| 429 |
+
pre_jsonl=Path(pre_jsonl),
|
| 430 |
+
post_jsonl=Path(post_jsonl),
|
| 431 |
+
md_path=paths.sample_trajectories_md,
|
| 432 |
+
)
|
| 433 |
+
render_training_curve(paths.training_log_csv, paths.training_curve_png)
|
| 434 |
+
render_reward_components(
|
| 435 |
+
paths.reward_components_csv, paths.reward_components_png,
|
| 436 |
+
)
|
| 437 |
+
render_checkpoint_progression(
|
| 438 |
+
paths.checkpoint_evals_csv, paths.checkpoint_progression_png,
|
| 439 |
+
)
|
| 440 |
+
log.write(json.dumps(metrics, indent=2) + "\n")
|
| 441 |
+
log.flush()
|
| 442 |
+
except Exception as exc:
|
| 443 |
+
log.write(f"[warn] evidence rendering failed: {exc}\n")
|
| 444 |
+
log.flush()
|
| 445 |
+
|
| 446 |
+
if os.environ.get("HF_TOKEN"):
|
| 447 |
+
if backend == "vanilla":
|
| 448 |
+
log.write("\n--- push vanilla model to Hub ---\n")
|
| 449 |
+
log.flush()
|
| 450 |
+
_push_model_folder_to_hub(
|
| 451 |
+
output_dir=Path(output_dir),
|
| 452 |
+
repo_id=push_repo,
|
| 453 |
+
base_model=model_name,
|
| 454 |
+
log=log,
|
| 455 |
+
)
|
| 456 |
+
else:
|
| 457 |
+
log.write("\n--- push adapters to Hub ---\n")
|
| 458 |
+
log.flush()
|
| 459 |
+
_stream_subprocess(
|
| 460 |
+
[
|
| 461 |
+
sys.executable, "-m", "scripts.push_to_hub", "model",
|
| 462 |
+
"--adapter_dir", output_dir,
|
| 463 |
+
"--repo_id", push_repo,
|
| 464 |
+
"--base_model", model_name,
|
| 465 |
+
],
|
| 466 |
+
log,
|
| 467 |
+
)
|
| 468 |
+
_push_evidence_to_hub(
|
| 469 |
+
evidence_dir=evidence_dir,
|
| 470 |
+
repo_id=push_repo,
|
| 471 |
+
log=log,
|
| 472 |
+
)
|
| 473 |
+
else:
|
| 474 |
+
log.write("\n[skip] HF_TOKEN not set — not pushing to Hub\n")
|
| 475 |
+
log.flush()
|
| 476 |
+
with STATE.lock:
|
| 477 |
+
STATE.status = "finished"
|
| 478 |
+
except Exception as exc:
|
| 479 |
+
logger.exception("training pipeline failed")
|
| 480 |
+
with STATE.lock:
|
| 481 |
+
STATE.status = "failed"
|
| 482 |
+
STATE.last_error = str(exc)
|
| 483 |
+
finally:
|
| 484 |
+
finished = datetime.now(timezone.utc).isoformat()
|
| 485 |
+
log.write(f"\n=== Training ended {finished} ===\n")
|
| 486 |
+
log.flush()
|
| 487 |
+
with STATE.lock:
|
| 488 |
+
STATE.finished_at = finished
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def _start_training(config: Dict[str, Any]) -> None:
|
| 492 |
+
with STATE.lock:
|
| 493 |
+
if STATE.status == "running":
|
| 494 |
+
raise RuntimeError("a training run is already in progress")
|
| 495 |
+
STATE.thread = threading.Thread(
|
| 496 |
+
target=_training_pipeline,
|
| 497 |
+
args=(config,),
|
| 498 |
+
name="cernenv-trainer",
|
| 499 |
+
daemon=True,
|
| 500 |
+
)
|
| 501 |
+
STATE.thread.start()
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
# ── FastAPI app ──────────────────────────────────────────────────────────
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
app = FastAPI(title="CERNenv Trainer", version="0.1.0")
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
_HTML = """\
|
| 511 |
+
<!doctype html>
|
| 512 |
+
<html lang=en>
|
| 513 |
+
<head>
|
| 514 |
+
<meta charset=utf-8>
|
| 515 |
+
<title>CERNenv Trainer</title>
|
| 516 |
+
<style>
|
| 517 |
+
body { font-family: ui-sans-serif, system-ui, sans-serif; margin: 2rem auto;
|
| 518 |
+
max-width: 1000px; color:#111; padding: 0 1rem; line-height:1.5 }
|
| 519 |
+
h1 { margin-bottom: 0 }
|
| 520 |
+
h2 { margin-top: 2rem; border-bottom:1px solid #eee; padding-bottom:.25rem }
|
| 521 |
+
.muted { color:#666 }
|
| 522 |
+
pre { background:#0e1116; color:#e6edf3; padding:1rem; border-radius:6px;
|
| 523 |
+
overflow-x:auto; max-height:40vh; font-size:.85em }
|
| 524 |
+
button { font-size:1rem; padding:.6rem 1rem; border-radius:6px; border:1px solid #888;
|
| 525 |
+
background:#fff; cursor:pointer; margin-right:.4rem }
|
| 526 |
+
.pill { display:inline-block; padding:.1rem .55rem; border-radius:999px;
|
| 527 |
+
background:#eef; color:#225; font-size:.85em }
|
| 528 |
+
.ok { background:#dfd; color:#272 }
|
| 529 |
+
.fail { background:#fdd; color:#822 }
|
| 530 |
+
.run { background:#fdf6d8; color:#774 }
|
| 531 |
+
table { border-collapse:collapse; margin:.5rem 0 }
|
| 532 |
+
td, th { padding:.25rem .8rem .25rem 0; vertical-align: top; text-align:left }
|
| 533 |
+
th { color:#444; font-weight:600 }
|
| 534 |
+
.grid { display:grid; grid-template-columns:1fr 1fr; gap:1rem }
|
| 535 |
+
.card { border:1px solid #e5e7eb; border-radius:8px; padding:.75rem; background:#fafafa }
|
| 536 |
+
.card img { max-width:100%; border-radius:4px }
|
| 537 |
+
.delta-pos { color:#15803d; font-weight:600 }
|
| 538 |
+
.delta-neg { color:#b91c1c; font-weight:600 }
|
| 539 |
+
code { background:#f4f4f4; padding:.05rem .35rem; border-radius:4px }
|
| 540 |
+
a { color:#1d4ed8 }
|
| 541 |
+
</style>
|
| 542 |
+
</head>
|
| 543 |
+
<body>
|
| 544 |
+
<h1>⚛️ CERNenv Trainer</h1>
|
| 545 |
+
<p class=muted>GRPO + Unsloth + LoRA on the CERNenv LHC discovery environment. Multi-GPU on Hugging Face Spaces.</p>
|
| 546 |
+
|
| 547 |
+
<h2>Run status</h2>
|
| 548 |
+
<p>Status: <span id=status class=pill>?</span></p>
|
| 549 |
+
<table id=meta></table>
|
| 550 |
+
<p>
|
| 551 |
+
<button onclick="startRun()">▶ Start training</button>
|
| 552 |
+
<button onclick="refresh()">↻ Refresh</button>
|
| 553 |
+
<a href="/evidence" target=_blank><button>📁 Evidence index</button></a>
|
| 554 |
+
<a href="/docs" target=_blank><button>🛠 API</button></a>
|
| 555 |
+
</p>
|
| 556 |
+
|
| 557 |
+
<h2>Training-progress evidence</h2>
|
| 558 |
+
<p class=muted>Auto-updated as training runs. All artifacts are also saved to <code>evidence/</code> and pushed to the model repo on the Hub.</p>
|
| 559 |
+
<div class=grid>
|
| 560 |
+
<div class=card><b>Per-step training curve</b><br>
|
| 561 |
+
<img id=curve src="/evidence/training_curve.png" onerror="this.style.display='none'">
|
| 562 |
+
<div id=curve_missing class=muted style="display:none">(not yet — waiting for first GRPO step)</div>
|
| 563 |
+
</div>
|
| 564 |
+
<div class=card><b>Reward components (terminal vs shaping)</b><br>
|
| 565 |
+
<img id=components src="/evidence/reward_components.png" onerror="this.style.display='none'">
|
| 566 |
+
<div id=components_missing class=muted style="display:none">(populated after a few rollouts — watches verifier hacks)</div>
|
| 567 |
+
</div>
|
| 568 |
+
<div class=card><b>Mid-training checkpoint progression</b><br>
|
| 569 |
+
<img id=ckpt src="/evidence/checkpoint_progression.png" onerror="this.style.display='none'">
|
| 570 |
+
<div id=ckpt_missing class=muted style="display:none">(not yet — waiting for first checkpoint eval)</div>
|
| 571 |
+
</div>
|
| 572 |
+
<div class=card><b>Before vs after summary</b><br>
|
| 573 |
+
<img id=summary src="/evidence/before_after_summary.png" onerror="this.style.display='none'">
|
| 574 |
+
<div id=summary_missing class=muted style="display:none">(generated after post-train eval)</div>
|
| 575 |
+
</div>
|
| 576 |
+
<div class=card><b>Reward distribution: pre vs post</b><br>
|
| 577 |
+
<img id=dist src="/evidence/reward_distribution.png" onerror="this.style.display='none'">
|
| 578 |
+
<div id=dist_missing class=muted style="display:none">(generated after post-train eval)</div>
|
| 579 |
+
</div>
|
| 580 |
+
</div>
|
| 581 |
+
|
| 582 |
+
<h2>Before / after metrics</h2>
|
| 583 |
+
<table id=metrics_table>
|
| 584 |
+
<tr><th>metric</th><th>pre</th><th>post</th><th>Δ</th></tr>
|
| 585 |
+
</table>
|
| 586 |
+
|
| 587 |
+
<h2>Live logs (tail)</h2>
|
| 588 |
+
<pre id=logs>loading…</pre>
|
| 589 |
+
|
| 590 |
+
<script>
|
| 591 |
+
function fmt(v) {
|
| 592 |
+
if (v == null) return '–';
|
| 593 |
+
if (typeof v === 'number') return v.toFixed(3);
|
| 594 |
+
return v;
|
| 595 |
+
}
|
| 596 |
+
function fmtDelta(d) {
|
| 597 |
+
if (d == null || isNaN(d)) return '–';
|
| 598 |
+
const sign = d >= 0 ? '+' : '';
|
| 599 |
+
const cls = d >= 0 ? 'delta-pos' : 'delta-neg';
|
| 600 |
+
return `<span class="${cls}">${sign}${d.toFixed(3)}</span>`;
|
| 601 |
+
}
|
| 602 |
+
|
| 603 |
+
async function refresh() {
|
| 604 |
+
// status
|
| 605 |
+
const s = await fetch('/status').then(r => r.json());
|
| 606 |
+
const pill = document.getElementById('status');
|
| 607 |
+
pill.textContent = s.status;
|
| 608 |
+
pill.className = 'pill ' + ({idle:'',running:'run',finished:'ok',failed:'fail'}[s.status] || '');
|
| 609 |
+
|
| 610 |
+
const meta = document.getElementById('meta');
|
| 611 |
+
meta.innerHTML = '';
|
| 612 |
+
const obj = {
|
| 613 |
+
started_at: s.started_at, finished_at: s.finished_at, error: s.last_error,
|
| 614 |
+
...(s.last_config || {}),
|
| 615 |
+
};
|
| 616 |
+
for (const [k, v] of Object.entries(obj)) {
|
| 617 |
+
if (v == null || v === '') continue;
|
| 618 |
+
const tr = document.createElement('tr');
|
| 619 |
+
tr.innerHTML = `<td><b>${k}</b></td><td><code>${v}</code></td>`;
|
| 620 |
+
meta.appendChild(tr);
|
| 621 |
+
}
|
| 622 |
+
|
| 623 |
+
// metrics
|
| 624 |
+
const m = await fetch('/metrics').then(r => r.json()).catch(() => ({pre:null, post:null}));
|
| 625 |
+
const tbody = document.getElementById('metrics_table');
|
| 626 |
+
tbody.innerHTML = '<tr><th>metric</th><th>pre</th><th>post</th><th>Δ</th></tr>';
|
| 627 |
+
const fields = ['mean_reward', 'success_rate', 'mass_acc', 'channel_acc', 'median_reward'];
|
| 628 |
+
for (const f of fields) {
|
| 629 |
+
const pre = m.pre && m.pre[f];
|
| 630 |
+
const post = m.post && m.post[f];
|
| 631 |
+
const delta = m.delta && m.delta[f];
|
| 632 |
+
const tr = document.createElement('tr');
|
| 633 |
+
tr.innerHTML = `<td><code>${f}</code></td><td>${fmt(pre)}</td><td>${fmt(post)}</td><td>${fmtDelta(delta)}</td>`;
|
| 634 |
+
tbody.appendChild(tr);
|
| 635 |
+
}
|
| 636 |
+
|
| 637 |
+
// bust caches on plots
|
| 638 |
+
const bust = '?t=' + Date.now();
|
| 639 |
+
for (const [imgId, missingId] of [
|
| 640 |
+
['curve', 'curve_missing'],
|
| 641 |
+
['components', 'components_missing'],
|
| 642 |
+
['ckpt', 'ckpt_missing'],
|
| 643 |
+
['summary', 'summary_missing'],
|
| 644 |
+
['dist', 'dist_missing'],
|
| 645 |
+
]) {
|
| 646 |
+
const img = document.getElementById(imgId);
|
| 647 |
+
const miss = document.getElementById(missingId);
|
| 648 |
+
const baseSrc = img.getAttribute('src').split('?')[0];
|
| 649 |
+
const probe = new Image();
|
| 650 |
+
probe.onload = () => { img.src = baseSrc + bust; img.style.display=''; miss.style.display='none'; };
|
| 651 |
+
probe.onerror = () => { img.style.display='none'; miss.style.display=''; };
|
| 652 |
+
probe.src = baseSrc + bust;
|
| 653 |
+
}
|
| 654 |
+
|
| 655 |
+
const logs = await fetch('/logs?tail=200').then(r => r.text());
|
| 656 |
+
document.getElementById('logs').textContent = logs || '(no logs yet)';
|
| 657 |
+
}
|
| 658 |
+
async function startRun() {
|
| 659 |
+
const r = await fetch('/train', {method:'POST'});
|
| 660 |
+
if (!r.ok) alert((await r.json()).detail || 'failed');
|
| 661 |
+
setTimeout(refresh, 500);
|
| 662 |
+
}
|
| 663 |
+
refresh();
|
| 664 |
+
setInterval(refresh, 5000);
|
| 665 |
+
</script>
|
| 666 |
+
</body>
|
| 667 |
+
</html>
|
| 668 |
+
"""
|
| 669 |
+
|
| 670 |
+
|
| 671 |
+
@app.get("/", response_class=HTMLResponse)
|
| 672 |
+
def index() -> HTMLResponse:
|
| 673 |
+
return HTMLResponse(_HTML)
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
@app.get("/health")
|
| 677 |
+
def health() -> Dict[str, str]:
|
| 678 |
+
return {"status": "ok"}
|
| 679 |
+
|
| 680 |
+
|
| 681 |
+
@app.get("/status")
|
| 682 |
+
def status() -> JSONResponse:
|
| 683 |
+
return JSONResponse(STATE.to_dict())
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
@app.get("/metrics")
|
| 687 |
+
def metrics() -> JSONResponse:
|
| 688 |
+
if METRICS_FILE.exists():
|
| 689 |
+
try:
|
| 690 |
+
return JSONResponse(json.loads(METRICS_FILE.read_text()))
|
| 691 |
+
except Exception:
|
| 692 |
+
return JSONResponse({"error": "metrics file unreadable"}, status_code=500)
|
| 693 |
+
return JSONResponse({"pre": None, "post": None, "delta": None})
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
@app.get("/evidence")
|
| 697 |
+
def evidence_index() -> JSONResponse:
|
| 698 |
+
"""List every evidence artifact currently on disk."""
|
| 699 |
+
files = []
|
| 700 |
+
if EVIDENCE_DIR.exists():
|
| 701 |
+
for p in sorted(EVIDENCE_DIR.iterdir()):
|
| 702 |
+
if p.is_file():
|
| 703 |
+
files.append({
|
| 704 |
+
"name": p.name,
|
| 705 |
+
"size": p.stat().st_size,
|
| 706 |
+
"url": f"/evidence/{p.name}",
|
| 707 |
+
})
|
| 708 |
+
return JSONResponse({"dir": str(EVIDENCE_DIR), "files": files})
|
| 709 |
+
|
| 710 |
+
|
| 711 |
+
@app.get("/evidence/{name}")
|
| 712 |
+
def evidence_file(name: str):
|
| 713 |
+
"""Serve a single evidence artifact (PNG/CSV/JSON/MD) by filename."""
|
| 714 |
+
if "/" in name or ".." in name:
|
| 715 |
+
raise HTTPException(status_code=400, detail="invalid name")
|
| 716 |
+
target = EVIDENCE_DIR / name
|
| 717 |
+
if not target.exists() or not target.is_file():
|
| 718 |
+
raise HTTPException(status_code=404, detail=f"{name} not found")
|
| 719 |
+
return FileResponse(target)
|
| 720 |
+
|
| 721 |
+
|
| 722 |
+
@app.get("/logs", response_class=PlainTextResponse)
|
| 723 |
+
def logs(tail: int = 400) -> PlainTextResponse:
|
| 724 |
+
if not LOG_FILE.exists():
|
| 725 |
+
return PlainTextResponse("")
|
| 726 |
+
text = LOG_FILE.read_text()
|
| 727 |
+
lines = text.splitlines()
|
| 728 |
+
return PlainTextResponse("\n".join(lines[-max(tail, 1):]))
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
@app.post("/train")
|
| 732 |
+
def train() -> JSONResponse:
|
| 733 |
+
try:
|
| 734 |
+
_start_training(dict(CONFIG))
|
| 735 |
+
except RuntimeError as exc:
|
| 736 |
+
raise HTTPException(status_code=409, detail=str(exc))
|
| 737 |
+
return JSONResponse({"status": "started", "config": CONFIG})
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
@app.on_event("startup")
|
| 741 |
+
def _maybe_autostart() -> None:
|
| 742 |
+
if CONFIG["autostart"]:
|
| 743 |
+
try:
|
| 744 |
+
_start_training(dict(CONFIG))
|
| 745 |
+
logger.info("autostarted training run")
|
| 746 |
+
except RuntimeError as exc:
|
| 747 |
+
logger.warning("autostart skipped: %s", exc)
|