125 lines
3.6 KiB
Python
125 lines
3.6 KiB
Python
from __future__ import annotations
|
|
|
|
import struct
|
|
import threading
|
|
import time
|
|
from typing import Callable, Dict, Iterator, Optional
|
|
|
|
try:
|
|
from multiprocessing import shared_memory
|
|
except ImportError: # Python < 3.8 — shared memory недоступен
|
|
shared_memory = None
|
|
|
|
_MAGIC = b"XENITHS1"
|
|
_FMT = "<8siiifffdddHH512s2048s"
|
|
_SIZE = struct.calcsize(_FMT)
|
|
|
|
_PHASES = {0: "idle", 1: "running", 2: "done", 3: "failed", 4: "cancelled"}
|
|
_PHASE_IDS = {v: k for k, v in _PHASES.items()}
|
|
|
|
|
|
def _pack(state) -> bytes:
|
|
err = (state.error or "")[:500].encode("utf-8", "replace")
|
|
notes = "\n".join(state.notes(12))[:2000].encode("utf-8", "replace")
|
|
phase = _PHASE_IDS.get(state.phase, 0)
|
|
return struct.pack(
|
|
_FMT, _MAGIC, phase, state.step, state.total,
|
|
state.loss, state.val_loss, state.lr,
|
|
state.tokens_per_sec, state.elapsed_sec, state.tokens_seen,
|
|
len(err), len(notes), err.ljust(512, b"\0"), notes.ljust(2048, b"\0"),
|
|
)
|
|
|
|
|
|
def _unpack(buf: bytes) -> Optional[Dict]:
|
|
if len(buf) < _SIZE:
|
|
return None
|
|
(magic, phase, step, total, loss, val_loss, lr, tps, elapsed, tokens,
|
|
err_len, notes_len, err, notes) = struct.unpack(_FMT, buf[:_SIZE])
|
|
if magic != _MAGIC:
|
|
return None
|
|
return {
|
|
"phase": _PHASES.get(phase, "?"),
|
|
"step": step,
|
|
"total": total,
|
|
"progress": (step / total) if total > 0 else 0.0,
|
|
"loss": loss,
|
|
"val_loss": val_loss,
|
|
"lr": lr,
|
|
"tokens_per_sec": tps,
|
|
"elapsed_sec": elapsed,
|
|
"tokens_seen": tokens,
|
|
"error": err[:err_len].decode("utf-8", "replace"),
|
|
"notes": [s for s in notes[:notes_len].decode("utf-8", "replace").split("\n") if s],
|
|
}
|
|
|
|
|
|
def mirror(model, name: str, interval: float = 0.2) -> Callable[[], None]:
|
|
if shared_memory is None:
|
|
raise RuntimeError("нужен Python >= 3.8 (multiprocessing.shared_memory)")
|
|
remove(name) # убрать возможные останки от прошлого запуска
|
|
shm = shared_memory.SharedMemory(name=name, create=True, size=_SIZE)
|
|
stop_ev = threading.Event()
|
|
|
|
def loop():
|
|
state = model.status()
|
|
while not stop_ev.is_set():
|
|
try:
|
|
shm.buf[:_SIZE] = _pack(state)
|
|
except (ValueError, BufferError):
|
|
break # сегмент закрыт
|
|
stop_ev.wait(interval)
|
|
try:
|
|
shm.buf[:_SIZE] = _pack(state) # финальный снимок
|
|
except Exception:
|
|
pass
|
|
|
|
th = threading.Thread(target=loop, daemon=True, name=f"xenith-shm-{name}")
|
|
th.start()
|
|
|
|
def stop():
|
|
stop_ev.set()
|
|
th.join(timeout=2.0)
|
|
try:
|
|
shm.close()
|
|
except Exception:
|
|
pass
|
|
return stop
|
|
|
|
|
|
def read(name: str) -> Optional[Dict]:
|
|
if shared_memory is None:
|
|
return None
|
|
try:
|
|
shm = shared_memory.SharedMemory(name=name, create=False)
|
|
except FileNotFoundError:
|
|
return None
|
|
try:
|
|
return _unpack(bytes(shm.buf[:_SIZE]))
|
|
finally:
|
|
shm.close()
|
|
|
|
|
|
def watch(name: str, interval: float = 0.5, until_done: bool = True) -> Iterator[Dict]:
|
|
while True:
|
|
snap = read(name)
|
|
if snap is None:
|
|
return
|
|
yield snap
|
|
if until_done and snap["phase"] in ("done", "failed", "cancelled"):
|
|
return
|
|
time.sleep(interval)
|
|
|
|
|
|
def remove(name: str) -> None:
|
|
if shared_memory is None:
|
|
return
|
|
try:
|
|
shm = shared_memory.SharedMemory(name=name, create=False)
|
|
except FileNotFoundError:
|
|
return
|
|
try:
|
|
shm.close()
|
|
shm.unlink()
|
|
except Exception:
|
|
pass
|