Spaces:
Running
Running
Host live chat with the frozen v17a compact weights
Browse filesStatic browser inference with separate conversation state per tab. Exact packed weights: 1,528,592 bytes. Analytically constructed weights — no training. Useful general chat was not achieved. Includes architecture, model card and benchmark links.
- LICENSE +21 -0
- README.md +64 -5
- app.mjs +30 -0
- config.json +0 -0
- index.html +37 -19
- runtime.mjs +229 -0
- weights.sparse.zip +3 -0
- worker.mjs +24 -0
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 SamG-Coder
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
README.md
CHANGED
|
@@ -1,12 +1,71 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: static
|
|
|
|
| 7 |
pinned: false
|
| 8 |
license: mit
|
| 9 |
short_description: Analytically constructed weights. No training. Browser chat.
|
|
|
|
|
|
|
| 10 |
---
|
| 11 |
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: direct-weight-chat
|
| 3 |
+
emoji: 💬
|
| 4 |
+
colorFrom: green
|
| 5 |
+
colorTo: blue
|
| 6 |
sdk: static
|
| 7 |
+
app_file: index.html
|
| 8 |
pinned: false
|
| 9 |
license: mit
|
| 10 |
short_description: Analytically constructed weights. No training. Browser chat.
|
| 11 |
+
models:
|
| 12 |
+
- SamGCoder/direct-weight-chat-v17a
|
| 13 |
---
|
| 14 |
|
| 15 |
+
# direct-weight-chat · v17a compact
|
| 16 |
+
|
| 17 |
+
**Analytically constructed weights — no training.** The experiment is finished.
|
| 18 |
+
**Useful open-ended chat was not achieved under these constraints.**
|
| 19 |
+
|
| 20 |
+
This is a live chat interface to the frozen experimental transformer. The model
|
| 21 |
+
generates tokens from its weights; the app does not select answers from a list.
|
| 22 |
+
It supports narrow fact statements, some corrections and conditional rules,
|
| 23 |
+
and addition/subtraction of two signed integers with magnitudes up to 999.
|
| 24 |
+
Unknown words use a bounded pointer vocabulary. Arbitrary language, general
|
| 25 |
+
reasoning, unrestricted arithmetic and reliable open-ended chat are unsupported.
|
| 26 |
+
|
| 27 |
+
The exact packed weight artifact is **1,528,592 bytes**. Config, browser runtime
|
| 28 |
+
and working memory are additional. The browser reads the same SHA-256 checked
|
| 29 |
+
`weights.sparse.zip` published in the model repository; no weights were trained
|
| 30 |
+
or modified for this Space.
|
| 31 |
+
|
| 32 |
+
- [Model card and Python downloads](https://huggingface.co/SamGCoder/direct-weight-chat-v17a)
|
| 33 |
+
- [GitHub source](https://github.com/SamG-Coder/direct-weight-chat)
|
| 34 |
+
- [Architecture](https://github.com/SamG-Coder/direct-weight-chat/blob/main/ARCHITECTURE.md)
|
| 35 |
+
- [Benchmark results and known failures](https://github.com/SamG-Coder/direct-weight-chat/blob/main/results/README.md)
|
| 36 |
+
- [Browser backend verification](https://github.com/SamG-Coder/direct-weight-chat/blob/main/publication/browser-suite-parity.json)
|
| 37 |
+
|
| 38 |
+
## Hosting and privacy
|
| 39 |
+
|
| 40 |
+
Hugging Face hosts the static files. Inference runs on the visitor's CPU in a
|
| 41 |
+
browser Web Worker. This is not a server inference API. No subscription, API key,
|
| 42 |
+
GPU or local Python installation is required to use it. After the assets load,
|
| 43 |
+
the app makes no inference network requests. It does not send messages to a
|
| 44 |
+
server or store chat in local storage. Each tab has a separate conversation;
|
| 45 |
+
refreshing or choosing **New conversation** clears it.
|
| 46 |
+
|
| 47 |
+
Use a current browser with Web Workers, Web Crypto and `DecompressionStream`
|
| 48 |
+
support for `deflate-raw`. Long conversations use more compute and memory.
|
| 49 |
+
The browser demo caps a conversation at 1,024 tokens, including 64 tokens
|
| 50 |
+
reserved for the next answer, to bound latency and memory on visitors' devices.
|
| 51 |
+
The Python runtime retains the model's full 5,048-token logical context.
|
| 52 |
+
|
| 53 |
+
## Browser implementation
|
| 54 |
+
|
| 55 |
+
`runtime.mjs` implements the original tokenizer, layer normalization, sparse
|
| 56 |
+
linear maps, causal attention, ReLU, residual connections and greedy generation.
|
| 57 |
+
It skips exact zero coefficients and computes attention only on dimensions that
|
| 58 |
+
can be nonzero according to the weight matrices. These are generic tensor
|
| 59 |
+
operations, not host fact parsing, arithmetic or rule solving.
|
| 60 |
+
|
| 61 |
+
The JavaScript backend accumulates dot products in double precision and stores
|
| 62 |
+
float32 activations. It is an independent numerical implementation, not a claim
|
| 63 |
+
of bitwise activation equivalence to PyTorch. The linked verification report
|
| 64 |
+
records exact text, token IDs and end-of-sequence comparisons against retained
|
| 65 |
+
v17a baseline runs, including their known incorrect answers.
|
| 66 |
+
|
| 67 |
+
The no-training claim describes weight construction: no optimizer, fitting,
|
| 68 |
+
training corpus or pretrained tensor transfer. Human/AI prior knowledge,
|
| 69 |
+
handwritten grammar, 40 authored atomic entities and manual test-guided
|
| 70 |
+
engineering were used. This experiment does not prove that useful chat is
|
| 71 |
+
mathematically impossible without training.
|
app.mjs
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const $=id=>document.getElementById(id);
|
| 2 |
+
const worker=new Worker(new URL('./worker.mjs',import.meta.url),{type:'module'});
|
| 3 |
+
let ready=false,busy=false;
|
| 4 |
+
function state(text) { $('status').textContent=text; }
|
| 5 |
+
function controls() { $('send').disabled=!ready||busy; $('prompt').disabled=!ready||busy; $('reset').disabled=!ready||busy; document.querySelectorAll('.example').forEach(b=>b.disabled=!ready||busy); }
|
| 6 |
+
function message(role,text,seconds) {
|
| 7 |
+
$('empty')?.remove();
|
| 8 |
+
const box=document.createElement('div'),who=document.createElement('div'),bubble=document.createElement('div');
|
| 9 |
+
box.className='message '+role; who.className='who'; bubble.className='bubble';
|
| 10 |
+
who.textContent=role==='user'?'YOU':'V17A · FROZEN WEIGHTS';
|
| 11 |
+
if(seconds!==undefined) { const timing=document.createElement('span');timing.className='timing';timing.textContent=` / ${Math.round(seconds*1000).toLocaleString()} ms on this device`;who.append(timing); }
|
| 12 |
+
bubble.textContent=text; box.append(who,bubble);$('messages').append(box);$('messages').scrollTop=$('messages').scrollHeight;
|
| 13 |
+
}
|
| 14 |
+
function error(text) { $('error').textContent=text;$('error').hidden=false; }
|
| 15 |
+
worker.onmessage=({data})=>{
|
| 16 |
+
if(data.type==='ready') { ready=true;state('Ready · inference in this browser');controls(); }
|
| 17 |
+
if(data.type==='reset') { $('messages').replaceChildren();$('error').hidden=true;$('context').textContent='Context: 1 / 1,024 tokens';busy=false;state('New conversation · ready');controls();$('prompt').focus(); }
|
| 18 |
+
if(data.type==='progress') state(data.phase==='prefill'?`Reading conversation · layer ${data.layer} / ${data.total}`:`Generating · ${data.tokens} tokens`);
|
| 19 |
+
if(data.type==='result') { const r=data.result;message('assistant',r.text,r.seconds);$('context').textContent=`Context: ${(r.prefix_tokens+r.generated_tokens).toLocaleString()} / 1,024 tokens`;busy=false;state('Ready · inference in this browser');controls();$('prompt').focus();if(!r.stopped_on_eos)error('The model reached the output limit. This response may be incomplete.'); }
|
| 20 |
+
if(data.type==='error') { busy=false;error(data.message);state(ready?'Model error · new conversation may help':'Loading failed · refresh to retry');controls(); }
|
| 21 |
+
};
|
| 22 |
+
worker.onerror=event=>{ busy=false;ready=false;error(event.message||'The browser worker stopped. Refresh to reload the model.');state('Worker stopped');controls(); };
|
| 23 |
+
$('compose').onsubmit=event=>{
|
| 24 |
+
event.preventDefault();const prompt=$('prompt').value.trim();if(!ready||busy||!prompt)return;
|
| 25 |
+
$('error').hidden=true;$('prompt').value='';message('user',prompt);busy=true;controls();state('Reading conversation…');worker.postMessage({action:'generate',prompt});
|
| 26 |
+
};
|
| 27 |
+
$('prompt').onkeydown=event=>{if(event.key==='Enter'&&!event.shiftKey&&!event.isComposing){event.preventDefault();$('compose').requestSubmit();}};
|
| 28 |
+
$('reset').onclick=()=>{if(busy)return;busy=true;controls();worker.postMessage({action:'reset'});};
|
| 29 |
+
document.querySelectorAll('.example').forEach(button=>button.onclick=()=>{$('prompt').value=button.dataset.prompt;$('prompt').focus();});
|
| 30 |
+
controls();worker.postMessage({action:'load'});
|
config.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
index.html
CHANGED
|
@@ -1,19 +1,37 @@
|
|
| 1 |
-
<!doctype html>
|
| 2 |
-
<html>
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
</
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
| 5 |
+
<meta name="description" content="Chat with the frozen direct-weight-chat experiment. Analytically constructed weights — no training. 1,528,592 bytes of packed weights.">
|
| 6 |
+
<title>direct-weight-chat · Try the experiment</title>
|
| 7 |
+
<link rel="icon" href="data:,">
|
| 8 |
+
<style>
|
| 9 |
+
:root{color-scheme:dark;--bg:#0a1119;--panel:#111d27;--line:#2b3b47;--text:#edf4f7;--muted:#a0b2bf;--mint:#91ebc7;--red:#ffbaac}*{box-sizing:border-box}body{margin:0;background:radial-gradient(ellipse at 70% 0,#183c3d44,transparent 65%),var(--bg);color:var(--text);font:15px/1.55 system-ui,'Segoe UI',sans-serif}button,textarea{font:inherit}button{cursor:pointer}button:disabled{opacity:.45;cursor:default}a{color:var(--mint);text-decoration:none}a:hover{text-decoration:underline}.shell{max-width:1440px;margin:24px auto;height:calc(100dvh - 48px);min-height:660px;border:1px solid var(--line);border-radius:22px;overflow:hidden;display:grid;grid-template:82px 1fr/292px 1fr;background:var(--panel);box-shadow:0 25px 90px #0004}header{grid-column:1/3;display:flex;align-items:center;justify-content:space-between;gap:16px;border-bottom:1px solid var(--line);padding:18px 28px}.brand{font-size:22px;letter-spacing:-.8px;font-weight:650;display:flex;align-items:center;gap:13px}.mark{color:var(--mint);font:26px ui-monospace,monospace}.version{font-size:11px;color:var(--muted);border:1px solid var(--line);border-radius:6px;padding:3px 8px;letter-spacing:.2px}.finished{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:1.1px}aside{padding:28px 24px;display:flex;flex-direction:column;border-right:1px solid var(--line);background:#0d1720}.eyebrow{font-size:10px;letter-spacing:1.4px;color:var(--muted)}.size{font-size:39px;letter-spacing:-1.5px;font-weight:650;margin-top:2px}.small{font-size:12px;color:var(--muted)}.chips{display:flex;flex-wrap:wrap;gap:6px;margin:17px 0 30px}.chip{font-size:9px;letter-spacing:.4px;padding:4px 7px;border:1px solid #345344;color:var(--mint);border-radius:5px}.example{display:block;width:100%;text-align:left;padding:12px 13px;border-radius:9px;border:1px solid var(--line);background:#17252f;color:var(--text);margin-top:9px;font-size:13px}.example:hover{background:#203931;border-color:#496759}.example span{display:block;color:var(--muted);font-size:11px;margin-top:2px}.aside-bottom{margin-top:auto;padding-top:26px;font-size:11px;color:var(--muted)}.aside-bottom a{display:block;margin-top:9px}.limit{color:var(--red)}main{min-width:0;min-height:0;display:flex;flex-direction:column}.topbar{padding:17px 30px;border-bottom:1px solid var(--line);display:flex;justify-content:space-between;align-items:center;gap:14px}.status{font-size:11px;letter-spacing:.4px;color:var(--mint)}.status:before{content:'';display:inline-block;width:6px;height:6px;border-radius:50%;background:currentColor;margin-right:8px}.new{color:var(--muted);border:1px solid var(--line);background:transparent;padding:7px 11px;border-radius:7px;font-size:12px}.intro{padding:25px 34px 12px}h1{font-size:27px;line-height:1.2;letter-spacing:-.8px;margin:0 0 9px}.intro p{margin:0;color:var(--muted);font-size:13px}.mobile-size{display:none}.messages{flex:1;min-height:0;overflow:auto;padding:5px 34px 22px;scrollbar-width:thin;scrollbar-color:#38515b transparent}.empty{border:1px dashed #34505b;border-radius:14px;padding:25px;margin-top:17px;max-width:630px;color:var(--muted);font-size:14px}.empty strong{color:var(--text);font-weight:500}.empty code{display:block;font:13px/1.8 ui-monospace,Consolas,monospace;color:#c9e6db;margin:10px 0}.message{max-width:88%;margin-top:18px}.message.user{margin-left:auto}.who{font-size:9px;letter-spacing:1px;color:var(--muted);margin-bottom:6px}.user .who{text-align:right}.bubble{background:#243744;border:1px solid #3b5463;padding:14px 18px;border-radius:15px 15px 4px 15px;white-space:pre-wrap;overflow-wrap:anywhere;font-size:16px}.assistant .bubble{background:#15312a;border-color:#365c4d;border-radius:15px 15px 15px 4px;color:#cef8e5}.timing{letter-spacing:0;opacity:.8}.banner{margin:0 34px 12px;padding:10px 13px;border:1px solid #5b4039;background:#30231f;border-radius:8px;font-size:12px;color:var(--red)}.compose{margin:0 34px;display:flex;gap:10px;align-items:stretch}.compose textarea{resize:vertical;min-height:61px;max-height:170px;width:100%;padding:13px 15px;border-radius:10px;border:1px solid #39505d;background:#0b1720;color:var(--text);outline:none;font-size:14px}.compose textarea:focus{border-color:var(--mint)}.send{background:var(--mint);border:0;border-radius:10px;color:#10291f;padding:0 21px;font-size:14px;font-weight:650}.foot{margin:9px 34px 19px;font-size:10px;display:flex;justify-content:space-between;gap:12px;color:var(--muted)}[hidden]{display:none!important}@media(max-width:1000px){.shell{margin:0;height:100dvh;min-height:600px;border-radius:0;grid-template:72px 1fr/240px}.brand{font-size:20px}aside{padding:24px 19px}.size{font-size:33px}.intro,.topbar{padding-left:25px;padding-right:25px}.messages{padding-left:25px;padding-right:25px}.compose,.banner{margin-left:25px;margin-right:25px}.foot{margin-left:25px;margin-right:25px}.message{max-width:94%}}@media(max-width:650px){.shell{display:flex;flex-direction:column;min-height:540px}header{padding:15px 17px;min-height:65px}.brand{font-size:18px;gap:8px}.finished{display:none}aside{display:none}main{flex:1}.intro{padding:17px 19px 10px}.intro h1{font-size:22px}.intro p{font-size:12px}.mobile-size{display:block!important;margin-top:7px!important;font-size:10px!important;color:var(--mint)!important}.topbar{padding:12px 19px}.messages{padding:3px 19px 15px}.compose,.banner{margin-left:19px;margin-right:19px}.foot{margin:8px 19px 13px}.foot span:last-child{display:none}.empty{padding:17px;font-size:13px}.bubble{font-size:15px}.status{font-size:10px}.send{padding:0 16px}}
|
| 10 |
+
</style>
|
| 11 |
+
</head>
|
| 12 |
+
<body>
|
| 13 |
+
<div class="shell">
|
| 14 |
+
<header><div class="brand"><span class="mark" aria-hidden="true">⌘</span>direct-weight-chat <span class="version">v17a compact</span></div><span class="finished">Experiment finished</span></header>
|
| 15 |
+
<aside>
|
| 16 |
+
<div class="eyebrow">EXACT PACKED WEIGHT SIZE</div><div class="size">1,528,592</div><div class="small">bytes · 995,905 nonzero coefficients</div>
|
| 17 |
+
<div class="chips"><span class="chip">NO TRAINING</span><span class="chip">NO PRETRAINED WEIGHTS</span><span class="chip">RUNS IN YOUR BROWSER</span></div>
|
| 18 |
+
<div class="eyebrow">TRY A STARTING MESSAGE</div>
|
| 19 |
+
<button class="example" data-prompt="A kelv can fly. What can a kelv do?">Facts & continued conversation<span>Give a fact, then ask about it.</span></button>
|
| 20 |
+
<button class="example" data-prompt="If a kelv can fly then a tal can swim. A kelv can fly. Can a tal swim?">A simple conditional rule<span>Try a short chain of stated facts.</span></button>
|
| 21 |
+
<button class="example" data-prompt="149 - 370">Signed arithmetic<span>Two operands, addition or subtraction.</span></button>
|
| 22 |
+
<button class="example" data-prompt="Write a story about a lighthouse.">Explore the limits<span>Open-ended chat was not achieved.</span></button>
|
| 23 |
+
<div class="aside-bottom"><strong class="limit">Useful general chat was not achieved.</strong><br>A finished experiment with narrow grammar and known failures. Config, code and working memory are additional to the packed weight size.
|
| 24 |
+
<a href="https://huggingface.co/SamGCoder/direct-weight-chat-v17a" target="_blank" rel="noreferrer">Model card & downloads ↗</a>
|
| 25 |
+
<a href="https://github.com/SamG-Coder/direct-weight-chat/blob/main/ARCHITECTURE.md" target="_blank" rel="noreferrer">Architecture ↗</a>
|
| 26 |
+
<a href="https://github.com/SamG-Coder/direct-weight-chat/blob/main/results/README.md" target="_blank" rel="noreferrer">Benchmark results & failures ↗</a>
|
| 27 |
+
</div></aside>
|
| 28 |
+
<main>
|
| 29 |
+
<div class="topbar"><span id="status" class="status" role="status">Loading and checking weights…</span><button id="reset" class="new" disabled>New conversation</button></div>
|
| 30 |
+
<div class="intro"><h1>Chat with the experiment</h1><p>Analytically constructed weights — no training. Live token generation from the frozen model.</p><p class="mobile-size">1,528,592 packed weight bytes · <a href="https://huggingface.co/SamGCoder/direct-weight-chat-v17a" target="_blank" rel="noreferrer">Model & limitations ↗</a></p></div>
|
| 31 |
+
<div id="messages" class="messages" role="log" aria-live="polite"><div id="empty" class="empty"><strong>Start with a fact. Keep the conversation going.</strong><code>A kelv can fly. What can a kelv do?<br>Can a kelv swim?<br>A kelv can swim. Can a kelv swim?</code>It can use some facts, corrections, short rules and two-operand arithmetic. It often replies “I do not know” outside its limited grammar. Useful general chat was not achieved.</div></div>
|
| 32 |
+
<div id="error" class="banner" role="alert" hidden></div>
|
| 33 |
+
<form id="compose" class="compose"><textarea id="prompt" rows="2" maxlength="20000" aria-label="Message to the model" placeholder="A kelv can fly. What can a kelv do?" disabled></textarea><button id="send" class="send" disabled>Send</button></form>
|
| 34 |
+
<div class="foot"><span>Messages stay in this tab. Refresh clears the conversation.</span><span id="context">Context: 1 / 1,024 tokens</span></div>
|
| 35 |
+
</main></div>
|
| 36 |
+
<script type="module" src="./app.mjs"></script>
|
| 37 |
+
</body></html>
|
runtime.mjs
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/** Browser inference for the frozen v17a transformer. No response rules or training.
|
| 2 |
+
* All linear maps come from the original, hash-checked sparse weight archive.
|
| 3 |
+
* Sparse dot products omit mathematical zero terms; JS accumulation differs from
|
| 4 |
+
* PyTorch, so this backend has its own measured token-parity report.
|
| 5 |
+
*/
|
| 6 |
+
export const WEIGHT_SHA = '4739a3511f5c4b9170f5d09524bd8105f5853a7999cbeefdea7a8cbae01d737d';
|
| 7 |
+
export const CONFIG_SHA = '56df33d5842a0d3a1351dae78732c01589bde1ce55a33868f9d13dec171bee91';
|
| 8 |
+
const decoder = new TextDecoder();
|
| 9 |
+
|
| 10 |
+
export async function sha256(bytes) {
|
| 11 |
+
return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), b => b.toString(16).padStart(2, '0')).join('');
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
async function inflate(bytes) {
|
| 15 |
+
const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('deflate-raw'));
|
| 16 |
+
return new Uint8Array(await new Response(stream).arrayBuffer());
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
export async function unpackZip(bytes, decompress = inflate) {
|
| 20 |
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
| 21 |
+
let end = bytes.length - 22;
|
| 22 |
+
while (end >= Math.max(0, bytes.length - 65557) && view.getUint32(end, true) !== 0x06054b50) end--;
|
| 23 |
+
if (end < 0) throw new Error('Invalid weight archive');
|
| 24 |
+
const count = view.getUint16(end + 10, true);
|
| 25 |
+
let pos = view.getUint32(end + 16, true);
|
| 26 |
+
const members = new Map();
|
| 27 |
+
for (let n = 0; n < count; n++) {
|
| 28 |
+
if (view.getUint32(pos, true) !== 0x02014b50) throw new Error('Invalid ZIP directory');
|
| 29 |
+
const method = view.getUint16(pos + 10, true), size = view.getUint32(pos + 20, true);
|
| 30 |
+
const original = view.getUint32(pos + 24, true), len = view.getUint16(pos + 28, true);
|
| 31 |
+
const extra = view.getUint16(pos + 30, true), comment = view.getUint16(pos + 32, true);
|
| 32 |
+
const local = view.getUint32(pos + 42, true), name = decoder.decode(bytes.subarray(pos + 46, pos + 46 + len));
|
| 33 |
+
const start = local + 30 + view.getUint16(local + 26, true) + view.getUint16(local + 28, true);
|
| 34 |
+
const compressed = bytes.subarray(start, start + size);
|
| 35 |
+
const raw = method === 0 ? compressed.slice() : method === 8 ? await decompress(compressed) : null;
|
| 36 |
+
if (!raw || raw.length !== original || members.has(name)) throw new Error('Invalid ZIP member');
|
| 37 |
+
members.set(name, raw);
|
| 38 |
+
pos += 46 + len + extra + comment;
|
| 39 |
+
}
|
| 40 |
+
return members;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
export class Tokenizer {
|
| 44 |
+
constructor(config) {
|
| 45 |
+
this.config = config;
|
| 46 |
+
this.labels = config.vocabulary;
|
| 47 |
+
this.ids = new Map(this.labels.map((x, i) => [x.toLowerCase(), i]));
|
| 48 |
+
this.pointers = new Map(); this.reverse = new Map(); this.used = [0, 0];
|
| 49 |
+
this.maxPhrase = Math.max(...this.labels.map(x => x.trim().split(/\s+/).length));
|
| 50 |
+
}
|
| 51 |
+
encode(text) {
|
| 52 |
+
// Python's original regex uses Unicode-aware \w in the punctuation branch.
|
| 53 |
+
const words = text.match(/[A-Za-z]+(?:'[A-Za-z]+)?|[0-9]+|[^\p{L}\p{N}_\s]/gu) || [];
|
| 54 |
+
const out = [];
|
| 55 |
+
for (let i = 0; i < words.length;) {
|
| 56 |
+
let found = false;
|
| 57 |
+
for (let len = Math.min(this.maxPhrase, words.length - i); len > 0; len--) {
|
| 58 |
+
const key = words.slice(i, i + len).join(' ').toLowerCase();
|
| 59 |
+
if (this.ids.has(key) && !key.startsWith('<')) { out.push(this.ids.get(key)); i += len; found = true; break; }
|
| 60 |
+
}
|
| 61 |
+
if (found) continue;
|
| 62 |
+
const original = words[i++], key = original.toLowerCase();
|
| 63 |
+
if (!this.pointers.has(key)) {
|
| 64 |
+
const section = 'aeiou'.includes(key[0]) ? 0 : 1;
|
| 65 |
+
if (this.used[section] >= 64) throw new Error('The fixed pointer vocabulary is full; start a new conversation.');
|
| 66 |
+
const tid = this.config.dynamic_start + 64 * section + this.used[section]++;
|
| 67 |
+
this.pointers.set(key, tid); this.reverse.set(tid, original);
|
| 68 |
+
}
|
| 69 |
+
out.push(this.pointers.get(key));
|
| 70 |
+
}
|
| 71 |
+
return out;
|
| 72 |
+
}
|
| 73 |
+
tokenText(id) { return this.reverse.get(id) ?? this.labels[id]; }
|
| 74 |
+
decode(ids) {
|
| 75 |
+
return ids.filter(x => x !== this.config.special.eos).map(x => this.tokenText(x)).join(' ')
|
| 76 |
+
.replace(/\s+([.,?!:;])/g, '$1').replace(/(?<![\p{L}\p{N}_])-\s+(?=\d)/gu, '-')
|
| 77 |
+
.replace(/\bi\b/g, 'I').replace(/(^|[.!?]\s+)([a-z])/g, (_, a, b) => a + b.toUpperCase());
|
| 78 |
+
}
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
class Tensor {
|
| 82 |
+
constructor(spec, members) {
|
| 83 |
+
this.shape = spec.shape;
|
| 84 |
+
const ib = members.get(spec.prefix + '.indices.u32'), vb = members.get(spec.prefix + '.values.f32');
|
| 85 |
+
if (!ib || !vb || ib.length !== spec.entries * 4 || vb.length !== ib.length) throw new Error('Truncated tensor');
|
| 86 |
+
this.indices = new Uint32Array(Uint8Array.from(ib).buffer);
|
| 87 |
+
this.values = new Float32Array(Uint8Array.from(vb).buffer);
|
| 88 |
+
const total = this.shape.reduce((a,b) => a*b, 1);
|
| 89 |
+
for (let i=0; i<this.indices.length; i++) if (this.indices[i]>=total || (i && this.indices[i]<=this.indices[i-1])) throw new Error('Invalid sparse indices');
|
| 90 |
+
if (this.shape.length === 1) {
|
| 91 |
+
this.dense = new Float32Array(this.shape[0]);
|
| 92 |
+
for (let i=0;i<this.indices.length;i++) this.dense[this.indices[i]]=this.values[i];
|
| 93 |
+
} else {
|
| 94 |
+
const [rows, cols] = this.shape;
|
| 95 |
+
this.rowPtr = new Uint32Array(rows + 1); this.col = new Uint32Array(this.indices.length);
|
| 96 |
+
for (let i=0;i<this.indices.length;i++) { this.rowPtr[Math.floor(this.indices[i]/cols)+1]++; this.col[i]=this.indices[i]%cols; }
|
| 97 |
+
for (let r=1;r<=rows;r++) this.rowPtr[r]+=this.rowPtr[r-1];
|
| 98 |
+
this.active = [];
|
| 99 |
+
for (let r=0;r<rows;r++) if (this.rowPtr[r]!==this.rowPtr[r+1]) this.active.push(r);
|
| 100 |
+
}
|
| 101 |
+
}
|
| 102 |
+
addRow(row, output, offset) {
|
| 103 |
+
for (let k=this.rowPtr[row];k<this.rowPtr[row+1];k++) output[offset+this.col[k]] += this.values[k];
|
| 104 |
+
}
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
export class Model {
|
| 108 |
+
static async fromBytes(configBytes, weightBytes, decompress) {
|
| 109 |
+
if (weightBytes.length !== 1528592 || await sha256(weightBytes) !== WEIGHT_SHA) throw new Error('Weight checksum mismatch');
|
| 110 |
+
if (await sha256(configBytes) !== CONFIG_SHA) throw new Error('Config checksum mismatch');
|
| 111 |
+
const members = await unpackZip(weightBytes, decompress);
|
| 112 |
+
const metadata = JSON.parse(decoder.decode(members.get('compact.json')));
|
| 113 |
+
if (metadata.config_sha256 !== CONFIG_SHA) throw new Error('Archive config mismatch');
|
| 114 |
+
return new Model(JSON.parse(decoder.decode(configBytes)), metadata, members);
|
| 115 |
+
}
|
| 116 |
+
constructor(config, metadata, members) {
|
| 117 |
+
this.config=config; this.w=new Map(); this.width=config.width;
|
| 118 |
+
if (config.format!=='direct-causal-transformer-f32-v1' || metadata.format!=='direct-causal-transformer-sparse-f32-v1') throw new Error('Unsupported model');
|
| 119 |
+
if (Object.keys(metadata.tensors).length!==Object.keys(config.tensors).length) throw new Error('Tensor inventory mismatch');
|
| 120 |
+
for (const [name, spec] of Object.entries(metadata.tensors)) {
|
| 121 |
+
if (JSON.stringify(spec.shape)!==JSON.stringify(config.tensors[name]?.shape)) throw new Error('Tensor shape mismatch');
|
| 122 |
+
this.w.set(name,new Tensor(spec,members));
|
| 123 |
+
}
|
| 124 |
+
// Discover structural sparsity from coefficients only; never from a prompt.
|
| 125 |
+
this.attentionDims=[];
|
| 126 |
+
for(let layer=0;layer<config.layers;layer++) {
|
| 127 |
+
const prefix=`blocks.${layer}.attn.qkv`, weight=this.w.get(prefix+'.weight'), bias=this.w.get(prefix+'.bias').dense;
|
| 128 |
+
const active=new Set(weight.active);
|
| 129 |
+
bias.forEach((v,i)=>{if(v!==0)active.add(i);});
|
| 130 |
+
const headDim=this.width/config.heads, heads=[];
|
| 131 |
+
for(let head=0;head<config.heads;head++) {
|
| 132 |
+
const dot=[], values=[];
|
| 133 |
+
for(let d=0;d<headDim;d++) {
|
| 134 |
+
const j=head*headDim+d;
|
| 135 |
+
if(active.has(j)&&active.has(this.width+j)) dot.push(j);
|
| 136 |
+
if(active.has(2*this.width+j)) values.push(j);
|
| 137 |
+
}
|
| 138 |
+
if(values.length) heads.push({dot,values});
|
| 139 |
+
}
|
| 140 |
+
this.attentionDims.push(heads);
|
| 141 |
+
}
|
| 142 |
+
this.reset();
|
| 143 |
+
}
|
| 144 |
+
reset() { this.tokenizer=new Tokenizer(this.config); this.history=[this.config.special.bos]; }
|
| 145 |
+
norm(x,prefix) {
|
| 146 |
+
const w=this.width, gain=this.w.get(prefix+'.weight').dense, bias=this.w.get(prefix+'.bias').dense;
|
| 147 |
+
const out=new Float32Array(x.length);
|
| 148 |
+
for(let offset=0;offset<x.length;offset+=w) {
|
| 149 |
+
let mean=0; for(let j=0;j<w;j++) mean+=x[offset+j]; mean/=w;
|
| 150 |
+
let variance=0; for(let j=0;j<w;j++) variance+=(x[offset+j]-mean)**2; variance/=w;
|
| 151 |
+
const scale=1/Math.sqrt(variance+this.config.norm_epsilon);
|
| 152 |
+
for(let j=0;j<w;j++) out[offset+j]=(x[offset+j]-mean)*scale*gain[j]+bias[j];
|
| 153 |
+
}
|
| 154 |
+
return out;
|
| 155 |
+
}
|
| 156 |
+
linear(x,prefix) {
|
| 157 |
+
const a=this.w.get(prefix+'.weight'), bias=this.w.get(prefix+'.bias').dense;
|
| 158 |
+
const [rows,cols]=a.shape, count=x.length/cols, out=new Float32Array(count*rows);
|
| 159 |
+
for(let t=0;t<count;t++) {
|
| 160 |
+
const xo=t*cols, yo=t*rows;
|
| 161 |
+
out.set(bias,yo);
|
| 162 |
+
for(const row of a.active) {
|
| 163 |
+
let sum=0;
|
| 164 |
+
for(let k=a.rowPtr[row];k<a.rowPtr[row+1];k++) sum+=x[xo+a.col[k]]*a.values[k];
|
| 165 |
+
out[yo+row]=sum+bias[row];
|
| 166 |
+
}
|
| 167 |
+
}
|
| 168 |
+
return out;
|
| 169 |
+
}
|
| 170 |
+
forward(ids,cache=null,progress=()=>{}) {
|
| 171 |
+
const c=this.config,w=this.width,n=ids.length,offset=cache?cache[0].length:0,total=offset+n;
|
| 172 |
+
if(total>c.context_length) throw new Error('Context is full; start a new conversation.');
|
| 173 |
+
let h=new Float32Array(n*w);
|
| 174 |
+
for(let t=0;t<n;t++) { this.w.get('token_embedding').addRow(ids[t],h,t*w); this.w.get('position_embedding').addRow(offset+t,h,t*w); }
|
| 175 |
+
const newCache=[];
|
| 176 |
+
for(let layer=0;layer<c.layers;layer++) {
|
| 177 |
+
const p=`blocks.${layer}`,qkv=this.linear(this.norm(h,p+'.ln1'),p+'.attn.qkv');
|
| 178 |
+
const keys=new Float32Array(total*w),values=new Float32Array(total*w);
|
| 179 |
+
if(cache) { keys.set(cache[layer].k); values.set(cache[layer].v); }
|
| 180 |
+
for(let t=0;t<n;t++) { keys.set(qkv.subarray(t*3*w+w,t*3*w+2*w),(offset+t)*w); values.set(qkv.subarray(t*3*w+2*w,t*3*w+3*w),(offset+t)*w); }
|
| 181 |
+
newCache.push({k:keys,v:values,length:total});
|
| 182 |
+
const attention=new Float32Array(n*w),scale=1/Math.sqrt(w/c.heads),scores=new Float32Array(total);
|
| 183 |
+
for(let t=0;t<n;t++) {
|
| 184 |
+
const upto=offset+t+1,qo=t*3*w;
|
| 185 |
+
for(const head of this.attentionDims[layer]) {
|
| 186 |
+
let max=-Infinity;
|
| 187 |
+
for(let j=0;j<upto;j++) {
|
| 188 |
+
let dot=0; for(const d of head.dot) dot+=qkv[qo+d]*keys[j*w+d];
|
| 189 |
+
scores[j]=dot*scale; if(scores[j]>max) max=scores[j];
|
| 190 |
+
}
|
| 191 |
+
let sum=0; for(let j=0;j<upto;j++) { scores[j]=Math.exp(scores[j]-max); sum+=scores[j]; }
|
| 192 |
+
for(let j=0;j<upto;j++) scores[j]/=sum;
|
| 193 |
+
for(const d of head.values) { let value=0; for(let j=0;j<upto;j++) value+=scores[j]*values[j*w+d]; attention[t*w+d]=value; }
|
| 194 |
+
}
|
| 195 |
+
}
|
| 196 |
+
const residual=this.linear(attention,p+'.attn.out');
|
| 197 |
+
for(let i=0;i<h.length;i++) h[i]+=residual[i];
|
| 198 |
+
const up=this.linear(this.norm(h,p+'.ln2'),p+'.mlp.up');
|
| 199 |
+
for(let i=0;i<up.length;i++) up[i]=Math.max(0,up[i]);
|
| 200 |
+
const down=this.linear(up,p+'.mlp.down');
|
| 201 |
+
for(let i=0;i<h.length;i++) h[i]+=down[i];
|
| 202 |
+
progress(layer+1,c.layers);
|
| 203 |
+
}
|
| 204 |
+
const logits=this.linear(this.norm(h.subarray((n-1)*w),'final_norm'),'lm_head');
|
| 205 |
+
for(const value of logits) if(!Number.isFinite(value)) throw new Error('Nonfinite token logits');
|
| 206 |
+
return {logits,cache:newCache};
|
| 207 |
+
}
|
| 208 |
+
generate(prompt,maxNewTokens=64,progress=()=>{}) {
|
| 209 |
+
const started=performance.now(),c=this.config;
|
| 210 |
+
const previous={pointers:new Map(this.tokenizer.pointers),reverse:new Map(this.tokenizer.reverse),used:[...this.tokenizer.used]};
|
| 211 |
+
let prefix;
|
| 212 |
+
try {
|
| 213 |
+
prefix=[...this.history,c.special.user,...this.tokenizer.encode(prompt),c.special.assistant];
|
| 214 |
+
if(prefix.length+maxNewTokens>(this.contextLimit??c.context_length)) throw new Error('Insufficient context space; start a new conversation.');
|
| 215 |
+
} catch(error) { Object.assign(this.tokenizer,previous);throw error; }
|
| 216 |
+
let state=this.forward(prefix,null,(layer,total)=>progress({phase:'prefill',layer,total,prefix_tokens:prefix.length}));
|
| 217 |
+
const output=[]; let stopped=false;
|
| 218 |
+
for(let step=0;step<maxNewTokens;step++) {
|
| 219 |
+
let token=0;
|
| 220 |
+
for(let j=1;j<state.logits.length;j++) if(state.logits[j]>state.logits[token]) token=j;
|
| 221 |
+
output.push(token); progress({phase:'generate',tokens:output.length});
|
| 222 |
+
if(token===c.special.eos) { stopped=true; break; }
|
| 223 |
+
state=this.forward([token],state.cache);
|
| 224 |
+
}
|
| 225 |
+
this.history=prefix.concat(output);
|
| 226 |
+
return {prompt,text:this.tokenizer.decode(output),token_ids:output,stopped_on_eos:stopped,
|
| 227 |
+
generated_tokens:output.length,seconds:(performance.now()-started)/1000,device:'browser-cpu',prefix_tokens:prefix.length};
|
| 228 |
+
}
|
| 229 |
+
}
|
weights.sparse.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4739a3511f5c4b9170f5d09524bd8105f5853a7999cbeefdea7a8cbae01d737d
|
| 3 |
+
size 1528592
|
worker.mjs
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import {Model} from './runtime.mjs';
|
| 2 |
+
let model;
|
| 3 |
+
async function load(path) {
|
| 4 |
+
const response=await fetch(new URL(path,import.meta.url));
|
| 5 |
+
if(!response.ok) throw new Error(`Could not download ${path} (${response.status})`);
|
| 6 |
+
return new Uint8Array(await response.arrayBuffer());
|
| 7 |
+
}
|
| 8 |
+
self.onmessage=async ({data})=>{
|
| 9 |
+
try {
|
| 10 |
+
if(data.action==='load') {
|
| 11 |
+
const [config,weights]=await Promise.all([load('config.json'),load('weights.sparse.zip')]);
|
| 12 |
+
model=await Model.fromBytes(config,weights);
|
| 13 |
+
model.contextLimit=1024;
|
| 14 |
+
self.postMessage({type:'ready',context:model.contextLimit});
|
| 15 |
+
} else if(data.action==='reset') {
|
| 16 |
+
model.reset(); self.postMessage({type:'reset'});
|
| 17 |
+
} else if(data.action==='generate') {
|
| 18 |
+
if(!model) throw new Error('The model is still loading.');
|
| 19 |
+
if(typeof data.prompt!=='string'||!data.prompt.trim()||data.prompt.length>20000) throw new Error('Enter a message of up to 20,000 characters.');
|
| 20 |
+
const result=model.generate(data.prompt,64,progress=>self.postMessage({type:'progress',...progress}));
|
| 21 |
+
self.postMessage({type:'result',result});
|
| 22 |
+
}
|
| 23 |
+
} catch(error) { self.postMessage({type:'error',message:error.message}); }
|
| 24 |
+
};
|