710 lines
29 KiB
Python
710 lines
29 KiB
Python
#!/usr/bin/env python3
|
||
"""demo/train_dashboard.py — Xenith Lab: визуальный дашборд обучения.
|
||
|
||
Что умеет:
|
||
* живой график loss (Canvas, EMA + сырой ряд, подсказки при наведении);
|
||
* анимированная «нейросеть» (слои, импульсы, свечение при обучении);
|
||
* панель обучения: steps / batch / block / lr / корпус;
|
||
* запросы к модели (prompt, n, temperature, top_k, top_p, seed);
|
||
* история действий и живой лог движка;
|
||
* REST API, чтобы всем этим управлять через curl.
|
||
|
||
Запуск:
|
||
python3 demo/train_dashboard.py
|
||
python3 demo/train_dashboard.py --model demo/demo.xnh --corpus corpus.txt --vulkan
|
||
python3 demo/train_dashboard.py --port 9000 --no-browser
|
||
|
||
API (curl):
|
||
curl -s localhost:8765/api/status
|
||
curl -s -X POST localhost:8765/api/train \
|
||
-H 'Content-Type: application/json' \
|
||
-d '{"steps":300,"batch":4,"block":32,"lr":0.003}'
|
||
curl -s -X POST localhost:8765/api/stop
|
||
curl -s -X POST localhost:8765/api/generate \
|
||
-H 'Content-Type: application/json' \
|
||
-d '{"prompt":"ветер","n":64,"temperature":0.8}'
|
||
curl -s -X POST localhost:8765/api/save
|
||
curl -s -X POST localhost:8765/api/reset
|
||
|
||
Безопасность: по умолчанию слушает 127.0.0.1 и не имеет авторизации.
|
||
Не выставляйте наружу без reverse-proxy/аутентификации.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import atexit
|
||
import json
|
||
import os
|
||
import sys
|
||
import threading
|
||
import time
|
||
import webbrowser
|
||
from collections import deque
|
||
from datetime import datetime
|
||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||
from pathlib import Path
|
||
from urllib.parse import urlparse
|
||
|
||
HERE = Path(__file__).resolve().parent
|
||
ROOT = HERE.parent
|
||
# build/ — собранный xenith_engine, ROOT — пакет xenith. Если модуль уже
|
||
# установлен через pip, эти пути просто не найдут его и import возьмёт wheel.
|
||
for _p in (ROOT / "build", ROOT):
|
||
if str(_p) not in sys.path:
|
||
sys.path.insert(0, str(_p))
|
||
|
||
try:
|
||
import xenith as xe
|
||
except Exception as _e: # ImportError или ошибка загрузки .so
|
||
print("xenith: не удалось загрузить движок.\n"
|
||
" Соберите: ./build.sh (или pip install .)\n"
|
||
f" Ошибка: {_e}", file=sys.stderr)
|
||
raise SystemExit(2)
|
||
|
||
DEFAULT_CORPUS = (
|
||
"утром солнце встаёт над рекой и ветер гонит воду. "
|
||
"вечером луна светит над домом, а звезда падает за дерево. "
|
||
"ветер гонит воду, солнце встаёт над рекой. "
|
||
"тихо в лесу, только птицы поют и листья шумят. "
|
||
"дом стоит у реки, в доме тепло и светло. "
|
||
"звезда падает за дерево, луна светит над домом. "
|
||
) * 6
|
||
|
||
|
||
class ApiError(Exception):
|
||
def __init__(self, message: str, code: int = 400):
|
||
super().__init__(message)
|
||
self.code = code
|
||
|
||
|
||
def now_hms() -> str:
|
||
return datetime.now().strftime("%H:%M:%S")
|
||
|
||
|
||
class AppState:
|
||
"""Всё общее между HTTP-потоками и потоком обучения."""
|
||
|
||
def __init__(self, args):
|
||
self.args = args
|
||
self.lock = threading.RLock()
|
||
self.model = None
|
||
self.model_path = os.path.abspath(args.model)
|
||
self.corpus_text = args.corpus_text
|
||
chat_data = HERE / "chat_dataset.json"
|
||
legacy = HERE / "dialogue.json"
|
||
self.dataset = str(chat_data if chat_data.exists() else legacy)
|
||
self.history = deque(maxlen=6000) # {step, loss, lr, tps}
|
||
self.history_file = str(HERE / "dashboard_history.json")
|
||
self._load_history()
|
||
self.events = deque(maxlen=400) # {t, kind, msg}
|
||
self.training = None
|
||
self.generating = False
|
||
self.last_phase = "idle"
|
||
self.started = time.time()
|
||
|
||
# ------------------------------------------------------------------ log
|
||
def event(self, kind: str, msg: str) -> None:
|
||
item = {"t": now_hms(), "kind": kind, "msg": msg}
|
||
with self.lock:
|
||
self.events.append(item)
|
||
print(f"[{item['t']}] {kind:8s} {msg}")
|
||
|
||
# --------------------------------------------------------------- model
|
||
def load_or_create(self) -> None:
|
||
path = self.model_path
|
||
if os.path.exists(path):
|
||
try:
|
||
pr = {}
|
||
try:
|
||
pr = xe.probe(path)
|
||
except Exception:
|
||
pass
|
||
with_opt = bool(pr.get("has_optimizer"))
|
||
self.model = xe.Model.load(path, with_grads=True, with_optimizer=with_opt)
|
||
self._configure_chat()
|
||
self.event("model", f"загружена {path} (шаг {self.model.step}, "
|
||
f"loss {self.model.loss:.4f})")
|
||
return
|
||
except Exception as e:
|
||
self.event("error", f"не удалось загрузить {path}: {e} — создаю заново")
|
||
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
||
self.model = xe.Model(
|
||
vocab=self.args.vocab, embd=self.args.embd, layers=self.args.layers,
|
||
heads=self.args.heads, ctx=self.args.ctx, seed=self.args.seed,
|
||
corpus_text=self.corpus_text,
|
||
)
|
||
self.model.save(path)
|
||
self._configure_chat()
|
||
info = self.model.info()
|
||
self.event("model", f"создана {path}: {info['n_layer']} слоёв, "
|
||
f"{info['n_head']} голов, {info['n_embd']} эмбеддинг, "
|
||
f"{info['vocab_entries']} токенов словаря")
|
||
|
||
def save(self, quiet: bool = False) -> None:
|
||
try:
|
||
self.model.save(self.model_path)
|
||
self._save_history()
|
||
if not quiet:
|
||
self.event("save", f"сохранено в {self.model_path}")
|
||
except Exception as e:
|
||
if not quiet:
|
||
self.event("error", f"save: {e}")
|
||
|
||
def _configure_chat(self) -> None:
|
||
# У модели нет системного промпта в датасете — не подмешиваем
|
||
# дефолтную фразу «Ты — ассистент Xenith…».
|
||
try:
|
||
self.model.chat_set_system("")
|
||
except Exception:
|
||
pass
|
||
|
||
def _load_history(self) -> None:
|
||
try:
|
||
raw = json.loads(Path(self.history_file).read_text(encoding="utf-8"))
|
||
points = raw.get("history", []) if isinstance(raw, dict) else raw
|
||
for p in points[-6000:]:
|
||
if isinstance(p, dict) and "step" in p and "loss" in p:
|
||
self.history.append({
|
||
"step": int(p["step"]),
|
||
"loss": float(p["loss"]),
|
||
"lr": float(p.get("lr", 0.0)),
|
||
"tps": float(p.get("tps", 0.0)),
|
||
})
|
||
except Exception:
|
||
pass
|
||
|
||
def _save_history(self) -> None:
|
||
try:
|
||
data = {"history": list(self.history)[-4000:]}
|
||
tmp = self.history_file + ".tmp"
|
||
Path(tmp).write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
||
os.replace(tmp, self.history_file)
|
||
except Exception:
|
||
pass
|
||
|
||
# -------------------------------------------------------------- status
|
||
def status(self) -> dict:
|
||
with self.lock:
|
||
m = self.model
|
||
st = self.training
|
||
hist = list(self.history)
|
||
ev = list(self.events)[-140:]
|
||
|
||
info = {}
|
||
try:
|
||
info = m.info()
|
||
except Exception:
|
||
pass
|
||
chat = {}
|
||
try:
|
||
chat = m.chat_history()
|
||
except Exception:
|
||
pass
|
||
|
||
running = bool(st and st.is_running)
|
||
phase = "running" if running else (st.phase if st else "idle")
|
||
|
||
# Переход running → done/failed фиксируем один раз.
|
||
if self.last_phase == "running" and st is not None and not running:
|
||
self.event("finish", f"обучение: {st.phase}, шаг {st.step}, "
|
||
f"loss {st.loss:.4f}")
|
||
self.last_phase = st.phase
|
||
elif running:
|
||
self.last_phase = "running"
|
||
|
||
log = []
|
||
try:
|
||
for lvl, msg in xe.get_log()[-100:]:
|
||
log.append({"level": int(lvl), "msg": str(msg)})
|
||
except Exception:
|
||
pass
|
||
|
||
return {
|
||
"ok": True,
|
||
"version": xe.version(),
|
||
"build_type": xe.build_type(),
|
||
"backend": xe.backend_name(),
|
||
"backend_is_gpu": bool(xe.backend_is_gpu()),
|
||
"model_path": self.model_path,
|
||
"info": info,
|
||
"phase": phase,
|
||
"is_running": running,
|
||
"generating": self.generating,
|
||
"step": int(st.step) if st is not None else int(info.get("step", 0)),
|
||
"total": int(st.total) if st is not None else 0,
|
||
"loss": float(st.loss) if st is not None else float(info.get("loss", 0.0)),
|
||
"val_loss": float(st.val_loss) if st is not None else 0.0,
|
||
"lr": float(st.lr) if st is not None else 0.0,
|
||
"tokens_per_sec": float(st.tokens_per_sec) if st is not None else 0.0,
|
||
"elapsed_sec": float(st.elapsed_sec) if st is not None else 0.0,
|
||
"tokens_seen": float(st.tokens_seen) if st is not None else 0.0,
|
||
"error": st.error if st is not None else "",
|
||
"history": hist[-1200:],
|
||
"events": ev,
|
||
"engine_log": log,
|
||
"chat_turns": int(chat.get("turns", 0)),
|
||
"chat_context": int(chat.get("context_used", 0)),
|
||
"uptime_sec": time.time() - self.started,
|
||
}
|
||
|
||
# ------------------------------------------------------------- training
|
||
def start_training(self, p: dict) -> dict:
|
||
try:
|
||
steps = int(p.get("steps", 200))
|
||
batch = int(p.get("batch", 4))
|
||
block = int(p.get("block", 32))
|
||
lr = float(p.get("lr", 0.003))
|
||
except (TypeError, ValueError):
|
||
raise ApiError("steps/batch/block/lr должны быть числами")
|
||
|
||
corpus = str(p.get("corpus") or "").strip()
|
||
corpus_path = str(p.get("corpus_path") or "").strip()
|
||
if corpus_path:
|
||
try:
|
||
corpus = Path(corpus_path).read_text(encoding="utf-8")
|
||
except Exception as e:
|
||
raise ApiError(f"не читается corpus_path {corpus_path}: {e}")
|
||
if not corpus:
|
||
corpus = self.corpus_text
|
||
if not corpus:
|
||
raise ApiError("пустой корпус: передайте corpus или --corpus FILE")
|
||
|
||
info = self.model.info()
|
||
block = max(1, min(block, int(info.get("block_size", block))))
|
||
steps = max(1, min(steps, 100000))
|
||
batch = max(1, min(batch, 64))
|
||
lr = max(1e-6, min(lr, 1.0))
|
||
|
||
with self.lock:
|
||
if self.generating:
|
||
raise ApiError("идёт генерация — дождитесь ответа", 409)
|
||
if self.training is not None and self.training.is_running:
|
||
raise ApiError("обучение уже идёт — сначала stop()", 409)
|
||
base = int(self.model.step)
|
||
target = base + steps if base > 0 else steps
|
||
if target <= base:
|
||
raise ApiError(f"модель уже на шаге {base}; steps={steps} нечего делать")
|
||
|
||
# ~150 точек на график, но не чаще каждого шага
|
||
log_every = max(1, min(25, steps // 200 or 1))
|
||
|
||
def on_tick(d):
|
||
with self.lock:
|
||
self.history.append({
|
||
"step": int(d.get("step", 0)),
|
||
"loss": float(d.get("loss", 0.0)),
|
||
"lr": float(d.get("lr", 0.0)),
|
||
"tps": float(d.get("tokens_per_sec", 0.0)),
|
||
})
|
||
if len(self.history) % 25 == 0:
|
||
self._save_history()
|
||
|
||
def on_note(s):
|
||
self.event("note", str(s))
|
||
|
||
st = self.model.train_async(
|
||
corpus_text=corpus,
|
||
out_path=self.model_path,
|
||
steps=target,
|
||
batch=batch,
|
||
block=block,
|
||
lr=lr,
|
||
wd=0.01,
|
||
clip=1.0,
|
||
warmup=max(5, min(100, steps // 20)),
|
||
log_every=log_every,
|
||
ckpt_every=0,
|
||
val_every=0,
|
||
optimizer="adamw",
|
||
resume=(base > 0),
|
||
on_tick=on_tick,
|
||
on_note=on_note,
|
||
)
|
||
self.training = st
|
||
self.last_phase = "running"
|
||
|
||
self.event("train", f"старт: {base} → {target} шагов, batch={batch}, "
|
||
f"block={block}, lr={lr:g}, log_every={log_every}")
|
||
return {"ok": True, "base": base, "target": target, "steps": steps}
|
||
|
||
def stop_training(self) -> dict:
|
||
if self.training is None or not self.training.is_running:
|
||
raise ApiError("обучение не идёт")
|
||
self.model.stop()
|
||
self.event("stop", "запрошена остановка обучения")
|
||
return {"ok": True}
|
||
|
||
# ------------------------------------------------------------ generation
|
||
def generate(self, p: dict) -> dict:
|
||
try:
|
||
prompt = str(p.get("prompt", ""))
|
||
n = int(p.get("n", 64))
|
||
temp = float(p.get("temperature", 0.8))
|
||
top_k = int(p.get("top_k", 40))
|
||
top_p = float(p.get("top_p", 0.95))
|
||
seed = int(p.get("seed", -1))
|
||
except (TypeError, ValueError):
|
||
raise ApiError("prompt/n/temperature/top_k/top_p/seed имеют неверный тип")
|
||
|
||
n = max(1, min(n, 1024))
|
||
temp = max(0.0, min(temp, 3.0))
|
||
top_k = max(1, min(top_k, 200))
|
||
top_p = max(0.0, min(top_p, 1.0))
|
||
|
||
with self.lock:
|
||
if self.training is not None and self.training.is_running:
|
||
raise ApiError("идёт обучение — генерация подождёт. "
|
||
"Нажмите Stop или дождитесь финиша.", 409)
|
||
if self.generating:
|
||
raise ApiError("уже генерирую", 409)
|
||
self.generating = True
|
||
try:
|
||
r = self.model.generate(prompt, n=n, temperature=temp, top_k=top_k,
|
||
top_p=top_p, seed=seed)
|
||
finally:
|
||
with self.lock:
|
||
self.generating = False
|
||
|
||
self.event("generate", f"«{prompt[:48]}» → {len(r.tokens)} ток., "
|
||
f"{r.stop_reason}, {r.tok_per_sec:.1f} ток/с")
|
||
d = dict(r.as_dict())
|
||
d["ok"] = True
|
||
return d
|
||
|
||
# ------------------------------------------------------------- finetune
|
||
def finetune(self, p: dict) -> dict:
|
||
data_path = str(p.get("data") or self.dataset)
|
||
data_json = p.get("data_json")
|
||
if isinstance(data_json, (list, dict)):
|
||
data_json = json.dumps(data_json, ensure_ascii=False)
|
||
try:
|
||
steps = int(p.get("steps", 300))
|
||
batch = int(p.get("batch", 4))
|
||
lr = float(p.get("lr", 0.002))
|
||
except (TypeError, ValueError):
|
||
raise ApiError("steps/batch/lr должны быть числами")
|
||
if not data_json and not os.path.exists(data_path):
|
||
raise ApiError(f"нет датасета: {data_path}")
|
||
info = self.model.info()
|
||
steps = max(1, min(steps, 5000))
|
||
batch = max(1, min(batch, 32))
|
||
lr = max(1e-6, min(lr, 1.0))
|
||
block = min(64, int(info.get("block_size", 64)))
|
||
|
||
with self.lock:
|
||
if self.generating:
|
||
raise ApiError("идёт генерация — дождитесь ответа", 409)
|
||
if self.training is not None and self.training.is_running:
|
||
raise ApiError("обучение уже идёт — сначала stop()", 409)
|
||
base = int(self.model.step)
|
||
target = base + steps
|
||
log_every = max(1, steps // 80)
|
||
|
||
def on_tick(d):
|
||
with self.lock:
|
||
self.history.append({
|
||
"step": int(d.get("step", 0)),
|
||
"loss": float(d.get("loss", 0.0)),
|
||
"lr": float(d.get("lr", 0.0)),
|
||
"tps": float(d.get("tokens_per_sec", 0.0)),
|
||
})
|
||
if len(self.history) % 25 == 0:
|
||
self._save_history()
|
||
|
||
def on_note(s):
|
||
self.event("note", str(s))
|
||
|
||
st = self.model.finetune_async(
|
||
data=(None if data_json else data_path),
|
||
data_json=data_json,
|
||
out_path=self.model_path,
|
||
steps=target,
|
||
batch=batch,
|
||
block=block,
|
||
lr=lr,
|
||
wd=0.0,
|
||
warmup=10,
|
||
mask=True,
|
||
pack_mode=1,
|
||
resume=(base > 0),
|
||
log_every=log_every,
|
||
ckpt_every=0,
|
||
val_every=0,
|
||
on_tick=on_tick,
|
||
on_note=on_note,
|
||
)
|
||
self.training = st
|
||
self.last_phase = "running"
|
||
|
||
self.event("finetune", f"диалог: {base} → {target} шагов, "
|
||
f"data={'json' if data_json else data_path}, pack_mode=1")
|
||
return {"ok": True, "base": base, "target": target, "steps": steps}
|
||
|
||
# ---------------------------------------------------------------- chat
|
||
def chat(self, p: dict) -> dict:
|
||
text = str(p.get("text") or p.get("prompt") or "").strip()
|
||
if not text:
|
||
raise ApiError("пустой текст")
|
||
try:
|
||
n = int(p.get("n", 64))
|
||
temp = float(p.get("temperature", 0.2))
|
||
top_k = int(p.get("top_k", 40))
|
||
top_p = float(p.get("top_p", 0.95))
|
||
seed = int(p.get("seed", -1))
|
||
except (TypeError, ValueError):
|
||
raise ApiError("n/temperature/top_k/top_p/seed имеют неверный тип")
|
||
n = max(1, min(n, 512))
|
||
temp = max(0.0, min(temp, 3.0))
|
||
top_k = max(1, min(top_k, 200))
|
||
top_p = max(0.0, min(top_p, 1.0))
|
||
|
||
if "system" in p:
|
||
try:
|
||
self.model.chat_set_system(str(p.get("system") or ""))
|
||
except Exception:
|
||
pass
|
||
|
||
with self.lock:
|
||
if self.training is not None and self.training.is_running:
|
||
raise ApiError("идёт обучение — диалог подождёт. Нажмите Stop.", 409)
|
||
if self.generating:
|
||
raise ApiError("уже генерирую", 409)
|
||
self.generating = True
|
||
try:
|
||
# По умолчанию держим контекст (модель обучена многотуровым
|
||
# диалогам). history=false — независимые реплики.
|
||
if not bool(p.get("history", True)):
|
||
self.model.chat_reset()
|
||
r = self.model.chat(text, n=n, temperature=temp, top_k=top_k,
|
||
top_p=top_p, seed=seed)
|
||
finally:
|
||
with self.lock:
|
||
self.generating = False
|
||
|
||
try:
|
||
hist = self.model.chat_history()
|
||
except Exception:
|
||
hist = {}
|
||
self.event("chat", f"вы: {text[:48]} → {len(r.tokens)} ток., {r.stop_reason}")
|
||
d = dict(r.as_dict())
|
||
d["ok"] = True
|
||
d["history"] = hist
|
||
return d
|
||
|
||
def chat_reset(self) -> dict:
|
||
self.model.chat_reset()
|
||
self.event("chat_reset", "история диалога сброшена")
|
||
return {"ok": True}
|
||
|
||
# ----------------------------------------------------------------- reset
|
||
def reset(self, p: dict) -> dict:
|
||
corpus = str(p.get("corpus") or self.corpus_text).strip() or self.corpus_text
|
||
with self.lock:
|
||
if self.training is not None and self.training.is_running:
|
||
raise ApiError("сначала остановите обучение", 409)
|
||
if self.generating:
|
||
raise ApiError("идёт генерация", 409)
|
||
info = self.model.info()
|
||
try:
|
||
new = xe.Model(
|
||
vocab=int(info.get("vocab_entries") or info.get("vocab_size") or 512),
|
||
embd=int(info.get("n_embd", 64)),
|
||
layers=int(info.get("n_layer", 2)),
|
||
heads=int(info.get("n_head", 4)),
|
||
ctx=int(info.get("block_size", 128)),
|
||
seed=int(info.get("seed") or 1337),
|
||
corpus_text=corpus,
|
||
)
|
||
except Exception as e:
|
||
raise ApiError(f"не удалось создать модель: {e}")
|
||
new.save(self.model_path)
|
||
self.model = new
|
||
self._configure_chat()
|
||
self.training = None
|
||
self.last_phase = "idle"
|
||
self.history.clear()
|
||
self._save_history()
|
||
self.events.clear()
|
||
self.event("reset", f"модель создана заново: {self.model_path}")
|
||
return {"ok": True}
|
||
|
||
|
||
# ===========================================================================
|
||
# HTTP
|
||
# ===========================================================================
|
||
class Handler(BaseHTTPRequestHandler):
|
||
server_version = "XenithLab/1.0"
|
||
protocol_version = "HTTP/1.1"
|
||
|
||
# ---- helpers ---------------------------------------------------------
|
||
def _cors(self) -> None:
|
||
self.send_header("Access-Control-Allow-Origin", "*")
|
||
self.send_header("Access-Control-Allow-Headers", "Content-Type")
|
||
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
||
|
||
def _send(self, code: int, body: bytes, ctype: str) -> None:
|
||
self.send_response(code)
|
||
self.send_header("Content-Type", ctype)
|
||
self.send_header("Content-Length", str(len(body)))
|
||
self.send_header("Cache-Control", "no-store")
|
||
self._cors()
|
||
self.end_headers()
|
||
if body:
|
||
self.wfile.write(body)
|
||
|
||
def _json(self, obj, code: int = 200) -> None:
|
||
body = json.dumps(obj, ensure_ascii=False).encode("utf-8")
|
||
self._send(code, body, "application/json; charset=utf-8")
|
||
|
||
def _html(self) -> None:
|
||
path = HERE / "train_dashboard.html"
|
||
if not path.exists():
|
||
self._json({"error": f"нет файла {path}"}, 500)
|
||
return
|
||
self._send(200, path.read_bytes(), "text/html; charset=utf-8")
|
||
|
||
def log_message(self, fmt, *args): # тише: события дашборда важнее
|
||
pass
|
||
|
||
# ---- routes ----------------------------------------------------------
|
||
def do_OPTIONS(self):
|
||
self.send_response(204)
|
||
self._cors()
|
||
self.send_header("Content-Length", "0")
|
||
self.end_headers()
|
||
|
||
def do_GET(self):
|
||
p = urlparse(self.path).path
|
||
st = self.server.state
|
||
if p in ("/", "/index.html"):
|
||
self._html()
|
||
elif p == "/api/status":
|
||
self._json(st.status())
|
||
elif p == "/api/health":
|
||
self._json({"ok": True, "version": xe.version()})
|
||
elif p == "/api/history":
|
||
with st.lock:
|
||
self._json({"history": list(st.history), "events": list(st.events)})
|
||
elif p == "/favicon.ico":
|
||
self.send_response(204)
|
||
self.send_header("Content-Length", "0")
|
||
self.end_headers()
|
||
else:
|
||
self._json({"error": "not found"}, 404)
|
||
|
||
def do_POST(self):
|
||
p = urlparse(self.path).path
|
||
st = self.server.state
|
||
try:
|
||
n = int(self.headers.get("Content-Length", "0") or 0)
|
||
raw = self.rfile.read(n) if n > 0 else b"{}"
|
||
try:
|
||
data = json.loads(raw.decode("utf-8") or "{}")
|
||
except Exception:
|
||
raise ApiError("тело должно быть JSON")
|
||
if not isinstance(data, dict):
|
||
raise ApiError("тело должно быть JSON-объектом")
|
||
|
||
if p == "/api/train":
|
||
self._json(st.start_training(data))
|
||
elif p == "/api/finetune":
|
||
self._json(st.finetune(data))
|
||
elif p == "/api/chat":
|
||
self._json(st.chat(data))
|
||
elif p == "/api/chat_reset":
|
||
self._json(st.chat_reset())
|
||
elif p == "/api/stop":
|
||
self._json(st.stop_training())
|
||
elif p == "/api/generate":
|
||
self._json(st.generate(data))
|
||
elif p == "/api/save":
|
||
st.save()
|
||
self._json({"ok": True, "path": st.model_path})
|
||
elif p == "/api/reset":
|
||
self._json(st.reset(data))
|
||
else:
|
||
self._json({"error": "not found"}, 404)
|
||
except ApiError as e:
|
||
self._json({"error": str(e)}, e.code)
|
||
except Exception as e:
|
||
self._json({"error": f"{type(e).__name__}: {e}"}, 500)
|
||
|
||
|
||
# ===========================================================================
|
||
# main
|
||
# ===========================================================================
|
||
def parse_args(argv=None):
|
||
ap = argparse.ArgumentParser(description="Xenith Lab — визуальный дашборд обучения")
|
||
ap.add_argument("--host", default="127.0.0.1")
|
||
ap.add_argument("--port", type=int, default=8765)
|
||
ap.add_argument("--model", default=str(HERE / "dashboard_model.xnh"),
|
||
help="путь к .xnh (создаётся, если нет)")
|
||
ap.add_argument("--corpus", default="", help="текстовый файл корпуса")
|
||
ap.add_argument("--vocab", type=int, default=512)
|
||
ap.add_argument("--embd", type=int, default=64)
|
||
ap.add_argument("--layers", type=int, default=2)
|
||
ap.add_argument("--heads", type=int, default=4)
|
||
ap.add_argument("--ctx", type=int, default=128)
|
||
ap.add_argument("--seed", type=int, default=1337)
|
||
ap.add_argument("--vulkan", action="store_true", help="инициализировать GPU")
|
||
ap.add_argument("--no-browser", action="store_true", help="не открывать браузер")
|
||
args = ap.parse_args(argv)
|
||
|
||
if args.corpus:
|
||
try:
|
||
args.corpus_text = Path(args.corpus).read_text(encoding="utf-8")
|
||
except Exception as e:
|
||
print(f"xenith: не читается корпус {args.corpus}: {e}", file=sys.stderr)
|
||
raise SystemExit(2)
|
||
else:
|
||
args.corpus_text = DEFAULT_CORPUS
|
||
return args
|
||
|
||
|
||
def main(argv=None) -> int:
|
||
args = parse_args(argv)
|
||
if args.vulkan:
|
||
r = xe.init_vulkan()
|
||
if not r.get("ok"):
|
||
print(f"xenith: Vulkan недоступен ({r.get('error')}) — остаюсь на CPU",
|
||
file=sys.stderr)
|
||
else:
|
||
print(f"xenith: Vulkan — {r.get('device', 'GPU')}")
|
||
|
||
state = AppState(args)
|
||
state.load_or_create()
|
||
atexit.register(lambda: state.save(quiet=True))
|
||
|
||
srv = ThreadingHTTPServer((args.host, args.port), Handler)
|
||
srv.state = state
|
||
srv.daemon_threads = True
|
||
|
||
url = f"http://{args.host if args.host not in ('0.0.0.0', '::') else '127.0.0.1'}:{args.port}/"
|
||
print("\n" + "═" * 64)
|
||
print(f" Xenith Lab {xe.version()} [{xe.build_type()}] backend={xe.backend_name()}")
|
||
print(f" модель : {state.model_path}")
|
||
print(f" открыть: {url}")
|
||
print("═" * 64)
|
||
print(" curl -s " + url + "api/status")
|
||
print(" curl -s -X POST " + url + "api/train -H 'Content-Type: application/json' \\")
|
||
print(" -d '{\"steps\":300,\"batch\":4,\"block\":32,\"lr\":0.003}'")
|
||
print(" curl -s -X POST " + url + "api/generate -H 'Content-Type: application/json' \\")
|
||
print(" -d '{\"prompt\":\"ветер\",\"n\":64,\"temperature\":0.8}'")
|
||
print("═" * 64 + "\n")
|
||
|
||
if not args.no_browser:
|
||
threading.Timer(0.8, lambda: webbrowser.open(url)).start()
|
||
|
||
try:
|
||
srv.serve_forever()
|
||
except KeyboardInterrupt:
|
||
print("\nостановка…")
|
||
finally:
|
||
state.save(quiet=True)
|
||
srv.server_close()
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|