omega-helix
This project has not described itself yet.
Brought by drakestapleton
omega-helix / tools / distill / pipeline.py
| 1 | """Distillation pipeline orchestrator (`dk-univ`, `seq-univ`, `dna-strand`). |
| 2 | |
| 3 | Coordinates multi-teacher harvesting/generation, fail-closed verifiers, canonical |
| 4 | OpenWALDO exports, pure-Omega OLLMDK01 sparse top-K hybrid CE+KL training, and |
| 5 | Merkle-verified OLLMSP01 specialist DNA strand distillation. |
| 6 | |
| 7 | Python 3 standard library only — zero external deps, zero telemetry. |
| 8 | """ |
| 9 | |
| 10 | from __future__ import annotations |
| 11 | |
| 12 | import datetime |
| 13 | import json |
| 14 | import math |
| 15 | import os |
| 16 | import re |
| 17 | import shutil |
| 18 | import struct |
| 19 | import subprocess |
| 20 | import sys |
| 21 | import threading |
| 22 | import time |
| 23 | import uuid |
| 24 | from pathlib import Path |
| 25 | from typing import Any, Callable |
| 26 | |
| 27 | TOOLS_DIR = Path(__file__).resolve().parents[1] |
| 28 | STUDIO_DIR = TOOLS_DIR / "studio" |
| 29 | OPENWALDO_DIR = TOOLS_DIR / "openwaldo" |
| 30 | for _p in (str(STUDIO_DIR), str(OPENWALDO_DIR)): |
| 31 | if _p not in sys.path: |
| 32 | sys.path.insert(0, _p) |
| 33 | |
| 34 | import catalog as studio_catalog # noqa: E402 |
| 35 | import chain_runner # noqa: E402 |
| 36 | import omega_helix_backend as univ_backend # noqa: E402 |
| 37 | import openwaldo_bridge as ow_bridge # noqa: E402 |
| 38 | |
| 39 | from .harvest import ( |
| 40 | harvest_paths, |
| 41 | read_ollmdk01_header, |
| 42 | write_ollmdk01, |
| 43 | write_openwaldo_export, |
| 44 | ) |
| 45 | from .teachers import ( |
| 46 | LocalHelixTeacher, |
| 47 | OpenAICompatTeacher, |
| 48 | TeacherAdapter, |
| 49 | TeacherRouter, |
| 50 | TraceReplayTeacher, |
| 51 | ) |
| 52 | from .verifiers import BUILTIN_VERIFIERS, VerifierPipeline |
| 53 | |
| 54 | LN2 = math.log(2.0) |
| 55 | DISTILL_MODES = ("dk-univ", "seq-univ", "dna-strand") |
| 56 | |
| 57 | |
| 58 | def utc_now() -> str: |
| 59 | return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") |
| 60 | |
| 61 | |
| 62 | def default_distill_runs_dir() -> Path: |
| 63 | env = os.environ.get("OMEGA_HELIX_DISTILL_DIR") |
| 64 | if env: |
| 65 | return Path(env).expanduser().resolve() |
| 66 | return (chain_runner.default_runs_dir().parent / "distill").resolve() |
| 67 | |
| 68 | |
| 69 | def _file_artifact(path: Path, name: str, kind: str, **extra: Any) -> dict[str, Any]: |
| 70 | sha, size = ow_bridge.file_sha256_and_bytes(path) |
| 71 | rec = {"name": name, "kind": kind, "path": str(path), "sha256": sha, "bytes": size} |
| 72 | rec.update(extra) |
| 73 | return rec |
| 74 | |
| 75 | |
| 76 | def estimate_distill(raw_spec: dict[str, Any]) -> dict[str, Any]: |
| 77 | """Validate and normalize a distillation pipeline specification.""" |
| 78 | if not isinstance(raw_spec, dict): |
| 79 | return {"valid": False, "error": "distillation spec must be a JSON object"} |
| 80 | |
| 81 | mode = str(raw_spec.get("mode", "dk-univ")).strip().lower() |
| 82 | if mode not in DISTILL_MODES: |
| 83 | return {"valid": False, "error": f"mode {mode!r} must be one of {DISTILL_MODES}"} |
| 84 | |
| 85 | arch = str(raw_spec.get("arch", "qwen3" if mode != "dna-strand" else "gpt")).strip().lower() |
| 86 | if arch not in univ_backend.ARCHES: |
| 87 | return {"valid": False, "error": f"arch {arch!r} must be one of {univ_backend.ARCHES}"} |
| 88 | |
| 89 | try: |
| 90 | V = int(raw_spec.get("V", 256 if mode == "dk-univ" else 256)) |
| 91 | T = int(raw_spec.get("T", 16)) |
| 92 | D = int(raw_spec.get("D", 32)) |
| 93 | H = int(raw_spec.get("H", 2)) |
| 94 | H_KV = int(raw_spec.get("H_KV", H)) |
| 95 | F = int(raw_spec.get("F", 64)) |
| 96 | L = int(raw_spec.get("L", 2)) |
| 97 | B = int(raw_spec.get("B", 2)) |
| 98 | K = int(raw_spec.get("K", min(8, V))) |
| 99 | alpha = float(raw_spec.get("alpha", 0.7)) |
| 100 | temperature = float(raw_spec.get("temperature", 1.5)) |
| 101 | steps = int(raw_spec.get("steps", 12)) |
| 102 | lr_micro = int(raw_spec.get("lr_micro", 3000)) |
| 103 | seed = int(raw_spec.get("seed", 42)) |
| 104 | held_mod = int(raw_spec.get("held_mod", 5)) |
| 105 | add_layers = int(raw_spec.get("add_layers", 1)) |
| 106 | except (TypeError, ValueError) as exc: |
| 107 | return {"valid": False, "error": f"invalid numeric parameter: {exc}"} |
| 108 | |
| 109 | if V < 2: |
| 110 | return {"valid": False, "error": "V must be >= 2"} |
| 111 | if T < 4 or D < 8 or H < 1 or D % H != 0: |
| 112 | return {"valid": False, "error": "require T >= 4, D >= 8, H >= 1, D % H == 0"} |
| 113 | if H_KV < 1 or H % H_KV != 0: |
| 114 | return {"valid": False, "error": "require H_KV >= 1 and H % H_KV == 0"} |
| 115 | if F < 8 or L < 1 or B < 1 or steps < 1: |
| 116 | return {"valid": False, "error": "require F >= 8, L >= 1, B >= 1, steps >= 1"} |
| 117 | if K < 1 or K > 64 or K > V: |
| 118 | return {"valid": False, "error": f"require 1 <= K <= min(64, V={V}), got {K}"} |
| 119 | if not (0.0 <= alpha <= 1.0): |
| 120 | return {"valid": False, "error": "require 0.0 <= alpha <= 1.0"} |
| 121 | if temperature <= 0.0: |
| 122 | return {"valid": False, "error": "require temperature > 0.0"} |
| 123 | |
| 124 | raw_vers = raw_spec.get("verifiers") |
| 125 | if raw_vers is None: |
| 126 | verifiers = ["nonempty"] |
| 127 | elif isinstance(raw_vers, str): |
| 128 | verifiers = [v.strip() for v in raw_vers.split(",") if v.strip()] or ["nonempty"] |
| 129 | elif isinstance(raw_vers, list): |
| 130 | verifiers = [str(v).strip() for v in raw_vers if str(v).strip()] or ["nonempty"] |
| 131 | else: |
| 132 | return {"valid": False, "error": "verifiers must be a list or comma-separated string"} |
| 133 | for v in verifiers: |
| 134 | if v not in BUILTIN_VERIFIERS: |
| 135 | return {"valid": False, "error": f"unknown verifier {v!r}; supported: {BUILTIN_VERIFIERS}"} |
| 136 | |
| 137 | strategy = str(raw_spec.get("router_strategy", "round_robin")).strip() |
| 138 | if strategy not in ("round_robin", "ensemble_best_of", "fallback"): |
| 139 | return {"valid": False, "error": f"invalid router_strategy {strategy!r}"} |
| 140 | |
| 141 | tokenizer = str(raw_spec.get("tokenizer", "byte")).strip().lower() |
| 142 | if tokenizer not in ("byte", "bpe", "u32"): |
| 143 | return {"valid": False, "error": f"invalid tokenizer {tokenizer!r}"} |
| 144 | |
| 145 | teachers = raw_spec.get("teachers") or [] |
| 146 | if not isinstance(teachers, list): |
| 147 | return {"valid": False, "error": "teachers must be a list"} |
| 148 | trace_paths = raw_spec.get("trace_paths") or [] |
| 149 | if isinstance(trace_paths, str): |
| 150 | trace_paths = [trace_paths] |
| 151 | prompts = raw_spec.get("prompts") or [] |
| 152 | if isinstance(prompts, str): |
| 153 | prompts = [p for p in prompts.splitlines() if p.strip()] |
| 154 | |
| 155 | spec = { |
| 156 | "name": str(raw_spec.get("name") or f"distill-{mode}"), |
| 157 | "mode": mode, |
| 158 | "arch": arch, |
| 159 | "tokenizer": tokenizer, |
| 160 | "V": V, |
| 161 | "T": T, |
| 162 | "D": D, |
| 163 | "H": H, |
| 164 | "H_KV": H_KV, |
| 165 | "F": F, |
| 166 | "L": L, |
| 167 | "B": B, |
| 168 | "K": K, |
| 169 | "alpha": alpha, |
| 170 | "temperature": temperature, |
| 171 | "steps": steps, |
| 172 | "lr_micro": lr_micro, |
| 173 | "seed": seed, |
| 174 | "held_mod": max(2, held_mod), |
| 175 | "add_layers": max(1, add_layers), |
| 176 | "verifiers": verifiers, |
| 177 | "regex_pattern": str(raw_spec.get("regex_pattern") or ""), |
| 178 | "json_required_keys": list(raw_spec.get("json_required_keys") or []), |
| 179 | "min_chars": int(raw_spec.get("min_chars", 1)), |
| 180 | "router_strategy": strategy, |
| 181 | "teachers": teachers, |
| 182 | "trace_paths": [str(p) for p in trace_paths], |
| 183 | "prompts": [str(p) for p in prompts], |
| 184 | "dk_path": str(raw_spec.get("dk_path") or ""), |
| 185 | "teacher_ckpt": str(raw_spec.get("teacher_ckpt") or ""), |
| 186 | "tokens_bin": str(raw_spec.get("tokens_bin") or ""), |
| 187 | "student_init_ck": str(raw_spec.get("student_init_ck") or ""), |
| 188 | "max_seqs": int(raw_spec.get("max_seqs", 64)), |
| 189 | "max_tokens": int(raw_spec.get("max_tokens", 128)), |
| 190 | "skip_dcheck": bool(raw_spec.get("skip_dcheck", False)), |
| 191 | "export_hf": bool(raw_spec.get("export_hf", False)), |
| 192 | "hf_dtype": str(raw_spec.get("hf_dtype", "f32")), |
| 193 | "export_gguf": bool(raw_spec.get("export_gguf", False)), |
| 194 | "flags": raw_spec.get("flags"), |
| 195 | "use_starter_fallback": bool(raw_spec.get("use_starter_fallback", True)), |
| 196 | "license": str(raw_spec.get("license") or "Apache-2.0"), |
| 197 | "corpus_name": str(raw_spec.get("corpus_name") or "distilled-traces"), |
| 198 | } |
| 199 | return {"valid": True, "error": "", "spec": spec} |
| 200 | |
| 201 | |
| 202 | class DistillRun: |
| 203 | """Thread-safe state + SSE event bus for a single distillation run.""" |
| 204 | |
| 205 | def __init__(self, run_id: str, spec: dict[str, Any], run_dir: Path) -> None: |
| 206 | self.run_id = run_id |
| 207 | self.spec = spec |
| 208 | self.run_dir = run_dir |
| 209 | self._lock = threading.Lock() |
| 210 | self._cond = threading.Condition(self._lock) |
| 211 | self._events: list[dict[str, Any]] = [] |
| 212 | self._seq = 0 |
| 213 | self._stop_event = threading.Event() |
| 214 | self._active_proc: subprocess.Popen[bytes] | None = None |
| 215 | |
| 216 | self.status = "queued" |
| 217 | self.stage = "queued" |
| 218 | self.stages: list[dict[str, Any]] = [] |
| 219 | self.started_at = utc_now() |
| 220 | self.finished_at = "" |
| 221 | self.latest_loss: float | None = None |
| 222 | self.latest_ce_loss: float | None = None |
| 223 | self.latest_kl_loss: float | None = None |
| 224 | self.latest_bpb: float | None = None |
| 225 | self.metrics: list[dict[str, Any]] = [] |
| 226 | self.artifacts: list[dict[str, Any]] = [] |
| 227 | self.verify_stats: dict[str, Any] = {} |
| 228 | self.dcheck_receipt: dict[str, Any] | None = None |
| 229 | self.bom: dict[str, Any] | None = None |
| 230 | self.error = "" |
| 231 | |
| 232 | def emit(self, _kind: str, **payload: Any) -> dict[str, Any]: |
| 233 | with self._cond: |
| 234 | self._seq += 1 |
| 235 | term: str | None = None |
| 236 | if _kind in ("done", "error", "stopped"): |
| 237 | term = _kind |
| 238 | self.finished_at = utc_now() |
| 239 | if _kind == "error": |
| 240 | self.error = str(payload.get("error", "distillation failed")) |
| 241 | clean_payload = dict(payload) |
| 242 | if "kind" in clean_payload: |
| 243 | clean_payload["artifact_kind"] = clean_payload.pop("kind") |
| 244 | ev = {"seq": self._seq, "ts": utc_now(), "kind": _kind, **clean_payload} |
| 245 | self._events.append(ev) |
| 246 | if _kind == "stage": |
| 247 | self.stage = str(clean_payload.get("stage", self.stage)) |
| 248 | self.stages.append({ |
| 249 | "stage": self.stage, |
| 250 | "label": clean_payload.get("label", self.stage), |
| 251 | "ts": ev["ts"], |
| 252 | "status": clean_payload.get("status", "active"), |
| 253 | }) |
| 254 | elif _kind == "verify": |
| 255 | self.verify_stats = dict(clean_payload) |
| 256 | elif _kind == "dcheck": |
| 257 | self.dcheck_receipt = dict(clean_payload) |
| 258 | elif _kind == "metric": |
| 259 | self.metrics.append(clean_payload) |
| 260 | if clean_payload.get("loss") is not None: |
| 261 | self.latest_loss = float(clean_payload["loss"]) |
| 262 | if clean_payload.get("ce_loss") is not None: |
| 263 | self.latest_ce_loss = float(clean_payload["ce_loss"]) |
| 264 | if clean_payload.get("kl_loss") is not None: |
| 265 | self.latest_kl_loss = float(clean_payload["kl_loss"]) |
| 266 | if clean_payload.get("bpb") is not None: |
| 267 | self.latest_bpb = float(clean_payload["bpb"]) |
| 268 | elif _kind == "artifact": |
| 269 | self.artifacts.append(dict(payload)) |
| 270 | if term is not None: |
| 271 | self.status = term |
| 272 | self._cond.notify_all() |
| 273 | return ev |
| 274 | |
| 275 | def iter_events(self, start_seq: int = 0, poll_timeout: float = 10.0): |
| 276 | cursor = start_seq |
| 277 | while True: |
| 278 | with self._cond: |
| 279 | while cursor >= len(self._events) and self.status in ("queued", "running"): |
| 280 | self._cond.wait(timeout=poll_timeout) |
| 281 | if cursor >= len(self._events) and self.status in ("queued", "running"): |
| 282 | yield None |
| 283 | batch = self._events[cursor:] |
| 284 | done = self.status not in ("queued", "running") |
| 285 | for ev in batch: |
| 286 | cursor = ev["seq"] |
| 287 | yield ev |
| 288 | if done and cursor >= len(self._events): |
| 289 | break |
| 290 | |
| 291 | def request_stop(self) -> bool: |
| 292 | self._stop_event.set() |
| 293 | with self._lock: |
| 294 | proc = self._active_proc |
| 295 | if proc is not None and proc.poll() is None: |
| 296 | try: |
| 297 | proc.terminate() |
| 298 | except OSError: |
| 299 | pass |
| 300 | return True |
| 301 | return self.status in ("queued", "running") |
| 302 | |
| 303 | def summary(self) -> dict[str, Any]: |
| 304 | with self._lock: |
| 305 | return { |
| 306 | "run_id": self.run_id, |
| 307 | "name": self.spec.get("name", self.run_id), |
| 308 | "mode": self.spec.get("mode", "dk-univ"), |
| 309 | "arch": self.spec.get("arch", "qwen3"), |
| 310 | "status": self.status, |
| 311 | "stage": self.stage, |
| 312 | "started_at": self.started_at, |
| 313 | "finished_at": self.finished_at, |
| 314 | "latest_loss": self.latest_loss, |
| 315 | "latest_ce_loss": self.latest_ce_loss, |
| 316 | "latest_kl_loss": self.latest_kl_loss, |
| 317 | "verify_stats": self.verify_stats, |
| 318 | } |
| 319 | |
| 320 | def to_dict(self) -> dict[str, Any]: |
| 321 | with self._lock: |
| 322 | return { |
| 323 | "run_id": self.run_id, |
| 324 | "spec": self.spec, |
| 325 | "status": self.status, |
| 326 | "stage": self.stage, |
| 327 | "stages": list(self.stages), |
| 328 | "started_at": self.started_at, |
| 329 | "finished_at": self.finished_at, |
| 330 | "latest_loss": self.latest_loss, |
| 331 | "latest_ce_loss": self.latest_ce_loss, |
| 332 | "latest_kl_loss": self.latest_kl_loss, |
| 333 | "latest_bpb": self.latest_bpb, |
| 334 | "metrics": list(self.metrics), |
| 335 | "artifacts": list(self.artifacts), |
| 336 | "verify_stats": self.verify_stats, |
| 337 | "dcheck_receipt": self.dcheck_receipt, |
| 338 | "bom": self.bom, |
| 339 | "error": self.error, |
| 340 | "run_dir": str(self.run_dir), |
| 341 | } |
| 342 | |
| 343 | def save_state(self, override_status: str | None = None) -> None: |
| 344 | self.run_dir.mkdir(parents=True, exist_ok=True) |
| 345 | doc = self.to_dict() |
| 346 | if override_status is not None: |
| 347 | doc["status"] = override_status |
| 348 | p = self.run_dir / "distill_state.json" |
| 349 | tmp = self.run_dir / ".distill_state.json.tmp" |
| 350 | tmp.write_text(json.dumps(doc, indent=2) + "\n", encoding="utf-8") |
| 351 | os.replace(tmp, p) |
| 352 | |
| 353 | @classmethod |
| 354 | def load_from_dir(cls, run_dir: Path) -> "DistillRun | None": |
| 355 | state_path = run_dir / "distill_state.json" |
| 356 | if not state_path.is_file(): |
| 357 | return None |
| 358 | try: |
| 359 | doc = json.loads(state_path.read_text(encoding="utf-8")) |
| 360 | except Exception: |
| 361 | return None |
| 362 | run = cls(doc["run_id"], doc.get("spec", {}), run_dir) |
| 363 | run.status = doc.get("status", "done") |
| 364 | if run.status in ("queued", "running"): |
| 365 | run.status = "interrupted" |
| 366 | run.stage = doc.get("stage", "done") |
| 367 | run.stages = doc.get("stages", []) |
| 368 | run.started_at = doc.get("started_at", "") |
| 369 | run.finished_at = doc.get("finished_at", "") |
| 370 | run.latest_loss = doc.get("latest_loss") |
| 371 | run.latest_ce_loss = doc.get("latest_ce_loss") |
| 372 | run.latest_kl_loss = doc.get("latest_kl_loss") |
| 373 | run.latest_bpb = doc.get("latest_bpb") |
| 374 | run.metrics = doc.get("metrics", []) |
| 375 | run.artifacts = doc.get("artifacts", []) |
| 376 | run.verify_stats = doc.get("verify_stats", {}) |
| 377 | run.dcheck_receipt = doc.get("dcheck_receipt") |
| 378 | run.bom = doc.get("bom") |
| 379 | run.error = doc.get("error", "") |
| 380 | return run |
| 381 | |
| 382 | |
| 383 | class DistillManager: |
| 384 | """Manages distillation runs (`dk-univ`, `seq-univ`, `dna-strand`) + persistence.""" |
| 385 | |
| 386 | def __init__( |
| 387 | self, |
| 388 | runs_dir: str | Path | None = None, |
| 389 | bin_dir: str | Path | None = None, |
| 390 | root: str | Path | None = None, |
| 391 | ) -> None: |
| 392 | self.runs_dir = Path(runs_dir).expanduser().resolve() if runs_dir else default_distill_runs_dir() |
| 393 | self.runs_dir.mkdir(parents=True, exist_ok=True) |
| 394 | self.bin_dir = Path(bin_dir).expanduser().resolve() if bin_dir else None |
| 395 | self.root = studio_catalog.repo_root(root) |
| 396 | self._lock = threading.Lock() |
| 397 | self._runs: dict[str, DistillRun] = {} |
| 398 | self._load_existing() |
| 399 | |
| 400 | def _load_existing(self) -> None: |
| 401 | if not self.runs_dir.is_dir(): |
| 402 | return |
| 403 | for sub in sorted(self.runs_dir.iterdir()): |
| 404 | if sub.is_dir(): |
| 405 | r = DistillRun.load_from_dir(sub) |
| 406 | if r is not None: |
| 407 | self._runs[r.run_id] = r |
| 408 | |
| 409 | def list_runs(self) -> list[dict[str, Any]]: |
| 410 | with self._lock: |
| 411 | runs = list(self._runs.values()) |
| 412 | runs.sort(key=lambda r: r.started_at, reverse=True) |
| 413 | return [r.summary() for r in runs] |
| 414 | |
| 415 | def get_run(self, run_id: str) -> DistillRun | None: |
| 416 | with self._lock: |
| 417 | r = self._runs.get(run_id) |
| 418 | if r is not None: |
| 419 | return r |
| 420 | cand = self.runs_dir / run_id |
| 421 | if cand.is_dir() and (cand / "distill_state.json").is_file(): |
| 422 | loaded = DistillRun.load_from_dir(cand.resolve()) |
| 423 | if loaded is not None: |
| 424 | with self._lock: |
| 425 | self._runs[loaded.run_id] = loaded |
| 426 | return loaded |
| 427 | return None |
| 428 | |
| 429 | def start_run(self, raw_spec: dict[str, Any], wait: bool = False) -> DistillRun: |
| 430 | est = estimate_distill(raw_spec) |
| 431 | if not est["valid"]: |
| 432 | raise ValueError(est["error"] or "invalid distill spec") |
| 433 | spec = est["spec"] |
| 434 | slug = re.sub(r"[^a-zA-Z0-9_-]+", "-", spec["name"]).strip("-").lower()[:24] or "distill" |
| 435 | ts = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%d-%H%M%S") |
| 436 | run_id = f"{ts}-{slug}-{uuid.uuid4().hex[:6]}" |
| 437 | run_dir = self.runs_dir / run_id |
| 438 | run_dir.mkdir(parents=True, exist_ok=True) |
| 439 | (run_dir / "distill_spec.json").write_text(json.dumps(spec, indent=2) + "\n", encoding="utf-8") |
| 440 | |
| 441 | run = DistillRun(run_id, spec, run_dir) |
| 442 | with self._lock: |
| 443 | self._runs[run_id] = run |
| 444 | run.save_state() |
| 445 | |
| 446 | if wait: |
| 447 | self._execute_run(run) |
| 448 | else: |
| 449 | t = threading.Thread(target=self._execute_run, args=(run,), name=f"distill-{run_id}", daemon=True) |
| 450 | t.start() |
| 451 | return run |
| 452 | |
| 453 | def stop_run(self, run_id: str) -> bool: |
| 454 | r = self.get_run(run_id) |
| 455 | if not r: |
| 456 | return False |
| 457 | return r.request_stop() |
| 458 | |
| 459 | def _run_stream( |
| 460 | self, |
| 461 | run: DistillRun, |
| 462 | argv: list[str], |
| 463 | stage: str, |
| 464 | line_cb: Callable[[str], None] | None = None, |
| 465 | ) -> str: |
| 466 | if run._stop_event.is_set(): |
| 467 | raise RuntimeError("distillation run stopped") |
| 468 | proc = subprocess.Popen( |
| 469 | argv, |
| 470 | stdout=subprocess.PIPE, |
| 471 | stderr=subprocess.STDOUT, |
| 472 | text=True, |
| 473 | bufsize=1, |
| 474 | ) |
| 475 | with run._lock: |
| 476 | run._active_proc = proc # type: ignore[assignment] |
| 477 | lines: list[str] = [] |
| 478 | assert proc.stdout is not None |
| 479 | try: |
| 480 | for line in proc.stdout: |
| 481 | clean = line.rstrip("\r\n") |
| 482 | lines.append(clean) |
| 483 | if clean: |
| 484 | run.emit("log", stage=stage, text=clean) |
| 485 | if line_cb is not None and clean: |
| 486 | line_cb(clean) |
| 487 | if run._stop_event.is_set() and proc.poll() is None: |
| 488 | proc.terminate() |
| 489 | rc = proc.wait() |
| 490 | finally: |
| 491 | if proc.stdout is not None: |
| 492 | proc.stdout.close() |
| 493 | with run._lock: |
| 494 | run._active_proc = None |
| 495 | if run._stop_event.is_set(): |
| 496 | raise RuntimeError("distillation run stopped") |
| 497 | out = "\n".join(lines) |
| 498 | if rc != 0: |
| 499 | tail = lines[-1] if lines else f"exit {rc}" |
| 500 | raise RuntimeError(f"command {Path(argv[0]).name} exited {rc}: {tail}") |
| 501 | return out |
| 502 | |
| 503 | def _build_teachers( |
| 504 | self, |
| 505 | spec: dict[str, Any], |
| 506 | ollm_univ_bin: Path | None, |
| 507 | ) -> tuple[list[TeacherAdapter], list[dict[str, Any]]]: |
| 508 | adapters: list[TeacherAdapter] = [] |
| 509 | meta: list[dict[str, Any]] = [] |
| 510 | for idx, tspec in enumerate(spec.get("teachers", [])): |
| 511 | if not isinstance(tspec, dict): |
| 512 | continue |
| 513 | kind = str(tspec.get("kind") or "openai_compat").strip().lower() |
| 514 | if kind in ("openai", "openai_compat", "http"): |
| 515 | base_url = str(tspec.get("base_url") or "http://127.0.0.1:18090/v1") |
| 516 | model = str(tspec.get("model") or "q36-35b") |
| 517 | t = OpenAICompatTeacher( |
| 518 | base_url, |
| 519 | model, |
| 520 | name=str(tspec.get("name") or f"teacher-{idx}:{model}"), |
| 521 | api_key=str(tspec.get("api_key") or ""), |
| 522 | timeout=float(tspec.get("timeout", 60.0)), |
| 523 | request_logprobs=bool(tspec.get("request_logprobs", True)), |
| 524 | ) |
| 525 | adapters.append(t) |
| 526 | meta.append({"name": t.name, "kind": "openai_compat", "base_url": t.base_url, "model": model}) |
| 527 | elif kind == "local_helix": |
| 528 | ckpt = tspec.get("ckpt_path") or spec.get("teacher_ckpt") |
| 529 | if not ckpt or ollm_univ_bin is None: |
| 530 | raise ValueError("local_helix teacher requires ckpt_path and ollm-univ binary") |
| 531 | t = LocalHelixTeacher(ckpt, ollm_univ_bin, name=str(tspec.get("name") or f"helix-{idx}")) |
| 532 | adapters.append(t) |
| 533 | meta.append({"name": t.name, "kind": "local_helix", "ckpt_path": str(Path(ckpt).resolve())}) |
| 534 | elif kind == "trace_replay": |
| 535 | tpaths = tspec.get("trace_paths") or spec.get("trace_paths") or [] |
| 536 | if not tpaths: |
| 537 | raise ValueError("trace_replay teacher requires trace_paths") |
| 538 | t = TraceReplayTeacher(tpaths, name=str(tspec.get("name") or f"trace-{idx}")) |
| 539 | adapters.append(t) |
| 540 | meta.append({"name": t.name, "kind": "trace_replay", "trace_paths": [str(x) for x in tpaths]}) |
| 541 | else: |
| 542 | raise ValueError(f"unsupported teacher kind {kind!r}") |
| 543 | return adapters, meta |
| 544 | |
| 545 | def _collect_and_verify( |
| 546 | self, |
| 547 | run: DistillRun, |
| 548 | ollm_univ_bin: Path | None, |
| 549 | ) -> dict[str, Any]: |
| 550 | spec = run.spec |
| 551 | run_dir = run.run_dir |
| 552 | records: list[dict[str, Any]] = [] |
| 553 | provenance_inputs: list[dict[str, Any]] = [] |
| 554 | |
| 555 | run.emit("stage", stage="harvest", label="Harvesting & Querying Teacher Network") |
| 556 | if spec["trace_paths"]: |
| 557 | harv = harvest_paths( |
| 558 | spec["trace_paths"], |
| 559 | source_tag=spec["corpus_name"], |
| 560 | license_id=spec["license"], |
| 561 | ) |
| 562 | records.extend(harv["records"]) |
| 563 | provenance_inputs.extend(harv["inputs"]) |
| 564 | run.emit("harvest", **harv["stats"]) |
| 565 | |
| 566 | adapters, teacher_meta = self._build_teachers(spec, ollm_univ_bin) |
| 567 | router_summary: list[dict[str, Any]] = [] |
| 568 | if adapters and spec["prompts"]: |
| 569 | router = TeacherRouter( |
| 570 | adapters, |
| 571 | strategy=spec["router_strategy"], |
| 572 | verifiers=spec["verifiers"], |
| 573 | ) |
| 574 | for p_idx, prompt_txt in enumerate(spec["prompts"]): |
| 575 | msgs = [{"role": "user", "content": prompt_txt}] |
| 576 | gen = router.generate_best( |
| 577 | msgs, |
| 578 | max_tokens=spec["max_tokens"], |
| 579 | temperature=spec["temperature"], |
| 580 | top_logprobs=spec["K"], |
| 581 | ) |
| 582 | full_msgs = [ |
| 583 | {"role": "user", "content": prompt_txt}, |
| 584 | {"role": "assistant", "content": gen["text"]}, |
| 585 | ] |
| 586 | rendered = f"user: {prompt_txt}\nassistant: {gen['text']}" |
| 587 | p_prefix = f"user: {prompt_txt}\nassistant: ".encode("utf-8") |
| 588 | tot_b = len(rendered.encode("utf-8")) |
| 589 | records.append({ |
| 590 | "kind": "conversation", |
| 591 | "messages": full_msgs, |
| 592 | "text": json.dumps({"messages": full_msgs}, ensure_ascii=False), |
| 593 | "rendered_text": rendered, |
| 594 | "assistant_text": gen["text"], |
| 595 | "assistant_spans": [[len(p_prefix), tot_b]], |
| 596 | "source": f"teacher:{gen.get('teacher_name') or gen.get('model')}", |
| 597 | "license": spec["license"], |
| 598 | "teacher_model": gen.get("model", ""), |
| 599 | "logprobs": gen.get("logprobs"), |
| 600 | "sha256": gen["sha256"], |
| 601 | }) |
| 602 | run.emit("log", stage="harvest", text=f"teacher[{gen.get('teacher_name')}] prompt {p_idx + 1}/{len(spec['prompts'])} ({gen['latency_ms']} ms)") |
| 603 | router_summary = router.summary() |
| 604 | |
| 605 | if not records and spec["use_starter_fallback"]: |
| 606 | # Fallback to local verified starter material inside the repo |
| 607 | cands = [ |
| 608 | self.root / "tools" / "openwaldo", |
| 609 | self.root / "docs" / "DISTILLATION.md", |
| 610 | self.root / "README.md", |
| 611 | ] |
| 612 | existing = [p for p in cands if p.exists()] |
| 613 | if existing: |
| 614 | harv = harvest_paths(existing[:1], source_tag="omega-helix-starter", license_id="Apache-2.0") |
| 615 | records.extend(harv["records"]) |
| 616 | provenance_inputs.extend(harv["inputs"]) |
| 617 | run.emit("harvest", **harv["stats"]) |
| 618 | |
| 619 | if not records: |
| 620 | raise RuntimeError("no records harvested or generated from teachers") |
| 621 | |
| 622 | run.emit("stage", stage="verify", label="Running Fail-Closed Verifier Gate") |
| 623 | vpipe = VerifierPipeline( |
| 624 | spec["verifiers"], |
| 625 | regex_pattern=spec["regex_pattern"] or None, |
| 626 | json_required_keys=spec["json_required_keys"] or None, |
| 627 | min_chars=spec["min_chars"], |
| 628 | ) |
| 629 | v_res = vpipe.filter_records(records) |
| 630 | run.emit("verify", **v_res["stats"]) |
| 631 | if not v_res["accepted"]: |
| 632 | raise RuntimeError( |
| 633 | f"verifier pipeline rejected all {len(records)} records (verifiers={spec['verifiers']})" |
| 634 | ) |
| 635 | |
| 636 | exp_dir = run_dir / "distilled_export" |
| 637 | exp_meta = write_openwaldo_export( |
| 638 | v_res["accepted"], |
| 639 | exp_dir, |
| 640 | corpus_name=spec["corpus_name"], |
| 641 | license_id=spec["license"], |
| 642 | source_tag=spec["corpus_name"], |
| 643 | ) |
| 644 | run.emit("artifact", **_file_artifact(Path(exp_meta["export_json"]), "distilled_export/EXPORT.json", "openwaldo_export")) |
| 645 | return { |
| 646 | "accepted": v_res["accepted"], |
| 647 | "verify_stats": v_res["stats"], |
| 648 | "export_meta": exp_meta, |
| 649 | "export_dir": exp_dir, |
| 650 | "teacher_meta": teacher_meta, |
| 651 | "router_summary": router_summary, |
| 652 | "input_shas": provenance_inputs, |
| 653 | } |
| 654 | |
| 655 | def _build_dk_from_records( |
| 656 | self, |
| 657 | records: list[dict[str, Any]], |
| 658 | out_path: Path, |
| 659 | *, |
| 660 | V: int, |
| 661 | K: int, |
| 662 | T: int, |
| 663 | max_seqs: int, |
| 664 | alpha_smooth: float = 0.08, |
| 665 | ) -> dict[str, Any]: |
| 666 | """Convert verified traces/logprobs into dense+masked OLLMDK01 teacher windows.""" |
| 667 | dk_records: list[dict[str, Any]] = [] |
| 668 | for rec in records: |
| 669 | rendered = str(rec.get("rendered_text") or rec.get("text") or "") |
| 670 | raw = rendered.encode("utf-8", errors="replace") |
| 671 | if len(raw) < T + 1: |
| 672 | # Pad cleanly with newlines if snippet is shorter than T+1 |
| 673 | raw = raw + b"\n" * (T + 1 - len(raw)) |
| 674 | spans = rec.get("assistant_spans") or [[0, len(raw)]] |
| 675 | byte_mask = bytearray(len(raw)) |
| 676 | for sp in spans: |
| 677 | lo = max(0, int(sp[0])) |
| 678 | hi = min(len(raw), int(sp[1])) |
| 679 | for bi in range(lo, hi): |
| 680 | byte_mask[bi] = 1 |
| 681 | # Map bytes into [0, V) and walk stride-T windows |
| 682 | for off in range(0, len(raw) - T, T): |
| 683 | if len(dk_records) >= max_seqs: |
| 684 | break |
| 685 | toks = [b % V for b in raw[off : off + T + 1]] |
| 686 | # Mask tracks target positions tokens[pos + 1] |
| 687 | msk = [int(byte_mask[off + p + 1]) for p in range(T)] |
| 688 | if sum(msk) == 0: |
| 689 | msk[-1] = 1 # Ensure at least one supervised target position in window |
| 690 | top_ids: list[int] = [] |
| 691 | top_probs: list[float] = [] |
| 692 | for p in range(T): |
| 693 | yt = toks[p + 1] |
| 694 | # Put primary target mass (1 - alpha_smooth) + K-1 smooth candidates mod V |
| 695 | ids_p = [yt] |
| 696 | cur = (yt + 1) % V |
| 697 | while len(ids_p) < K: |
| 698 | if cur not in ids_p: |
| 699 | ids_p.append(cur) |
| 700 | cur = (cur + 1) % V |
| 701 | if K == 1: |
| 702 | prs_p = [1.0] |
| 703 | else: |
| 704 | rem_p = alpha_smooth / float(K - 1) |
| 705 | prs_p = [1.0 - alpha_smooth] + [rem_p] * (K - 1) |
| 706 | top_ids.extend(ids_p) |
| 707 | top_probs.extend(prs_p) |
| 708 | dk_records.append({ |
| 709 | "tokens": toks, |
| 710 | "mask": msk, |
| 711 | "top_ids": top_ids, |
| 712 | "top_probs": top_probs, |
| 713 | }) |
| 714 | if len(dk_records) >= max_seqs: |
| 715 | break |
| 716 | if not dk_records: |
| 717 | raise RuntimeError("could not build any OLLMDK01 windows from harvested records") |
| 718 | return write_ollmdk01(dk_records, out_path, V=V, K=K, T=T) |
| 719 | |
| 720 | def _run_dk_univ(self, run: DistillRun, bins: dict[str, Path]) -> dict[str, Any]: |
| 721 | spec = run.spec |
| 722 | run_dir = run.run_dir |
| 723 | V, T, D, H, H_KV, F, L, B = ( |
| 724 | spec["V"], spec["T"], spec["D"], spec["H"], spec["H_KV"], spec["F"], spec["L"], spec["B"] |
| 725 | ) |
| 726 | K = spec["K"] |
| 727 | alpha_micro = int(round(spec["alpha"] * 1_000_000)) |
| 728 | temp_milli = max(1, int(round(spec["temperature"] * 1000))) |
| 729 | univ_bin = str(bins["ollm_univ"]) |
| 730 | |
| 731 | collected: dict[str, Any] | None = None |
| 732 | dk_path = run_dir / "teacher.dk" |
| 733 | tokens_path: Path | None = None |
| 734 | |
| 735 | if spec["dk_path"]: |
| 736 | src_dk = Path(spec["dk_path"]).expanduser().resolve() |
| 737 | shutil.copy2(src_dk, dk_path) |
| 738 | dk_hdr = read_ollmdk01_header(dk_path) |
| 739 | run.emit("log", stage="harvest", text=f"Verified external OLLMDK01 shard: N={dk_hdr['N']} K={dk_hdr['K']} FNV={dk_hdr['fnv_hex']}") |
| 740 | elif spec["teacher_ckpt"]: |
| 741 | run.emit("stage", stage="harvest", label="Emitting Sparse Top-K Shard from Teacher Helix Checkpoint") |
| 742 | t_ck = Path(spec["teacher_ckpt"]).expanduser().resolve() |
| 743 | if spec["tokens_bin"]: |
| 744 | tokens_path = Path(spec["tokens_bin"]).expanduser().resolve() |
| 745 | else: |
| 746 | collected = self._collect_and_verify(run, bins.get("ollm_univ")) |
| 747 | # Concatenate accepted texts cleanly as byte tokens % V |
| 748 | tokens_path = run_dir / "teacher_tokens.bin" |
| 749 | raw_chunks = [str(r.get("rendered_text") or r["text"]).encode("utf-8", errors="replace") for r in collected["accepted"]] |
| 750 | raw_bytes = b"\n".join(raw_chunks) |
| 751 | if len(raw_bytes) <= T + 2: |
| 752 | raw_bytes = raw_bytes * ((T + 8) // max(1, len(raw_bytes)) + 1) |
| 753 | if V <= 256: |
| 754 | tokens_path.write_bytes(bytes(b % V for b in raw_bytes)) |
| 755 | else: |
| 756 | tokens_path.write_bytes(b"".join(struct.pack("<H", b % V) for b in raw_bytes)) |
| 757 | t_adapter = LocalHelixTeacher(t_ck, univ_bin) |
| 758 | dk_hdr = t_adapter.emit_dk(tokens_path, dk_path, K=K, temp=spec["temperature"], max_seqs=spec["max_seqs"]) |
| 759 | run.emit("log", stage="harvest", text=f"dkemit wrote N={dk_hdr['N']} K={dk_hdr['K']} FNV={dk_hdr['fnv_hex']}") |
| 760 | else: |
| 761 | collected = self._collect_and_verify(run, bins.get("ollm_univ")) |
| 762 | dk_hdr = self._build_dk_from_records( |
| 763 | collected["accepted"], |
| 764 | dk_path, |
| 765 | V=V, |
| 766 | K=K, |
| 767 | T=T, |
| 768 | max_seqs=spec["max_seqs"], |
| 769 | ) |
| 770 | run.emit("log", stage="harvest", text=f"Packed OLLMDK01 from harvested traces: N={dk_hdr['N']} K={dk_hdr['K']} FNV={dk_hdr['fnv_hex']}") |
| 771 | |
| 772 | dk_art = _file_artifact(dk_path, "teacher.dk", "ollmdk01", **{k: dk_hdr[k] for k in ("V", "K", "T", "N", "fnv_hex")}) |
| 773 | run.emit("artifact", **dk_art) |
| 774 | |
| 775 | run.emit("stage", stage="init", label="Initializing Universal Student Checkpoint") |
| 776 | student_ck = run_dir / "student.ck" |
| 777 | if spec["student_init_ck"]: |
| 778 | shutil.copy2(Path(spec["student_init_ck"]).expanduser().resolve(), student_ck) |
| 779 | else: |
| 780 | self._run_stream( |
| 781 | run, |
| 782 | [ |
| 783 | univ_bin, "init", str(student_ck), spec["arch"], |
| 784 | str(V), str(T), str(D), str(H), str(H_KV), str(F), str(L), str(B), |
| 785 | str(spec["seed"]), str(spec["steps"]), str(spec["lr_micro"]), |
| 786 | ], |
| 787 | "init", |
| 788 | ) |
| 789 | |
| 790 | dcheck_rec: dict[str, Any] | None = None |
| 791 | if not spec["skip_dcheck"]: |
| 792 | run.emit("stage", stage="dcheck", label="Verifying Hybrid CE+KL Analytic Gradients (dcheck)") |
| 793 | dc_out = self._run_stream( |
| 794 | run, |
| 795 | [univ_bin, "dcheck", str(student_ck), str(dk_path), str(alpha_micro), str(temp_milli), "24"], |
| 796 | "dcheck", |
| 797 | ) |
| 798 | for ln in dc_out.splitlines(): |
| 799 | parts = ln.split() |
| 800 | if len(parts) == 6 and parts[0] == "C": |
| 801 | dcheck_rec = { |
| 802 | "passed": True, |
| 803 | "samples": int(parts[1]), |
| 804 | "mxrel_hex": parts[2], |
| 805 | "mxrel_milli": int(parts[3]) / 1_000_000.0, |
| 806 | "worst_param": int(parts[4]), |
| 807 | "retries": int(parts[5]), |
| 808 | } |
| 809 | run.emit("dcheck", **dcheck_rec) |
| 810 | break |
| 811 | |
| 812 | run.emit("stage", stage="distill", label=f"Distilling Student via OLLMDK01 (alpha={spec['alpha']}, tau={spec['temperature']})") |
| 813 | every = max(1, min(spec["steps"], max(1, spec["steps"] // 6))) |
| 814 | |
| 815 | def _on_dtrain_line(line: str) -> None: |
| 816 | parts = line.split() |
| 817 | if len(parts) == 5 and parts[0] == "D": |
| 818 | try: |
| 819 | st = int(parts[1]) |
| 820 | tot_l = int(parts[2]) / 1e6 |
| 821 | ce_l = int(parts[3]) / 1e6 |
| 822 | kl_l = int(parts[4]) / 1e6 |
| 823 | run.emit("metric", stage="distill", step=st, loss=tot_l, ce_loss=ce_l, kl_loss=kl_l, bpb=round(ce_l / LN2, 6)) |
| 824 | except ValueError: |
| 825 | pass |
| 826 | |
| 827 | self._run_stream( |
| 828 | run, |
| 829 | [ |
| 830 | univ_bin, "dtrain", str(student_ck), str(dk_path), |
| 831 | str(spec["steps"]), str(every), str(alpha_micro), str(temp_milli), |
| 832 | ], |
| 833 | "distill", |
| 834 | line_cb=_on_dtrain_line, |
| 835 | ) |
| 836 | ck_hdr = univ_backend.read_ck4_header(student_ck) |
| 837 | ck_art = _file_artifact(student_ck, "student.ck", "checkpoint_v4", magic="OLLMCK04", step=ck_hdr["step"]) |
| 838 | run.emit("artifact", **ck_art) |
| 839 | |
| 840 | exports = self._maybe_export_v4(run, student_ck, bins) |
| 841 | return { |
| 842 | "kind": "omega-helix-distill-bom", |
| 843 | "schema": 1, |
| 844 | "generated": utc_now(), |
| 845 | "run_id": run.run_id, |
| 846 | "mode": "dk-univ", |
| 847 | "spec": spec, |
| 848 | "dk_shard": dk_art, |
| 849 | "dcheck": dcheck_rec, |
| 850 | "verify_stats": collected["verify_stats"] if collected else run.verify_stats, |
| 851 | "openwaldo_export": collected["export_meta"] if collected else None, |
| 852 | "teachers": collected["teacher_meta"] if collected else [], |
| 853 | "router_summary": collected["router_summary"] if collected else [], |
| 854 | "student_checkpoint": ck_hdr, |
| 855 | "final_metrics": run.metrics[-1] if run.metrics else None, |
| 856 | "exports": exports, |
| 857 | } |
| 858 | |
| 859 | def _run_seq_univ(self, run: DistillRun, bins: dict[str, Path]) -> dict[str, Any]: |
| 860 | spec = run.spec |
| 861 | run_dir = run.run_dir |
| 862 | collected = self._collect_and_verify(run, bins.get("ollm_univ")) |
| 863 | |
| 864 | run.emit("stage", stage="distill", label=f"Training Universal Student ({spec['arch'].upper()})") |
| 865 | backend_spec: dict[str, Any] = { |
| 866 | "export_dir": str(collected["export_dir"]), |
| 867 | "workdir": str(run_dir / "universal"), |
| 868 | "arch": spec["arch"], |
| 869 | "tokenizer": spec["tokenizer"], |
| 870 | "vocab": spec["V"], |
| 871 | "held_mod": spec["held_mod"], |
| 872 | "T": spec["T"], |
| 873 | "D": spec["D"], |
| 874 | "H": spec["H"], |
| 875 | "H_KV": spec["H_KV"], |
| 876 | "F": spec["F"], |
| 877 | "L": spec["L"], |
| 878 | "B": spec["B"], |
| 879 | "seed": spec["seed"], |
| 880 | "steps": spec["steps"], |
| 881 | "lr_micro": spec["lr_micro"], |
| 882 | "export_hf": spec["export_hf"], |
| 883 | "hf_dtype": spec["hf_dtype"], |
| 884 | "export_gguf": spec["export_gguf"], |
| 885 | "ollm_waldo": str(bins["ollm_waldo"]), |
| 886 | "ollm_univ": str(bins["ollm_univ"]), |
| 887 | } |
| 888 | if spec["arch"] == "custom" and spec["flags"] is not None: |
| 889 | backend_spec["flags"] = spec["flags"] |
| 890 | if "ollm" in bins: |
| 891 | backend_spec["ollm"] = str(bins["ollm"]) |
| 892 | if "ollm_interchange" in bins: |
| 893 | backend_spec["ollm_interchange"] = str(bins["ollm_interchange"]) |
| 894 | |
| 895 | rc, obs = univ_backend.run_backend(backend_spec) |
| 896 | if rc != 0: |
| 897 | raise RuntimeError(f"omega_helix_backend failed at stage {obs.get('stage')}: {obs.get('error')}") |
| 898 | |
| 899 | for row in obs.get("train_log", []): |
| 900 | st = int(row["step"]) |
| 901 | lv = float(row["loss"]) |
| 902 | run.emit("metric", stage="distill", step=st, loss=lv, ce_loss=lv, kl_loss=0.0, bpb=round(lv / LN2, 6)) |
| 903 | |
| 904 | ck_p = run_dir / "universal" / "model.ck" |
| 905 | ck_hdr = univ_backend.read_ck4_header(ck_p) |
| 906 | run.emit("artifact", **_file_artifact(ck_p, "universal/model.ck", "checkpoint_v4", magic="OLLMCK04", step=ck_hdr["step"])) |
| 907 | return { |
| 908 | "kind": "omega-helix-distill-bom", |
| 909 | "schema": 1, |
| 910 | "generated": utc_now(), |
| 911 | "run_id": run.run_id, |
| 912 | "mode": "seq-univ", |
| 913 | "spec": spec, |
| 914 | "verify_stats": collected["verify_stats"], |
| 915 | "openwaldo_export": collected["export_meta"], |
| 916 | "teachers": collected["teacher_meta"], |
| 917 | "router_summary": collected["router_summary"], |
| 918 | "student_checkpoint": ck_hdr, |
| 919 | "observations": obs, |
| 920 | "exports": obs.get("exports", []), |
| 921 | } |
| 922 | |
| 923 | def _run_dna_strand(self, run: DistillRun, bins: dict[str, Path]) -> dict[str, Any]: |
| 924 | spec = run.spec |
| 925 | run_dir = run.run_dir |
| 926 | V, T, D, H, F, L, B = spec["V"], spec["T"], spec["D"], spec["H"], spec["F"], spec["L"], spec["B"] |
| 927 | collected = self._collect_and_verify(run, bins.get("ollm_univ")) |
| 928 | |
| 929 | run.emit("stage", stage="tokenize", label="Ingesting Distilled OpenWALDO Corpus via ollm-waldo") |
| 930 | data_dir = run_dir / "data" |
| 931 | bridge_argv = [ |
| 932 | sys.executable, |
| 933 | str(Path(ow_bridge.__file__).resolve()), |
| 934 | "prepare", |
| 935 | str(collected["export_dir"]), |
| 936 | str(data_dir), |
| 937 | "--ollm-waldo", |
| 938 | str(bins["ollm_waldo"]), |
| 939 | "--held-mod", |
| 940 | str(spec["held_mod"]), |
| 941 | ] |
| 942 | if spec["tokenizer"] == "bpe" and V > 256: |
| 943 | bridge_argv += ["--ollm", str(bins["ollm"]), "--vocab", str(V)] |
| 944 | self._run_stream(run, bridge_argv, "tokenize") |
| 945 | train_data = data_dir / ("train.tok" if (spec["tokenizer"] == "bpe" and V > 256) else "train.bin") |
| 946 | |
| 947 | run.emit("stage", stage="base", label="Training Base DNA Checkpoint") |
| 948 | base_ck = run_dir / "base.ck" |
| 949 | self._run_stream( |
| 950 | run, |
| 951 | [ |
| 952 | str(bins["ollm"]), "init", str(base_ck), |
| 953 | str(V), str(T), str(D), str(H), str(F), str(L), str(B), |
| 954 | str(spec["seed"]), str(max(2, spec["steps"] // 2)), str(spec["lr_micro"]), |
| 955 | ], |
| 956 | "base", |
| 957 | ) |
| 958 | base_steps = max(2, spec["steps"] // 2) |
| 959 | self._run_stream(run, [str(bins["ollm"]), "train", str(base_ck), str(train_data), str(base_steps), str(max(1, base_steps // 2))], "base") |
| 960 | |
| 961 | run.emit("stage", stage="distill", label="Growing & Distilling Merkle DNA Strand (OLLMSP01)") |
| 962 | strand_ck = run_dir / "strand_distill.ck" |
| 963 | strand_sp = run_dir / "strand_distill.sp" |
| 964 | new_L = L + spec["add_layers"] |
| 965 | self._run_stream( |
| 966 | run, |
| 967 | [str(bins["ollm"]), "growpro", str(base_ck), str(strand_ck), str(new_L), str(spec["steps"]), str(spec["lr_micro"])], |
| 968 | "distill", |
| 969 | ) |
| 970 | every = max(1, min(spec["steps"], max(1, spec["steps"] // 4))) |
| 971 | |
| 972 | def _on_dna_line(line: str) -> None: |
| 973 | parts = line.split() |
| 974 | if len(parts) == 3 and parts[0] == "T": |
| 975 | try: |
| 976 | st = int(parts[1]) |
| 977 | lv = int(parts[2]) / 1e6 |
| 978 | run.emit("metric", stage="distill", step=st, loss=lv, ce_loss=lv, kl_loss=0.0, bpb=round(lv / LN2, 6)) |
| 979 | except ValueError: |
| 980 | pass |
| 981 | |
| 982 | self._run_stream( |
| 983 | run, |
| 984 | [str(bins["ollm"]), "trainf", str(strand_ck), str(train_data), str(spec["steps"]), str(every), str(L)], |
| 985 | "distill", |
| 986 | line_cb=_on_dna_line, |
| 987 | ) |
| 988 | self._run_stream(run, [str(bins["ollm"]), "spext", str(base_ck), str(strand_ck), str(strand_sp)], "distill") |
| 989 | sp_hdr = chain_runner.read_sp_header(strand_sp) |
| 990 | run.emit("artifact", **_file_artifact(strand_ck, "strand_distill.ck", "checkpoint_dna")) |
| 991 | run.emit("artifact", **_file_artifact(strand_sp, "strand_distill.sp", "specialist_pack", pack_hash=sp_hdr.get("pack_hash_hex", ""))) |
| 992 | |
| 993 | return { |
| 994 | "kind": "omega-helix-distill-bom", |
| 995 | "schema": 1, |
| 996 | "generated": utc_now(), |
| 997 | "run_id": run.run_id, |
| 998 | "mode": "dna-strand", |
| 999 | "spec": spec, |
| 1000 | "verify_stats": collected["verify_stats"], |
| 1001 | "openwaldo_export": collected["export_meta"], |
| 1002 | "teachers": collected["teacher_meta"], |
| 1003 | "router_summary": collected["router_summary"], |
| 1004 | "student_checkpoint": ow_bridge.read_ollm_checkpoint_header(strand_ck), |
| 1005 | "specialist_pack": sp_hdr, |
| 1006 | "exports": [], |
| 1007 | } |
| 1008 | |
| 1009 | def _maybe_export_v4(self, run: DistillRun, ck_path: Path, bins: dict[str, Path]) -> list[dict[str, Any]]: |
| 1010 | spec = run.spec |
| 1011 | exports: list[dict[str, Any]] = [] |
| 1012 | if not (spec["export_hf"] or spec["export_gguf"]) or "ollm_interchange" not in bins: |
| 1013 | return exports |
| 1014 | run.emit("stage", stage="export", label="Exporting Student HF Safetensors / GGUF") |
| 1015 | ic_bin = str(bins["ollm_interchange"]) |
| 1016 | if spec["export_hf"]: |
| 1017 | hf_dir = run.run_dir / "export-hf" |
| 1018 | hf_dir.mkdir(parents=True, exist_ok=True) |
| 1019 | self._run_stream(run, [ic_bin, "export-hf", str(ck_path), str(hf_dir), spec["hf_dtype"]], "export") |
| 1020 | hf_files = sorted(p for p in hf_dir.iterdir() if p.is_file()) |
| 1021 | exports.append({"format": "hf-safetensors", "dtype": spec["hf_dtype"], "dir": str(hf_dir), "files": [_file_artifact(p, p.name, "hf_export") for p in hf_files]}) |
| 1022 | if spec["export_gguf"]: |
| 1023 | gguf_p = run.run_dir / "student.gguf" |
| 1024 | self._run_stream(run, [ic_bin, "export-gguf", str(ck_path), str(gguf_p)], "export") |
| 1025 | art = _file_artifact(gguf_p, "student.gguf", "gguf_export") |
| 1026 | run.emit("artifact", **art) |
| 1027 | exports.append({"format": "gguf", "version": 3, **art}) |
| 1028 | return exports |
| 1029 | |
| 1030 | def _execute_run(self, run: DistillRun) -> None: |
| 1031 | with run._lock: |
| 1032 | run.status = "running" |
| 1033 | run.save_state() |
| 1034 | try: |
| 1035 | spec = run.spec |
| 1036 | mode = spec["mode"] |
| 1037 | run.emit("stage", stage="resolve", label="Resolving Pure-Omega Distillation Binaries") |
| 1038 | needed: list[str] = ["ollm_univ", "ollm_waldo"] |
| 1039 | if mode == "dna-strand" or spec["tokenizer"] == "bpe": |
| 1040 | needed.append("ollm") |
| 1041 | if spec["export_hf"] or spec["export_gguf"]: |
| 1042 | needed.append("ollm_interchange") |
| 1043 | bins = chain_runner.ensure_binaries( |
| 1044 | needed, |
| 1045 | bin_dir=self.bin_dir, |
| 1046 | root=self.root, |
| 1047 | log_cb=lambda msg: run.emit("log", stage="resolve", text=msg), |
| 1048 | ) |
| 1049 | if mode == "dk-univ": |
| 1050 | bom = self._run_dk_univ(run, bins) |
| 1051 | elif mode == "seq-univ": |
| 1052 | bom = self._run_seq_univ(run, bins) |
| 1053 | else: |
| 1054 | bom = self._run_dna_strand(run, bins) |
| 1055 | |
| 1056 | bom_path = run.run_dir / "distill-bom.json" |
| 1057 | tmp = run.run_dir / ".distill-bom.json.tmp" |
| 1058 | tmp.write_text(json.dumps(bom, indent=2) + "\n", encoding="utf-8") |
| 1059 | os.replace(tmp, bom_path) |
| 1060 | run.bom = bom |
| 1061 | bom_art = _file_artifact(bom_path, "distill-bom.json", "distill_bom") |
| 1062 | run.emit("artifact", **bom_art) |
| 1063 | run.emit("done", status="done", bom_sha256=bom_art["sha256"]) |
| 1064 | except Exception as exc: |
| 1065 | kind = "stopped" if run._stop_event.is_set() else "error" |
| 1066 | run.emit(kind, error=str(exc)) |
| 1067 | finally: |
| 1068 | run.save_state() |