1053 lines
47 KiB
HTML
1053 lines
47 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="ru">
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
<title>Xenith Lab — обучение нейросети</title>
|
||
<style>
|
||
:root{
|
||
--bg:#05070f; --panel:rgba(15,23,42,.62); --panel2:rgba(2,6,23,.45);
|
||
--line:rgba(148,163,184,.14); --line2:rgba(148,163,184,.08);
|
||
--text:#e6edf7; --muted:#8b9bb4; --dim:#5b6b82;
|
||
--cyan:#22d3ee; --violet:#a78bfa; --pink:#f472b6; --green:#34d399;
|
||
--amber:#fbbf24; --red:#fb7185; --blue:#60a5fa;
|
||
--mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
|
||
--sans:Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;
|
||
}
|
||
*{box-sizing:border-box}
|
||
html,body{height:100%}
|
||
body{
|
||
margin:0;background:var(--bg);color:var(--text);font-family:var(--sans);
|
||
overflow-x:hidden;-webkit-font-smoothing:antialiased;
|
||
}
|
||
body::after{
|
||
content:"";position:fixed;inset:0;pointer-events:none;z-index:0;
|
||
background:radial-gradient(1200px 700px at 50% -20%,rgba(34,211,238,.06),transparent 60%),
|
||
radial-gradient(900px 600px at 110% 110%,rgba(167,139,250,.06),transparent 60%);
|
||
}
|
||
.bg{position:fixed;inset:0;overflow:hidden;z-index:0;pointer-events:none}
|
||
.blob{position:absolute;width:46vw;height:46vw;border-radius:50%;filter:blur(90px);opacity:.42;mix-blend-mode:screen}
|
||
.b1{background:radial-gradient(circle,#0891b2,transparent 65%);left:-12vw;top:-14vw;animation:float1 19s ease-in-out infinite alternate}
|
||
.b2{background:radial-gradient(circle,#7c3aed,transparent 65%);right:-14vw;top:8vh;animation:float2 23s ease-in-out infinite alternate}
|
||
.b3{background:radial-gradient(circle,#db2777,transparent 65%);left:22vw;bottom:-22vw;animation:float3 27s ease-in-out infinite alternate}
|
||
@keyframes float1{to{transform:translate(8vw,10vh) scale(1.15)}}
|
||
@keyframes float2{to{transform:translate(-7vw,14vh) scale(1.1)}}
|
||
@keyframes float3{to{transform:translate(10vw,-12vh) scale(1.2)}}
|
||
|
||
.topbar{
|
||
position:sticky;top:0;z-index:20;display:flex;align-items:center;justify-content:space-between;
|
||
gap:18px;padding:13px 24px;background:rgba(5,7,15,.7);backdrop-filter:blur(18px);
|
||
border-bottom:1px solid var(--line);
|
||
}
|
||
.brand{display:flex;align-items:center;gap:12px;min-width:0}
|
||
.logo{
|
||
width:42px;height:42px;border-radius:14px;display:grid;place-items:center;font-size:19px;
|
||
background:linear-gradient(135deg,var(--cyan),var(--violet));color:#04121a;
|
||
box-shadow:0 0 34px rgba(34,211,238,.35);animation:logoPulse 4.5s ease-in-out infinite;
|
||
flex:none;
|
||
}
|
||
@keyframes logoPulse{0%,100%{box-shadow:0 0 24px rgba(34,211,238,.25)}50%{box-shadow:0 0 44px rgba(167,139,250,.5)}}
|
||
h1{font-size:16px;margin:0;letter-spacing:.2px;white-space:nowrap}
|
||
.sub{font-size:11.5px;color:var(--muted);margin-top:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.pills{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end}
|
||
.pill{display:inline-flex;align-items:center;gap:7px;font-size:11.5px;padding:6px 10px;border-radius:999px;border:1px solid var(--line);background:rgba(15,23,42,.55);color:var(--muted);white-space:nowrap}
|
||
.pill b{color:var(--text);font-weight:600}
|
||
.pill .dot{width:7px;height:7px;border-radius:50%;background:var(--dim);flex:none}
|
||
.pill.running .dot{background:var(--amber);box-shadow:0 0 12px var(--amber);animation:pulse 1.1s infinite}
|
||
.pill.done .dot{background:var(--green);box-shadow:0 0 12px var(--green)}
|
||
.pill.failed .dot{background:var(--red);box-shadow:0 0 12px var(--red);animation:pulse 1.1s infinite}
|
||
.pill.generating .dot{background:var(--violet);box-shadow:0 0 12px var(--violet);animation:pulse .9s infinite}
|
||
.pill.offline .dot{background:var(--red)}
|
||
@keyframes pulse{0%,100%{opacity:1;transform:scale(1)}50%{opacity:.35;transform:scale(.7)}}
|
||
|
||
.grid{position:relative;z-index:1;display:grid;grid-template-columns:repeat(12,1fr);gap:16px;max-width:1580px;margin:0 auto;padding:18px 22px 64px}
|
||
.card{
|
||
position:relative;background:linear-gradient(180deg,rgba(15,23,42,.74),rgba(10,15,28,.62));
|
||
border:1px solid var(--line);border-radius:20px;padding:18px;
|
||
box-shadow:0 22px 60px -24px rgba(0,0,0,.9),inset 0 1px 0 rgba(255,255,255,.035);
|
||
backdrop-filter:blur(14px);animation:rise .7s cubic-bezier(.2,.7,.2,1) both;overflow:hidden;
|
||
}
|
||
.card::before{content:"";position:absolute;inset:0;pointer-events:none;
|
||
background:radial-gradient(700px 220px at 100% 0,rgba(34,211,238,.07),transparent 60%)}
|
||
.card:nth-child(2){animation-delay:.05s}.card:nth-child(3){animation-delay:.1s}
|
||
.card:nth-child(4){animation-delay:.15s}.card:nth-child(5){animation-delay:.2s}
|
||
.card:nth-child(6){animation-delay:.25s}.card:nth-child(7){animation-delay:.3s}
|
||
@keyframes rise{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:none}}
|
||
.c8{grid-column:span 8}.c4{grid-column:span 4}.c7{grid-column:span 7}.c5{grid-column:span 5}.c12{grid-column:span 12}
|
||
.card h2{margin:0;font-size:11px;font-weight:700;letter-spacing:.16em;text-transform:uppercase;color:var(--muted);display:flex;align-items:center;gap:8px}
|
||
.card h2 .tag{font-size:9.5px;letter-spacing:.08em;color:var(--dim);border:1px solid var(--line);padding:2px 7px;border-radius:999px;font-weight:500;text-transform:none}
|
||
.card .head{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:12px}
|
||
|
||
.metrics{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin:14px 0 10px}
|
||
.metric{background:var(--panel2);border:1px solid var(--line2);border-radius:14px;padding:10px 12px;min-width:0}
|
||
.metric .v{font-family:var(--mono);font-size:20px;font-weight:600;letter-spacing:-.5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.metric .l{font-size:10px;text-transform:uppercase;letter-spacing:.13em;color:var(--dim);margin-top:3px;white-space:nowrap}
|
||
.metric.hl .v{color:var(--cyan);text-shadow:0 0 18px rgba(34,211,238,.35)}
|
||
|
||
.chart-wrap{position:relative;height:272px}
|
||
#lossChart{width:100%;height:100%;display:block;border-radius:12px;cursor:crosshair}
|
||
.empty{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;color:var(--dim);font-size:12.5px;pointer-events:none;text-align:center;padding:20px}
|
||
|
||
.progress{height:9px;border-radius:999px;background:var(--panel2);border:1px solid var(--line2);overflow:hidden;margin-top:14px}
|
||
.progress .bar{height:100%;width:0;background:linear-gradient(90deg,var(--cyan),var(--violet),var(--pink));background-size:220% 100%;animation:gradientMove 3.2s linear infinite;transition:width .35s ease;box-shadow:0 0 18px rgba(34,211,238,.55)}
|
||
@keyframes gradientMove{to{background-position:220% 0}}
|
||
.progress-meta{display:flex;justify-content:space-between;margin-top:7px;font-size:11px;color:var(--dim);font-family:var(--mono)}
|
||
|
||
.fields{display:grid;grid-template-columns:repeat(2,1fr);gap:10px}
|
||
.field{display:flex;flex-direction:column;gap:5px;min-width:0}
|
||
.field label{font-size:10.5px;color:var(--muted);letter-spacing:.05em;text-transform:uppercase}
|
||
.field .hint{font-size:10px;color:var(--dim);font-family:var(--mono)}
|
||
input,textarea,select{
|
||
background:rgba(2,6,23,.55);border:1px solid var(--line);border-radius:12px;color:var(--text);
|
||
padding:10px 12px;font:inherit;outline:none;transition:border-color .2s,box-shadow .2s;width:100%;
|
||
}
|
||
input:focus,textarea:focus,select:focus{border-color:rgba(34,211,238,.55);box-shadow:0 0 0 3px rgba(34,211,238,.12)}
|
||
textarea{resize:vertical;min-height:74px;font-family:var(--mono);font-size:11.5px;line-height:1.55}
|
||
input[type=range]{padding:0;height:26px;accent-color:var(--cyan);background:transparent;border:0;box-shadow:none}
|
||
.range-row{display:flex;align-items:center;gap:10px}
|
||
.range-row .val{font-family:var(--mono);font-size:12px;color:var(--cyan);min-width:52px;text-align:right}
|
||
|
||
.btn{
|
||
position:relative;border:0;border-radius:12px;padding:11px 16px;font-weight:650;font-size:13px;color:#04121a;
|
||
background:linear-gradient(135deg,var(--cyan),#7dd3fc);cursor:pointer;overflow:hidden;
|
||
transition:transform .15s,box-shadow .2s,filter .2s;box-shadow:0 12px 28px -12px rgba(34,211,238,.7);
|
||
}
|
||
.btn:hover{transform:translateY(-1px);box-shadow:0 18px 34px -14px rgba(34,211,238,.85)}
|
||
.btn:active{transform:scale(.98)}
|
||
.btn:disabled{opacity:.42;cursor:not-allowed;transform:none;box-shadow:none;filter:grayscale(.4)}
|
||
.btn.violet{background:linear-gradient(135deg,var(--violet),var(--pink));color:#170a20;box-shadow:0 12px 28px -12px rgba(167,139,250,.7)}
|
||
.btn.ghost{background:rgba(148,163,184,.09);color:var(--text);border:1px solid var(--line);box-shadow:none}
|
||
.btn.danger{background:linear-gradient(135deg,#fb7185,#f43f5e);color:#1a0508;box-shadow:0 12px 28px -12px rgba(251,113,133,.6)}
|
||
.btn.loading::after{content:"";position:absolute;inset:0;background:linear-gradient(90deg,transparent,rgba(255,255,255,.4),transparent);animation:shimmer 1s infinite}
|
||
@keyframes shimmer{from{transform:translateX(-100%)}to{transform:translateX(100%)}}
|
||
.btn-row{display:flex;gap:8px;flex-wrap:wrap;margin-top:12px}
|
||
.seg{display:inline-flex;background:var(--panel2);border:1px solid var(--line);border-radius:10px;padding:3px;gap:2px}
|
||
.seg button{border:0;background:transparent;color:var(--muted);padding:5px 10px;border-radius:8px;font-size:11px;cursor:pointer;transition:.2s;font-family:inherit}
|
||
.seg button.on{background:rgba(34,211,238,.14);color:var(--cyan);box-shadow:0 0 12px rgba(34,211,238,.16)}
|
||
.check{display:inline-flex;align-items:center;gap:6px;font-size:11px;color:var(--muted);cursor:pointer;user-select:none}
|
||
.check input{width:auto;accent-color:var(--cyan)}
|
||
|
||
.output{
|
||
min-height:130px;max-height:320px;overflow:auto;background:var(--panel2);border:1px solid var(--line2);
|
||
border-radius:14px;padding:14px;font-family:var(--mono);font-size:13px;line-height:1.62;
|
||
white-space:pre-wrap;color:#c9f9ff;margin-top:12px;
|
||
}
|
||
.chatlog{display:flex;flex-direction:column;gap:8px;min-height:260px;max-height:360px;overflow:auto;
|
||
padding:10px;background:var(--panel2);border:1px solid var(--line2);border-radius:14px;margin-top:12px;scroll-behavior:smooth}
|
||
.msg{max-width:84%;padding:9px 12px;border-radius:14px;font-size:12.5px;line-height:1.55;
|
||
white-space:pre-wrap;animation:msgIn .3s ease both;border:1px solid transparent}
|
||
.msg.user{align-self:flex-end;background:linear-gradient(135deg,rgba(34,211,238,.18),rgba(34,211,238,.06));
|
||
border-color:rgba(34,211,238,.28);border-bottom-right-radius:4px}
|
||
.msg.bot{align-self:flex-start;background:rgba(167,139,250,.09);border-color:rgba(167,139,250,.22);
|
||
border-bottom-left-radius:4px}
|
||
.msg .who{font-size:9px;text-transform:uppercase;letter-spacing:.12em;color:var(--dim);margin-bottom:3px}
|
||
.msg .body{color:var(--text)}
|
||
@keyframes msgIn{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
|
||
.cursor{display:inline-block;width:8px;height:15px;background:var(--cyan);margin-left:2px;vertical-align:-2px;animation:blink 1s steps(2) infinite}
|
||
@keyframes blink{50%{opacity:0}}
|
||
.meta{font-size:11px;color:var(--dim);font-family:var(--mono);margin-top:8px;min-height:15px}
|
||
|
||
.events{list-style:none;margin:0;padding:0;max-height:330px;overflow:auto}
|
||
.event{display:grid;grid-template-columns:20px 54px 1fr;gap:8px;align-items:start;padding:7px 4px;border-bottom:1px dashed var(--line2);font-size:12px;animation:slideIn .35s ease both}
|
||
.event .ico{font-size:13px;line-height:1.2}
|
||
.event .t{font-family:var(--mono);font-size:10.5px;color:var(--dim);padding-top:1px}
|
||
.event .msg{color:var(--muted);word-break:break-word}
|
||
.event.kind-train .msg,.event.kind-reset .msg{color:#a5f3fc}
|
||
.event.kind-generate .msg{color:#ddd6fe}
|
||
.event.kind-error .msg{color:#fecdd3}
|
||
.event.kind-finish .msg{color:#bbf7d0}
|
||
.event.kind-note .msg{color:#fde68a}
|
||
@keyframes slideIn{from{opacity:0;transform:translateX(-8px)}to{opacity:1;transform:none}}
|
||
|
||
.log{max-height:270px;overflow:auto;background:var(--panel2);border:1px solid var(--line2);border-radius:14px;padding:12px;font-family:var(--mono);font-size:11px;line-height:1.55;color:#8ea3bd;white-space:pre-wrap}
|
||
.log .warn{color:#fcd34d}.log .err{color:#fda4af}.log .info{color:#93c5fd}.log .dbg{color:#64748b}
|
||
|
||
.net-wrap{position:relative;height:248px}
|
||
#netCanvas{width:100%;height:100%;display:block}
|
||
.net-caption{font-family:var(--mono);font-size:10.5px;color:var(--dim);text-align:center;margin-top:6px}
|
||
|
||
.curl-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:12px}
|
||
.curl{position:relative;background:var(--panel2);border:1px solid var(--line2);border-radius:14px;padding:13px 12px 11px;min-width:0}
|
||
.curl .k{font-size:10px;text-transform:uppercase;letter-spacing:.12em;color:var(--dim);padding-right:58px}
|
||
.curl pre{margin:7px 0 0;font-family:var(--mono);font-size:11px;color:#a5f3fc;white-space:pre-wrap;word-break:break-word;line-height:1.5}
|
||
.copy{position:absolute;right:8px;top:8px;font-size:10px;padding:4px 8px;border-radius:8px;border:1px solid var(--line);background:rgba(148,163,184,.08);color:var(--muted);cursor:pointer;transition:.2s}
|
||
.copy:hover{color:var(--cyan);border-color:rgba(34,211,238,.4)}
|
||
|
||
.toast{
|
||
position:fixed;right:20px;bottom:20px;max-width:380px;padding:12px 16px;border-radius:14px;
|
||
background:rgba(15,23,42,.94);border:1px solid rgba(34,211,238,.38);
|
||
box-shadow:0 22px 60px rgba(0,0,0,.7);color:var(--text);font-size:13px;
|
||
transform:translateY(22px);opacity:0;pointer-events:none;transition:.35s cubic-bezier(.2,.7,.2,1);z-index:60;
|
||
}
|
||
.toast.show{transform:translateY(0);opacity:1}
|
||
.toast.err{border-color:rgba(251,113,133,.55)}
|
||
|
||
.footer{color:var(--dim);font-size:11px;text-align:center;padding:6px 20px 30px;position:relative;z-index:1}
|
||
.footer b{color:var(--muted)}
|
||
|
||
::-webkit-scrollbar{width:9px;height:9px}
|
||
::-webkit-scrollbar-track{background:transparent}
|
||
::-webkit-scrollbar-thumb{background:rgba(148,163,184,.18);border-radius:9px;border:2px solid transparent;background-clip:content-box}
|
||
::-webkit-scrollbar-thumb:hover{background:rgba(34,211,238,.35);background-clip:content-box}
|
||
|
||
@media (max-width:1120px){
|
||
.c8,.c4,.c7,.c5{grid-column:span 12}
|
||
.metrics{grid-template-columns:repeat(2,1fr)}
|
||
.curl-grid{grid-template-columns:1fr}
|
||
}
|
||
@media (max-width:640px){
|
||
.topbar{padding:11px 14px}
|
||
.pills{display:none}
|
||
.grid{padding:12px 12px 44px;gap:12px}
|
||
.fields{grid-template-columns:1fr}
|
||
.metrics{grid-template-columns:repeat(2,1fr)}
|
||
.metric .v{font-size:17px}
|
||
}
|
||
@media (prefers-reduced-motion:reduce){
|
||
*,*::before,*::after{animation-duration:.001s!important;animation-iteration-count:1!important;transition-duration:.001s!important}
|
||
}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<div class="bg"><div class="blob b1"></div><div class="blob b2"></div><div class="blob b3"></div></div>
|
||
|
||
<header class="topbar">
|
||
<div class="brand">
|
||
<div class="logo">◈</div>
|
||
<div>
|
||
<h1>Xenith Lab</h1>
|
||
<div class="sub" id="model-name">визуальный дашборд обучения · C++17 · CPU/Vulkan</div>
|
||
</div>
|
||
</div>
|
||
<div class="pills">
|
||
<span class="pill" id="pill-state"><span class="dot"></span><span class="txt">idle</span></span>
|
||
<span class="pill" id="pill-backend"><span class="dot"></span><span class="txt">backend</span></span>
|
||
<span class="pill" id="pill-version"><span class="dot"></span><span class="txt">v—</span></span>
|
||
<span class="pill" id="pill-model"><span class="dot"></span><span class="txt">model</span></span>
|
||
</div>
|
||
</header>
|
||
|
||
<main class="grid">
|
||
<!-- LOSS -->
|
||
<section class="card c8">
|
||
<div class="head">
|
||
<h2>Кривая обучения <span class="tag">loss · EMA</span></h2>
|
||
<div class="pill" id="pill-phase"><span class="dot"></span><span class="txt">idle</span></div>
|
||
</div>
|
||
<div class="metrics">
|
||
<div class="metric hl"><div class="v" id="m-loss">—</div><div class="l">loss</div></div>
|
||
<div class="metric"><div class="v" id="m-step">0</div><div class="l">шаг</div></div>
|
||
<div class="metric"><div class="v" id="m-tps">0</div><div class="l">ток/сек</div></div>
|
||
<div class="metric"><div class="v" id="m-elapsed">0</div><div class="l">секунд</div></div>
|
||
</div>
|
||
<div class="chart-wrap">
|
||
<canvas id="lossChart"></canvas>
|
||
<div class="empty" id="chart-empty">Нажмите «Старт» — здесь появится живая кривая loss.<br>Чем ниже, тем лучше.</div>
|
||
</div>
|
||
<div class="progress"><div class="bar" id="bar"></div></div>
|
||
<div class="progress-meta"><span id="progress-label">0 / 0</span><span id="lr-label">lr —</span></div>
|
||
</section>
|
||
|
||
<!-- NETWORK -->
|
||
<section class="card c4">
|
||
<div class="head"><h2>Нейросеть <span class="tag">live</span></h2></div>
|
||
<div class="net-wrap"><canvas id="netCanvas"></canvas></div>
|
||
<div class="net-caption" id="net-caption">—</div>
|
||
</section>
|
||
|
||
<!-- TRAINING -->
|
||
<section class="card c4">
|
||
<div class="head"><h2>Обучение <span class="tag">API</span></h2></div>
|
||
<div class="fields">
|
||
<div class="field"><label for="f-steps">Шаги (+)</label><input id="f-steps" type="number" min="1" max="100000" value="200"></div>
|
||
<div class="field"><label for="f-batch">Batch</label><input id="f-batch" type="number" min="1" max="64" value="4"></div>
|
||
<div class="field"><label for="f-block">Block</label><input id="f-block" type="number" min="1" max="1024" value="32"><div class="hint" id="f-block-hint">≤ контекста модели</div></div>
|
||
<div class="field"><label for="f-lr">Learning rate</label><input id="f-lr" type="number" step="0.0001" min="0.000001" max="1" value="0.003"></div>
|
||
</div>
|
||
<div class="field" style="margin-top:10px">
|
||
<label for="f-corpus">Корпус (текст)</label>
|
||
<textarea id="f-corpus" spellcheck="false" placeholder="Текст, на котором учимся…"></textarea>
|
||
<div class="hint">Пусто — встроенный корпус. Словарь фиксируется при создании модели; незнакомые символы → <unk>.</div>
|
||
</div>
|
||
<div class="btn-row">
|
||
<button class="btn" id="btn-train">▶ Старт</button>
|
||
<button class="btn ghost" id="btn-stop" disabled>⏹ Стоп</button>
|
||
<button class="btn ghost" id="btn-save">💾 Сохранить</button>
|
||
<button class="btn ghost" id="btn-finetune">💬 Дообучить диалогу</button>
|
||
<button class="btn ghost" id="btn-reset">✨ Новая модель</button>
|
||
</div>
|
||
</section>
|
||
|
||
<!-- QUERY -->
|
||
<section class="card c8">
|
||
<div class="head">
|
||
<h2>Запрос к модели <span class="tag" id="query-tag">chat</span></h2>
|
||
<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap">
|
||
<span class="tag" id="chat-turns">контекст 0</span>
|
||
<div class="seg" id="mode-seg">
|
||
<button data-mode="chat" class="on">Диалог</button>
|
||
<button data-mode="gen">Продолжение</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="field">
|
||
<label for="q-prompt">Сообщение</label>
|
||
<textarea id="q-prompt" spellcheck="false" placeholder="Например: привет">привет</textarea>
|
||
</div>
|
||
<div class="fields" style="margin-top:10px">
|
||
<div class="field"><label>Длина (n)</label><div class="range-row"><input id="q-n" type="range" min="1" max="256" value="64"><span class="val" id="q-n-val">64</span></div></div>
|
||
<div class="field"><label>Temperature</label><div class="range-row"><input id="q-temp" type="range" min="0" max="2" step="0.05" value="0.20"><span class="val" id="q-temp-val">0.20</span></div></div>
|
||
<div class="field"><label>Top-k</label><div class="range-row"><input id="q-topk" type="range" min="1" max="100" value="40"><span class="val" id="q-topk-val">40</span></div></div>
|
||
<div class="field"><label>Top-p</label><div class="range-row"><input id="q-topp" type="range" min="0" max="1" step="0.01" value="0.95"><span class="val" id="q-topp-val">0.95</span></div></div>
|
||
</div>
|
||
<div class="btn-row">
|
||
<button class="btn violet" id="btn-gen">💬 Отправить</button>
|
||
<input id="q-seed" type="number" value="-1" title="seed (-1 = случайный)" style="max-width:110px" aria-label="seed">
|
||
<button class="btn ghost" id="btn-chat-reset">↺ Сбросить диалог</button>
|
||
<label class="check"><input type="checkbox" id="q-history" checked> помнить контекст</label>
|
||
</div>
|
||
<div class="chatlog" id="chat-log"></div>
|
||
<div class="output" id="q-out" style="display:none">Здесь появится ответ модели…</div>
|
||
<div class="meta" id="q-meta"></div>
|
||
</section>
|
||
|
||
<!-- HISTORY -->
|
||
<section class="card c5">
|
||
<div class="head"><h2>История действий <span class="tag">timeline</span></h2></div>
|
||
<ul class="events" id="events"></ul>
|
||
</section>
|
||
|
||
<!-- LOG -->
|
||
<section class="card c7">
|
||
<div class="head"><h2>Живой лог движка <span class="tag">engine</span></h2></div>
|
||
<div class="log" id="log">—</div>
|
||
</section>
|
||
|
||
<!-- CURL -->
|
||
<section class="card c12">
|
||
<div class="head"><h2>Управление через curl <span class="tag">REST API</span></h2><span class="pill"><span class="dot"></span><span class="txt">127.0.0.1</span></span></div>
|
||
<div class="curl-grid">
|
||
<div class="curl"><div class="k">статус</div><button class="copy">copy</button><pre id="curl-status"></pre></div>
|
||
<div class="curl"><div class="k">обучение</div><button class="copy">copy</button><pre id="curl-train"></pre></div>
|
||
<div class="curl"><div class="k">запрос</div><button class="copy">copy</button><pre id="curl-gen"></pre></div>
|
||
<div class="curl"><div class="k">стоп / сохранить / сброс</div><button class="copy">copy</button><pre id="curl-misc"></pre></div>
|
||
</div>
|
||
</section>
|
||
</main>
|
||
|
||
<div class="footer">Xenith Lab · <b>обучение, график и запросы</b> в одном окне. API слушает только localhost.</div>
|
||
<div class="toast" id="toast"></div>
|
||
|
||
<script>
|
||
"use strict";
|
||
const $ = id => document.getElementById(id);
|
||
const esc = s => String(s).replace(/[&<>"']/g, c => ({"&":"&","<":"<",">":">",'"':""","'":"'"}[c]));
|
||
|
||
/* ------------------------------------------------------------------ state */
|
||
const S = {
|
||
running:false, generating:false, phase:"idle", prevPhase:"idle", mode:"chat",
|
||
history:[], netKey:"", lastError:"", evSeen:new Set(), logHash:"", chartInit:false,
|
||
messages:[],
|
||
};
|
||
|
||
const display = {};
|
||
function fmtNum(v, d=0){
|
||
if(!Number.isFinite(v)) return "—";
|
||
return d ? v.toFixed(d) : Math.round(v).toLocaleString("ru-RU");
|
||
}
|
||
function targetNum(id, v, d=0){
|
||
const el = $(id); if(!el) return;
|
||
const cur = display[id]?.cur ?? 0;
|
||
el.dataset.digits = d;
|
||
const to = Number(v) || 0;
|
||
// Не перезапускаем анимацию, если значение не изменилось (иначе каждый
|
||
// poll сбрасывал t и анимация дёргалась).
|
||
if(display[id] && Math.abs(display[id].to - to) < 1e-9) return;
|
||
display[id] = {from:cur, to, t:performance.now()};
|
||
}
|
||
function tickNums(now){
|
||
for(const id in display){
|
||
const d = display[id];
|
||
// rAF-timestamp может быть чуть МЕНЬШЕ performance.now(), взятого в
|
||
// poll-ответе между кадрами. Без clamp k<0 даёт e<0 и огромные
|
||
// отрицательные числа в UI.
|
||
const k = Math.max(0, Math.min(1, (now - d.t) / 420));
|
||
const e = 1 - Math.pow(1-k, 3);
|
||
const v = d.from + (d.to - d.from) * e;
|
||
d.cur = v;
|
||
const el = $(id);
|
||
if(el) el.textContent = fmtNum(v, +el.dataset.digits || 0);
|
||
}
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ toast */
|
||
let toastTimer = null;
|
||
function toast(msg, err=false){
|
||
const t = $("toast");
|
||
t.textContent = msg;
|
||
t.className = "toast show" + (err ? " err" : "");
|
||
clearTimeout(toastTimer);
|
||
toastTimer = setTimeout(()=>{ t.className = "toast" + (err ? " err" : ""); }, 4200);
|
||
}
|
||
|
||
/* ------------------------------------------------------------------- api */
|
||
async function api(path, body){
|
||
const opt = body === undefined ? {} : {
|
||
method:"POST", headers:{"Content-Type":"application/json"}, body:JSON.stringify(body),
|
||
};
|
||
const r = await fetch(path, opt);
|
||
let j;
|
||
try { j = await r.json(); } catch(e){ j = {error:"некорректный ответ сервера"}; }
|
||
if(!r.ok) throw new Error(j.error || ("HTTP " + r.status));
|
||
return j;
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ pills */
|
||
function setPill(id, cls, text){
|
||
const p = $(id); if(!p) return;
|
||
p.className = "pill " + (cls||"");
|
||
const t = p.querySelector(".txt"); if(t) t.textContent = text;
|
||
}
|
||
|
||
/* --------------------------------------------------------------- status */
|
||
function applyStatus(s){
|
||
S.running = !!s.is_running;
|
||
S.generating = !!s.generating;
|
||
|
||
const phaseCls = S.running ? "running" : (s.phase==="failed" ? "failed" :
|
||
(s.phase==="done"||s.phase==="cancelled") ? "done" :
|
||
(s.generating ? "generating" : ""));
|
||
const phaseTxt = S.generating ? "генерация" : (S.running ? "обучение" : s.phase);
|
||
setPill("pill-state", phaseCls, phaseTxt);
|
||
setPill("pill-phase", phaseCls, phaseTxt);
|
||
setPill("pill-backend", s.backend_is_gpu ? "done" : "", s.backend + (s.backend_is_gpu ? " · GPU" : " · CPU"));
|
||
setPill("pill-version", "", "v" + s.version);
|
||
const base = (s.model_path || "").split(/[\\/]/).pop() || "—";
|
||
setPill("pill-model", "", base);
|
||
$("model-name").textContent = s.model_path || "модель в памяти";
|
||
|
||
targetNum("m-loss", s.loss, 4);
|
||
targetNum("m-step", s.step, 0);
|
||
targetNum("m-tps", s.tokens_per_sec, 1);
|
||
targetNum("m-elapsed", s.elapsed_sec, 1);
|
||
|
||
S.history = s.history || [];
|
||
chartData = S.history;
|
||
if(chartData.length < 2){ chartView = 0; S.chartInit = false; }
|
||
chartTarget = chartData.length;
|
||
// При первой загрузке истории показываем её целиком, без «дорисовки».
|
||
if(!S.chartInit && chartData.length > 1){ chartView = chartData.length; S.chartInit = true; }
|
||
|
||
const pct = s.total ? Math.min(100, 100*s.step/s.total) : 0;
|
||
$("bar").style.width = pct.toFixed(2) + "%";
|
||
$("progress-label").textContent = (s.total ? s.step + " / " + s.total : String(s.step));
|
||
$("lr-label").textContent = "lr " + (s.lr ? s.lr.toExponential(2) : "—");
|
||
|
||
const info = s.info || {};
|
||
if(info.n_layer) $("net-caption").textContent =
|
||
`${info.n_layer} слоёв · ${info.n_head} голов · ${info.n_embd} эмбеддинг · ` +
|
||
`${(Number(info.n_params||0)/1e6).toFixed(2)}M параметров`;
|
||
if(info.block_size) {
|
||
$("f-block").max = String(info.block_size);
|
||
$("f-block-hint").textContent = "≤ " + info.block_size + " (контекст модели)";
|
||
}
|
||
const key = [info.n_layer, info.n_head, info.n_embd].join(":");
|
||
if(key !== S.netKey){ S.netKey = key; buildNet(info); }
|
||
|
||
renderEvents(s.events || []);
|
||
const eng = (s.engine_log && s.engine_log.length)
|
||
? s.engine_log
|
||
: (s.events || []).map(e => ({level: e.kind === "error" ? 3 : 1,
|
||
msg: `${e.t} ${e.msg}`}));
|
||
renderLog(eng);
|
||
|
||
if(s.error && s.error !== S.lastError){
|
||
S.lastError = s.error;
|
||
toast("Ошибка: " + s.error, true);
|
||
}
|
||
if(S.prevPhase !== s.phase){
|
||
if(s.phase === "done") toast("Обучение завершено ✓");
|
||
if(s.phase === "failed") toast("Обучение упало: " + (s.error || "см. лог"), true);
|
||
if(s.phase === "cancelled") toast("Обучение остановлено");
|
||
S.prevPhase = s.phase;
|
||
}
|
||
|
||
$("btn-train").disabled = S.running || S.generating;
|
||
$("btn-stop").disabled = !S.running;
|
||
$("btn-gen").disabled = S.running || S.generating;
|
||
$("btn-reset").disabled = S.running || S.generating;
|
||
$("btn-chat-reset").disabled = S.running || S.generating;
|
||
$("btn-finetune").disabled = S.running || S.generating;
|
||
$("btn-gen").classList.toggle("loading", S.generating);
|
||
const turns = s.chat_turns || 0;
|
||
$("chat-turns").textContent = "контекст " + turns;
|
||
if(S.mode === "chat" && turns === 0 && S.messages.length && !S.generating){
|
||
// Сервер перезапустился/сбросил историю — не показываем «висящий» диалог.
|
||
clearChatLog();
|
||
$("q-meta").textContent = "";
|
||
}
|
||
if(S.mode === "chat" && !$("q-meta").textContent && turns)
|
||
$("q-meta").textContent = "история: " + turns + " ход(ов)";
|
||
}
|
||
|
||
async function poll(){
|
||
try{
|
||
const s = await api("/api/status");
|
||
applyStatus(s);
|
||
}catch(e){
|
||
setPill("pill-state", "offline", "offline");
|
||
}
|
||
setTimeout(poll, S.running ? 320 : 900);
|
||
}
|
||
|
||
/* --------------------------------------------------------------- events */
|
||
const ICONS = {train:"🚀", stop:"⏹", finish:"🏁", generate:"💬", model:"🧠",
|
||
save:"💾", reset:"✨", note:"📝", error:"⚠️"};
|
||
function renderEvents(ev){
|
||
const list = $("events");
|
||
if(!ev.length){
|
||
if(list.children.length){ list.innerHTML = ""; S.evSeen.clear(); }
|
||
return;
|
||
}
|
||
// сервер отдаёт oldest→newest; новые кладём сверху
|
||
for(const e of ev){
|
||
const key = e.t + "|" + e.kind + "|" + e.msg;
|
||
if(S.evSeen.has(key)) continue;
|
||
S.evSeen.add(key);
|
||
const li = document.createElement("li");
|
||
li.className = "event kind-" + e.kind;
|
||
li.innerHTML = `<span class="ico">${ICONS[e.kind] || "•"}</span>` +
|
||
`<span class="t">${esc(e.t)}</span>` +
|
||
`<span class="msg">${esc(e.msg)}</span>`;
|
||
list.prepend(li);
|
||
}
|
||
while(list.children.length > 140) list.lastChild.remove();
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ log */
|
||
function renderLog(log){
|
||
const h = log.map(l => l.level + ":" + l.msg).join("\n");
|
||
if(h === S.logHash) return;
|
||
S.logHash = h;
|
||
const pre = $("log");
|
||
const atBottom = pre.scrollTop + pre.clientHeight >= pre.scrollHeight - 40;
|
||
const names = ["dbg","info","warn","err"];
|
||
pre.innerHTML = log.slice(-90).map(l => {
|
||
const lvl = Math.max(0, Math.min(3, Number(l.level)||0));
|
||
return `<span class="${names[lvl]}">${names[lvl].padStart(3)}</span> ` + esc(l.msg);
|
||
}).join("\n") || "—";
|
||
if(atBottom) pre.scrollTop = pre.scrollHeight;
|
||
}
|
||
|
||
/* ---------------------------------------------------------------- chart */
|
||
const lossCanvas = $("lossChart");
|
||
const lctx = lossCanvas.getContext("2d");
|
||
let chartData = [], chartTarget = 0, chartView = 0, hoverX = null, chartGeom = null;
|
||
|
||
function fitCanvas(c){
|
||
const dpr = Math.min(2, window.devicePixelRatio || 1);
|
||
const w = c.clientWidth, h = c.clientHeight;
|
||
if(!w || !h) return false;
|
||
if(c.width !== Math.round(w*dpr) || c.height !== Math.round(h*dpr)){
|
||
c.width = Math.round(w*dpr); c.height = Math.round(h*dpr);
|
||
}
|
||
const g = c.getContext("2d");
|
||
g.setTransform(dpr,0,0,dpr,0,0);
|
||
return true;
|
||
}
|
||
|
||
function drawLoss(now){
|
||
if(!fitCanvas(lossCanvas)) return;
|
||
const W = lossCanvas.clientWidth, H = lossCanvas.clientHeight;
|
||
lctx.clearRect(0,0,W,H);
|
||
const pad = {l:46,r:14,t:14,b:26};
|
||
const x0 = pad.l, x1 = W-pad.r, y0 = pad.t, y1 = H-pad.b;
|
||
|
||
const n = chartData.length;
|
||
const empty = $("chart-empty");
|
||
if(n < 2){
|
||
if(empty) empty.style.display = "flex";
|
||
lctx.strokeStyle = "rgba(148,163,184,.10)";
|
||
lctx.lineWidth = 1;
|
||
for(let i=0;i<=4;i++){
|
||
const y = y0 + (y1-y0)*i/4;
|
||
lctx.beginPath(); lctx.moveTo(x0,y); lctx.lineTo(x1,y); lctx.stroke();
|
||
}
|
||
chartGeom = null;
|
||
return;
|
||
}
|
||
if(empty) empty.style.display = "none";
|
||
|
||
chartView += (chartTarget - chartView) * 0.30;
|
||
const m = Math.max(2, Math.min(n, Math.floor(chartView)));
|
||
const data = chartData.slice(0, m);
|
||
|
||
let lo = Infinity, hi = -Infinity;
|
||
for(const p of data){
|
||
const v = Number(p.loss);
|
||
if(Number.isFinite(v)){ if(v<lo) lo=v; if(v>hi) hi=v; }
|
||
}
|
||
if(!Number.isFinite(lo)){ lo = 0; hi = 1; }
|
||
if(hi - lo < 1e-6) hi = lo + 1e-3;
|
||
const padY = (hi-lo)*0.14; lo -= padY; hi += padY;
|
||
|
||
const firstStep = data[0].step, lastStep = data[data.length-1].step;
|
||
const spanX = Math.max(1, lastStep - firstStep);
|
||
const sx = s => x0 + (x1-x0) * ((s-firstStep)/spanX);
|
||
const sy = v => y1 - (y1-y0) * ((v-lo)/(hi-lo));
|
||
|
||
// сетка
|
||
lctx.font = "10px " + getComputedStyle(document.body).fontFamily;
|
||
lctx.textBaseline = "middle";
|
||
for(let i=0;i<=4;i++){
|
||
const y = y0 + (y1-y0)*i/4;
|
||
lctx.strokeStyle = "rgba(148,163,184,.10)";
|
||
lctx.lineWidth = 1;
|
||
lctx.beginPath(); lctx.moveTo(x0,y); lctx.lineTo(x1,y); lctx.stroke();
|
||
lctx.fillStyle = "rgba(139,155,180,.75)";
|
||
lctx.textAlign = "right";
|
||
lctx.fillText((hi - (hi-lo)*i/4).toFixed(3), x0-8, y);
|
||
}
|
||
lctx.textAlign = "center";
|
||
lctx.fillStyle = "rgba(139,155,180,.75)";
|
||
const mid = Math.round(firstStep + spanX/2);
|
||
lctx.fillText(String(firstStep), x0+8, y1+15);
|
||
lctx.fillText(String(mid), (x0+x1)/2, y1+15);
|
||
lctx.fillText(String(lastStep), x1-8, y1+15);
|
||
|
||
// сырой loss
|
||
lctx.beginPath();
|
||
data.forEach((p,i)=>{ const x=sx(p.step), y=sy(Number(p.loss)||0); i?lctx.lineTo(x,y):lctx.moveTo(x,y); });
|
||
lctx.strokeStyle = "rgba(34,211,238,.26)";
|
||
lctx.lineWidth = 1.2;
|
||
lctx.stroke();
|
||
|
||
// EMA
|
||
const ema = [];
|
||
let e = null;
|
||
for(const p of data){
|
||
const v = Number(p.loss)||0;
|
||
e = (e === null) ? v : e*0.84 + v*0.16;
|
||
ema.push(e);
|
||
}
|
||
const grad = lctx.createLinearGradient(x0,0,x1,0);
|
||
grad.addColorStop(0,"#22d3ee");
|
||
grad.addColorStop(.55,"#818cf8");
|
||
grad.addColorStop(1,"#a78bfa");
|
||
lctx.beginPath();
|
||
data.forEach((p,i)=>{ const x=sx(p.step), y=sy(ema[i]); i?lctx.lineTo(x,y):lctx.moveTo(x,y); });
|
||
lctx.strokeStyle = grad;
|
||
lctx.lineWidth = 2.4;
|
||
lctx.shadowColor = "rgba(34,211,238,.55)";
|
||
lctx.shadowBlur = 14;
|
||
lctx.stroke();
|
||
lctx.shadowBlur = 0;
|
||
|
||
// заливка
|
||
lctx.beginPath();
|
||
data.forEach((p,i)=>{ const x=sx(p.step), y=sy(ema[i]); i?lctx.lineTo(x,y):lctx.moveTo(x,y); });
|
||
lctx.lineTo(sx(data[data.length-1].step), y1);
|
||
lctx.lineTo(sx(data[0].step), y1);
|
||
lctx.closePath();
|
||
const fg = lctx.createLinearGradient(0,y0,0,y1);
|
||
fg.addColorStop(0,"rgba(34,211,238,.20)");
|
||
fg.addColorStop(1,"rgba(34,211,238,0)");
|
||
lctx.fillStyle = fg;
|
||
lctx.fill();
|
||
|
||
// последняя точка
|
||
const lp = data[data.length-1];
|
||
const lx = sx(lp.step), ly = sy(ema[ema.length-1]);
|
||
const pr = 3.6 + Math.sin(now/280)*1.1;
|
||
lctx.beginPath(); lctx.arc(lx,ly,pr,0,Math.PI*2);
|
||
lctx.fillStyle = "#67e8f9";
|
||
lctx.shadowColor = "#22d3ee"; lctx.shadowBlur = 20; lctx.fill(); lctx.shadowBlur = 0;
|
||
|
||
chartGeom = {x0,x1,y0,y1,data,sx,sy,ema};
|
||
|
||
// подсказка
|
||
if(hoverX !== null && hoverX >= x0 && hoverX <= x1){
|
||
let best = 0, bd = Infinity;
|
||
for(let i=0;i<data.length;i++){
|
||
const d = Math.abs(sx(data[i].step) - hoverX);
|
||
if(d < bd){ bd = d; best = i; }
|
||
}
|
||
const p = data[best];
|
||
const px = sx(p.step), py = sy(ema[best]);
|
||
lctx.strokeStyle = "rgba(167,139,250,.45)";
|
||
lctx.setLineDash([4,4]);
|
||
lctx.beginPath(); lctx.moveTo(px,y0); lctx.lineTo(px,y1); lctx.stroke();
|
||
lctx.setLineDash([]);
|
||
lctx.beginPath(); lctx.arc(px,py,3.2,0,Math.PI*2);
|
||
lctx.fillStyle = "#c4b5fd"; lctx.fill();
|
||
|
||
const txt1 = "шаг " + p.step;
|
||
const txt2 = "loss " + Number(p.loss).toFixed(4);
|
||
lctx.font = "11px " + getComputedStyle(document.body).fontFamily;
|
||
const w = Math.max(lctx.measureText(txt1).width, lctx.measureText(txt2).width) + 18;
|
||
const bh = 38;
|
||
let bx = px + 12, by = py - bh - 10;
|
||
if(bx + w > x1) bx = px - w - 12;
|
||
if(by < y0) by = py + 12;
|
||
lctx.fillStyle = "rgba(2,6,23,.92)";
|
||
lctx.strokeStyle = "rgba(148,163,184,.25)";
|
||
lctx.lineWidth = 1;
|
||
roundRect(lctx, bx, by, w, bh, 8);
|
||
lctx.fill(); lctx.stroke();
|
||
lctx.fillStyle = "#e6edf7"; lctx.textAlign = "left"; lctx.textBaseline = "top";
|
||
lctx.fillText(txt1, bx+9, by+6);
|
||
lctx.fillStyle = "#67e8f9";
|
||
lctx.fillText(txt2, bx+9, by+21);
|
||
}
|
||
}
|
||
|
||
function roundRect(g,x,y,w,h,r){
|
||
g.beginPath();
|
||
g.moveTo(x+r,y); g.arcTo(x+w,y,x+w,y+h,r); g.arcTo(x+w,y+h,x,y+h,r);
|
||
g.arcTo(x,y+h,x,y,r); g.arcTo(x,y,x+w,y,r); g.closePath();
|
||
}
|
||
|
||
lossCanvas.addEventListener("mousemove", e => {
|
||
const r = lossCanvas.getBoundingClientRect();
|
||
hoverX = e.clientX - r.left;
|
||
});
|
||
lossCanvas.addEventListener("mouseleave", ()=>{ hoverX = null; });
|
||
|
||
/* --------------------------------------------------------------- network */
|
||
const netCanvas = $("netCanvas");
|
||
const nctx = netCanvas.getContext("2d");
|
||
const net = {layers:[], pulses:[]};
|
||
|
||
function buildNet(info){
|
||
info = info || {};
|
||
const hidden = Math.max(2, Math.min(6, Number(info.n_layer)||3));
|
||
const sizes = [6];
|
||
for(let i=0;i<hidden;i++) sizes.push(7);
|
||
sizes.push(5);
|
||
net.layers = sizes.map((count, li) => ({li, count, nodes:[]}));
|
||
net.pulses = [];
|
||
}
|
||
|
||
function drawNet(now){
|
||
if(!fitCanvas(netCanvas)) return;
|
||
const W = netCanvas.clientWidth, H = netCanvas.clientHeight;
|
||
nctx.clearRect(0,0,W,H);
|
||
const L = net.layers;
|
||
if(!L.length) return;
|
||
|
||
const padX = 26, padY = 16;
|
||
const maxN = Math.max(...L.map(l=>l.count));
|
||
const gap = Math.min(24, (H - 2*padY) / Math.max(1, maxN-1));
|
||
for(const layer of L){
|
||
const x = L.length === 1 ? W/2 : padX + (W - 2*padX) * layer.li / (L.length - 1);
|
||
layer.nodes = [];
|
||
for(let i=0;i<layer.count;i++){
|
||
layer.nodes.push({x, y: H/2 + (i - (layer.count-1)/2) * gap, ph: Math.random()*6.283});
|
||
}
|
||
}
|
||
|
||
// рёбра
|
||
nctx.lineWidth = 1;
|
||
for(let li=0; li<L.length-1; li++){
|
||
for(const a of L[li].nodes){
|
||
for(const b of L[li+1].nodes){
|
||
nctx.strokeStyle = "rgba(148,163,184,.07)";
|
||
nctx.beginPath(); nctx.moveTo(a.x,a.y); nctx.lineTo(b.x,b.y); nctx.stroke();
|
||
}
|
||
}
|
||
}
|
||
|
||
// импульсы
|
||
const rate = S.running ? 0.55 : 0.05;
|
||
if(L.length > 1 && Math.random() < rate){
|
||
const li = Math.floor(Math.random()*(L.length-1));
|
||
const a = L[li].nodes[Math.floor(Math.random()*L[li].count)];
|
||
const b = L[li+1].nodes[Math.floor(Math.random()*L[li+1].count)];
|
||
net.pulses.push({a,b,t:0,sp:0.008+Math.random()*0.013,hue:Math.random()<.55?190:265});
|
||
}
|
||
net.pulses = net.pulses.filter(p => {
|
||
p.t += p.sp;
|
||
if(p.t > 1) return false;
|
||
const x = p.a.x + (p.b.x - p.a.x) * p.t;
|
||
const y = p.a.y + (p.b.y - p.a.y) * p.t;
|
||
nctx.beginPath(); nctx.arc(x,y,2.1,0,6.283);
|
||
nctx.fillStyle = `hsla(${p.hue},95%,70%,${0.9*(1-p.t)+0.12})`;
|
||
nctx.shadowColor = `hsla(${p.hue},95%,70%,.85)`;
|
||
nctx.shadowBlur = 11; nctx.fill(); nctx.shadowBlur = 0;
|
||
return true;
|
||
});
|
||
|
||
// узлы
|
||
for(const layer of L){
|
||
for(const n of layer.nodes){
|
||
const pulse = 0.5 + 0.5*Math.sin(now/900 + n.ph);
|
||
const glow = S.running ? 0.50 : 0.16;
|
||
const r = 3.0 + pulse*1.2;
|
||
const grd = nctx.createRadialGradient(n.x,n.y,0,n.x,n.y,r*3.4);
|
||
grd.addColorStop(0, `rgba(34,211,238,${glow})`);
|
||
grd.addColorStop(1, "rgba(34,211,238,0)");
|
||
nctx.beginPath(); nctx.arc(n.x,n.y,r*3.4,0,6.283);
|
||
nctx.fillStyle = grd; nctx.fill();
|
||
nctx.beginPath(); nctx.arc(n.x,n.y,r,0,6.283);
|
||
nctx.fillStyle = S.running ? "#67e8f9" : "#334155";
|
||
nctx.fill();
|
||
}
|
||
}
|
||
}
|
||
|
||
/* -------------------------------------------------------------- controls */
|
||
function bindRange(id, out, digits, suffix=""){
|
||
const r = $(id), o = $(out);
|
||
const upd = () => { o.textContent = Number(r.value).toFixed(digits) + suffix; };
|
||
r.addEventListener("input", upd);
|
||
upd();
|
||
}
|
||
bindRange("q-n","q-n-val",0);
|
||
bindRange("q-temp","q-temp-val",2);
|
||
bindRange("q-topk","q-topk-val",0);
|
||
bindRange("q-topp","q-topp-val",2);
|
||
|
||
async function startTrain(){
|
||
const btn = $("btn-train");
|
||
const payload = {
|
||
steps: +$("f-steps").value,
|
||
batch: +$("f-batch").value,
|
||
block: +$("f-block").value,
|
||
lr: +$("f-lr").value,
|
||
corpus: $("f-corpus").value,
|
||
};
|
||
btn.disabled = true;
|
||
try{
|
||
const r = await api("/api/train", payload);
|
||
toast(`Обучение: ${r.base} → ${r.target} шагов`);
|
||
}catch(e){
|
||
toast(e.message, true);
|
||
btn.disabled = false;
|
||
}
|
||
}
|
||
|
||
async function stopTrain(){
|
||
try{ await api("/api/stop", {}); toast("Останавливаю…"); }
|
||
catch(e){ toast(e.message, true); }
|
||
}
|
||
|
||
async function saveModel(){
|
||
try{ const r = await api("/api/save", {}); toast("Сохранено: " + r.path); }
|
||
catch(e){ toast(e.message, true); }
|
||
}
|
||
|
||
async function resetModel(){
|
||
if(!confirm("Создать модель заново? Текущие веса и история будут потеряны.")) return;
|
||
try{
|
||
await api("/api/reset", {corpus:$("f-corpus").value});
|
||
chartData = []; chartTarget = 0; chartView = 0; S.history = []; S.chartInit = false;
|
||
S.evSeen.clear(); $("events").innerHTML = "";
|
||
S.logHash = ""; $("log").textContent = "—";
|
||
$("q-out").textContent = "Здесь появится ответ модели…";
|
||
toast("Новая модель создана ✨");
|
||
}catch(e){ toast(e.message, true); }
|
||
}
|
||
|
||
let typeTimer = null;
|
||
function typewrite(node, text){
|
||
if(typeTimer) clearInterval(typeTimer);
|
||
node.innerHTML = "";
|
||
const span = document.createElement("span");
|
||
const cur = document.createElement("span");
|
||
cur.className = "cursor";
|
||
node.appendChild(span); node.appendChild(cur);
|
||
const full = text || " ";
|
||
const step = Math.max(1, Math.ceil(full.length/240));
|
||
let i = 0;
|
||
typeTimer = setInterval(() => {
|
||
i = Math.min(full.length, i + step);
|
||
span.textContent = full.slice(0, i);
|
||
node.scrollTop = node.scrollHeight;
|
||
if(i >= full.length){ clearInterval(typeTimer); typeTimer = null; cur.remove(); }
|
||
}, 16);
|
||
}
|
||
|
||
function scrollChat(){
|
||
const log = $("chat-log");
|
||
if(log) log.scrollTop = log.scrollHeight;
|
||
}
|
||
|
||
function appendMessage(role, text, animate, track = true){
|
||
const log = $("chat-log");
|
||
if(!log) return null;
|
||
const wrap = document.createElement("div");
|
||
wrap.className = "msg " + (role === "user" ? "user" : "bot");
|
||
const who = document.createElement("div");
|
||
who.className = "who";
|
||
who.textContent = role === "user" ? "вы" : "бот";
|
||
const body = document.createElement("div");
|
||
body.className = "body";
|
||
wrap.append(who, body);
|
||
log.appendChild(wrap);
|
||
if(animate) typewrite(body, text);
|
||
else body.textContent = text;
|
||
scrollChat();
|
||
if(track) S.messages.push({role, text});
|
||
return body;
|
||
}
|
||
|
||
function clearChatLog(){
|
||
const log = $("chat-log");
|
||
if(log) log.innerHTML = "";
|
||
S.messages = [];
|
||
appendMessage("bot", "привет! давай поговорим.", false, false);
|
||
}
|
||
|
||
function setMode(mode){
|
||
S.mode = mode;
|
||
document.querySelectorAll("#mode-seg button").forEach(
|
||
b => b.classList.toggle("on", b.dataset.mode === mode));
|
||
$("query-tag").textContent = mode === "chat" ? "chat" : "generate";
|
||
$("btn-gen").textContent = mode === "chat" ? "💬 Отправить" : "✦ Сгенерировать";
|
||
$("btn-chat-reset").style.display = mode === "chat" ? "" : "none";
|
||
$("chat-log").style.display = mode === "chat" ? "flex" : "none";
|
||
$("q-out").style.display = mode === "chat" ? "none" : "block";
|
||
$("q-prompt").placeholder = mode === "chat" ? "Например: привет" : "Например: утром солнце";
|
||
if(mode === "chat" && !$("chat-log").children.length) clearChatLog();
|
||
}
|
||
|
||
async function generate(){
|
||
const btn = $("btn-gen");
|
||
const text = $("q-prompt").value.trim();
|
||
const opts = {
|
||
n: +$("q-n").value,
|
||
temperature: +$("q-temp").value,
|
||
top_k: +$("q-topk").value,
|
||
top_p: +$("q-topp").value,
|
||
seed: +$("q-seed").value,
|
||
};
|
||
if(S.mode === "chat" && !text){ toast("Введите сообщение", true); return; }
|
||
btn.disabled = true; btn.classList.add("loading");
|
||
try{
|
||
if(S.mode === "chat"){
|
||
appendMessage("user", text, false);
|
||
$("q-prompt").value = "";
|
||
const r = await api("/api/chat", {text, history: $("q-history").checked, ...opts});
|
||
appendMessage("bot", r.text || "(пусто)", true);
|
||
const turns = (r.history && r.history.turns != null) ? r.history.turns : "—";
|
||
$("q-meta").textContent =
|
||
`${(r.tokens||[]).length} ток. · ${Number(r.tok_per_sec||0).toFixed(1)} ток/с · ` +
|
||
`${r.stop_reason} · ходов ${turns}`;
|
||
toast("Ответ готов 💬");
|
||
} else {
|
||
const r = await api("/api/generate", {prompt: text, ...opts});
|
||
typewrite($("q-out"), r.text || "(пусто)");
|
||
$("q-meta").textContent =
|
||
`${(r.tokens||[]).length} ток. · ${Number(r.tok_per_sec||0).toFixed(1)} ток/с · ` +
|
||
`prefill ${Number(r.prefill_sec||0).toFixed(2)}s · gen ${Number(r.gen_sec||0).toFixed(2)}s · ${r.stop_reason}`;
|
||
toast("Ответ готов ✦");
|
||
}
|
||
}catch(e){
|
||
toast(e.message, true);
|
||
if(S.mode === "chat") appendMessage("bot", "не получилось: " + e.message, false);
|
||
}finally{
|
||
btn.disabled = S.running || S.generating;
|
||
btn.classList.remove("loading");
|
||
}
|
||
}
|
||
|
||
async function chatReset(){
|
||
try{
|
||
await api("/api/chat_reset", {});
|
||
}catch(e){
|
||
toast(e.message, true);
|
||
}
|
||
clearChatLog();
|
||
$("q-meta").textContent = "";
|
||
toast("Новый диалог");
|
||
}
|
||
|
||
async function finetuneDialogue(){
|
||
if(!confirm("Дообучить модель на demo/chat_dataset.json (200 шагов)?")) return;
|
||
try{
|
||
const r = await api("/api/finetune", {steps:200, batch:8, lr:0.0015});
|
||
toast(`Диалог: ${r.base} → ${r.target} шагов`);
|
||
}catch(e){
|
||
toast(e.message, true);
|
||
}
|
||
}
|
||
|
||
/* ---------------------------------------------------------------- wiring */
|
||
$("btn-train").addEventListener("click", startTrain);
|
||
$("btn-stop").addEventListener("click", stopTrain);
|
||
$("btn-save").addEventListener("click", saveModel);
|
||
$("btn-finetune").addEventListener("click", finetuneDialogue);
|
||
$("btn-reset").addEventListener("click", resetModel);
|
||
$("btn-gen").addEventListener("click", generate);
|
||
$("btn-chat-reset").addEventListener("click", chatReset);
|
||
document.querySelectorAll("#mode-seg button").forEach(
|
||
b => b.addEventListener("click", () => setMode(b.dataset.mode)));
|
||
$("q-prompt").addEventListener("keydown", e => {
|
||
if(S.mode === "chat" && e.key === "Enter" && !e.shiftKey){
|
||
e.preventDefault();
|
||
generate();
|
||
}
|
||
});
|
||
$("f-corpus").value = $("f-corpus").value || "";
|
||
|
||
document.querySelectorAll(".copy").forEach(b => {
|
||
b.addEventListener("click", async () => {
|
||
const code = b.closest(".curl").querySelector("pre").textContent;
|
||
try{
|
||
await navigator.clipboard.writeText(code);
|
||
toast("Скопировано в буфер");
|
||
}catch(e){
|
||
const ta = document.createElement("textarea");
|
||
ta.value = code; document.body.appendChild(ta); ta.select();
|
||
try{ document.execCommand("copy"); toast("Скопировано"); }
|
||
catch(_){ toast("Не удалось скопировать", true); }
|
||
ta.remove();
|
||
}
|
||
});
|
||
});
|
||
|
||
/* --------------------------------------------------------------- curl UI */
|
||
function setCurl(){
|
||
const o = location.origin;
|
||
$("curl-status").textContent = `curl -s ${o}/api/status`;
|
||
$("curl-train").textContent =
|
||
`curl -s -X POST ${o}/api/train \\
|
||
-H 'Content-Type: application/json' \\
|
||
-d '{"steps":300,"batch":4,"block":32,"lr":0.003}'`;
|
||
$("curl-gen").textContent =
|
||
`curl -s -X POST ${o}/api/chat \\
|
||
-H 'Content-Type: application/json' \\
|
||
-d '{"text":"привет","n":32,"temperature":0.2}'
|
||
|
||
curl -s -X POST ${o}/api/generate \\
|
||
-H 'Content-Type: application/json' \\
|
||
-d '{"prompt":"утром солнце","n":64,"temperature":0.8}'`;
|
||
$("curl-misc").textContent =
|
||
`curl -s -X POST ${o}/api/finetune \\
|
||
-H 'Content-Type: application/json' \\
|
||
-d '{"steps":300,"batch":8,"lr":0.0015}'
|
||
curl -s -X POST ${o}/api/chat_reset
|
||
curl -s -X POST ${o}/api/stop
|
||
curl -s -X POST ${o}/api/save
|
||
curl -s -X POST ${o}/api/reset \\
|
||
-H 'Content-Type: application/json' -d '{}'`;
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ boot */
|
||
setCurl();
|
||
setMode("chat");
|
||
clearChatLog();
|
||
api("/api/chat_reset", {}).catch(() => {});
|
||
buildNet({n_layer:2, n_head:4, n_embd:64});
|
||
function frame(now){
|
||
drawLoss(now);
|
||
drawNet(now);
|
||
tickNums(now);
|
||
requestAnimationFrame(frame);
|
||
}
|
||
requestAnimationFrame(frame);
|
||
poll();
|
||
</script>
|
||
</body>
|
||
</html>
|