Download index.html from IvmeLabs/Ivme-Conversate-on-Device: direct link, hf CLI and curl.
- Browser
- Download file 71.6 kB
-
https://huggingface.co/spaces/IvmeLabs/Ivme-Conversate-on-Device/resolve/main/index.html
- Command line
-
hf download hf://spaces/IvmeLabs/Ivme-Conversate-on-Device/index.html
-
curl -L -o index.html https://huggingface.co/spaces/IvmeLabs/Ivme-Conversate-on-Device/resolve/main/index.html
71.6 kB
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>İvme-Conversate · raw WebGPU inference</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Newsreader:ital,opsz,wght@0,6..72,380;0,6..72,500;0,6..72,600;0,6..72,700;1,6..72,400&family=JetBrains+Mono:wght@400;500;600&display=swap');
html{ background:#f7f4ec; }
*,*::before,*::after{ box-sizing:border-box; }
body{
margin:0;
background:
repeating-linear-gradient(180deg, rgba(0,0,0,0.014) 0px, rgba(0,0,0,0.014) 1px, transparent 1px, transparent 3px),
#f7f4ec;
color:#1c1a16;
font-family:'Newsreader', Georgia, serif;
min-height:100vh;
-webkit-font-smoothing:antialiased;
}
::selection{ background:#ff0000; color:#f7f4ec; }
a{ color:#c40000; text-decoration:none; border-bottom:1px solid rgba(255,0,0,.35); }
a:hover{ border-bottom-color:#ff0000; }
code{
font-family:'JetBrains Mono', monospace !important;
font-size:.86em;
background:#ece5d3;
color:#a02020;
padding:1px 6px;
border-radius:2px;
border:1px solid #d9d2bf;
}
.page{ max-width:880px; margin:0 auto; padding:0 32px 70px; }
/* ============ MASTHEAD ============ */
.masthead{ padding:52px 0 0; text-align:center; }
.eyebrow{
font-family:'JetBrains Mono', monospace;
font-size:11px; letter-spacing:.28em; text-transform:uppercase;
color:#ff0000; margin-bottom:22px;
display:flex; align-items:center; justify-content:center; gap:10px;
}
.eyebrow .dot-live{
width:6px; height:6px; border-radius:50%; background:#c7c1ae; display:inline-block;
}
.eyebrow .dot-live.on{ background:#ff0000; animation:pulse 2.4s ease-in-out infinite; }
@keyframes pulse{ 0%,100%{opacity:1;} 50%{opacity:.35;} }
@media (prefers-reduced-motion: reduce){ .eyebrow .dot-live{ animation:none; } }
.wordmark{
font-size:clamp(40px, 7vw, 68px);
font-weight:700; line-height:.98; letter-spacing:-.015em; margin:0;
}
.wordmark .dot{ color:#ff0000; }
.tagline{
font-size:16.5px; font-style:italic; color:#4a463d;
max-width:520px; margin:18px auto 0; line-height:1.6;
}
.tagline code{ font-style:normal; }
.tickline{
height:14px; margin:40px 0 0;
background-image: repeating-linear-gradient(90deg, #ff0000 0, #ff0000 1px, transparent 1px, transparent 10px);
background-position: center; background-size:10px 1px; background-repeat:repeat-x;
background-position-y:6px; opacity:.9;
}
/* ============ META STRIP ============ */
.meta-strip{
display:flex; justify-content:center; gap:0; padding:26px 0 6px; flex-wrap:wrap;
}
.meta-item{
font-family:'JetBrains Mono', monospace; font-size:11px; letter-spacing:.05em;
color:#4a463d; padding:0 22px; border-right:1px solid #d9d2bf; text-align:center;
}
.meta-item:last-child{ border-right:none; }
.meta-item b{
display:block; color:#1c1a16; font-weight:600; font-size:12.5px;
margin-top:2px; letter-spacing:.02em;
}
/* ============ SECTIONS ============ */
section{ padding:48px 0; border-top:1px solid #d9d2bf; }
.section-head{ display:flex; align-items:baseline; gap:16px; margin-bottom:8px; }
.section-index{ font-family:'JetBrains Mono', monospace; font-size:13px; color:#ff0000; letter-spacing:.05em; }
h2{ font-size:24px; font-weight:600; margin:0; letter-spacing:-.01em; }
.section-desc{
font-size:14.5px; color:#4a463d; max-width:580px; margin:12px 0 30px; line-height:1.65;
}
p.lede{ font-size:16.5px; line-height:1.72; color:#2b2822; max-width:640px; margin:0 0 30px; }
p.lede b{ font-weight:600; box-shadow: inset 0 -.35em 0 rgba(255,0,0,.16); }
/* ============ LOAD SEQUENCE (quiet log list, no boxes) ============ */
.stage-list{ border-top:1px solid #1c1a16; }
.stage{
display:grid; grid-template-columns:100px 1fr auto; gap:20px; align-items:baseline;
padding:13px 0; border-bottom:1px solid #d9d2bf;
}
.stage .mark{
font-family:'JetBrains Mono', monospace; font-size:10px; letter-spacing:.06em; text-transform:uppercase;
color:#8a8474; position:relative; padding-left:14px;
}
.stage .mark::before{
content:""; position:absolute; left:0; top:4px; width:6px; height:6px; border-radius:50%; background:#c7c1ae;
}
.stage.active .mark{ color:#1c1a16; }
.stage.active .mark::before{ background:#ff0000; animation:pulse 1.1s ease-in-out infinite; }
.stage.done .mark{ color:#1c1a16; }
.stage.done .mark::before{ background:#ff0000; }
.stage .label{ font-size:14.5px; color:#4a463d; }
.stage.done .label, .stage.active .label{ color:#1c1a16; }
.stage .meta{
font-family:'JetBrains Mono', monospace; font-size:11px; color:#8a8474; white-space:nowrap; text-align:right;
}
.progress-track{ height:2px; background:#ece7d8; margin-top:22px; position:relative; overflow:hidden; }
.progress-fill{ position:absolute; left:0; top:0; bottom:0; width:0%; background:#ff0000; transition:width .15s ease; }
.progress-num{
font-family:'JetBrains Mono', monospace; font-size:11px; color:#8a8474; margin-top:9px;
display:flex; justify-content:space-between;
}
.load-row{ margin-top:26px; display:flex; align-items:center; gap:16px; flex-wrap:wrap; }
button{
font-family:'JetBrains Mono', monospace; font-size:11.5px; letter-spacing:.05em; text-transform:uppercase;
background:#1c1a16; color:#f7f4ec; border:1px solid #1c1a16;
padding:13px 24px; cursor:pointer; transition:background .15s ease, color .15s ease, border-color .15s ease;
}
button:hover:not(:disabled){ background:#ff0000; border-color:#ff0000; }
button:disabled{ opacity:.35; cursor:not-allowed; }
button.ghost{ background:transparent; color:#1c1a16; border:1px solid #d9d2bf; }
button.ghost:hover:not(:disabled){ background:#1c1a16; color:#f7f4ec; border-color:#1c1a16; }
.load-hint{ font-family:'JetBrains Mono', monospace; font-size:11px; color:#8a8474; }
.note-box{
font-size:13.5px; color:#4a463d; line-height:1.6; margin:18px 0 0;
padding-left:16px; border-left:2px solid #ff0000;
}
.err-box{
font-family:'JetBrains Mono', monospace; font-size:12px; line-height:1.6; color:#7a1010;
margin:18px 0 0; padding-left:16px; border-left:2px solid #c40000; white-space:pre-wrap; word-break:break-word;
}
/* ============ SPEC TABLE ============ */
table.kv{ width:100%; border-collapse:collapse; font-size:13.5px; }
table.kv td{ padding:11px 12px 11px 0; border-bottom:1px solid #ece7d8; vertical-align:top; }
table.kv tr:first-child td{ padding-top:0; }
table.kv tr:last-child td{ border-bottom:none; }
table.kv td:first-child{
font-family:'JetBrains Mono', monospace; font-size:11px; color:#8a8474; width:38%; white-space:nowrap; padding-top:12px;
}
table.kv td:last-child{ color:#4a463d; line-height:1.55; }
/* ============ CHAT ============ */
.chat-shell{ display:none; }
.chat-shell.active{ display:block; }
.stat-strip{ display:flex; justify-content:flex-start; gap:0; margin-bottom:32px; }
.stat{ padding:0 26px 0 0; margin-right:26px; border-right:1px solid #d9d2bf; }
.stat:last-child{ border-right:none; margin-right:0; padding-right:0; }
.stat-num{ font-family:'JetBrains Mono', monospace; font-size:16px; font-weight:600; color:#1c1a16; display:block; }
.stat-label{ font-family:'JetBrains Mono', monospace; font-size:9px; letter-spacing:.06em; text-transform:uppercase; color:#8a8474; margin-top:3px; display:block; }
.transcript{
border-top:1px solid #1c1a16; border-bottom:1px solid #1c1a16;
min-height:220px; max-height:52vh; overflow-y:auto;
padding:26px 2px; font-size:16px; line-height:1.8;
}
.msg{ margin-bottom:24px; }
.msg:last-child{ margin-bottom:0; }
.msg .who{
font-family:'JetBrains Mono', monospace; font-size:9.5px; letter-spacing:.12em; text-transform:uppercase;
color:#8a8474; margin-bottom:5px;
}
.msg.user .who{ color:#ff0000; }
.msg .txt{ color:#1c1a16; white-space:pre-wrap; }
.msg .txt .cursor{
display:inline-block; width:7px; height:1em; background:#ff0000; vertical-align:text-bottom;
animation:blink .85s steps(1) infinite; margin-left:1px;
}
@keyframes blink{ 50%{ opacity:.2; } }
.placeholder-hint{ color:#8a8474; font-size:14px; font-style:italic; }
.composer{ display:flex; gap:12px; margin-top:20px; }
.composer textarea{
flex:1; resize:none; font-family:'Newsreader', Georgia, serif; font-size:16px;
border:none; border-bottom:1px solid #1c1a16; background:transparent; color:#1c1a16;
padding:8px 2px; line-height:1.5; height:44px;
}
.composer textarea:focus{ outline:none; border-bottom-color:#ff0000; }
.control-row{ display:flex; align-items:center; justify-content:space-between; gap:16px; margin-top:22px; flex-wrap:wrap; }
.sliders{ display:flex; gap:30px; flex-wrap:wrap; }
.slider-group{ font-family:'JetBrains Mono', monospace; font-size:10.5px; color:#8a8474; }
.slider-group .val{ color:#1c1a16; font-weight:600; }
.slider-group input[type=range]{ display:block; width:130px; margin-top:7px; accent-color:#ff0000; }
.perf-line{
font-family:'JetBrains Mono', monospace; font-size:11px; color:#8a8474;
margin-top:18px; padding-top:14px; border-top:1px solid #ece7d8;
display:flex; gap:20px; flex-wrap:wrap;
}
.perf-line b{ color:#4a463d; font-weight:600; }
/* ============ KERNEL SOURCE ============ */
details.expivme{ margin-top:22px; border-top:1px solid #d9d2bf; padding-top:18px; }
details.expivme summary{
cursor:pointer; font-family:'JetBrains Mono', monospace; font-size:12px; letter-spacing:.03em;
color:#1c1a16; list-style:none; display:flex; align-items:center; gap:10px;
}
details.expivme summary::-webkit-details-marker{ display:none; }
details.expivme summary::before{
content:"+"; color:#ff0000; font-family:'JetBrains Mono', monospace; font-weight:600; width:14px;
}
details.expivme[open] summary::before{ content:"–"; }
details.expivme pre{
margin:18px 0 0; padding:18px 20px; background:#1c1a16; overflow-x:auto; max-height:340px; overflow-y:auto;
}
details.expivme pre code{
background:transparent; border:none; color:#e9e4d6; font-size:11.5px; line-height:1.6; padding:0; white-space:pre;
}
/* ============ LIMITATIONS LIST ============ */
ul.limits{ margin:0; padding:0; list-style:none; }
ul.limits li{
font-size:14px; line-height:1.6; color:#4a463d; padding:11px 0 11px 20px;
border-bottom:1px solid #ece7d8; position:relative;
}
ul.limits li:last-child{ border-bottom:none; }
ul.limits li::before{ content:"–"; position:absolute; left:0; color:#ff0000; font-weight:600; }
/* ============ FOOTER ============ */
footer{
padding:44px 0 10px; display:flex; justify-content:space-between; align-items:center;
font-family:'JetBrains Mono', monospace; font-size:11px; color:#8a8474; letter-spacing:.02em;
border-top:1px solid #d9d2bf; flex-wrap:wrap; gap:8px;
}
footer .fmark{ color:#ff0000; }
@media (max-width:620px){
.page{ padding:0 18px 60px; }
.masthead{ padding:36px 0 0; }
.stage{ grid-template-columns:1fr; gap:4px; }
.stage .meta{ text-align:left; }
.stat-strip{ flex-wrap:wrap; row-gap:16px; }
table.kv td:first-child{ width:auto; white-space:normal; }
footer{ flex-direction:column; text-align:center; }
}
/* ============ MODEL PICKER ============ */
.model-grid{ display:grid; grid-template-columns:repeat(4, minmax(0,1fr)); gap:0; border-top:1px solid #1c1a16; border-bottom:1px solid #d9d2bf; margin-bottom:28px; }
.model-opt{
text-align:left; background:transparent; color:#1c1a16; border:none; border-right:1px solid #d9d2bf;
padding:16px 14px 14px; cursor:pointer; text-transform:none; letter-spacing:0; font-family:'Newsreader', Georgia, serif;
display:flex; flex-direction:column; gap:6px; position:relative;
}
.model-opt:last-child{ border-right:none; }
.model-opt:hover:not(:disabled){ background:#efe9da; color:#1c1a16; border-color:#d9d2bf; }
.model-opt .m-name{ font-size:16px; font-weight:600; letter-spacing:-.005em; }
.model-opt .m-meta{ font-family:'JetBrains Mono', monospace; font-size:10px; color:#8a8474; letter-spacing:.04em; }
.model-opt .m-tag{
font-family:'JetBrains Mono', monospace; font-size:9px; letter-spacing:.12em; text-transform:uppercase;
color:#8a8474; border:1px solid #d9d2bf; padding:2px 6px; align-self:flex-start;
}
.model-opt.chat .m-tag{ color:#c40000; border-color:rgba(255,0,0,.35); }
.model-opt.selected{ background:#1c1a16; color:#f7f4ec; }
.model-opt.selected:hover:not(:disabled){ background:#1c1a16; color:#f7f4ec; }
.model-opt.selected .m-meta{ color:#c7c1ae; }
.model-opt.selected .m-tag{ color:#f7f4ec; border-color:#8a8474; }
.model-opt.selected::after{ content:""; position:absolute; left:0; right:0; top:-1px; height:3px; background:#ff0000; }
.msg.assistant .who{ color:#1c1a16; }
.composer-hint{ font-family:'JetBrains Mono', monospace; font-size:10.5px; color:#8a8474; margin-top:10px; }
.safety-note{ font-size:13px; color:#4a463d; line-height:1.6; margin:20px 0 0; padding-left:16px; border-left:2px solid #d9d2bf; }
@media (max-width:620px){
.model-grid{ grid-template-columns:repeat(2, minmax(0,1fr)); }
.model-opt:nth-child(2){ border-right:none; }
.model-opt:nth-child(-n+2){ border-bottom:1px solid #d9d2bf; }
}
</style>
</head>
<body>
<div class="page">
<div class="masthead">
<div class="eyebrow"><span class="dot-live" id="live-dot"></span> Raw WebGPU · No ONNX · No transformers.js</div>
<h1 class="wordmark">İvme-Conversate<span class="dot">.</span></h1>
<p class="tagline">Hand-written WGSL kernels reading <code>model.safetensors</code> straight off the wire — the tensor bytes go into GPU buffers directly, no export step, no runtime graph compiler.</p>
</div>
<div class="tickline"></div>
<div class="meta-strip">
<div class="meta-item">MODEL<br><b id="meta-model">–</b></div>
<div class="meta-item">PARAMS<br><b id="meta-params">–</b></div>
<div class="meta-item">RUNTIME<br><b>Browser / WebGPU</b></div>
<div class="meta-item">WEIGHTS<br><b><a id="meta-weights" href="https://huggingface.co/IvmeLabs" target="_blank" rel="noopener">İvmeLabs</a></b></div>
</div>
<!-- ============ LOAD ============ -->
<section id="boot-section">
<div class="section-head"><span class="section-index">01</span><h2>Load model</h2></div>
<p class="section-desc">Pick a model. The page fetches its <code>config.json</code>, <code>tokenizer.json</code>, and <code>model.safetensors</code> from the Hugging Face CDN, parses the safetensors header by hand, and uploads every tensor straight into <code>GPUBuffer</code>s.</p>
<div class="model-grid" id="model-grid"></div>
<div class="stage-list" id="stage-list">
<div class="stage" data-stage="webgpu"><span class="mark">idle</span><span class="label">Request WebGPU adapter + device</span><span class="meta"></span></div>
<div class="stage" data-stage="config"><span class="mark">idle</span><span class="label">Fetch config.json</span><span class="meta"></span></div>
<div class="stage" data-stage="tokenizer"><span class="mark">idle</span><span class="label">Fetch + build tokenizer (byte-level BPE)</span><span class="meta"></span></div>
<div class="stage" data-stage="weights"><span class="mark">idle</span><span class="label">Stream model.safetensors</span><span class="meta"></span></div>
<div class="stage" data-stage="upload"><span class="mark">idle</span><span class="label">Parse header, upload tensors to GPU</span><span class="meta"></span></div>
<div class="stage" data-stage="pipelines"><span class="mark">idle</span><span class="label">Compile WGSL, build compute pipelines</span><span class="meta"></span></div>
<div class="stage" data-stage="warmup"><span class="mark">idle</span><span class="label">Warm-up forward pass</span><span class="meta"></span></div>
</div>
<div class="progress-track"><div class="progress-fill" id="progress-fill"></div></div>
<div class="progress-num"><span id="progress-label">idle</span><span id="progress-bytes"></span></div>
<div class="load-row">
<button id="load-btn">Load model & run in-browser</button>
<span class="load-hint" id="load-hint"></span>
</div>
<div class="err-box" id="err-box" style="display:none;"></div>
<div class="note-box" id="webgpu-warning" style="display:none;">
This browser doesn't expose <code>navigator.gpu</code>. WebGPU currently ships in Chrome/Edge 113+, and behind a flag in Firefox Nightly and Safari Technology Preview.
</div>
</section>
<!-- ============ GENERATE / CHAT ============ -->
<section class="chat-shell" id="chat-shell">
<div class="section-head"><span class="section-index">02</span><h2 id="gen-title">Generate</h2></div>
<p class="section-desc" id="gen-desc"></p>
<div class="stat-strip">
<div class="stat"><span class="stat-num" id="stat-params">–</span><span class="stat-label">Parameters</span></div>
<div class="stat"><span class="stat-num" id="stat-backend">–</span><span class="stat-label">GPU backend</span></div>
<div class="stat"><span class="stat-num" id="stat-loadtime">–</span><span class="stat-label">Load time</span></div>
<div class="stat"><span class="stat-num" id="stat-toksec">–</span><span class="stat-label">tok/s (last run)</span></div>
</div>
<div class="transcript" id="transcript"></div>
<div class="composer">
<textarea id="prompt-input" spellcheck="false"></textarea>
<button id="gen-btn">Run</button>
</div>
<div class="composer-hint" id="composer-hint"></div>
<div class="control-row">
<div class="sliders">
<div class="slider-group">temperature <span class="val" id="temp-val">0.80</span>
<input type="range" id="temp-slider" min="0.05" max="1.5" step="0.05" value="0.8">
</div>
<div class="slider-group">top-k <span class="val" id="topk-val">50</span>
<input type="range" id="topk-slider" min="1" max="200" step="1" value="50">
</div>
<div class="slider-group">repetition penalty <span class="val" id="rep-val">1.00</span>
<input type="range" id="rep-slider" min="1" max="1.5" step="0.05" value="1">
</div>
<div class="slider-group">max new tokens <span class="val" id="maxtok-val">200</span>
<input type="range" id="maxtok-slider" min="10" max="1000" step="10" value="200">
</div>
</div>
<div style="display:flex; gap:10px;">
<button class="ghost" id="clear-btn">Clear</button>
<button class="ghost" id="stop-btn" disabled>Stop</button>
</div>
</div>
<div class="perf-line" id="perf-line"></div>
<p class="safety-note" id="safety-note" style="display:none;">This is a 25M-parameter model. It is often wrong, and it is not a safety system. If you are struggling or thinking about hurting yourself, please reach out to someone you trust or a crisis line (US: call or text 988 · Turkey: 112 · elsewhere: your local emergency number).</p>
</section>
<!-- ============ ARCHITECTURE NOTE ============ -->
<section>
<div class="section-head"><span class="section-index">03</span><h2>What's actually running</h2></div>
<table class="kv" id="arch-table"></table>
<details class="expivme">
<summary>View the WGSL kernel source (matmul, RMSNorm, RoPE, attention + XSA, SwiGLU)</summary>
<pre><code id="kernel-source-view"></code></pre>
</details>
</section>
<section>
<div class="section-head"><span class="section-index">04</span><h2>Limitations of this demo</h2></div>
<ul class="limits">
<li>These are tiny models (24–25M parameters). Base models only continue text; the Instruct model chats, but it is often confidently wrong and can't do multi-step reasoning</li>
<li>1024-token context window. In chat mode, the oldest turns are dropped to make room; in base mode, generation stops at the limit</li>
<li>All matmuls run in f32 with a naive tiled kernel — no fusion, no int8/int4 quantization, so this favors correctness and readability over raw throughput</li>
<li>KV cache lives in a fixed-size GPU buffer sized to <code>context_len</code>; no paging, no batching, single sequence only</li>
<li>Tokenizer is a from-scratch byte-level BPE that reads its pre-tokenizer regex and merges from each model's <code>tokenizer.json</code> (including v3's digit-by-digit split), tested against the reference tokenizer</li>
</ul>
</section>
<footer>
<span>İvmeLabs <span class="fmark">/</span> Conversate <span class="fmark">/</span> WebGPU</span>
<span>Weights: <a id="footer-weights" href="https://huggingface.co/IvmeLabs" target="_blank" rel="noopener">IvmeLabs</a></span>
</footer>
</div>
<script type="module">
/* =========================================================================
İvme-Conversate — from-scratch WebGPU inference engine
=========================================================================
Pipeline:
1. Fetch config.json, tokenizer.json, model.safetensors from the HF CDN
2. Parse the safetensors header ourselves (it's just JSON + a byte offset table)
3. Upload every tensor straight into a GPUBuffer (STORAGE usage)
4. Compile hand-written WGSL kernels for every op in the forward pass
5. Run an autoregressive decode loop entirely with GPU dispatches,
pulling back only the final logits row each step
Two architecture families are supported:
v2 — RMSNorm, interleaved RoPE, plain attention, SwiGLU
v3 — RMSNorm, QK-Norm, rotate-half RoPE, attention + XSA
(Exclusive Self-Attention), SwiGLU. v3, v3.1-Base and
v3.1-Instruct share this exact architecture.
========================================================================= */
const MODELS = [
{
key: "v3.1-instruct", name: "v3.1 Instruct", repo: "IvmeLabs/Ivme-Conversate-v3.1-Instruct",
arch: "v3", chat: true, params: "25.0M", size: "~100MB",
defaults: { temperature: 0.5, topK: 40, repPenalty: 1.15, maxNew: 256 },
},
{
key: "v3.1-base", name: "v3.1 Base", repo: "IvmeLabs/Ivme-Conversate-v3.1-Base",
arch: "v3", chat: false, params: "25.0M", size: "~100MB",
defaults: { temperature: 0.8, topK: 50, repPenalty: 1.0, maxNew: 200 },
},
{
key: "v3-base", name: "v3 Base", repo: "IvmeLabs/Ivme-Conversate-v3-Base",
arch: "v3", chat: false, params: "24.8M", size: "~99MB",
defaults: { temperature: 0.8, topK: 50, repPenalty: 1.0, maxNew: 200 },
},
{
key: "v2-base", name: "v2 Base", repo: "IvmeLabs/Ivme-Conversate-v2-Base",
arch: "v2", chat: false, params: "23.8M", size: "~96MB",
defaults: { temperature: 0.8, topK: 50, repPenalty: 1.0, maxNew: 200 },
},
];
/* Normalize each family's config.json + tensor names into one shape the engine uses. */
const ARCH = {
v2: {
cfg: (c) => ({
nLayers: c.n_layers, dModel: c.hidden_dim, nHeads: c.n_heads, contextLen: c.context_len,
vocabSize: c.vocab_size, ropeTheta: c.rope_theta, normEps: c.norm_eps, qkEps: null,
ropeStyle: "interleaved", qkNorm: false, xsa: false,
}),
w: (l) => ({
attnNorm: `model.blocks.${l}.attn_norm.weight`, ffnNorm: `model.blocks.${l}.ffn_norm.weight`,
wq: `model.blocks.${l}.attn.q_proj.weight`, wk: `model.blocks.${l}.attn.k_proj.weight`,
wv: `model.blocks.${l}.attn.v_proj.weight`, wo: `model.blocks.${l}.attn.out_proj.weight`,
gate: `model.blocks.${l}.ffn.gate_proj.weight`, up: `model.blocks.${l}.ffn.up_proj.weight`,
down: `model.blocks.${l}.ffn.down_proj.weight`,
}),
},
v3: {
cfg: (c) => ({
nLayers: c.n_layers, dModel: c.d_model, nHeads: c.n_heads, contextLen: c.context_len,
vocabSize: c.vocab_size, ropeTheta: c.rope_theta, normEps: c.rmsnorm_eps, qkEps: c.qknorm_eps,
ropeStyle: "half", qkNorm: true, xsa: true,
}),
w: (l) => ({
attnNorm: `model.blocks.${l}.attn_norm.weight`, ffnNorm: `model.blocks.${l}.ffn_norm.weight`,
wq: `model.blocks.${l}.attn.wq.weight`, wk: `model.blocks.${l}.attn.wk.weight`,
wv: `model.blocks.${l}.attn.wv.weight`, wo: `model.blocks.${l}.attn.wo.weight`,
qNorm: `model.blocks.${l}.attn.q_norm.weight`, kNorm: `model.blocks.${l}.attn.k_norm.weight`,
gate: `model.blocks.${l}.ffn.w_gate.weight`, up: `model.blocks.${l}.ffn.w_up.weight`,
down: `model.blocks.${l}.ffn.w_down.weight`,
}),
},
};
const EMBED = "model.tok_embed.weight";
const FINAL_NORM = "model.final_norm.weight";
const EOT_ID = 0; // <|endoftext|>
/* ---------------------------------------------------------------------
0. WGSL kernel source. Every shader the model needs, kept in one
template-literal map so the "view source" panel can render it verbatim.
--------------------------------------------------------------------- */
const WGSL = {};
// ---- RMSNorm: y = (x / rms(x)) * weight ----
// One workgroup per row. Used for the block norms (row = token, dim = d_model)
// and for v3's QK-Norm (row = one head of one token, dim = head_dim).
WGSL.rmsnorm = /* wgsl */`
struct Dims { rows: u32, dim: u32, eps: f32, _pad: u32 };
@group(0) @binding(0) var<uniform> dims: Dims;
@group(0) @binding(1) var<storage, read> x: array<f32>;
@group(0) @binding(2) var<storage, read> weight: array<f32>;
@group(0) @binding(3) var<storage, read_write> y: array<f32>;
var<workgroup> partial: array<f32, 256>;
@compute @workgroup_size(256)
fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
let row = wg.x;
if (row >= dims.rows) { return; }
let base = row * dims.dim;
var acc: f32 = 0.0;
var i: u32 = lid.x;
loop {
if (i >= dims.dim) { break; }
let v = x[base + i];
acc = acc + v * v;
i = i + 256u;
}
partial[lid.x] = acc;
workgroupBarrier();
var stride: u32 = 128u;
loop {
if (stride == 0u) { break; }
if (lid.x < stride) { partial[lid.x] = partial[lid.x] + partial[lid.x + stride]; }
workgroupBarrier();
stride = stride / 2u;
}
let meanSq = partial[0] / f32(dims.dim);
let rms = inverseSqrt(meanSq + dims.eps);
i = lid.x;
loop {
if (i >= dims.dim) { break; }
y[base + i] = x[base + i] * rms * weight[i];
i = i + 256u;
}
}
`;
// ---- Tiled matmul: Y[rows, N] = X[rows, K] @ W^T[K, N] (W stored [N, K], PyTorch nn.Linear layout) ----
WGSL.matmul = /* wgsl */`
struct Dims { rows: u32, K: u32, N: u32, _pad: u32 };
@group(0) @binding(0) var<uniform> dims: Dims;
@group(0) @binding(1) var<storage, read> X: array<f32>; // [rows, K]
@group(0) @binding(2) var<storage, read> W: array<f32>; // [N, K] (nn.Linear weight, row-major)
@group(0) @binding(3) var<storage, read_write> Y: array<f32>; // [rows, N]
const TILE = 16u;
var<workgroup> Xs: array<array<f32, TILE>, TILE>;
var<workgroup> Ws: array<array<f32, TILE>, TILE>;
@compute @workgroup_size(TILE, TILE)
fn main(@builtin(global_invocation_id) gid: vec3<u32>,
@builtin(local_invocation_id) lid: vec3<u32>) {
let row = gid.y; // output row (token)
let col = gid.x; // output col (feature n)
var acc: f32 = 0.0;
let numTiles = (dims.K + TILE - 1u) / TILE;
for (var t: u32 = 0u; t < numTiles; t = t + 1u) {
let kX = t * TILE + lid.x;
if (row < dims.rows && kX < dims.K) {
Xs[lid.y][lid.x] = X[row * dims.K + kX];
} else {
Xs[lid.y][lid.x] = 0.0;
}
let kW = t * TILE + lid.y;
if (col < dims.N && kW < dims.K) {
Ws[lid.y][lid.x] = W[col * dims.K + kW];
} else {
Ws[lid.y][lid.x] = 0.0;
}
workgroupBarrier();
for (var k: u32 = 0u; k < TILE; k = k + 1u) {
acc = acc + Xs[lid.y][k] * Ws[k][lid.x];
}
workgroupBarrier();
}
if (row < dims.rows && col < dims.N) {
Y[row * dims.N + col] = acc;
}
}
`;
// ---- RoPE (v2): complex rotation on interleaved pairs (x[2i], x[2i+1]).
// Layout: [T, H, Dh]. ----
WGSL.rope = /* wgsl */`
struct Dims { T: u32, H: u32, headDim: u32, posOffset: u32 };
@group(0) @binding(0) var<uniform> dims: Dims;
@group(0) @binding(1) var<storage, read_write> qk: array<f32>; // [T, H, headDim]
@group(0) @binding(2) var<storage, read> invFreq: array<f32>; // [headDim/2]
@compute @workgroup_size(8, 8)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let t = gid.x;
let h = gid.y;
if (t >= dims.T || h >= dims.H) { return; }
let pos = f32(t + dims.posOffset);
let half = dims.headDim / 2u;
let base = (t * dims.H + h) * dims.headDim;
for (var i: u32 = 0u; i < half; i = i + 1u) {
let angle = pos * invFreq[i];
let c = cos(angle);
let s = sin(angle);
let x0 = qk[base + 2u * i];
let x1 = qk[base + 2u * i + 1u];
qk[base + 2u * i] = x0 * c - x1 * s;
qk[base + 2u * i + 1u] = x0 * s + x1 * c;
}
}
`;
// ---- RoPE (v3): rotate-half layout. The first and second halves of each
// head vector are the two components: out = [x1*c - x2*s, x1*s + x2*c]. ----
WGSL.rope_half = /* wgsl */`
struct Dims { T: u32, H: u32, headDim: u32, posOffset: u32 };
@group(0) @binding(0) var<uniform> dims: Dims;
@group(0) @binding(1) var<storage, read_write> qk: array<f32>; // [T, H, headDim]
@group(0) @binding(2) var<storage, read> invFreq: array<f32>; // [headDim/2]
@compute @workgroup_size(8, 8)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let t = gid.x;
let h = gid.y;
if (t >= dims.T || h >= dims.H) { return; }
let pos = f32(t + dims.posOffset);
let half = dims.headDim / 2u;
let base = (t * dims.H + h) * dims.headDim;
for (var i: u32 = 0u; i < half; i = i + 1u) {
let angle = pos * invFreq[i];
let c = cos(angle);
let s = sin(angle);
let x1 = qk[base + i];
let x2 = qk[base + i + half];
qk[base + i] = x1 * c - x2 * s;
qk[base + i + half] = x1 * s + x2 * c;
}
}
`;
// ---- Causal scaled-dot-product attention, one workgroup per (query token, head),
// with an online softmax over the key dimension. K/V come from the persistent
// KV cache. When xsa != 0 (v3), the output is then made orthogonal to the
// token's own value vector (Exclusive Self-Attention):
// z = y - (y . v_self) / (|v_self|^2 + eps) * v_self ----
WGSL.attention = /* wgsl */`
struct Dims { qLen: u32, kvLen: u32, H: u32, headDim: u32, scale: f32, queryOffset: u32, xsa: u32, xsaEps: f32 };
@group(0) @binding(0) var<uniform> dims: Dims;
@group(0) @binding(1) var<storage, read> Q: array<f32>; // [qLen, H, headDim]
@group(0) @binding(2) var<storage, read> Kc: array<f32>; // [ctx, H, headDim] cache
@group(0) @binding(3) var<storage, read> Vc: array<f32>; // [ctx, H, headDim] cache
@group(0) @binding(4) var<storage, read_write> O: array<f32>; // [qLen, H, headDim]
const MAX_HD = 128u;
@compute @workgroup_size(1)
fn main(@builtin(workgroup_id) wg: vec3<u32>) {
let qi = wg.x;
let h = wg.y;
if (qi >= dims.qLen || h >= dims.H) { return; }
let qBase = (qi * dims.H + h) * dims.headDim;
var qvec: array<f32, MAX_HD>;
for (var d: u32 = 0u; d < dims.headDim; d = d + 1u) {
qvec[d] = Q[qBase + d];
}
// causal boundary: this query (absolute position queryOffset+qi) may attend
// to all cached keys up through its own absolute position.
let selfPos = dims.queryOffset + qi;
var validLen = dims.kvLen;
if (selfPos + 1u < validLen) { validLen = selfPos + 1u; }
var m: f32 = -3.4e38;
var l: f32 = 0.0;
var acc: array<f32, MAX_HD>;
for (var d: u32 = 0u; d < dims.headDim; d = d + 1u) { acc[d] = 0.0; }
for (var ki: u32 = 0u; ki < validLen; ki = ki + 1u) {
let kBase = (ki * dims.H + h) * dims.headDim;
var score: f32 = 0.0;
for (var d: u32 = 0u; d < dims.headDim; d = d + 1u) {
score = score + qvec[d] * Kc[kBase + d];
}
score = score * dims.scale;
let newM = max(m, score);
let corr = exp(m - newM);
let p = exp(score - newM);
l = l * corr + p;
for (var d: u32 = 0u; d < dims.headDim; d = d + 1u) {
acc[d] = acc[d] * corr + p * Vc[kBase + d];
}
m = newM;
}
let invL = 1.0 / max(l, 1e-20);
for (var d: u32 = 0u; d < dims.headDim; d = d + 1u) { acc[d] = acc[d] * invL; }
if (dims.xsa != 0u) {
let vBase = (selfPos * dims.H + h) * dims.headDim;
var dotYV: f32 = 0.0;
var vv: f32 = 0.0;
for (var d: u32 = 0u; d < dims.headDim; d = d + 1u) {
let vd = Vc[vBase + d];
dotYV = dotYV + acc[d] * vd;
vv = vv + vd * vd;
}
let coef = dotYV / (vv + dims.xsaEps);
for (var d: u32 = 0u; d < dims.headDim; d = d + 1u) {
acc[d] = acc[d] - coef * Vc[vBase + d];
}
}
let oBase = (qi * dims.H + h) * dims.headDim;
for (var d: u32 = 0u; d < dims.headDim; d = d + 1u) {
O[oBase + d] = acc[d];
}
}
`;
// ---- elementwise: y = silu(gate) * up (SwiGLU gating, pre-down_proj) ----
WGSL.swiglu_gate = /* wgsl */`
@group(0) @binding(0) var<storage, read> gate: array<f32>;
@group(0) @binding(1) var<storage, read> up: array<f32>;
@group(0) @binding(2) var<storage, read_write> out: array<f32>;
@compute @workgroup_size(256)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let i = gid.x;
if (i >= arrayLength(&gate)) { return; }
let g = gate[i];
let silu = g / (1.0 + exp(-g));
out[i] = silu * up[i];
}
`;
// ---- elementwise residual add: y = a + b ----
WGSL.add = /* wgsl */`
@group(0) @binding(0) var<storage, read> a: array<f32>;
@group(0) @binding(1) var<storage, read> b: array<f32>;
@group(0) @binding(2) var<storage, read_write> out: array<f32>;
@compute @workgroup_size(256)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let i = gid.x;
if (i >= arrayLength(&a)) { return; }
out[i] = a[i] + b[i];
}
`;
// ---- write freshly-computed K/V for the newest tokens into the persistent
// KV cache at the right offset. ----
WGSL.kvwrite = /* wgsl */`
struct Dims { T: u32, H: u32, headDim: u32, destOffset: u32 };
@group(0) @binding(0) var<uniform> dims: Dims;
@group(0) @binding(1) var<storage, read> src: array<f32>; // [T, H, headDim]
@group(0) @binding(2) var<storage, read_write> cache: array<f32>; // [context_len, H, headDim]
@compute @workgroup_size(256)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let i = gid.x;
let total = dims.T * dims.H * dims.headDim;
if (i >= total) { return; }
let perTok = dims.H * dims.headDim;
let t = i / perTok;
let rem = i % perTok;
let destBase = (dims.destOffset + t) * perTok;
cache[destBase + rem] = src[i];
}
`;
// Full logits (vocab = 16000) are read back and sampled in JS: temperature,
// repetition penalty, top-k, then a categorical draw. Cheap at this vocab size.
const KERNEL_ORDER = ["rmsnorm", "matmul", "rope", "rope_half", "attention", "swiglu_gate", "add", "kvwrite"];
/* ---------------------------------------------------------------------
1. Byte-level BPE tokenizer, built from tokenizer.json
The pre-tokenizer split regex is read from the file itself: v2 uses the
GPT-2 pattern, v3 uses its own digit-atomic pattern (" ?[0-9]"). Text the
regex doesn't match is kept as its own piece, like HF's "Isolated" Split.
--------------------------------------------------------------------- */
const GPT2_SPLIT = String.raw`'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+`;
class ByteLevelBPE {
constructor(tokJson) {
this.vocab = tokJson.model.vocab; // token string -> id
this.idToToken = new Array(Object.keys(this.vocab).length);
for (const [tok, id] of Object.entries(this.vocab)) this.idToToken[id] = tok;
const merges = tokJson.model.merges.map(pair => Array.isArray(pair) ? pair : pair.split(" "));
this.mergeRank = new Map();
merges.forEach(([a, b], i) => this.mergeRank.set(a + "\u0001" + b, i));
this.specials = new Map();
for (const t of (tokJson.added_tokens || [])) this.specials.set(t.content, t.id);
this.specialIds = new Set(this.specials.values());
this.byteEncoder = ByteLevelBPE._buildByteEncoder();
this.byteDecoder = new Map();
for (const [b, ch] of this.byteEncoder.entries()) this.byteDecoder.set(ch, b);
this.splitRe = new RegExp(ByteLevelBPE._splitPattern(tokJson.pre_tokenizer), "gu");
this._cache = new Map();
}
static _splitPattern(pre) {
const find = (p) => {
if (!p) return null;
if (p.type === "Split" && p.pattern && p.pattern.Regex) return p.pattern.Regex;
if (p.type === "Sequence") {
for (const q of (p.pretokenizers || [])) { const r = find(q); if (r) return r; }
}
return null;
};
return find(pre) || GPT2_SPLIT;
}
static _buildByteEncoder() {
const bs = [];
for (let i = "!".charCodeAt(0); i <= "~".charCodeAt(0); i++) bs.push(i);
for (let i = "¡".charCodeAt(0); i <= "¬".charCodeAt(0); i++) bs.push(i);
for (let i = "®".charCodeAt(0); i <= "ÿ".charCodeAt(0); i++) bs.push(i);
const cs = bs.slice();
let n = 0;
for (let b = 0; b < 256; b++) {
if (!bs.includes(b)) { bs.push(b); cs.push(256 + n); n++; }
}
const map = new Map();
for (let i = 0; i < bs.length; i++) map.set(bs[i], String.fromCodePoint(cs[i]));
return map;
}
/** Split like HF's Split(behavior="Isolated"): matches and the gaps between them are both pieces. */
_split(text) {
const out = [];
let last = 0;
this.splitRe.lastIndex = 0;
for (const m of text.matchAll(this.splitRe)) {
if (m.index > last) out.push(text.slice(last, m.index));
if (m[0].length) out.push(m[0]);
last = m.index + m[0].length;
}
if (last < text.length) out.push(text.slice(last));
return out;
}
_bpe(token) {
if (this._cache.has(token)) return this._cache.get(token);
let word = Array.from(token);
if (word.length === 1) { this._cache.set(token, word); return word; }
while (true) {
let bestRank = Infinity, bestIdx = -1;
for (let i = 0; i < word.length - 1; i++) {
const r = this.mergeRank.get(word[i] + "\u0001" + word[i + 1]);
if (r !== undefined && r < bestRank) { bestRank = r; bestIdx = i; }
}
if (bestIdx === -1) break;
word = [...word.slice(0, bestIdx), word[bestIdx] + word[bestIdx + 1], ...word.slice(bestIdx + 2)];
}
this._cache.set(token, word);
return word;
}
encode(text) {
const ids = [];
const enc = new TextEncoder();
for (const chunk of this._split(text)) {
let mapped = "";
for (const b of enc.encode(chunk)) mapped += this.byteEncoder.get(b);
for (const p of this._bpe(mapped)) {
const id = this.vocab[p];
if (id !== undefined) { ids.push(id); continue; }
// unknown merged piece (shouldn't happen with a byte-level vocab): fall back to single bytes
for (const ch of Array.from(p)) { const bid = this.vocab[ch]; if (bid !== undefined) ids.push(bid); }
}
}
return ids;
}
decode(ids) {
let mapped = "";
for (const id of ids) {
if (this.specialIds.has(id)) continue;
const tok = this.idToToken[id];
if (tok !== undefined) mapped += tok;
}
const bytes = [];
for (const ch of mapped) {
const b = this.byteDecoder.get(ch);
if (b !== undefined) bytes.push(b);
}
return new TextDecoder("utf-8", { fatal: false }).decode(new Uint8Array(bytes));
}
}
/* ---------------------------------------------------------------------
2. safetensors parsing — read the 8-byte little-endian header length,
then the JSON header itself, which gives byte offsets for every tensor.
--------------------------------------------------------------------- */
function parseSafetensors(buffer) {
const view = new DataView(buffer);
const headerLen = Number(view.getBigUint64(0, true));
const header = JSON.parse(new TextDecoder("utf-8").decode(new Uint8Array(buffer, 8, headerLen)));
const dataStart = 8 + headerLen;
const tensors = {};
for (const [name, info] of Object.entries(header)) {
if (name === "__metadata__") continue;
const [begin, end] = info.data_offsets;
tensors[name] = { dtype: info.dtype, shape: info.shape, byteOffset: dataStart + begin, byteLength: end - begin };
}
return { tensors, buffer };
}
/* ---------------------------------------------------------------------
3. The engine itself
--------------------------------------------------------------------- */
class IvmeEngine {
constructor(device, spec) {
this.device = device;
this.spec = spec; // entry from MODELS
this.arch = ARCH[spec.arch];
this.pipelines = {};
this.weights = {}; // name -> { buffer, shape }
this.cfg = null; // normalized config
this.rawCfg = null;
this.tokenizer = null;
this.kvCacheK = [];
this.kvCacheV = [];
this.curLen = 0; // tokens currently resident in the KV cache
this._tmp = []; // per-forward temporary buffers, destroyed after readback
}
setConfig(raw) {
this.rawCfg = raw;
this.cfg = this.arch.cfg(raw);
this.cfg.headDim = this.cfg.dModel / this.cfg.nHeads;
}
async buildPipelines() {
for (const name of KERNEL_ORDER) {
const module = this.device.createShaderModule({ code: WGSL[name] });
this.pipelines[name] = this.device.createComputePipeline({ layout: "auto", compute: { module, entryPoint: "main" } });
}
}
loadWeightsFromSafetensors(parsed) {
const { tensors, buffer } = parsed;
for (const [name, t] of Object.entries(tensors)) {
if (t.dtype !== "F32") throw new Error(`unexpected dtype ${t.dtype} for ${name}; this loader only handles F32 safetensors`);
const gbuf = this.device.createBuffer({
size: Math.ceil(t.byteLength / 4) * 4,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
mappedAtCreation: true,
});
new Uint8Array(gbuf.getMappedRange()).set(new Uint8Array(buffer, t.byteOffset, t.byteLength));
gbuf.unmap();
this.weights[name] = { buffer: gbuf, shape: t.shape };
}
// sanity check: every tensor the architecture needs must be present
const need = [EMBED, FINAL_NORM];
for (let l = 0; l < this.cfg.nLayers; l++) need.push(...Object.values(this.arch.w(l)));
const missing = need.filter(n => !this.weights[n]);
if (missing.length) throw new Error(`missing tensors in model.safetensors: ${missing.slice(0, 4).join(", ")}${missing.length > 4 ? " …" : ""}`);
}
destroy() {
for (const w of Object.values(this.weights)) w.buffer.destroy();
for (const b of [...this.kvCacheK, ...this.kvCacheV]) b.destroy();
this.invFreqBuf?.destroy();
this.weights = {}; this.kvCacheK = []; this.kvCacheV = [];
}
_uniform(bytes) {
const buf = this.device.createBuffer({ size: Math.max(16, Math.ceil(bytes.byteLength / 16) * 16), usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
this.device.queue.writeBuffer(buf, 0, bytes);
this._tmp.push(buf);
return buf;
}
_storage(size, extraUsage = 0) {
const buf = this.device.createBuffer({
size: Math.max(4, Math.ceil(size / 4) * 4),
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC | extraUsage,
});
this._tmp.push(buf);
return buf;
}
initKVCache() {
for (const b of [...this.kvCacheK, ...this.kvCacheV]) b.destroy();
const { nLayers, contextLen, dModel } = this.cfg;
const bytesPerLayer = contextLen * dModel * 4;
this.kvCacheK = []; this.kvCacheV = [];
const mk = () => this.device.createBuffer({ size: bytesPerLayer, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST });
for (let l = 0; l < nLayers; l++) { this.kvCacheK.push(mk()); this.kvCacheV.push(mk()); }
this.curLen = 0;
}
_pass(enc, pipeline, entries, x, y = 1) {
const bg = this.device.createBindGroup({
layout: pipeline.getBindGroupLayout(0),
entries: entries.map((buffer, binding) => ({ binding, resource: { buffer } })),
});
const pass = enc.beginComputePass();
pass.setPipeline(pipeline);
pass.setBindGroup(0, bg);
pass.dispatchWorkgroups(x, y);
pass.end();
}
_matmul(enc, X, rows, K, W, N, Y) {
const dims = this._uniform(new Uint32Array([rows, K, N, 0]));
this._pass(enc, this.pipelines.matmul, [dims, X, W, Y], Math.ceil(N / 16), Math.ceil(rows / 16));
}
_rmsnorm(enc, X, rows, dim, eps, weightBuf, Y) {
const ab = new ArrayBuffer(16), dv = new DataView(ab);
dv.setUint32(0, rows, true); dv.setUint32(4, dim, true); dv.setFloat32(8, eps, true); dv.setUint32(12, 0, true);
this._pass(enc, this.pipelines.rmsnorm, [this._uniform(new Uint8Array(ab)), X, weightBuf, Y], rows);
}
_rope(enc, qkBuf, T, posOffset) {
const { nHeads, headDim, ropeStyle } = this.cfg;
const dims = this._uniform(new Uint32Array([T, nHeads, headDim, posOffset]));
const pipe = ropeStyle === "half" ? this.pipelines.rope_half : this.pipelines.rope;
this._pass(enc, pipe, [dims, qkBuf, this.invFreqBuf], Math.ceil(T / 8), Math.ceil(nHeads / 8));
}
_kvwrite(enc, src, T, destOffset, cache) {
const { nHeads, headDim } = this.cfg;
const dims = this._uniform(new Uint32Array([T, nHeads, headDim, destOffset]));
this._pass(enc, this.pipelines.kvwrite, [dims, src, cache], Math.ceil((T * nHeads * headDim) / 256));
}
_attention(enc, Q, qLen, queryOffset, Kc, Vc, O) {
const { nHeads, headDim, xsa } = this.cfg;
const ab = new ArrayBuffer(32), dv = new DataView(ab);
dv.setUint32(0, qLen, true);
dv.setUint32(4, queryOffset + qLen, true);
dv.setUint32(8, nHeads, true);
dv.setUint32(12, headDim, true);
dv.setFloat32(16, 1.0 / Math.sqrt(headDim), true);
dv.setUint32(20, queryOffset, true);
dv.setUint32(24, xsa ? 1 : 0, true);
dv.setFloat32(28, 1e-6, true);
this._pass(enc, this.pipelines.attention, [this._uniform(new Uint8Array(ab)), Q, Kc, Vc, O], qLen, nHeads);
}
_elemwise(enc, name, a, b, out, count) {
this._pass(enc, this.pipelines[name], [a, b, out], Math.ceil(count / 256));
}
/** Precompute RoPE inverse frequencies once: 1 / theta^(2i / head_dim). */
_buildInvFreq() {
const { headDim, ropeTheta } = this.cfg;
const arr = new Float32Array(headDim / 2);
for (let i = 0; i < arr.length; i++) arr[i] = 1.0 / Math.pow(ropeTheta, (2 * i) / headDim);
this.invFreqBuf = this.device.createBuffer({ size: arr.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST, mappedAtCreation: true });
new Float32Array(this.invFreqBuf.getMappedRange()).set(arr);
this.invFreqBuf.unmap();
}
/**
* Run the model forward on `tokenIds` (appended after whatever is already
* in the KV cache) and return the logits for the LAST position only,
* as a plain JS Float32Array of length vocab_size.
*/
async forward(tokenIds) {
const { dModel, nHeads, headDim, nLayers, vocabSize, contextLen, normEps, qkEps, qkNorm } = this.cfg;
const T = tokenIds.length;
const posOffset = this.curLen;
if (T === 0) throw new Error("forward() called with no tokens");
if (posOffset + T > contextLen) throw new Error(`sequence length ${posOffset + T} exceeds context_len ${contextLen}`);
const enc = this.device.createCommandEncoder();
const W = (n) => this.weights[n].buffer;
// embedding lookup: CPU-side gather from the raw embedding matrix, then upload
const x0 = this._storage(T * dModel * 4);
{
const rows = new Float32Array(T * dModel);
for (let t = 0; t < T; t++) {
const id = tokenIds[t];
rows.set(this._embedRaw.subarray(id * dModel, (id + 1) * dModel), t * dModel);
}
this.device.queue.writeBuffer(x0, 0, rows);
}
let x = x0;
for (let l = 0; l < nLayers; l++) {
const w = this.arch.w(l);
const ffnDim = this.weights[w.gate].shape[0];
const normed = this._storage(T * dModel * 4);
this._rmsnorm(enc, x, T, dModel, normEps, W(w.attnNorm), normed);
let q = this._storage(T * dModel * 4);
let k = this._storage(T * dModel * 4);
const v = this._storage(T * dModel * 4);
this._matmul(enc, normed, T, dModel, W(w.wq), dModel, q);
this._matmul(enc, normed, T, dModel, W(w.wk), dModel, k);
this._matmul(enc, normed, T, dModel, W(w.wv), dModel, v);
// v3: QK-Norm — RMSNorm over each head's vector (rows = T*H, dim = head_dim), before RoPE
if (qkNorm) {
const qn = this._storage(T * dModel * 4), kn = this._storage(T * dModel * 4);
this._rmsnorm(enc, q, T * nHeads, headDim, qkEps, W(w.qNorm), qn);
this._rmsnorm(enc, k, T * nHeads, headDim, qkEps, W(w.kNorm), kn);
q = qn; k = kn;
}
this._rope(enc, q, T, posOffset);
this._rope(enc, k, T, posOffset);
this._kvwrite(enc, k, T, posOffset, this.kvCacheK[l]);
this._kvwrite(enc, v, T, posOffset, this.kvCacheV[l]);
const attnOut = this._storage(T * dModel * 4);
this._attention(enc, q, T, posOffset, this.kvCacheK[l], this.kvCacheV[l], attnOut);
const attnProj = this._storage(T * dModel * 4);
this._matmul(enc, attnOut, T, dModel, W(w.wo), dModel, attnProj);
const afterAttn = this._storage(T * dModel * 4);
this._elemwise(enc, "add", x, attnProj, afterAttn, T * dModel);
const ffnNormed = this._storage(T * dModel * 4);
this._rmsnorm(enc, afterAttn, T, dModel, normEps, W(w.ffnNorm), ffnNormed);
const gate = this._storage(T * ffnDim * 4), up = this._storage(T * ffnDim * 4), gated = this._storage(T * ffnDim * 4);
this._matmul(enc, ffnNormed, T, dModel, W(w.gate), ffnDim, gate);
this._matmul(enc, ffnNormed, T, dModel, W(w.up), ffnDim, up);
this._elemwise(enc, "swiglu_gate", gate, up, gated, T * ffnDim);
const ffnOut = this._storage(T * dModel * 4);
this._matmul(enc, gated, T, ffnDim, W(w.down), dModel, ffnOut);
const afterFFN = this._storage(T * dModel * 4);
this._elemwise(enc, "add", afterAttn, ffnOut, afterFFN, T * dModel);
x = afterFFN;
}
const finalNormed = this._storage(T * dModel * 4);
this._rmsnorm(enc, x, T, dModel, normEps, W(FINAL_NORM), finalNormed);
// lm_head is tied to tok_embed; only the last position's logits are needed
const lastHidden = this._storage(dModel * 4);
enc.copyBufferToBuffer(finalNormed, (T - 1) * dModel * 4, lastHidden, 0, dModel * 4);
const logits = this._storage(vocabSize * 4);
this._matmul(enc, lastHidden, 1, dModel, W(EMBED), vocabSize, logits);
const readBuf = this.device.createBuffer({ size: vocabSize * 4, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });
enc.copyBufferToBuffer(logits, 0, readBuf, 0, vocabSize * 4);
this.device.queue.submit([enc.finish()]);
await readBuf.mapAsync(GPUMapMode.READ);
const out = new Float32Array(readBuf.getMappedRange().slice(0));
readBuf.unmap();
readBuf.destroy();
for (const b of this._tmp) b.destroy();
this._tmp = [];
this.curLen = posOffset + T;
return out;
}
/** Temperature, repetition penalty (over `recent` token ids), top-k, categorical draw. */
sample(logits, { temperature, topK, repPenalty = 1.0, recent = [] }) {
const n = logits.length;
const scaled = new Float32Array(logits);
if (repPenalty !== 1.0) {
for (const id of new Set(recent)) {
const v = scaled[id];
scaled[id] = v > 0 ? v / repPenalty : v * repPenalty;
}
}
const invT = 1.0 / Math.max(temperature, 1e-6);
for (let i = 0; i < n; i++) scaled[i] *= invT;
const k = Math.min(topK, n);
const idx = Array.from({ length: n }, (_, i) => i);
idx.sort((a, b) => scaled[b] - scaled[a]);
const top = idx.slice(0, k);
const maxLogit = scaled[top[0]];
let sum = 0;
const probs = top.map(i => { const p = Math.exp(scaled[i] - maxLogit); sum += p; return p; });
let r = Math.random() * sum;
for (let j = 0; j < top.length; j++) { r -= probs[j]; if (r <= 0) return top[j]; }
return top[top.length - 1];
}
}
/* ---------------------------------------------------------------------
4. Chat format for the Instruct model (exactly the training format):
<|endoftext|>User: q\n\nAssistant: a<|endoftext|>User: q2\n\nAssistant:
Each piece is tokenized on its own, the same way the training data was.
--------------------------------------------------------------------- */
function chatIds(tok, turns) {
const ids = [EOT_ID];
for (const t of turns) {
if (t.role === "assistant") ids.push(...tok.encode(" " + t.text.trim()), EOT_ID);
else ids.push(...tok.encode(`User: ${t.text.trim()}\n\nAssistant:`));
}
return ids;
}
/* ---------------------------------------------------------------------
5. UI wiring
--------------------------------------------------------------------- */
const $ = (id) => document.getElementById(id);
const stageListEl = $("stage-list");
const loadBtn = $("load-btn");
const errBox = $("err-box");
const chatShell = $("chat-shell");
const transcriptEl = $("transcript");
const promptInput = $("prompt-input");
const genBtn = $("gen-btn");
const stopBtn = $("stop-btn");
const clearBtn = $("clear-btn");
const sliders = {
temp: [$("temp-slider"), $("temp-val"), (v) => Number(v).toFixed(2)],
topk: [$("topk-slider"), $("topk-val"), (v) => v],
rep: [$("rep-slider"), $("rep-val"), (v) => Number(v).toFixed(2)],
maxtok: [$("maxtok-slider"), $("maxtok-val"), (v) => v],
};
for (const [s, label, fmt] of Object.values(sliders)) s.addEventListener("input", () => label.textContent = fmt(s.value));
const setSlider = (key, v) => { const [s, label, fmt] = sliders[key]; s.value = v; label.textContent = fmt(s.value); };
let device = null;
let backendLabel = "WebGPU";
let engine = null;
let selected = MODELS[0];
let busy = false;
let genController = { stop: false };
let chatTurns = []; // [{role, text}] for the Instruct model
let cachedIds = []; // token ids currently resident in the KV cache (chat mode)
function renderModelGrid() {
const grid = $("model-grid");
grid.innerHTML = "";
for (const m of MODELS) {
const b = document.createElement("button");
b.className = "model-opt" + (m.chat ? " chat" : "") + (m === selected ? " selected" : "");
b.innerHTML = `<span class="m-tag">${m.chat ? "Instruct · chat" : "Base · completion"}</span><span class="m-name"></span><span class="m-meta">${m.params} · ${m.size}</span>`;
b.querySelector(".m-name").textContent = m.name;
b.disabled = busy;
b.addEventListener("click", () => {
if (busy || m === selected) return;
selected = m;
renderModelGrid();
renderSelectedMeta();
loadBtn.disabled = false;
loadBtn.textContent = engine ? `Switch to ${m.name}` : "Load model & run in-browser";
});
grid.appendChild(b);
}
}
function renderSelectedMeta() {
const m = selected;
const url = `https://huggingface.co/${m.repo}`;
$("meta-model").textContent = `Conversate-${m.name.replace(" ", "-")}`;
$("meta-params").textContent = m.params;
for (const a of [$("meta-weights"), $("footer-weights")]) a.href = url;
$("footer-weights").textContent = m.repo;
$("load-hint").textContent = `${m.size}, cached by the browser after first load`;
renderArchTable(m);
}
function renderArchTable(m) {
const v3 = m.arch === "v3";
const ffn = m.key === "v3-base" ? 853 : 864;
const rows = v3 ? [
["Architecture", `Dense decoder-only, 16 layers, hidden 320, 8 heads (head_dim 40), SwiGLU FFN inner ${ffn}, tied embeddings`],
["Positional encoding", "RoPE, θ=10000, rotate-half layout: the first and second halves of each head vector are rotated as pairs (i, i + head_dim/2)"],
["Normalization", "RMSNorm, pre-norm, eps=1e-5; plus QK-Norm: a per-head RMSNorm on queries and keys before RoPE"],
["Attention", "Causal scaled dot-product attention with an online softmax, followed by XSA (Exclusive Self-Attention): each head's output has its component along the token's own value vector removed, z = y − (y·v)/(‖v‖²+ε)·v"],
["Feedforward", `SwiGLU: w_down(silu(w_gate(x)) ⊙ w_up(x)), inner dim ${ffn}`],
["Tokenizer", "16,000-token byte-level BPE with digit-atomic pre-tokenization: every digit is its own token"],
["Sampling", m.chat
? "Chat format <|endoftext|>User: …\\n\\nAssistant: …<|endoftext|>; stops at <|endoftext|>; temperature + repetition penalty over the reply so far + top-k, drawn on the CPU"
: "Temperature + optional repetition penalty + top-k, categorical draw on the CPU over the logits read back from the GPU"],
] : [
["Architecture", "Dense decoder-only, 10 layers, hidden 384, 6 heads (head_dim 64), FFN inner 1024, tied embeddings"],
["Positional encoding", "RoPE, θ=10000, applied as complex-plane rotation on interleaved (x0,x1),(x2,x3)… pairs"],
["Normalization", "RMSNorm, pre-norm, eps=1e-5, computed in f32"],
["Attention", "Full scaled dot-product attention with an online softmax and a causal early-exit on the key loop"],
["Feedforward", "SwiGLU: down_proj(silu(gate_proj(x)) ⊙ up_proj(x)), inner dim 1024"],
["Tokenizer", "16,000-token byte-level BPE, GPT-2 style pre-tokenization"],
["Sampling", "Temperature + optional repetition penalty + top-k, categorical draw on the CPU over the logits read back from the GPU"],
];
rows.push(["Weight loading", "Raw fetch() of model.safetensors, JSON header parsed by hand, each tensor's byte range copied into a GPUBuffer — no ONNX export, no ORT runtime, no transformers.js"]);
const tbl = $("arch-table");
tbl.innerHTML = "";
for (const [k, v] of rows) {
const tr = document.createElement("tr");
const a = document.createElement("td"), b = document.createElement("td");
a.textContent = k; b.textContent = v;
tr.append(a, b); tbl.appendChild(tr);
}
}
function setStage(name, state, meta = "") {
const el = stageListEl.querySelector(`[data-stage="${name}"]`);
if (!el) return;
el.classList.remove("active", "done");
if (state === "active") { el.classList.add("active"); el.querySelector(".mark").textContent = "running"; }
if (state === "done") { el.classList.add("done"); el.querySelector(".mark").textContent = "done"; }
if (state === "idle") { el.querySelector(".mark").textContent = "idle"; }
el.querySelector(".meta").textContent = meta;
}
function resetStages() { for (const el of stageListEl.querySelectorAll(".stage")) setStage(el.dataset.stage, "idle"); }
function setProgress(frac, label, bytesLabel = "") {
$("progress-fill").style.width = `${Math.round(frac * 100)}%`;
$("progress-label").textContent = label;
$("progress-bytes").textContent = bytesLabel;
}
function showError(err) {
console.error(err);
errBox.style.display = "block";
errBox.textContent = (err && err.message) ? err.message : String(err);
}
function fmtBytes(n) {
if (n > 1e6) return (n / 1e6).toFixed(1) + " MB";
if (n > 1e3) return (n / 1e3).toFixed(1) + " KB";
return n + " B";
}
async function fetchWithProgress(url, onProgress) {
const resp = await fetch(url);
if (!resp.ok) throw new Error(`fetch failed: ${resp.status} ${resp.statusText} — ${url}`);
const total = Number(resp.headers.get("content-length")) || 0;
const reader = resp.body.getReader();
const chunks = [];
let received = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
received += value.length;
if (onProgress) onProgress(received, total);
}
const buf = new Uint8Array(received);
let offset = 0;
for (const c of chunks) { buf.set(c, offset); offset += c.length; }
return buf.buffer;
}
function setBusy(b) {
busy = b;
for (const el of document.querySelectorAll(".model-opt")) el.disabled = b;
}
async function boot() {
if (busy) return;
errBox.style.display = "none";
loadBtn.disabled = true;
setBusy(true);
resetStages();
const spec = selected;
const cdn = `https://huggingface.co/${spec.repo}/resolve/main`;
const t0 = performance.now();
try {
if (!device) {
if (!("gpu" in navigator)) {
$("webgpu-warning").style.display = "block";
throw new Error("navigator.gpu is undefined — WebGPU is not available in this browser.");
}
setStage("webgpu", "active");
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) throw new Error("navigator.gpu.requestAdapter() returned null — no compatible GPU found.");
device = await adapter.requestDevice();
device.lost.then((info) => showError(new Error(`GPU device lost: ${info.message || info.reason}. Reload the page.`)));
try {
const info = adapter.info || (adapter.requestAdapterInfo ? await adapter.requestAdapterInfo() : null);
if (info && (info.vendor || info.architecture)) backendLabel = [info.vendor, info.architecture].filter(Boolean).join(" / ");
} catch (_) {}
}
$("stat-backend").textContent = backendLabel || "WebGPU";
setStage("webgpu", "done", "device acquired");
// free the previous model's GPU memory before loading the next one
if (engine) { engine.destroy(); engine = null; }
chatShell.classList.remove("active");
const eng = new IvmeEngine(device, spec);
setStage("config", "active");
const cfgResp = await fetch(`${cdn}/config.json`);
if (!cfgResp.ok) throw new Error(`config.json fetch failed: ${cfgResp.status}`);
eng.setConfig(await cfgResp.json());
setStage("config", "done", `${eng.cfg.nLayers}L / d${eng.cfg.dModel} / ${eng.cfg.nHeads}H`);
setStage("tokenizer", "active");
const tokBuf = await fetchWithProgress(`${cdn}/tokenizer.json`, (r, t) => {
setProgress(t ? r / t : 0, "fetching tokenizer.json", `${fmtBytes(r)}${t ? " / " + fmtBytes(t) : ""}`);
});
const tokJson = JSON.parse(new TextDecoder().decode(tokBuf));
eng.tokenizer = new ByteLevelBPE(tokJson);
setStage("tokenizer", "done", `${Object.keys(tokJson.model.vocab).length} vocab, ${tokJson.model.merges.length} merges`);
setStage("weights", "active");
const weightsBuf = await fetchWithProgress(`${cdn}/model.safetensors`, (r, t) => {
setProgress(t ? r / t : 0, "streaming model.safetensors", `${fmtBytes(r)}${t ? " / " + fmtBytes(t) : ""}`);
});
setStage("weights", "done", fmtBytes(weightsBuf.byteLength));
setStage("upload", "active");
const parsed = parseSafetensors(weightsBuf);
eng.loadWeightsFromSafetensors(parsed);
{
// keep the raw embedding matrix as a typed array for the CPU-side gather
const t = parsed.tensors[EMBED];
eng._embedRaw = new Float32Array(parsed.buffer.slice(t.byteOffset, t.byteOffset + t.byteLength));
}
setStage("upload", "done", `${Object.keys(parsed.tensors).length} tensors`);
setStage("pipelines", "active");
await eng.buildPipelines();
eng._buildInvFreq();
eng.initKVCache();
setStage("pipelines", "done", `${KERNEL_ORDER.length} kernels compiled`);
setStage("warmup", "active");
await eng.forward([EOT_ID]);
eng.initKVCache(); // warm-up shouldn't count toward context
setStage("warmup", "done", "ok");
engine = eng;
window.__ivme.engine = eng;
setProgress(1, "ready", "");
$("live-dot").classList.add("on");
const loadMs = performance.now() - t0;
$("stat-loadtime").textContent = loadMs > 1000 ? (loadMs / 1000).toFixed(1) + "s" : Math.round(loadMs) + "ms";
$("stat-params").textContent = spec.params;
$("kernel-source-view").textContent = KERNEL_ORDER.map(k => `// ==== ${k} ====\n${WGSL[k]}`).join("\n\n");
setupGenerateSection(spec);
loadBtn.textContent = `${spec.name} loaded ✓`;
chatShell.classList.add("active");
chatShell.scrollIntoView({ behavior: "smooth", block: "start" });
} catch (err) {
showError(err);
loadBtn.disabled = false;
loadBtn.textContent = "Retry";
} finally {
setBusy(false);
}
}
function setupGenerateSection(spec) {
const d = spec.defaults;
setSlider("temp", d.temperature);
setSlider("topk", d.topK);
setSlider("rep", d.repPenalty);
setSlider("maxtok", d.maxNew);
chatTurns = []; cachedIds = [];
transcriptEl.innerHTML = "";
$("perf-line").innerHTML = "";
const hint = document.createElement("div");
hint.className = "placeholder-hint";
if (spec.chat) {
$("gen-title").textContent = "Chat";
$("gen-desc").textContent = "Instruct model — it follows a simple chat format and gives short answers. Multi-turn: earlier messages stay in context until the 1024-token window fills up.";
hint.textContent = "Say hi, ask a simple question, or try some arithmetic like \"what is 12 plus 9?\".";
promptInput.placeholder = "Ask something…";
genBtn.textContent = "Send";
clearBtn.textContent = "New chat";
$("composer-hint").textContent = "Enter to send · Shift+Enter for a new line";
$("safety-note").style.display = "block";
} else {
$("gen-title").textContent = "Generate";
$("gen-desc").textContent = "Base model — it continues text, it doesn't follow instructions. Try a story opener or a sentence fragment and let it run.";
hint.textContent = "This is a base model — it continues text, it doesn't follow instructions. Try a story opener, a sentence fragment, anything it can run with.";
promptInput.placeholder = "Once upon a time, there was a";
genBtn.textContent = "Run";
clearBtn.textContent = "Clear";
$("composer-hint").textContent = "";
$("safety-note").style.display = "none";
}
transcriptEl.appendChild(hint);
}
function addMsg(cls, who, text) {
const hint = transcriptEl.querySelector(".placeholder-hint");
if (hint) hint.remove();
const el = document.createElement("div");
el.className = `msg ${cls}`;
el.innerHTML = `<div class="who"></div><div class="txt"></div>`;
el.querySelector(".who").textContent = who;
el.querySelector(".txt").textContent = text;
transcriptEl.appendChild(el);
transcriptEl.scrollTop = transcriptEl.scrollHeight;
return el.querySelector(".txt");
}
function renderStreaming(txtEl, text, done) {
txtEl.textContent = text;
if (!done) { const c = document.createElement("span"); c.className = "cursor"; txtEl.appendChild(c); }
transcriptEl.scrollTop = transcriptEl.scrollHeight;
}
/** Make the KV cache hold exactly `ids` minus the last token, reusing the longest common prefix. Returns logits after `ids`. */
async function syncCacheAndForward(ids) {
let lcp = 0;
while (lcp < cachedIds.length && lcp < ids.length - 1 && cachedIds[lcp] === ids[lcp]) lcp++;
engine.curLen = lcp; // drop everything after the shared prefix (it gets overwritten)
const logits = await engine.forward(ids.slice(lcp));
cachedIds = ids.slice();
return logits;
}
async function decodeLoop({ logits, maxNew, temperature, topK, repPenalty, onToken, stopOnEOT }) {
const out = [];
const contextLen = engine.cfg.contextLen;
while (out.length < maxNew && !genController.stop) {
const next = engine.sample(logits, { temperature, topK, repPenalty, recent: out.slice(-256) });
if (stopOnEOT && next === EOT_ID) return { out, hitEOT: true };
out.push(next);
onToken(out);
if (engine.curLen >= contextLen) break;
logits = await engine.forward([next]);
if (cachedIds) cachedIds.push(next);
}
return { out, hitEOT: false };
}
async function runGeneration() {
const prompt = promptInput.value;
if (!prompt.trim() || !engine || busy) return;
setBusy(true);
genBtn.disabled = true; stopBtn.disabled = false; promptInput.disabled = true; clearBtn.disabled = true; loadBtn.disabled = true;
genController.stop = false;
errBox.style.display = "none";
const spec = engine.spec;
const tok = engine.tokenizer;
const maxNew = Number(sliders.maxtok[0].value);
const temperature = Number(sliders.temp[0].value);
const topK = Number(sliders.topk[0].value);
const repPenalty = Number(sliders.rep[0].value);
const contextLen = engine.cfg.contextLen;
let txtEl = null;
try {
const t0 = performance.now();
let promptTokens = 0, res;
if (spec.chat) {
addMsg("user", "you", prompt.trim());
promptInput.value = "";
chatTurns.push({ role: "user", text: prompt.trim() });
// drop the oldest turns until the history plus the reply fits in the context window
const budget = contextLen - Math.min(maxNew, contextLen / 2);
let ids = chatIds(tok, chatTurns);
let dropped = 0;
while (ids.length > budget && chatTurns.length > 1) {
chatTurns.shift(); dropped++;
while (chatTurns.length > 1 && chatTurns[0].role !== "user") { chatTurns.shift(); dropped++; } // keep user-first order
ids = chatIds(tok, chatTurns);
}
if (ids.length > budget) throw new Error("That message is too long for the 1024-token context window.");
if (dropped) addMsg("note", "context", `Dropped ${dropped} oldest message${dropped > 1 ? "s" : ""} to stay within 1024 tokens.`);
promptTokens = ids.length;
txtEl = addMsg("assistant", spec.name, "");
const logits = await syncCacheAndForward(ids);
res = await decodeLoop({
logits, maxNew: Math.min(maxNew, contextLen - ids.length), temperature, topK, repPenalty, stopOnEOT: true,
onToken: (out) => renderStreaming(txtEl, tok.decode(out).trim(), false),
});
const reply = tok.decode(res.out).trim();
renderStreaming(txtEl, reply || "…", true);
chatTurns.push({ role: "assistant", text: reply });
} else {
addMsg("user", "prompt", prompt);
txtEl = addMsg("gen", spec.name, "");
cachedIds = null;
engine.initKVCache();
const ids = tok.encode(prompt);
if (ids.length >= contextLen) throw new Error(`Prompt is ${ids.length} tokens; the context window is ${contextLen}.`);
promptTokens = ids.length;
const logits = await engine.forward(ids);
res = await decodeLoop({
logits, maxNew, temperature, topK, repPenalty, stopOnEOT: true,
onToken: (out) => renderStreaming(txtEl, tok.decode(out), false),
});
renderStreaming(txtEl, tok.decode(res.out), true);
}
const elapsed = (performance.now() - t0) / 1000;
const n = res.out.length;
const tps = n / Math.max(elapsed, 1e-6);
$("stat-toksec").textContent = tps.toFixed(1);
$("perf-line").innerHTML = `<span><b>${n}</b> tokens generated</span><span><b>${elapsed.toFixed(2)}s</b> wall time</span><span><b>${tps.toFixed(2)}</b> tok/s</span><span><b>${promptTokens}</b> context tokens</span>` +
(res.hitEOT ? `<span>stopped at <b><|endoftext|></b></span>` : "");
} catch (err) {
showError(err);
if (txtEl) txtEl.querySelector(".cursor")?.remove();
if (spec.chat && chatTurns.length && chatTurns[chatTurns.length - 1].role === "user") chatTurns.pop();
cachedIds = [];
} finally {
setBusy(false);
genBtn.disabled = false; stopBtn.disabled = true; promptInput.disabled = false; clearBtn.disabled = false;
loadBtn.disabled = (selected === engine?.spec);
promptInput.focus();
}
}
function clearTranscript() {
if (busy || !engine) return;
setupGenerateSection(engine.spec);
}
loadBtn.addEventListener("click", boot);
genBtn.addEventListener("click", runGeneration);
clearBtn.addEventListener("click", clearTranscript);
promptInput.addEventListener("keydown", (e) => {
if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); runGeneration(); }
});
stopBtn.addEventListener("click", () => { genController.stop = true; });
// small hook for automated testing (tokenizer + forward pass), harmless in normal use
window.__ivme = { MODELS, ByteLevelBPE, chatIds, engine: null, select: (key) => { selected = MODELS.find(m => m.key === key); renderModelGrid(); renderSelectedMeta(); }, boot };
renderModelGrid();
renderSelectedMeta();
</script>
</body>
</html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>İvme-Conversate · raw WebGPU inference</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Newsreader:ital,opsz,wght@0,6..72,380;0,6..72,500;0,6..72,600;0,6..72,700;1,6..72,400&family=JetBrains+Mono:wght@400;500;600&display=swap');
html{ background:#f7f4ec; }
*,*::before,*::after{ box-sizing:border-box; }
body{
margin:0;
background:
repeating-linear-gradient(180deg, rgba(0,0,0,0.014) 0px, rgba(0,0,0,0.014) 1px, transparent 1px, transparent 3px),
#f7f4ec;
color:#1c1a16;
font-family:'Newsreader', Georgia, serif;
min-height:100vh;
-webkit-font-smoothing:antialiased;
}
::selection{ background:#ff0000; color:#f7f4ec; }
a{ color:#c40000; text-decoration:none; border-bottom:1px solid rgba(255,0,0,.35); }
a:hover{ border-bottom-color:#ff0000; }
code{
font-family:'JetBrains Mono', monospace ;
font-size:.86em;
background:#ece5d3;
color:#a02020;
padding:1px 6px;
border-radius:2px;
border:1px solid #d9d2bf;
}
.page{ max-width:880px; margin:0 auto; padding:0 32px 70px; }
/* ============ MASTHEAD ============ */
.masthead{ padding:52px 0 0; text-align:center; }
.eyebrow{
font-family:'JetBrains Mono', monospace;
font-size:11px; letter-spacing:.28em; text-transform:uppercase;
color:#ff0000; margin-bottom:22px;
display:flex; align-items:center; justify-content:center; gap:10px;
}
.eyebrow .dot-live{
width:6px; height:6px; border-radius:50%; background:#c7c1ae; display:inline-block;
}
.eyebrow .dot-live.on{ background:#ff0000; animation:pulse 2.4s ease-in-out infinite; }
@keyframes pulse{ 0%,100%{opacity:1;} 50%{opacity:.35;} }
@media (prefers-reduced-motion: reduce){ .eyebrow .dot-live{ animation:none; } }
.wordmark{
font-size:clamp(40px, 7vw, 68px);
font-weight:700; line-height:.98; letter-spacing:-.015em; margin:0;
}
.wordmark .dot{ color:#ff0000; }
.tagline{
font-size:16.5px; font-style:italic; color:#4a463d;
max-width:520px; margin:18px auto 0; line-height:1.6;
}
.tagline code{ font-style:normal; }
.tickline{
height:14px; margin:40px 0 0;
background-image: repeating-linear-gradient(90deg, #ff0000 0, #ff0000 1px, transparent 1px, transparent 10px);
background-position: center; background-size:10px 1px; background-repeat:repeat-x;
background-position-y:6px; opacity:.9;
}
/* ============ META STRIP ============ */
.meta-strip{
display:flex; justify-content:center; gap:0; padding:26px 0 6px; flex-wrap:wrap;
}
.meta-item{
font-family:'JetBrains Mono', monospace; font-size:11px; letter-spacing:.05em;
color:#4a463d; padding:0 22px; border-right:1px solid #d9d2bf; text-align:center;
}
.meta-item:last-child{ border-right:none; }
.meta-item b{
display:block; color:#1c1a16; font-weight:600; font-size:12.5px;
margin-top:2px; letter-spacing:.02em;
}
/* ============ SECTIONS ============ */
section{ padding:48px 0; border-top:1px solid #d9d2bf; }
.section-head{ display:flex; align-items:baseline; gap:16px; margin-bottom:8px; }
.section-index{ font-family:'JetBrains Mono', monospace; font-size:13px; color:#ff0000; letter-spacing:.05em; }
h2{ font-size:24px; font-weight:600; margin:0; letter-spacing:-.01em; }
.section-desc{
font-size:14.5px; color:#4a463d; max-width:580px; margin:12px 0 30px; line-height:1.65;
}
p.lede{ font-size:16.5px; line-height:1.72; color:#2b2822; max-width:640px; margin:0 0 30px; }
p.lede b{ font-weight:600; box-shadow: inset 0 -.35em 0 rgba(255,0,0,.16); }
/* ============ LOAD SEQUENCE (quiet log list, no boxes) ============ */
.stage-list{ border-top:1px solid #1c1a16; }
.stage{
display:grid; grid-template-columns:100px 1fr auto; gap:20px; align-items:baseline;
padding:13px 0; border-bottom:1px solid #d9d2bf;