multimodalart HF Staff commited on
Commit
b49802f
·
verified ·
1 Parent(s): 53c9369

Upload q4-ort-metal.html with huggingface_hub

Browse files
Files changed (1) hide show
  1. q4-ort-metal.html +1365 -0
q4-ort-metal.html ADDED
@@ -0,0 +1,1365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8"/>
5
+ <meta name="viewport" content="width=device-width, initial-scale=1"/>
6
+ <title>Magenta RT · Live (custom WGSL temporal + custom WGSL depth)</title>
7
+ <style>
8
+ :root{ --bg:#fffdf3; --ink:#1c1917; --mut:#78716c; --amber:#f59e0b; --amber2:#fbbf24; --lime:#84cc16; --line:#e7e1c8; --card:#fffef9; }
9
+ *{ box-sizing:border-box; } body{ margin:0; font-family:"Segoe UI",-apple-system,sans-serif; color:var(--ink);
10
+ background:radial-gradient(900px 480px at 80% -5%, #fef3c7, var(--bg) 55%); min-height:100vh; }
11
+ .wrap{ max-width:680px; margin:0 auto; padding:30px 20px 60px; }
12
+ h1{ font-size:23px; margin:0 0 2px; font-weight:800; letter-spacing:-.4px; }
13
+ h1 .em{ background:linear-gradient(90deg,var(--amber),var(--lime)); -webkit-background-clip:text; background-clip:text; color:transparent; }
14
+ .sub{ color:var(--mut); font-size:13px; margin-bottom:22px; }
15
+ .card{ background:var(--card); border:1px solid var(--line); border-radius:16px; padding:18px; margin-bottom:14px; }
16
+ label{ font-size:12px; color:var(--mut); text-transform:uppercase; letter-spacing:.5px; display:block; margin-bottom:8px; }
17
+ .row{ display:flex; gap:18px; flex-wrap:wrap; align-items:flex-end; }
18
+ select,button.go{ font-family:inherit; font-weight:700; }
19
+ select{ padding:10px 12px; border-radius:10px; border:1.5px solid var(--line); background:#fff; font-size:15px; color:var(--ink); }
20
+ button.go{ padding:12px 26px; border:none; border-radius:999px; font-size:15px; color:#3a2c05;
21
+ background:linear-gradient(135deg,var(--amber2),var(--amber)); box-shadow:0 4px 14px #f59e0b55; cursor:pointer; }
22
+ button.go:disabled{ opacity:.5; cursor:default; }
23
+ .stat{ font-size:13px; color:var(--mut); margin-top:10px; min-height:18px; }
24
+ .brk{ font-size:12px; color:var(--mut); margin-top:4px; min-height:16px; font-variant-numeric:tabular-nums; }
25
+ canvas{ width:100%; height:70px; display:block; border-radius:10px; background:#fffdf3; margin-top:10px; border:1px solid var(--line); }
26
+ #prog{ display:none; height:10px; background:#fef9e7; border:1px solid var(--line); border-radius:999px; overflow:hidden; margin-top:10px; }
27
+ #bar{ height:100%; width:0%; border-radius:999px; background:linear-gradient(90deg,var(--amber),var(--lime)); transition:width .15s; }
28
+ code{ background:#fef9e7; padding:1px 6px; border-radius:6px; font-size:12px; }
29
+ .badge{ font-size:11px; padding:2px 8px; border-radius:999px; background:#f7fee7; color:#3f6212; border:1px solid #d9f99d; }
30
+ </style>
31
+ </head>
32
+ <body>
33
+ <div class="wrap">
34
+ <h1>🍋 Magenta RT · <span class="em">full custom WGSL on your GPU</span></h1>
35
+ <div class="sub">ORT encoder → <b>custom WGSL temporal</b> → <b>custom WGSL depth</b> (all GPU-resident, shared ORT device) → ORT streaming decoder. Both transformers run as hand-written WebGPU kernels.</div>
36
+
37
+ <div class="card">
38
+ <label>Style</label>
39
+ <div class="row">
40
+ <select id="prompt"></select>
41
+ <button class="go" id="load">Load model</button>
42
+ <button class="go" id="play" disabled>▶ Play</button>
43
+ <button class="go" id="stop" disabled style="background:#2a2e45;color:#fff">■ Stop</button>
44
+ <span class="badge" id="rt"></span>
45
+ </div>
46
+ <div class="stat" id="stat">Press <b>Load model</b> (downloads encoder + decoder + 157 MB q4 WGSL temporal + 66 MB q4 WGSL depth weights, cached after first run).</div>
47
+ <div class="brk" id="brk"></div>
48
+ <div id="prog"><div id="bar"></div></div>
49
+ <canvas id="viz" width="640" height="70"></canvas>
50
+ </div>
51
+ </div>
52
+
53
+ <script type="module">
54
+ import * as ort from "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.23.0/dist/ort.webgpu.min.mjs";
55
+ ort.env.wasm.numThreads = navigator.hardwareConcurrency ? Math.min(4, navigator.hardwareConcurrency) : 2;
56
+ ort.env.webgpu.powerPreference = "high-performance";
57
+
58
+ const $ = id => document.getElementById(id);
59
+ // fixed config: WebGPU. Temporal AND depth are custom WGSL kernels on ORT's device.
60
+ const sz = "small", dev = "webgpu";
61
+ const REPO = `https://huggingface.co/magenta-torch/magenta-rt-onnx-${sz}/resolve/main`;
62
+ const COMMUNITY = "https://huggingface.co/magenta-community/magenta-rt-onnx-small/resolve/main";
63
+ const DEC_URL = COMMUNITY + "/spectrostream_stream.onnx"; // stateful streaming decoder
64
+ const DEC_STATE_URL = COMMUNITY + "/stream_state.json";
65
+ const DEPTH_BASE = COMMUNITY + "/depth_wgsl/"; // depth_q4_ort.bin + depth_q4_ort_layout.json (q4)
66
+ const TEMP_BASE = COMMUNITY + "/temporal_wgsl/"; // temporal_q4_ort.bin + temporal_q4_ort_layout.json (q4)
67
+ let cfg=null, S={}, EMB=null, QUANT=null, presets={};
68
+ let DSJ=null, DSTATE=null, HIFLUSH=undefined;
69
+ let DEPTH=null; // custom WGSL depth engine (built on ort.env.webgpu.device)
70
+ let TEMPORAL=null;// custom WGSL temporal engine (same device)
71
+
72
+ function setBar(f){ $("bar").style.width=Math.min(100,Math.max(0,f*100)).toFixed(1)+"%"; }
73
+
74
+ // ── fp16 -> f32 (for EMB/QUANT bin tables) ──
75
+ function f16(u){ const s=(u&0x8000)>>15,e=(u&0x7c00)>>10,f=u&0x03ff;
76
+ if(e===0) return (s?-1:1)*Math.pow(2,-14)*(f/1024);
77
+ if(e===31) return f?NaN:(s?-1:1)*Infinity;
78
+ return (s?-1:1)*Math.pow(2,e-15)*(1+f/1024); }
79
+ function f16decode(b){ const u=new Uint16Array(b.buffer,b.byteOffset,b.byteLength>>1), o=new Float32Array(u.length); for(let i=0;i<u.length;i++)o[i]=f16(u[i]); return o; }
80
+
81
+ // ── cached fetch (Cache API) with streaming progress ──
82
+ async function fetchBuf(url, onFrac){
83
+ let cache=null;
84
+ try{ cache=await caches.open("mrt-fullcustom-q4-v1"); const hit=await cache.match(url);
85
+ if(hit){ onFrac&&onFrac(1); return new Uint8Array(await hit.arrayBuffer()); } }catch(e){}
86
+ const r=await fetch(url); if(!r.ok) throw new Error(r.status+" "+url.split("/").pop());
87
+ const total=+r.headers.get("content-length")||0, reader=r.body.getReader(), chunks=[]; let recv=0;
88
+ for(;;){ const {done,value}=await reader.read(); if(done)break; chunks.push(value); recv+=value.length; if(total&&onFrac)onFrac(recv/total); }
89
+ const buf=new Uint8Array(recv); let o=0; for(const c of chunks){buf.set(c,o);o+=c.length;}
90
+ if(cache){ try{ await cache.put(url, new Response(buf)); }catch(e){} }
91
+ return buf;
92
+ }
93
+ async function fetchJSON(url){ const r=await fetch(url); if(!r.ok) throw new Error(r.status+" "+url); return r.json(); }
94
+
95
+ /* ====================================================================== *
96
+ * CUSTOM WGSL TEMPORAL (ported verbatim from temporal_q4_gpu.ts — q4)
97
+ * 12 layers: self-attn (1 sink) -> cross-attn (1 sink) -> FFN. Big matmul
98
+ * matrices are q4 block-quantized along K (block_size=32, zero=8): packed
99
+ * nibbles in u32 (8/word, k-contiguous), per-block fp32 scales; the matvec
100
+ * unpacks (nibble-8)*scale with u32 shift/mask ONLY (NO unpack2x16float ->
101
+ * avoids the Metal compile hang). PACKED split P0|P1 (<120MB each), SCALES,
102
+ * and a small fp32 SMALL blob (embedding/norms/biases/sink/per_dim_scale).
103
+ * Self/cross KV are GPU buffers persisted across frames, slot-appended, grown
104
+ * to cap KV_CAP and reset on Play/restart. Built on the SAME GPUDevice ORT
105
+ * uses so the temporal `out` GPUBuffer feeds the WGSL depth with zero copy.
106
+ * ONE step = embed(prev[12]) -> 12 layers -> out[1024] (raw, no final norm).
107
+ * ====================================================================== */
108
+ const T_D_MODEL=1024, T_D_SRC=256, T_D_FF=4096, T_NUM_LAYERS=12, T_NUM_HEADS=8,
109
+ T_UPH=128, T_HD=T_NUM_HEADS*T_UPH, T_KV_CAP=42, T_EPS=1e-6, T_R_SOFTPLUS_0=1.442695041;
110
+ const T_BLK=32; // q4 block size
111
+ // bandwidth (q4 matvec) tiling
112
+ const T_RED=32, T_ROWS=8, T_T_WG=T_ROWS*T_RED; // 256
113
+ const tNWGT=N=>Math.ceil(N/T_ROWS);
114
+
115
+ // Build the whole temporal engine on ORT's device. q4 weights (what ships).
116
+ // Returns { runTemporal(prevToks)->outBuf, resetKV(), setSource(), kvLen(), outBuf }.
117
+ async function buildTemporal(device, layout, binBytes){
118
+ let USE_SUBGROUPS=false; // browser: layout:auto + shared-mem tree (subgroup-free)
119
+
120
+ const D_MODEL=T_D_MODEL, D_SRC=T_D_SRC, D_FF=T_D_FF, NUM_LAYERS=T_NUM_LAYERS,
121
+ NUM_HEADS=T_NUM_HEADS, UPH=T_UPH, HD=T_HD, KV_CAP=T_KV_CAP, EPS=T_EPS,
122
+ R_SOFTPLUS_0=T_R_SOFTPLUS_0, RED=T_RED, ROWS=T_ROWS, T_WG=T_T_WG, BLK=T_BLK;
123
+
124
+ const EMBED_SCALE=layout.embed_scale;
125
+ // q4 layout: q4[name]={K,N,packed_off,scale_off,...}; small[name]={offset,...}
126
+ const q4=n=>layout.q4[n];
127
+ const smallOff=n=>layout.small[n].offset;
128
+ const L=(li,blk,t)=>smallOff(`L${li}.${blk}.${t}`);
129
+
130
+ // section byte ranges within temporal_q4_ort.bin
131
+ const PACKED_BYTE_OFF=layout.packed_byte_off, SCALE_BYTE_OFF=layout.scale_byte_off,
132
+ SMALL_BYTE_OFF=layout.small_byte_off;
133
+ const PACKED_WORDS=layout.packed_words, SCALE_FLOATS=layout.scale_floats, SMALL_FLOATS=layout.small_floats;
134
+ // split PACKED across two storage buffers (binding 0/6) — each well under cap.
135
+ const P_SPLIT_WORDS=Math.ceil(PACKED_WORDS/2);
136
+
137
+ // ---------------- WGSL header / weight access ----------------
138
+ const CONSTS=`
139
+ const D_MODEL : u32 = ${D_MODEL}u;
140
+ const D_SRC : u32 = ${D_SRC}u;
141
+ const D_FF : u32 = ${D_FF}u;
142
+ const NUM_HEADS : u32 = ${NUM_HEADS}u;
143
+ const UPH : u32 = ${UPH}u;
144
+ const HD : u32 = ${HD}u;
145
+ const EPS : f32 = ${EPS};
146
+ const R_SOFTPLUS_0 : f32 = ${R_SOFTPLUS_0};
147
+ const RED : u32 = ${RED}u;
148
+ const ROWS : u32 = ${ROWS}u;
149
+ const BLK : u32 = ${BLK}u;
150
+ `;
151
+ // SMALL fp32 params (binding 8), float-indexed via wv().
152
+ const SMALLBUF=`
153
+ @group(0) @binding(8) var<storage, read> SMALL : array<f32>;
154
+ fn wv(i : u32) -> f32 { return SMALL[i]; }
155
+ fn softplus(x: f32) -> f32 {
156
+ return log(1.0 + exp(-abs(x))) + max(x, 0.0);
157
+ }
158
+ fn gelu_tanh(x: f32) -> f32 {
159
+ let c : f32 = 0.7978845608028654;
160
+ // clamp: Metal fast-math tanh overflows to 0/NaN for |arg|>~44.
161
+ // |t|>=12 already rounds tanh(t) to +/-1 in f32, so this is exact.
162
+ let t = clamp(c * (x + 0.044715 * x * x * x), -12.0, 12.0);
163
+ return 0.5 * x * (1.0 + tanh(t));
164
+ }
165
+ `;
166
+ // PACKED q4 nibbles (binding 0/6) + SCALES (binding 7). qword() routes a global
167
+ // u32-word index to the right packed buffer; deq() dequantizes w[col,k].
168
+ const QBUF=`
169
+ @group(0) @binding(0) var<storage, read> P0 : array<u32>;
170
+ @group(0) @binding(6) var<storage, read> P1 : array<u32>;
171
+ @group(0) @binding(7) var<storage, read> SC : array<f32>;
172
+ const P_SPLIT_WORDS : u32 = ${P_SPLIT_WORDS}u;
173
+ fn qword(wi : u32) -> u32 {
174
+ if (wi < P_SPLIT_WORDS) { return P0[wi]; }
175
+ return P1[wi - P_SPLIT_WORDS];
176
+ }
177
+ fn deq(qOff : u32, sOff : u32, K : u32, col : u32, k : u32) -> f32 {
178
+ let word = qword(qOff + col * (K >> 3u) + (k >> 3u));
179
+ let nib = (word >> ((k & 7u) * 4u)) & 0xfu;
180
+ let s = SC[sOff + col * (K >> 5u) + (k >> 5u)];
181
+ return (f32(nib) - 8.0) * s;
182
+ }
183
+ // double-single (df64) compensated summation: emulates fp64-precision reductions
184
+ // in fp32 so the temporal autoregressive loop stays stable indefinitely.
185
+ fn two_sum(a : f32, b : f32) -> vec2<f32> {
186
+ let s = a + b;
187
+ let bb = s - a;
188
+ return vec2<f32>(s, (a - (s - bb)) + (b - bb));
189
+ }
190
+ fn df_add_f32(acc : vec2<f32>, x : f32) -> vec2<f32> {
191
+ let t = two_sum(acc.x, x);
192
+ return vec2<f32>(t.x, acc.y + t.y);
193
+ }
194
+ fn df_add(a : vec2<f32>, b : vec2<f32>) -> vec2<f32> {
195
+ let t = two_sum(a.x, b.x);
196
+ return vec2<f32>(t.x, (a.y + b.y) + t.y);
197
+ }
198
+ `;
199
+ const HEADER=CONSTS+QBUF+SMALLBUF;
200
+
201
+ // ===== qMatmul (q4 bandwidth matvec; replaces gridMatmulT/gridMatmul2) =====
202
+ // out[n] = sum_k inEff[k] * deq(W)[n,k]. lane reads k-contiguous packed u32s.
203
+ // uniform: { qOff, sOff, colBase, normOff, biasOff }.
204
+ function qMatmul(opts){
205
+ const K=opts.K, sg=USE_SUBGROUPS;
206
+ const inDecl=`@group(0) @binding(${opts.inBinding}) var<storage, read> vin : array<f32>;`;
207
+ const outDecl=`@group(0) @binding(${opts.outBinding}) var<storage, read_write> vout : array<f32>;`;
208
+ const uniformDecl=`struct U { qOff:u32, sOff:u32, colBase:u32, normOff:u32, biasOff:u32, };
209
+ @group(0) @binding(5) var<uniform> u : U;`;
210
+ const normReduce=opts.rmsnorm?`
211
+ var lss : f32 = 0.0;
212
+ for (var i : u32 = tid; i < ${K}u; i = i + ${T_WG}u) {
213
+ let xv = vin[i]; lss = lss + xv * xv;
214
+ }
215
+ red[tid] = lss;
216
+ workgroupBarrier();
217
+ for (var s : u32 = ${T_WG/2}u; s > 0u; s = s >> 1u) {
218
+ if (tid < s) { red[tid] = red[tid] + red[tid + s]; }
219
+ workgroupBarrier();
220
+ }
221
+ let rms = 1.0 / sqrt(red[0] / f32(${K}u) + EPS);
222
+ workgroupBarrier();
223
+ for (var i : u32 = tid; i < ${K}u; i = i + ${T_WG}u) {
224
+ inS[i] = (vin[i] * rms) * wv(u.normOff + i);
225
+ }
226
+ workgroupBarrier();`:`
227
+ for (var i : u32 = tid; i < ${K}u; i = i + ${T_WG}u) { inS[i] = vin[i]; }
228
+ workgroupBarrier();`;
229
+ let epi="";
230
+ if(opts.epilogue==="geluBias"){ epi=`acc = gelu_tanh(acc + wv(u.biasOff + col));`; }
231
+ else { epi=opts.hasBias?`acc = acc + wv(u.biasOff + col);`:``; }
232
+ const reduceWrite=sg?`
233
+ let total = subgroupAdd(acc.x) + subgroupAdd(acc.y);
234
+ if (lane == 0u) {
235
+ var accf : f32 = total;
236
+ ${epi.replace(/\bacc\b/g,"accf")}
237
+ vout[outIdx] = accf;
238
+ }`:`
239
+ part[tid] = acc;
240
+ workgroupBarrier();
241
+ for (var s : u32 = ${RED/2}u; s > 0u; s = s >> 1u) {
242
+ if (lane < s) { part[tid] = df_add(part[tid], part[tid + s]); }
243
+ workgroupBarrier();
244
+ }
245
+ if (lane == 0u) {
246
+ var accf : f32 = part[row * RED].x;
247
+ ${epi.replace(/\bacc\b/g,"accf")}
248
+ vout[outIdx] = accf;
249
+ }`;
250
+ const enableSg=sg?"enable subgroups;\n":"";
251
+ return enableSg+HEADER+`
252
+ ${inDecl}
253
+ ${outDecl}
254
+ ${uniformDecl}
255
+
256
+ var<workgroup> inS : array<f32, ${K}>;
257
+ ${opts.rmsnorm?`var<workgroup> red : array<f32, ${T_WG}>;`:``}
258
+ ${sg?"":`var<workgroup> part : array<vec2<f32>, ${T_WG}>;`}
259
+
260
+ @compute @workgroup_size(${T_WG})
261
+ fn main(@builtin(local_invocation_id) lid : vec3<u32>,
262
+ @builtin(workgroup_id) wid : vec3<u32>) {
263
+ let tid = lid.x;
264
+ let row = tid / RED;
265
+ let lane = tid % RED;
266
+ ${normReduce}
267
+ let outIdx = wid.x * ROWS + row;
268
+ let col = u.colBase + outIdx; // global output column (== weight column)
269
+ var acc : vec2<f32> = vec2<f32>(0.0, 0.0); // (hi,lo) double-single accumulator
270
+ for (var k : u32 = lane; k < ${K}u; k = k + RED) {
271
+ let p = inS[k] * deq(u.qOff, u.sOff, ${K}u, col, k);
272
+ acc = df_add_f32(acc, p);
273
+ }
274
+ ${reduceWrite}
275
+ }
276
+ `;
277
+ }
278
+
279
+ // ===== buildKV (combined q4 QKV self / KV cross) =====
280
+ // uniform: { normOff, qQ,qS, kQ,kS, vQ,vS, slot }.
281
+ function buildKV(opts){
282
+ const K=opts.K, sg=USE_SUBGROUPS, enableSg=sg?"enable subgroups;\n":"";
283
+ const qPart=opts.writeQ?`var qa : vec2<f32> = vec2<f32>(0.0, 0.0);`:``;
284
+ const qAccum=opts.writeQ?`qa = df_add_f32(qa, hv * deq(u.qQ, u.qS, ${K}u, oi, k));`:``;
285
+ const reduceWrite=sg?`
286
+ let sk = subgroupAdd(ka.x) + subgroupAdd(ka.y);
287
+ let sv = subgroupAdd(va.x) + subgroupAdd(va.y);
288
+ ${opts.writeQ?"let sq = subgroupAdd(qa.x) + subgroupAdd(qa.y);":""}
289
+ if (lane == 0u) {
290
+ let cbase = u.slot * HD;
291
+ kcache[cbase + oi] = sk;
292
+ vcache[cbase + oi] = sv;
293
+ ${opts.writeQ?"qbuf[oi] = sq;":""}
294
+ }`:`
295
+ pk[tid] = ka; pv[tid] = va;
296
+ ${opts.writeQ?"pq[tid] = qa;":""}
297
+ workgroupBarrier();
298
+ for (var s : u32 = ${RED/2}u; s > 0u; s = s >> 1u) {
299
+ if (lane < s) {
300
+ pk[tid] = df_add(pk[tid], pk[tid + s]);
301
+ pv[tid] = df_add(pv[tid], pv[tid + s]);
302
+ ${opts.writeQ?"pq[tid] = df_add(pq[tid], pq[tid + s]);":""}
303
+ }
304
+ workgroupBarrier();
305
+ }
306
+ if (lane == 0u) {
307
+ let cbase = u.slot * HD;
308
+ kcache[cbase + oi] = pk[row * RED].x;
309
+ vcache[cbase + oi] = pv[row * RED].x;
310
+ ${opts.writeQ?"qbuf[oi] = pq[row * RED].x;":""}
311
+ }`;
312
+ const normReduce=opts.rmsnorm?`
313
+ var lss : f32 = 0.0;
314
+ for (var i : u32 = tid; i < ${K}u; i = i + ${T_WG}u) {
315
+ let xv = vin[i]; lss = lss + xv * xv;
316
+ }
317
+ red[tid] = lss;
318
+ workgroupBarrier();
319
+ for (var s : u32 = ${T_WG/2}u; s > 0u; s = s >> 1u) {
320
+ if (tid < s) { red[tid] = red[tid] + red[tid + s]; }
321
+ workgroupBarrier();
322
+ }
323
+ let rms = 1.0 / sqrt(red[0] / f32(${K}u) + EPS);
324
+ workgroupBarrier();
325
+ for (var i : u32 = tid; i < ${K}u; i = i + ${T_WG}u) {
326
+ inS[i] = (vin[i] * rms) * wv(u.normOff + i);
327
+ }
328
+ workgroupBarrier();`:`
329
+ for (var i : u32 = tid; i < ${K}u; i = i + ${T_WG}u) { inS[i] = vin[i]; }
330
+ workgroupBarrier();`;
331
+ return enableSg+HEADER+`
332
+ @group(0) @binding(1) var<storage, read> vin : array<f32>;
333
+ ${opts.writeQ?`@group(0) @binding(2) var<storage, read_write> qbuf : array<f32>;`:``}
334
+ @group(0) @binding(3) var<storage, read_write> kcache : array<f32>;
335
+ @group(0) @binding(4) var<storage, read_write> vcache : array<f32>;
336
+ struct U {
337
+ normOff:u32,
338
+ qQ:u32, qS:u32,
339
+ kQ:u32, kS:u32,
340
+ vQ:u32, vS:u32,
341
+ slot:u32,
342
+ };
343
+ @group(0) @binding(5) var<uniform> u : U;
344
+
345
+ var<workgroup> inS : array<f32, ${K}>;
346
+ var<workgroup> red : array<f32, ${T_WG}>;
347
+ ${sg?"":`var<workgroup> pk : array<vec2<f32>, ${T_WG}>;
348
+ var<workgroup> pv : array<vec2<f32>, ${T_WG}>;
349
+ ${opts.writeQ?`var<workgroup> pq : array<vec2<f32>, ${T_WG}>;`:``}`}
350
+
351
+ @compute @workgroup_size(${T_WG})
352
+ fn main(@builtin(local_invocation_id) lid : vec3<u32>,
353
+ @builtin(workgroup_id) wid : vec3<u32>) {
354
+ let tid = lid.x;
355
+ let row = tid / RED;
356
+ let lane = tid % RED;
357
+ ${normReduce}
358
+ let oi = wid.x * ROWS + row; // output column in [0,HD)
359
+ var ka : vec2<f32> = vec2<f32>(0.0, 0.0); var va : vec2<f32> = vec2<f32>(0.0, 0.0);
360
+ ${qPart}
361
+ for (var k : u32 = lane; k < ${K}u; k = k + RED) {
362
+ let hv = inS[k];
363
+ ka = df_add_f32(ka, hv * deq(u.kQ, u.kS, ${K}u, oi, k));
364
+ va = df_add_f32(va, hv * deq(u.vQ, u.vS, ${K}u, oi, k));
365
+ ${qAccum}
366
+ }
367
+ ${reduceWrite}
368
+ }
369
+ `;
370
+ }
371
+ const buildQonly=()=>qMatmul({K:D_MODEL,inBinding:1,outBinding:2,rmsnorm:true,epilogue:"none",hasBias:false});
372
+
373
+ // ===== attention core (1 sink + per-dim scale) =====
374
+ const ATTN_SINK_WGSL=HEADER+`
375
+ @group(0) @binding(1) var<storage, read> qbuf : array<f32>; // [HD]
376
+ @group(0) @binding(2) var<storage, read> kcache : array<f32>; // [cap,HD]
377
+ @group(0) @binding(3) var<storage, read> vcache : array<f32>; // [cap,HD]
378
+ @group(0) @binding(4) var<storage, read_write> ctxbuf : array<f32>; // [HD]
379
+ struct U { per_dim_scale:u32, sink_k:u32, sink_v:u32, cacheLen:u32, start:u32, };
380
+ @group(0) @binding(5) var<uniform> u : U;
381
+
382
+ var<workgroup> logitsW : array<f32, ${KV_CAP + 1}>;
383
+ var<workgroup> red : array<f32, 256>;
384
+ var<workgroup> mden : array<f32, 2>;
385
+
386
+ @compute @workgroup_size(256)
387
+ fn main(@builtin(local_invocation_id) lid : vec3<u32>) {
388
+ let t = lid.x;
389
+ let T = u.cacheLen; // number of real keys
390
+ let nkeys = T + 1u; // + sink
391
+ let qscale = R_SOFTPLUS_0 * (1.0 / sqrt(f32(UPH)));
392
+
393
+ for (var h : u32 = 0u; h < NUM_HEADS; h = h + 1u) {
394
+ let qbase = h * UPH;
395
+ for (var ki : u32 = t; ki < nkeys; ki = ki + 256u) {
396
+ var acc : vec2<f32> = vec2<f32>(0.0, 0.0); // (hi,lo) double-single
397
+ if (ki == 0u) {
398
+ let sbase = u.sink_k + qbase;
399
+ for (var d : u32 = 0u; d < UPH; d = d + 1u) {
400
+ acc = df_add_f32(acc, qbuf[qbase + d] * wv(sbase + d));
401
+ }
402
+ } else {
403
+ let kk = ki - 1u;
404
+ // read KV in temporal order (oldest->newest): physical ring slot.
405
+ let phys = (u.start + kk) % ${KV_CAP}u;
406
+ let kbase = phys * HD + qbase;
407
+ for (var d : u32 = 0u; d < UPH; d = d + 1u) {
408
+ let sc = qscale * softplus(wv(u.per_dim_scale + d));
409
+ acc = df_add_f32(acc, (qbuf[qbase + d] * sc) * kcache[kbase + d]);
410
+ }
411
+ }
412
+ logitsW[ki] = acc.x;
413
+ }
414
+ workgroupBarrier();
415
+ if (t == 0u) {
416
+ var m : f32 = logitsW[0];
417
+ for (var ki : u32 = 1u; ki < nkeys; ki = ki + 1u) { m = max(m, logitsW[ki]); }
418
+ var s : f32 = 0.0;
419
+ for (var ki : u32 = 0u; ki < nkeys; ki = ki + 1u) {
420
+ let e = exp(logitsW[ki] - m);
421
+ logitsW[ki] = e; s = s + e;
422
+ }
423
+ mden[0] = s;
424
+ }
425
+ workgroupBarrier();
426
+ let denom = mden[0];
427
+ for (var d : u32 = t; d < UPH; d = d + 256u) {
428
+ // ctx = sum_keys w * V, accumulated in double-single (hi,lo).
429
+ var acc : vec2<f32> = vec2<f32>((logitsW[0] / denom) * wv(u.sink_v + qbase + d), 0.0);
430
+ for (var kk : u32 = 0u; kk < T; kk = kk + 1u) {
431
+ let w = logitsW[kk + 1u] / denom;
432
+ // read V in temporal order (oldest->newest): physical ring slot.
433
+ let phys = (u.start + kk) % ${KV_CAP}u;
434
+ acc = df_add_f32(acc, w * vcache[phys * HD + qbase + d]);
435
+ }
436
+ ctxbuf[qbase + d] = acc.x;
437
+ }
438
+ workgroupBarrier();
439
+ }
440
+ }
441
+ `;
442
+
443
+ // ===== RESID =====
444
+ const RESID_WGSL=HEADER+`
445
+ @group(0) @binding(1) var<storage, read_write> x : array<f32>;
446
+ @group(0) @binding(2) var<storage, read> y : array<f32>;
447
+ struct U { post:u32, };
448
+ @group(0) @binding(5) var<uniform> u : U;
449
+
450
+ var<workgroup> red : array<f32, 256>;
451
+ @compute @workgroup_size(256)
452
+ fn main(@builtin(local_invocation_id) lid : vec3<u32>) {
453
+ let t = lid.x;
454
+ var ss : f32 = 0.0;
455
+ for (var i : u32 = t; i < D_MODEL; i = i + 256u) { let v = y[i]; ss = ss + v*v; }
456
+ red[t] = ss;
457
+ workgroupBarrier();
458
+ for (var s : u32 = 128u; s > 0u; s = s >> 1u) {
459
+ if (t < s) { red[t] = red[t] + red[t + s]; }
460
+ workgroupBarrier();
461
+ }
462
+ let rms = 1.0 / sqrt(red[0] / f32(D_MODEL) + EPS);
463
+ workgroupBarrier();
464
+ for (var i : u32 = t; i < D_MODEL; i = i + 256u) {
465
+ x[i] = x[i] + (y[i] * rms) * wv(u.post + i);
466
+ }
467
+ }
468
+ `;
469
+
470
+ // ===== EMBED prev =====
471
+ const EMBED_WGSL=HEADER+`
472
+ @group(0) @binding(1) var<storage, read> prevBuf : array<u32>; // [12]
473
+ @group(0) @binding(2) var<storage, read_write> xout : array<f32>; // [1024]
474
+ struct EU { embeddingOff:u32, embed_scale:f32, };
475
+ @group(0) @binding(5) var<uniform> u : EU;
476
+
477
+ @compute @workgroup_size(256)
478
+ fn main(@builtin(local_invocation_id) lid : vec3<u32>) {
479
+ let i = lid.x;
480
+ for (var di : u32 = i; di < D_MODEL; di = di + 256u) {
481
+ var acc : f32 = 0.0;
482
+ for (var c : u32 = 0u; c < 12u; c = c + 1u) {
483
+ let tok = prevBuf[c];
484
+ acc = acc + wv(u.embeddingOff + tok * D_MODEL + di);
485
+ }
486
+ xout[di] = (acc / 12.0) * u.embed_scale;
487
+ }
488
+ }
489
+ `;
490
+
491
+ // ---------------- q4 weight storage buffers (PACKED P0|P1, SCALES, SMALL) ----
492
+ const P0_BYTES=P_SPLIT_WORDS*4, P1_BYTES=PACKED_WORDS*4-P0_BYTES;
493
+ const p0Buf=device.createBuffer({ size:Math.max(4,P0_BYTES), usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST });
494
+ const p1Buf=device.createBuffer({ size:Math.max(4,P1_BYTES), usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST });
495
+ device.queue.writeBuffer(p0Buf,0,binBytes,PACKED_BYTE_OFF,P0_BYTES);
496
+ device.queue.writeBuffer(p1Buf,0,binBytes,PACKED_BYTE_OFF+P0_BYTES,P1_BYTES);
497
+ const scBuf=device.createBuffer({ size:Math.max(4,SCALE_FLOATS*4), usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST });
498
+ device.queue.writeBuffer(scBuf,0,binBytes,SCALE_BYTE_OFF,SCALE_FLOATS*4);
499
+ const smBuf=device.createBuffer({ size:Math.max(4,SMALL_FLOATS*4), usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST });
500
+ device.queue.writeBuffer(smBuf,0,binBytes,SMALL_BYTE_OFF,SMALL_FLOATS*4);
501
+ console.log(`temporal q4: PACKED ${(PACKED_WORDS*4/1048576).toFixed(1)}MB (P0 ${(P0_BYTES/1048576).toFixed(1)} / P1 ${(P1_BYTES/1048576).toFixed(1)}), SCALES ${(SCALE_FLOATS*4/1048576).toFixed(1)}MB, SMALL ${(SMALL_FLOATS*4/1048576).toFixed(1)}MB`);
502
+
503
+ // ---------------- activation buffers (GPU-resident) ----------------
504
+ const makeStorage=(floats,extra=0)=>device.createBuffer({
505
+ size:Math.max(4,floats*4),
506
+ usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC|extra });
507
+ const xBuf=makeStorage(D_MODEL); // residual stream x[1024] == temporal `out`
508
+ const srcBuf=makeStorage(D_SRC); // source[256] (uploaded per style)
509
+ const qBuf=makeStorage(HD);
510
+ const ctxBuf=makeStorage(HD);
511
+ const blkOutBuf=makeStorage(D_MODEL);
512
+ const ffBuf=makeStorage(D_FF);
513
+ // KV caches: per layer, capacity KV_CAP+1 rows of HD.
514
+ const selfK=[],selfV=[],crossK=[],crossV=[];
515
+ for(let li=0;li<NUM_LAYERS;li++){
516
+ selfK.push(makeStorage((KV_CAP+1)*HD));
517
+ selfV.push(makeStorage((KV_CAP+1)*HD));
518
+ crossK.push(makeStorage((KV_CAP+1)*HD));
519
+ crossV.push(makeStorage((KV_CAP+1)*HD));
520
+ }
521
+ const prevBuf=device.createBuffer({ size:12*4, usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST });
522
+ // debug-only: map-read copy of the temporal out (xBuf). Headless verification.
523
+ const dbgOutBuf=device.createBuffer({ size:D_MODEL*4, usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST });
524
+
525
+ const makeUniform=bytes=>device.createBuffer({ size:bytes, usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST });
526
+ const pipeline=code=>{ const m=device.createShaderModule({code}); return device.createComputePipeline({ layout:"auto", compute:{module:m,entryPoint:"main"} }); };
527
+
528
+ // ---------------- pipelines ----------------
529
+ const pEmbed=pipeline(EMBED_WGSL);
530
+ const pSelfKV=pipeline(buildKV({K:D_MODEL,writeQ:true,rmsnorm:true}));
531
+ const pCrossQ=pipeline(buildQonly());
532
+ const pCrossKV=pipeline(buildKV({K:D_SRC,writeQ:false,rmsnorm:false}));
533
+ const pAttn=pipeline(ATTN_SINK_WGSL);
534
+ const pWo=pipeline(qMatmul({K:HD,inBinding:1,outBinding:2,rmsnorm:false,epilogue:"none",hasBias:false}));
535
+ const pResid=pipeline(RESID_WGSL);
536
+ const pWi=pipeline(qMatmul({K:D_MODEL,inBinding:1,outBinding:2,rmsnorm:true,epilogue:"geluBias",hasBias:true}));
537
+ const pWoFfn=pipeline(qMatmul({K:D_FF,inBinding:1,outBinding:2,rmsnorm:false,epilogue:"none",hasBias:true}));
538
+
539
+ // ---------------- uniform buffers (per layer) ----------------
540
+ // qMatmul U { qOff,sOff,colBase,normOff,biasOff } = 20 -> pad 32.
541
+ const uEmbed=makeUniform(16);
542
+ const uSelfKV=[],uCrossQ=[],uCrossKV=[],uAttnSelf=[],uAttnCross=[],uWoSelf=[],uWoCross=[],
543
+ uResidSAttn=[],uResidCAttn=[],uResidFfn=[],uWi=[],uWoFfn=[];
544
+ for(let li=0;li<NUM_LAYERS;li++){
545
+ uSelfKV.push(makeUniform(32)); uCrossQ.push(makeUniform(32)); uCrossKV.push(makeUniform(32));
546
+ uAttnSelf.push(makeUniform(32)); uAttnCross.push(makeUniform(32)); // {per_dim_scale,sink_k,sink_v,cacheLen,start} (5 u32 -> pad 32)
547
+ uWoSelf.push(makeUniform(32)); uWoCross.push(makeUniform(32));
548
+ uResidSAttn.push(makeUniform(16)); uResidCAttn.push(makeUniform(16)); uResidFfn.push(makeUniform(16));
549
+ uWi.push(makeUniform(32)); uWoFfn.push(makeUniform(32));
550
+ }
551
+ // helper to fill a 5-u32 qMatmul uniform { qOff, sOff, colBase, normOff, biasOff }
552
+ function fillMM(buf,qOff,sOff,colBase,normOff,biasOff){
553
+ const a=new Uint32Array(8); a[0]=qOff; a[1]=sOff; a[2]=colBase; a[3]=normOff; a[4]=biasOff;
554
+ device.queue.writeBuffer(buf,0,a);
555
+ }
556
+ // embed uniform
557
+ { const e=new ArrayBuffer(16); new Uint32Array(e,0,1)[0]=smallOff("embedding"); new Float32Array(e,4,1)[0]=EMBED_SCALE;
558
+ device.queue.writeBuffer(uEmbed,0,e); }
559
+ // per-layer static uniforms (slot/cacheLen filled per frame)
560
+ for(let li=0;li<NUM_LAYERS;li++){
561
+ const saWq=q4(`L${li}.sa.Wq`), saWk=q4(`L${li}.sa.Wk`), saWv=q4(`L${li}.sa.Wv`);
562
+ const caWk=q4(`L${li}.ca.Wk`), caWv=q4(`L${li}.ca.Wv`);
563
+ // self KV: {normOff=sa.pre_norm, qQ,qS, kQ,kS, vQ,vS, slot}
564
+ { const a=new Uint32Array(8); a[0]=L(li,"sa","pre_norm");
565
+ a[1]=saWq.packed_off; a[2]=saWq.scale_off; a[3]=saWk.packed_off; a[4]=saWk.scale_off;
566
+ a[5]=saWv.packed_off; a[6]=saWv.scale_off; device.queue.writeBuffer(uSelfKV[li],0,a); } // slot @ word 7 per frame
567
+ // cross Q (qMatmul): {qOff=ca.Wq, sOff, colBase=0, normOff=ca.pre_norm, bias=0}
568
+ { const caWq=q4(`L${li}.ca.Wq`); fillMM(uCrossQ[li], caWq.packed_off, caWq.scale_off, 0, L(li,"ca","pre_norm"), 0); }
569
+ // cross KV: {normOff(unused), q*(unused), kQ,kS, vQ,vS, slot}
570
+ { const a=new Uint32Array(8); a[0]=0; a[1]=0; a[2]=0;
571
+ a[3]=caWk.packed_off; a[4]=caWk.scale_off; a[5]=caWv.packed_off; a[6]=caWv.scale_off;
572
+ device.queue.writeBuffer(uCrossKV[li],0,a); } // slot @ word 7 per frame
573
+ { const a=new Uint32Array(4); a[0]=L(li,"sa","per_dim_scale"); a[1]=L(li,"sa","sink_k"); a[2]=L(li,"sa","sink_v");
574
+ device.queue.writeBuffer(uAttnSelf[li],0,a); }
575
+ { const a=new Uint32Array(4); a[0]=L(li,"ca","per_dim_scale"); a[1]=L(li,"ca","sink_k"); a[2]=L(li,"ca","sink_v");
576
+ device.queue.writeBuffer(uAttnCross[li],0,a); }
577
+ { const saWo=q4(`L${li}.sa.Wo`); fillMM(uWoSelf[li], saWo.packed_off, saWo.scale_off, 0, 0, 0); }
578
+ { const caWo=q4(`L${li}.ca.Wo`); fillMM(uWoCross[li], caWo.packed_off, caWo.scale_off, 0, 0, 0); }
579
+ { const a=new Uint32Array(4); a[0]=L(li,"sa","post_norm"); device.queue.writeBuffer(uResidSAttn[li],0,a); }
580
+ { const a=new Uint32Array(4); a[0]=L(li,"ca","post_norm"); device.queue.writeBuffer(uResidCAttn[li],0,a); }
581
+ { const a=new Uint32Array(4); a[0]=L(li,"ffn","post_norm"); device.queue.writeBuffer(uResidFfn[li],0,a); }
582
+ { const wi=q4(`L${li}.ffn.wi`); fillMM(uWi[li], wi.packed_off, wi.scale_off, 0, L(li,"ffn","pre_norm"), L(li,"ffn","bi")); }
583
+ { const wo=q4(`L${li}.ffn.wo`); fillMM(uWoFfn[li], wo.packed_off, wo.scale_off, 0, 0, L(li,"ffn","bo")); }
584
+ }
585
+
586
+ // ---------------- bind groups ----------------
587
+ // q4 binding scheme: P0@0, P1@6, SC@7, SMALL@8, in@1, out@2, uniform@5.
588
+ const bgEmbed=device.createBindGroup({ layout:pEmbed.getBindGroupLayout(0), entries:[
589
+ {binding:8,resource:{buffer:smBuf}},
590
+ {binding:1,resource:{buffer:prevBuf}},{binding:2,resource:{buffer:xBuf}},{binding:5,resource:{buffer:uEmbed}}] });
591
+ const bgSelfKV=Array.from({length:NUM_LAYERS},(_,li)=>device.createBindGroup({ layout:pSelfKV.getBindGroupLayout(0), entries:[
592
+ {binding:0,resource:{buffer:p0Buf}},{binding:6,resource:{buffer:p1Buf}},{binding:7,resource:{buffer:scBuf}},{binding:8,resource:{buffer:smBuf}},
593
+ {binding:1,resource:{buffer:xBuf}},{binding:2,resource:{buffer:qBuf}},
594
+ {binding:3,resource:{buffer:selfK[li]}},{binding:4,resource:{buffer:selfV[li]}},{binding:5,resource:{buffer:uSelfKV[li]}}] }));
595
+ const bgCrossQ=Array.from({length:NUM_LAYERS},(_,li)=>device.createBindGroup({ layout:pCrossQ.getBindGroupLayout(0), entries:[
596
+ {binding:0,resource:{buffer:p0Buf}},{binding:6,resource:{buffer:p1Buf}},{binding:7,resource:{buffer:scBuf}},{binding:8,resource:{buffer:smBuf}},
597
+ {binding:1,resource:{buffer:xBuf}},{binding:2,resource:{buffer:qBuf}},{binding:5,resource:{buffer:uCrossQ[li]}}] }));
598
+ const bgCrossKV=Array.from({length:NUM_LAYERS},(_,li)=>device.createBindGroup({ layout:pCrossKV.getBindGroupLayout(0), entries:[
599
+ // pCrossKV (rmsnorm=false) never calls wv() -> SMALL@8 pruned by layout:auto.
600
+ {binding:0,resource:{buffer:p0Buf}},{binding:6,resource:{buffer:p1Buf}},{binding:7,resource:{buffer:scBuf}},
601
+ {binding:1,resource:{buffer:srcBuf}},
602
+ {binding:3,resource:{buffer:crossK[li]}},{binding:4,resource:{buffer:crossV[li]}},{binding:5,resource:{buffer:uCrossKV[li]}}] }));
603
+ const bgAttnSelf=Array.from({length:NUM_LAYERS},(_,li)=>device.createBindGroup({ layout:pAttn.getBindGroupLayout(0), entries:[
604
+ {binding:8,resource:{buffer:smBuf}},
605
+ {binding:1,resource:{buffer:qBuf}},{binding:2,resource:{buffer:selfK[li]}},
606
+ {binding:3,resource:{buffer:selfV[li]}},{binding:4,resource:{buffer:ctxBuf}},{binding:5,resource:{buffer:uAttnSelf[li]}}] }));
607
+ const bgAttnCross=Array.from({length:NUM_LAYERS},(_,li)=>device.createBindGroup({ layout:pAttn.getBindGroupLayout(0), entries:[
608
+ {binding:8,resource:{buffer:smBuf}},
609
+ {binding:1,resource:{buffer:qBuf}},{binding:2,resource:{buffer:crossK[li]}},
610
+ {binding:3,resource:{buffer:crossV[li]}},{binding:4,resource:{buffer:ctxBuf}},{binding:5,resource:{buffer:uAttnCross[li]}}] }));
611
+ const bgWoSelf=Array.from({length:NUM_LAYERS},(_,li)=>device.createBindGroup({ layout:pWo.getBindGroupLayout(0), entries:[
612
+ // Wo qMatmul: no rmsnorm/bias -> wv() never called -> SMALL@8 pruned.
613
+ {binding:0,resource:{buffer:p0Buf}},{binding:6,resource:{buffer:p1Buf}},{binding:7,resource:{buffer:scBuf}},
614
+ {binding:1,resource:{buffer:ctxBuf}},{binding:2,resource:{buffer:blkOutBuf}},{binding:5,resource:{buffer:uWoSelf[li]}}] }));
615
+ const bgWoCross=Array.from({length:NUM_LAYERS},(_,li)=>device.createBindGroup({ layout:pWo.getBindGroupLayout(0), entries:[
616
+ {binding:0,resource:{buffer:p0Buf}},{binding:6,resource:{buffer:p1Buf}},{binding:7,resource:{buffer:scBuf}},
617
+ {binding:1,resource:{buffer:ctxBuf}},{binding:2,resource:{buffer:blkOutBuf}},{binding:5,resource:{buffer:uWoCross[li]}}] }));
618
+ const bgResidSAttn=Array.from({length:NUM_LAYERS},(_,li)=>device.createBindGroup({ layout:pResid.getBindGroupLayout(0), entries:[
619
+ {binding:8,resource:{buffer:smBuf}},
620
+ {binding:1,resource:{buffer:xBuf}},{binding:2,resource:{buffer:blkOutBuf}},{binding:5,resource:{buffer:uResidSAttn[li]}}] }));
621
+ const bgResidCAttn=Array.from({length:NUM_LAYERS},(_,li)=>device.createBindGroup({ layout:pResid.getBindGroupLayout(0), entries:[
622
+ {binding:8,resource:{buffer:smBuf}},
623
+ {binding:1,resource:{buffer:xBuf}},{binding:2,resource:{buffer:blkOutBuf}},{binding:5,resource:{buffer:uResidCAttn[li]}}] }));
624
+ const bgWi=Array.from({length:NUM_LAYERS},(_,li)=>device.createBindGroup({ layout:pWi.getBindGroupLayout(0), entries:[
625
+ {binding:0,resource:{buffer:p0Buf}},{binding:6,resource:{buffer:p1Buf}},{binding:7,resource:{buffer:scBuf}},{binding:8,resource:{buffer:smBuf}},
626
+ {binding:1,resource:{buffer:xBuf}},{binding:2,resource:{buffer:ffBuf}},{binding:5,resource:{buffer:uWi[li]}}] }));
627
+ const bgWoFfn=Array.from({length:NUM_LAYERS},(_,li)=>device.createBindGroup({ layout:pWoFfn.getBindGroupLayout(0), entries:[
628
+ {binding:0,resource:{buffer:p0Buf}},{binding:6,resource:{buffer:p1Buf}},{binding:7,resource:{buffer:scBuf}},{binding:8,resource:{buffer:smBuf}},
629
+ {binding:1,resource:{buffer:ffBuf}},{binding:2,resource:{buffer:blkOutBuf}},{binding:5,resource:{buffer:uWoFfn[li]}}] }));
630
+ const bgResidFfn=Array.from({length:NUM_LAYERS},(_,li)=>device.createBindGroup({ layout:pResid.getBindGroupLayout(0), entries:[
631
+ {binding:8,resource:{buffer:smBuf}},
632
+ {binding:1,resource:{buffer:xBuf}},{binding:2,resource:{buffer:blkOutBuf}},{binding:5,resource:{buffer:uResidFfn[li]}}] }));
633
+
634
+ const WG_KV=tNWGT(HD), WG_Q=tNWGT(HD), WG_WO=tNWGT(D_MODEL), WG_WI=tNWGT(D_FF), WG_WOFFN=tNWGT(D_MODEL);
635
+
636
+ // ---------------- KV growth state (persists across frames) ----------------
637
+ // T = number of accumulated real KV rows. Next frame appends at slot=T, then
638
+ // (after this frame) the new length is min(T+1, KV_CAP). The temporal_gpu.ts
639
+ // reference grows by writing the appended row at slot T (no eviction below cap;
640
+ // at cap the model trims oldest — here we cap T at KV_CAP, appending at slot T
641
+ // until T==KV_CAP, then keep appending at the last slot like a ring's head).
642
+ // To match the ORT temporal_step semantics (sliding window, trim oldest) the
643
+ // KV is treated as append-then-clip-to-cap. We implement the simple grow-to-cap
644
+ // policy used by the validated reference (slot = min(T, KV_CAP)).
645
+ let T_LEN=0; // current accumulated real KV rows (before this frame's append)
646
+
647
+ function resetKV(){ T_LEN=0; }
648
+
649
+ // upload `source` (256 floats) once per style change.
650
+ function setSource(srcF32){ device.queue.writeBuffer(srcBuf,0, srcF32 instanceof Float32Array?srcF32:Float32Array.from(srcF32)); }
651
+
652
+ // runTemporal: prevToks[12] (global token ids) -> writes out into xBuf[1024]
653
+ // (GPU-resident) and appends this frame's self/cross K,V at slot T_LEN. Returns
654
+ // the xBuf so the depth adapter can read it directly (zero copy). No readback.
655
+ function runTemporal(prevToks){
656
+ const slot=T_LEN % KV_CAP; // RING buffer write: overwrite oldest when full
657
+ const cacheLen=Math.min(T_LEN+1, KV_CAP);// recent-window length; ≤KV_CAP so sink+cacheLen fits logitsW[KV_CAP+1]
658
+ // start = physical index of the OLDEST key currently in the ring (read in temporal order oldest->newest).
659
+ const start=(T_LEN+1 <= KV_CAP) ? 0 : (T_LEN+1) % KV_CAP;
660
+
661
+ device.queue.writeBuffer(prevBuf,0,new Uint32Array(prevToks));
662
+ for(let li=0;li<NUM_LAYERS;li++){
663
+ // slot lives at word 7 (byte 28) of the 32-byte q4 selfKV/crossKV uniforms.
664
+ { const a=new Uint32Array(1); a[0]=slot; device.queue.writeBuffer(uSelfKV[li],28,a); device.queue.writeBuffer(uCrossKV[li],28,a); }
665
+ // cacheLen (word 3 / byte 12) + start (word 4 / byte 16) of the attn uniforms.
666
+ { const a=new Uint32Array(2); a[0]=cacheLen; a[1]=start; device.queue.writeBuffer(uAttnSelf[li],12,a); device.queue.writeBuffer(uAttnCross[li],12,a); }
667
+ }
668
+
669
+ const enc=device.createCommandEncoder();
670
+ const pass=enc.beginComputePass();
671
+ pass.setPipeline(pEmbed); pass.setBindGroup(0,bgEmbed); pass.dispatchWorkgroups(1);
672
+ for(let li=0;li<NUM_LAYERS;li++){
673
+ // self attention
674
+ pass.setPipeline(pSelfKV); pass.setBindGroup(0,bgSelfKV[li]); pass.dispatchWorkgroups(WG_KV);
675
+ pass.setPipeline(pAttn); pass.setBindGroup(0,bgAttnSelf[li]); pass.dispatchWorkgroups(1);
676
+ pass.setPipeline(pWo); pass.setBindGroup(0,bgWoSelf[li]); pass.dispatchWorkgroups(WG_WO);
677
+ pass.setPipeline(pResid); pass.setBindGroup(0,bgResidSAttn[li]);pass.dispatchWorkgroups(1);
678
+ // cross attention
679
+ pass.setPipeline(pCrossQ); pass.setBindGroup(0,bgCrossQ[li]); pass.dispatchWorkgroups(WG_Q);
680
+ pass.setPipeline(pCrossKV); pass.setBindGroup(0,bgCrossKV[li]); pass.dispatchWorkgroups(WG_KV);
681
+ pass.setPipeline(pAttn); pass.setBindGroup(0,bgAttnCross[li]); pass.dispatchWorkgroups(1);
682
+ pass.setPipeline(pWo); pass.setBindGroup(0,bgWoCross[li]); pass.dispatchWorkgroups(WG_WO);
683
+ pass.setPipeline(pResid); pass.setBindGroup(0,bgResidCAttn[li]);pass.dispatchWorkgroups(1);
684
+ // FFN
685
+ pass.setPipeline(pWi); pass.setBindGroup(0,bgWi[li]); pass.dispatchWorkgroups(WG_WI);
686
+ pass.setPipeline(pWoFfn); pass.setBindGroup(0,bgWoFfn[li]); pass.dispatchWorkgroups(WG_WOFFN);
687
+ pass.setPipeline(pResid); pass.setBindGroup(0,bgResidFfn[li]); pass.dispatchWorkgroups(1);
688
+ }
689
+ pass.end();
690
+ device.queue.submit([enc.finish()]);
691
+
692
+ // advance KV length — grow indefinitely; the ring wraps at KV_CAP (slot=T_LEN%KV_CAP)
693
+ T_LEN++;
694
+ return xBuf;
695
+ }
696
+
697
+ // debug-only: read back the current temporal out (xBuf[1024]) to CPU.
698
+ async function debugReadOut(){
699
+ const enc=device.createCommandEncoder();
700
+ enc.copyBufferToBuffer(xBuf,0,dbgOutBuf,0,D_MODEL*4);
701
+ device.queue.submit([enc.finish()]);
702
+ await dbgOutBuf.mapAsync(GPUMapMode.READ);
703
+ const out=new Float32Array(dbgOutBuf.getMappedRange().slice(0));
704
+ dbgOutBuf.unmap();
705
+ let absmax=0, hasNaN=false, sum=0, sumsq=0;
706
+ for(let i=0;i<out.length;i++){ const v=out[i]; if(Number.isNaN(v)||!Number.isFinite(v))hasNaN=true; const a=Math.abs(v); if(a>absmax)absmax=a; sum+=v; sumsq+=v*v; }
707
+ const mean=sum/out.length, std=Math.sqrt(Math.max(0,sumsq/out.length-mean*mean));
708
+ return { absmax, hasNaN, mean, std, first4:[out[0],out[1],out[2],out[3]] };
709
+ }
710
+ return { runTemporal, resetKV, setSource, kvLen:()=>T_LEN, outBuf:xBuf, debugReadOut };
711
+ }
712
+
713
+ /* ====================================================================== *
714
+ * CUSTOM WGSL DEPTH (ported verbatim from depth_q4_gpu.ts — q4)
715
+ * Big matmuls (adapter, Wq/Wk/Wv, Wo, Wi, Wo_ffn, to_logits) are q4 block-
716
+ * quantized along K (block_size=32, zero=8): packed nibbles in u32 (8/word,
717
+ * k-contiguous) + per-block fp32 scales; unpack via u32 shift/mask only (NO
718
+ * unpack2x16float). Small params (norms/biases/per_dim_scale/embedding) stay
719
+ * fp32 in SMALL. Built on the SAME GPUDevice ORT uses so the temporal-out
720
+ * GPUBuffer and the depth kernels share GPU memory: zero copy, zero readback
721
+ * except the 12 sampled tokens once per frame.
722
+ * ====================================================================== */
723
+ const D_IN=1024, D_MODEL=768, D_FF=3072, VOCAB=12294, NUM_CODEBOOKS=12,
724
+ CODEBOOK_SIZE=1024, NUM_RESERVED=6, NUM_LAYERS=2, NUM_HEADS=6, UPH=128;
725
+ const HD=NUM_HEADS*UPH, QKV=3*HD, SOFT_CAP=30.0, EPS=1e-6, R_SOFTPLUS_0=1.442695041;
726
+ const D_BLK=32; // q4 block size
727
+ const RED=32, ROWS=8, T_WG=ROWS*RED; // bandwidth tiling
728
+ const nWGT=N=>Math.ceil(N/ROWS);
729
+ let USE_SUBGROUPS=false;
730
+
731
+ const CONSTS=`
732
+ const D_IN : u32 = ${D_IN}u;
733
+ const D_MODEL : u32 = ${D_MODEL}u;
734
+ const D_FF : u32 = ${D_FF}u;
735
+ const VOCAB : u32 = ${VOCAB}u;
736
+ const NUM_HEADS : u32 = ${NUM_HEADS}u;
737
+ const UPH : u32 = ${UPH}u;
738
+ const HD : u32 = ${HD}u;
739
+ const QKV : u32 = ${QKV}u;
740
+ const SOFT_CAP : f32 = ${SOFT_CAP};
741
+ const EPS : f32 = ${EPS};
742
+ const R_SOFTPLUS_0 : f32 = ${R_SOFTPLUS_0};
743
+ const NUM_RESERVED : u32 = ${NUM_RESERVED}u;
744
+ const CODEBOOK_SIZE : u32 = ${CODEBOOK_SIZE}u;
745
+ const RED : u32 = ${RED}u;
746
+ const ROWS : u32 = ${ROWS}u;
747
+ const BLK : u32 = ${D_BLK}u;
748
+ `;
749
+ // q4 HEADER: SMALL fp32 params @8 (wv) + PACKED P0/P1 @0/6 + SCALES @7 (deq).
750
+ function buildHeaders(P_SPLIT_WORDS){
751
+ const SMALLBUF=`
752
+ @group(0) @binding(8) var<storage, read> SMALL : array<f32>;
753
+ fn wv(i : u32) -> f32 { return SMALL[i]; }
754
+ fn softplus(x: f32) -> f32 { return log(1.0 + exp(-abs(x))) + max(x, 0.0); }
755
+ fn gelu_tanh(x: f32) -> f32 {
756
+ let c : f32 = 0.7978845608028654;
757
+ // clamp: Metal fast-math tanh overflows to 0/NaN for |arg|>~44.
758
+ // |t|>=12 already rounds tanh(t) to +/-1 in f32, so this is exact.
759
+ let t = clamp(c * (x + 0.044715 * x * x * x), -12.0, 12.0);
760
+ return 0.5 * x * (1.0 + tanh(t));
761
+ }`;
762
+ const QBUF=`
763
+ @group(0) @binding(0) var<storage, read> P0 : array<u32>;
764
+ @group(0) @binding(6) var<storage, read> P1 : array<u32>;
765
+ @group(0) @binding(7) var<storage, read> SC : array<f32>;
766
+ const P_SPLIT_WORDS : u32 = ${P_SPLIT_WORDS}u;
767
+ fn qword(wi : u32) -> u32 {
768
+ if (wi < P_SPLIT_WORDS) { return P0[wi]; }
769
+ return P1[wi - P_SPLIT_WORDS];
770
+ }
771
+ fn deq(qOff : u32, sOff : u32, K : u32, col : u32, k : u32) -> f32 {
772
+ let word = qword(qOff + col * (K >> 3u) + (k >> 3u));
773
+ let nib = (word >> ((k & 7u) * 4u)) & 0xfu;
774
+ let s = SC[sOff + col * (K >> 5u) + (k >> 5u)];
775
+ return (f32(nib) - 8.0) * s;
776
+ }`;
777
+ return CONSTS+QBUF+SMALLBUF;
778
+ }
779
+ // q4 bandwidth matmul (replaces gridMatmulT/gridMatmul2). uniform {qOff,sOff,colBase,normOff,biasOff}.
780
+ function qMatmul(HEADER, opts){
781
+ const K=opts.K, sg=USE_SUBGROUPS;
782
+ const inDecl=`@group(0) @binding(${opts.inBinding}) var<storage, read> vin : array<f32>;`;
783
+ const outDecl=`@group(0) @binding(${opts.outBinding}) var<storage, read_write> vout : array<f32>;`;
784
+ const uniformDecl=`struct U { qOff:u32, sOff:u32, colBase:u32, normOff:u32, biasOff:u32, };
785
+ @group(0) @binding(5) var<uniform> u : U;`;
786
+ const normReduce=opts.rmsnorm?`
787
+ var lss : f32 = 0.0;
788
+ for (var i : u32 = tid; i < ${K}u; i = i + ${T_WG}u) { let xv = vin[i]; lss = lss + xv * xv; }
789
+ red[tid] = lss; workgroupBarrier();
790
+ for (var s : u32 = ${T_WG/2}u; s > 0u; s = s >> 1u) { if (tid < s) { red[tid] = red[tid] + red[tid + s]; } workgroupBarrier(); }
791
+ let rms = 1.0 / sqrt(red[0] / f32(${K}u) + EPS); workgroupBarrier();
792
+ for (var i : u32 = tid; i < ${K}u; i = i + ${T_WG}u) { inS[i] = (vin[i] * rms) * wv(u.normOff + i); }
793
+ workgroupBarrier();`:`
794
+ for (var i : u32 = tid; i < ${K}u; i = i + ${T_WG}u) { inS[i] = vin[i]; }
795
+ workgroupBarrier();`;
796
+ let epi="";
797
+ if(opts.epilogue==="geluBias") epi=`acc = gelu_tanh(acc + wv(u.biasOff + col));`;
798
+ else if(opts.epilogue==="softcap"){ const b=opts.hasBias?`acc = acc + wv(u.biasOff + col);`:``; epi=`${b}
799
+ acc = SOFT_CAP * tanh(clamp(acc / SOFT_CAP, -12.0, 12.0));`; }
800
+ else epi=opts.hasBias?`acc = acc + wv(u.biasOff + col);`:``;
801
+ const reduceWrite=sg?`
802
+ let total = subgroupAdd(acc);
803
+ if (lane == 0u) { var accf : f32 = total; ${epi.replace(/\bacc\b/g,"accf")} vout[outIdx] = accf; }`:`
804
+ part[tid] = acc; workgroupBarrier();
805
+ for (var s : u32 = ${RED/2}u; s > 0u; s = s >> 1u) { if (lane < s) { part[tid] = part[tid] + part[tid + s]; } workgroupBarrier(); }
806
+ if (lane == 0u) { var accf : f32 = part[row * RED]; ${epi.replace(/\bacc\b/g,"accf")} vout[outIdx] = accf; }`;
807
+ const enableSg=sg?"enable subgroups;\n":"";
808
+ return enableSg+HEADER+`
809
+ ${inDecl}
810
+ ${outDecl}
811
+ ${uniformDecl}
812
+ var<workgroup> inS : array<f32, ${K}>;
813
+ ${opts.rmsnorm?`var<workgroup> red : array<f32, ${T_WG}>;`:``}
814
+ ${sg?"":`var<workgroup> part : array<f32, ${T_WG}>;`}
815
+ @compute @workgroup_size(${T_WG})
816
+ fn main(@builtin(local_invocation_id) lid : vec3<u32>, @builtin(workgroup_id) wid : vec3<u32>) {
817
+ let tid = lid.x; let row = tid / RED; let lane = tid % RED;
818
+ ${normReduce}
819
+ let outIdx = wid.x * ROWS + row;
820
+ let col = u.colBase + outIdx;
821
+ var acc : f32 = 0.0;
822
+ for (var k : u32 = lane; k < ${K}u; k = k + RED) { acc = acc + inS[k] * deq(u.qOff, u.sOff, ${K}u, col, k); }
823
+ ${reduceWrite}
824
+ }`;
825
+ }
826
+ // q4 combined QKV (folds attn-pre RMSNorm). uniform {normOff,qQ,qS,kQ,kS,vQ,vS,slot}.
827
+ function buildQKV(HEADER){
828
+ const sg=USE_SUBGROUPS, enableSg=sg?"enable subgroups;\n":"";
829
+ const reduceWrite=sg?`
830
+ let sq = subgroupAdd(qa); let sk = subgroupAdd(ka); let sv = subgroupAdd(va);
831
+ if (lane == 0u) { qbuf[oi] = sq; let cbase = u.slot * HD; kcache[cbase + oi] = sk; vcache[cbase + oi] = sv; }`:`
832
+ pq[tid] = qa; pk[tid] = ka; pv[tid] = va; workgroupBarrier();
833
+ for (var s : u32 = ${RED/2}u; s > 0u; s = s >> 1u) {
834
+ if (lane < s) { pq[tid] = pq[tid] + pq[tid + s]; pk[tid] = pk[tid] + pk[tid + s]; pv[tid] = pv[tid] + pv[tid + s]; }
835
+ workgroupBarrier(); }
836
+ if (lane == 0u) { qbuf[oi] = pq[row * RED]; let cbase = u.slot * HD; kcache[cbase + oi] = pk[row * RED]; vcache[cbase + oi] = pv[row * RED]; }`;
837
+ return enableSg+HEADER+`
838
+ @group(0) @binding(1) var<storage, read> vin : array<f32>;
839
+ @group(0) @binding(2) var<storage, read_write> qbuf : array<f32>;
840
+ @group(0) @binding(3) var<storage, read_write> kcache : array<f32>;
841
+ @group(0) @binding(4) var<storage, read_write> vcache : array<f32>;
842
+ struct U { normOff:u32, qQ:u32, qS:u32, kQ:u32, kS:u32, vQ:u32, vS:u32, slot:u32, };
843
+ @group(0) @binding(5) var<uniform> u : U;
844
+ var<workgroup> inS : array<f32, ${D_MODEL}>;
845
+ var<workgroup> red : array<f32, ${T_WG}>;
846
+ ${sg?"":`var<workgroup> pq : array<f32, ${T_WG}>;
847
+ var<workgroup> pk : array<f32, ${T_WG}>;
848
+ var<workgroup> pv : array<f32, ${T_WG}>;`}
849
+ @compute @workgroup_size(${T_WG})
850
+ fn main(@builtin(local_invocation_id) lid : vec3<u32>, @builtin(workgroup_id) wid : vec3<u32>) {
851
+ let tid = lid.x; let row = tid / RED; let lane = tid % RED;
852
+ var lss : f32 = 0.0;
853
+ for (var i : u32 = tid; i < D_MODEL; i = i + ${T_WG}u) { let xv = vin[i]; lss = lss + xv * xv; }
854
+ red[tid] = lss; workgroupBarrier();
855
+ for (var s : u32 = ${T_WG/2}u; s > 0u; s = s >> 1u) { if (tid < s) { red[tid] = red[tid] + red[tid + s]; } workgroupBarrier(); }
856
+ let rms = 1.0 / sqrt(red[0] / f32(D_MODEL) + EPS); workgroupBarrier();
857
+ for (var i : u32 = tid; i < D_MODEL; i = i + ${T_WG}u) { inS[i] = (vin[i] * rms) * wv(u.normOff + i); }
858
+ workgroupBarrier();
859
+ let oi = wid.x * ROWS + row;
860
+ var qa : f32 = 0.0; var ka : f32 = 0.0; var va : f32 = 0.0;
861
+ for (var k : u32 = lane; k < D_MODEL; k = k + RED) {
862
+ let hv = inS[k];
863
+ qa = qa + hv * deq(u.qQ, u.qS, D_MODEL, oi, k);
864
+ ka = ka + hv * deq(u.kQ, u.kS, D_MODEL, oi, k);
865
+ va = va + hv * deq(u.vQ, u.vS, D_MODEL, oi, k);
866
+ }
867
+ ${reduceWrite}
868
+ }`;
869
+ }
870
+ function buildAttnCore(HEADER){ return HEADER+`
871
+ @group(0) @binding(1) var<storage, read> qbuf : array<f32>;
872
+ @group(0) @binding(2) var<storage, read> kcache : array<f32>;
873
+ @group(0) @binding(3) var<storage, read> vcache : array<f32>;
874
+ @group(0) @binding(4) var<storage, read_write> ctxbuf : array<f32>;
875
+ struct U { per_dim_scale:u32, cacheLen:u32, };
876
+ @group(0) @binding(5) var<uniform> u : U;
877
+ var<workgroup> logitsW : array<f32, ${NUM_HEADS*NUM_CODEBOOKS}>;
878
+ var<workgroup> red : array<f32, 2>;
879
+ @compute @workgroup_size(256)
880
+ fn main(@builtin(local_invocation_id) lid : vec3<u32>) {
881
+ let t = lid.x; let T = u.cacheLen;
882
+ let qscale = R_SOFTPLUS_0 * (1.0 / sqrt(f32(UPH)));
883
+ for (var h : u32 = 0u; h < NUM_HEADS; h = h + 1u) {
884
+ for (var k : u32 = t; k < T; k = k + 256u) {
885
+ var acc : f32 = 0.0; let kbase = k * HD + h * UPH; let qbase = h * UPH;
886
+ for (var d : u32 = 0u; d < UPH; d = d + 1u) {
887
+ let sv = qscale * softplus(wv(u.per_dim_scale + d));
888
+ acc = acc + (qbuf[qbase + d] * sv) * kcache[kbase + d];
889
+ }
890
+ logitsW[h * T + k] = acc;
891
+ }
892
+ }
893
+ workgroupBarrier();
894
+ for (var h : u32 = 0u; h < NUM_HEADS; h = h + 1u) {
895
+ if (t == 0u) { var m : f32 = logitsW[h * T + 0u]; for (var k : u32 = 1u; k < T; k = k + 1u) { m = max(m, logitsW[h * T + k]); } red[0] = m; }
896
+ workgroupBarrier(); let m = red[0];
897
+ if (t == 0u) { var s : f32 = 0.0; for (var k : u32 = 0u; k < T; k = k + 1u) { let e = exp(logitsW[h * T + k] - m); logitsW[h * T + k] = e; s = s + e; } red[1] = s; }
898
+ workgroupBarrier(); let denom = red[1];
899
+ for (var d : u32 = t; d < UPH; d = d + 256u) {
900
+ var acc : f32 = 0.0;
901
+ for (var k : u32 = 0u; k < T; k = k + 1u) { let w = logitsW[h * T + k] / denom; acc = acc + w * vcache[k * HD + h * UPH + d]; }
902
+ ctxbuf[h * UPH + d] = acc;
903
+ }
904
+ workgroupBarrier();
905
+ }
906
+ }`;
907
+ }
908
+ function buildResid(HEADER){ return HEADER+`
909
+ @group(0) @binding(1) var<storage, read_write> x : array<f32>;
910
+ @group(0) @binding(2) var<storage, read> y : array<f32>;
911
+ struct U { post:u32, };
912
+ @group(0) @binding(5) var<uniform> u : U;
913
+ var<workgroup> red : array<f32, 256>;
914
+ @compute @workgroup_size(256)
915
+ fn main(@builtin(local_invocation_id) lid : vec3<u32>) {
916
+ let t = lid.x; var ss : f32 = 0.0;
917
+ for (var i : u32 = t; i < D_MODEL; i = i + 256u) { let v = y[i]; ss = ss + v*v; }
918
+ red[t] = ss; workgroupBarrier();
919
+ for (var s : u32 = 128u; s > 0u; s = s >> 1u) { if (t < s) { red[t] = red[t] + red[t + s]; } workgroupBarrier(); }
920
+ let rms = 1.0 / sqrt(red[0] / f32(D_MODEL) + EPS); workgroupBarrier();
921
+ for (var i : u32 = t; i < D_MODEL; i = i + 256u) { x[i] = x[i] + (y[i] * rms) * wv(u.post + i); }
922
+ }`;
923
+ }
924
+ function buildFinalLN(HEADER){ return HEADER+`
925
+ @group(0) @binding(1) var<storage, read> x : array<f32>;
926
+ @group(0) @binding(2) var<storage, read_write> xn : array<f32>;
927
+ struct U { final_scale:u32, final_bias:u32, };
928
+ @group(0) @binding(5) var<uniform> u : U;
929
+ var<workgroup> red : array<f32, 256>;
930
+ @compute @workgroup_size(256)
931
+ fn main(@builtin(local_invocation_id) lid : vec3<u32>) {
932
+ let t = lid.x; var sm : f32 = 0.0;
933
+ for (var i : u32 = t; i < D_MODEL; i = i + 256u) { sm = sm + x[i]; }
934
+ red[t] = sm; workgroupBarrier();
935
+ for (var s : u32 = 128u; s > 0u; s = s >> 1u) { if (t < s) { red[t] = red[t] + red[t + s]; } workgroupBarrier(); }
936
+ let mean = red[0] / f32(D_MODEL); workgroupBarrier();
937
+ var vs : f32 = 0.0;
938
+ for (var i : u32 = t; i < D_MODEL; i = i + 256u) { let dd = x[i] - mean; vs = vs + dd*dd; }
939
+ red[t] = vs; workgroupBarrier();
940
+ for (var s : u32 = 128u; s > 0u; s = s >> 1u) { if (t < s) { red[t] = red[t] + red[t + s]; } workgroupBarrier(); }
941
+ let rstd = 1.0 / sqrt(red[0] / f32(D_MODEL) + EPS); workgroupBarrier();
942
+ for (var i : u32 = t; i < D_MODEL; i = i + 256u) { xn[i] = ((x[i] - mean) * rstd) * wv(u.final_scale + i) + wv(u.final_bias + i); }
943
+ }`;
944
+ }
945
+ // sampler: gumbel over the 1024-wide active slice. noise is COMPACT [Q*1024].
946
+ function buildSample(){ return CONSTS+`
947
+ @group(0) @binding(1) var<storage, read> logits1024 : array<f32>;
948
+ @group(0) @binding(2) var<storage, read> noise : array<f32>;
949
+ @group(0) @binding(3) var<storage, read_write> outTok : array<u32>;
950
+ struct U { lo:u32, temperature:f32, slot:u32, noiseBase:u32, };
951
+ @group(0) @binding(5) var<uniform> u : U;
952
+ var<workgroup> bestScore : array<f32, 256>;
953
+ var<workgroup> bestIdx : array<u32, 256>;
954
+ @compute @workgroup_size(256)
955
+ fn main(@builtin(local_invocation_id) lid : vec3<u32>) {
956
+ let t = lid.x; let lo = u.lo;
957
+ var bScore : f32 = -3.0e38; var bIdx : u32 = 0xffffffffu;
958
+ for (var j : u32 = t; j < CODEBOOK_SIZE; j = j + 256u) {
959
+ var score : f32 = logits1024[j];
960
+ let gidx = lo + j;
961
+ if (u.temperature > 0.0) {
962
+ var un = noise[u.noiseBase + j];
963
+ un = clamp(un, 1.0e-10, 1.0 - 1.0e-7);
964
+ let g = -log(-log(un));
965
+ score = score + g * u.temperature;
966
+ }
967
+ if (score > bScore || (score == bScore && gidx < bIdx)) { bScore = score; bIdx = gidx; }
968
+ }
969
+ bestScore[t] = bScore; bestIdx[t] = bIdx; workgroupBarrier();
970
+ for (var s : u32 = 128u; s > 0u; s = s >> 1u) {
971
+ if (t < s) { let a = bestScore[t]; let ai = bestIdx[t]; let b = bestScore[t + s]; let bi = bestIdx[t + s];
972
+ if (b > a || (b == a && bi < ai)) { bestScore[t] = b; bestIdx[t] = bi; } }
973
+ workgroupBarrier();
974
+ }
975
+ if (t == 0u) { outTok[u.slot] = bestIdx[0]; }
976
+ }`;
977
+ }
978
+ function buildEmbed(HEADER){ return HEADER+`
979
+ @group(0) @binding(1) var<storage, read> tokBuf : array<u32>;
980
+ @group(0) @binding(2) var<storage, read_write> xout : array<f32>;
981
+ struct EU { embeddingOff : u32, embed_scale : f32, slot : u32 };
982
+ @group(0) @binding(3) var<uniform> u : EU;
983
+ @compute @workgroup_size(256)
984
+ fn main(@builtin(local_invocation_id) lid : vec3<u32>) {
985
+ let t = lid.x; let tok = tokBuf[u.slot];
986
+ let base = u.embeddingOff + tok * D_IN;
987
+ for (var i : u32 = t; i < D_IN; i = i + 256u) { xout[i] = wv(base + i) * u.embed_scale; }
988
+ }`;
989
+ }
990
+
991
+ // Build the whole depth engine on ORT's device. Returns { runDepth }.
992
+ async function buildDepth(device, layout, binBytes){
993
+ const EMBED_SCALE=layout.embed_scale;
994
+ const q4=n=>layout.q4[n];
995
+ const smallOff=n=>layout.small[n].offset;
996
+ const layerOffsets=li=>{ const p="l"+li+"_"; return {
997
+ attn_pre:smallOff(p+"attn_pre"), attn_post:smallOff(p+"attn_post"),
998
+ per_dim_scale:smallOff(p+"per_dim_scale"),
999
+ ffn_pre:smallOff(p+"ffn_pre"), ffn_post:smallOff(p+"ffn_post"),
1000
+ bi:smallOff(p+"bi"), bo:smallOff(p+"bo") }; };
1001
+
1002
+ const makeStorage=(floats,extra=0)=>device.createBuffer({ size:Math.max(4,floats*4),
1003
+ usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC|extra });
1004
+
1005
+ // section byte ranges within depth_q4_ort.bin
1006
+ const PACKED_BYTE_OFF=layout.packed_byte_off, SCALE_BYTE_OFF=layout.scale_byte_off, SMALL_BYTE_OFF=layout.small_byte_off;
1007
+ const PACKED_WORDS=layout.packed_words, SCALE_FLOATS=layout.scale_floats, SMALL_FLOATS=layout.small_floats;
1008
+ const P_SPLIT_WORDS=Math.ceil(PACKED_WORDS/2);
1009
+ const P0_BYTES=P_SPLIT_WORDS*4, P1_BYTES=PACKED_WORDS*4-P0_BYTES;
1010
+ const p0Buf=device.createBuffer({ size:Math.max(4,P0_BYTES), usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST });
1011
+ const p1Buf=device.createBuffer({ size:Math.max(4,P1_BYTES), usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST });
1012
+ device.queue.writeBuffer(p0Buf,0,binBytes,PACKED_BYTE_OFF,P0_BYTES);
1013
+ device.queue.writeBuffer(p1Buf,0,binBytes,PACKED_BYTE_OFF+P0_BYTES,P1_BYTES);
1014
+ const scBuf=device.createBuffer({ size:Math.max(4,SCALE_FLOATS*4), usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST });
1015
+ device.queue.writeBuffer(scBuf,0,binBytes,SCALE_BYTE_OFF,SCALE_FLOATS*4);
1016
+ const smBuf=device.createBuffer({ size:Math.max(4,SMALL_FLOATS*4), usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST });
1017
+ device.queue.writeBuffer(smBuf,0,binBytes,SMALL_BYTE_OFF,SMALL_FLOATS*4);
1018
+ console.log(`depth q4: PACKED ${(PACKED_WORDS*4/1048576).toFixed(1)}MB (P0 ${(P0_BYTES/1048576).toFixed(1)} / P1 ${(P1_BYTES/1048576).toFixed(1)}), SCALES ${(SCALE_FLOATS*4/1048576).toFixed(1)}MB, SMALL ${(SMALL_FLOATS*4/1048576).toFixed(1)}MB`);
1019
+
1020
+ const xinBuf=makeStorage(D_IN), x768Buf=makeStorage(D_MODEL), qBuf=makeStorage(HD), ctxBuf=makeStorage(HD),
1021
+ attnOutBuf=makeStorage(D_MODEL), ffBuf=makeStorage(D_FF), ffnOutBuf=makeStorage(D_MODEL),
1022
+ xnBuf=makeStorage(D_MODEL), logits1024Buf=makeStorage(CODEBOOK_SIZE);
1023
+ const kBufs=[makeStorage(NUM_CODEBOOKS*D_MODEL),makeStorage(NUM_CODEBOOKS*D_MODEL)];
1024
+ const vBufs=[makeStorage(NUM_CODEBOOKS*D_MODEL),makeStorage(NUM_CODEBOOKS*D_MODEL)];
1025
+ const tokBuf=device.createBuffer({ size:NUM_CODEBOOKS*4, usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC });
1026
+ const tokReadBuf=device.createBuffer({ size:NUM_CODEBOOKS*4, usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST });
1027
+ const noiseBuf=makeStorage(NUM_CODEBOOKS*CODEBOOK_SIZE);
1028
+
1029
+ const makeUniform=bytes=>device.createBuffer({ size:bytes, usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST });
1030
+ const pipeline=code=>{ const m=device.createShaderModule({code}); return device.createComputePipeline({ layout:"auto", compute:{module:m,entryPoint:"main"} }); };
1031
+
1032
+ const HEADER=buildHeaders(P_SPLIT_WORDS);
1033
+ const pAdapter=pipeline(qMatmul(HEADER,{K:D_IN,inBinding:1,outBinding:2,rmsnorm:false,epilogue:"none",hasBias:false}));
1034
+ const pQKV=pipeline(buildQKV(HEADER));
1035
+ const pAttnCore=pipeline(buildAttnCore(HEADER));
1036
+ const pWo=pipeline(qMatmul(HEADER,{K:HD,inBinding:1,outBinding:2,rmsnorm:false,epilogue:"none",hasBias:false}));
1037
+ const pResid=pipeline(buildResid(HEADER));
1038
+ const pWi=pipeline(qMatmul(HEADER,{K:D_MODEL,inBinding:1,outBinding:2,rmsnorm:true,epilogue:"geluBias",hasBias:true}));
1039
+ const pWoFfn=pipeline(qMatmul(HEADER,{K:D_FF,inBinding:1,outBinding:2,rmsnorm:false,epilogue:"none",hasBias:true}));
1040
+ const pFinalLN=pipeline(buildFinalLN(HEADER));
1041
+ const pToLogits=pipeline(qMatmul(HEADER,{K:D_MODEL,inBinding:1,outBinding:2,rmsnorm:false,epilogue:"softcap",hasBias:true}));
1042
+ const pSample=pipeline(buildSample());
1043
+ const pEmbed=pipeline(buildEmbed(HEADER));
1044
+
1045
+ // qMatmul U { qOff,sOff,colBase,normOff,biasOff } = 20 -> pad 32.
1046
+ const uAdapter=makeUniform(32), uWo=[makeUniform(32),makeUniform(32)], uWi=[makeUniform(32),makeUniform(32)], uWoFfn=[makeUniform(32),makeUniform(32)];
1047
+ const uToLogits=Array.from({length:NUM_CODEBOOKS},()=>makeUniform(32));
1048
+ const uQKV=Array.from({length:NUM_CODEBOOKS},()=>[makeUniform(32),makeUniform(32)]);
1049
+ const uAttnCore=Array.from({length:NUM_CODEBOOKS},()=>[makeUniform(16),makeUniform(16)]);
1050
+ const uResidAttn=[makeUniform(16),makeUniform(16)], uResidFfn=[makeUniform(16),makeUniform(16)], uFinalLN=makeUniform(16);
1051
+ const uSample=Array.from({length:NUM_CODEBOOKS},()=>makeUniform(16));
1052
+ const uEmbed=Array.from({length:NUM_CODEBOOKS},()=>makeUniform(16));
1053
+
1054
+ // fill a 5-u32 qMatmul uniform { qOff, sOff, colBase, normOff, biasOff }
1055
+ const fillMM=(buf,qOff,sOff,colBase,normOff,biasOff)=>{ const a=new Uint32Array(8);
1056
+ a[0]=qOff; a[1]=sOff; a[2]=colBase; a[3]=normOff; a[4]=biasOff; device.queue.writeBuffer(buf,0,a); };
1057
+
1058
+ { const a=q4("adapter"); fillMM(uAdapter, a.packed_off, a.scale_off, 0, 0, 0); }
1059
+ for(let li=0;li<NUM_LAYERS;li++){ const Lr=layerOffsets(li), p="l"+li+"_";
1060
+ const Wq=q4(p+"Wq"), Wk=q4(p+"Wk"), Wv=q4(p+"Wv");
1061
+ for(let q=0;q<NUM_CODEBOOKS;q++){
1062
+ const a=new Uint32Array(8); a[0]=Lr.attn_pre;
1063
+ a[1]=Wq.packed_off; a[2]=Wq.scale_off; a[3]=Wk.packed_off; a[4]=Wk.scale_off;
1064
+ a[5]=Wv.packed_off; a[6]=Wv.scale_off; a[7]=q; // slot
1065
+ device.queue.writeBuffer(uQKV[q][li],0,a);
1066
+ const c=new Uint32Array(4); c[0]=Lr.per_dim_scale; c[1]=q+1; device.queue.writeBuffer(uAttnCore[q][li],0,c); }
1067
+ { const a=new Uint32Array(4); a[0]=Lr.attn_post; device.queue.writeBuffer(uResidAttn[li],0,a); }
1068
+ { const Wo=q4(p+"Wo"); fillMM(uWo[li], Wo.packed_off, Wo.scale_off, 0, 0, 0); }
1069
+ { const Wi=q4(p+"Wi"); fillMM(uWi[li], Wi.packed_off, Wi.scale_off, 0, Lr.ffn_pre, Lr.bi); }
1070
+ { const Wofn=q4(p+"Wo_ffn"); fillMM(uWoFfn[li], Wofn.packed_off, Wofn.scale_off, 0, 0, Lr.bo); }
1071
+ { const a=new Uint32Array(4); a[0]=Lr.ffn_post; device.queue.writeBuffer(uResidFfn[li],0,a); }
1072
+ }
1073
+ { const a=new Uint32Array(4); a[0]=smallOff("final_scale"); a[1]=smallOff("final_bias"); device.queue.writeBuffer(uFinalLN,0,a); }
1074
+ for(let q=0;q<NUM_CODEBOOKS;q++){ const e=new ArrayBuffer(16);
1075
+ new Uint32Array(e,0,1)[0]=smallOff("embedding"); new Float32Array(e,4,1)[0]=EMBED_SCALE; new Uint32Array(e,8,1)[0]=q;
1076
+ device.queue.writeBuffer(uEmbed[q],0,e); }
1077
+ { const tl=q4("to_logits_w");
1078
+ for(let q=0;q<NUM_CODEBOOKS;q++){ const lo=NUM_RESERVED+q*CODEBOOK_SIZE;
1079
+ fillMM(uToLogits[q], tl.packed_off, tl.scale_off, lo, 0, smallOff("to_logits_b")); } }
1080
+
1081
+ // q4 matmul bind group: P0@0, P1@6, SC@7, SMALL@8, in@1, out@2, uniform@5.
1082
+ // usesSmall=false (adapter/Wo: no rmsnorm/bias) -> wv() pruned -> don't bind SMALL@8.
1083
+ function bgMM(p,inBuf,outBuf,uBuf,usesSmall=true){
1084
+ const entries=[{binding:0,resource:{buffer:p0Buf}},{binding:6,resource:{buffer:p1Buf}},{binding:7,resource:{buffer:scBuf}},
1085
+ {binding:1,resource:{buffer:inBuf}},{binding:2,resource:{buffer:outBuf}},{binding:5,resource:{buffer:uBuf}}];
1086
+ if(usesSmall) entries.push({binding:8,resource:{buffer:smBuf}});
1087
+ return device.createBindGroup({ layout:p.getBindGroupLayout(0), entries });
1088
+ }
1089
+ const bgAdapterXin=bgMM(pAdapter,xinBuf,x768Buf,uAdapter,false);
1090
+ const mkAdapterBG=inBuf=>bgMM(pAdapter,inBuf,x768Buf,uAdapter,false);
1091
+ const bgWo=[0,1].map(li=>bgMM(pWo,ctxBuf,attnOutBuf,uWo[li],false));
1092
+ const bgQKV=Array.from({length:NUM_CODEBOOKS},(_,q)=>[0,1].map(li=>device.createBindGroup({
1093
+ layout:pQKV.getBindGroupLayout(0), entries:[
1094
+ {binding:0,resource:{buffer:p0Buf}},{binding:6,resource:{buffer:p1Buf}},{binding:7,resource:{buffer:scBuf}},{binding:8,resource:{buffer:smBuf}},
1095
+ {binding:1,resource:{buffer:x768Buf}},{binding:2,resource:{buffer:qBuf}},
1096
+ {binding:3,resource:{buffer:kBufs[li]}},{binding:4,resource:{buffer:vBufs[li]}},{binding:5,resource:{buffer:uQKV[q][li]}}] })));
1097
+ const bgAttnCore=Array.from({length:NUM_CODEBOOKS},(_,q)=>[0,1].map(li=>device.createBindGroup({
1098
+ layout:pAttnCore.getBindGroupLayout(0), entries:[
1099
+ {binding:8,resource:{buffer:smBuf}},
1100
+ {binding:1,resource:{buffer:qBuf}},{binding:2,resource:{buffer:kBufs[li]}},
1101
+ {binding:3,resource:{buffer:vBufs[li]}},{binding:4,resource:{buffer:ctxBuf}},{binding:5,resource:{buffer:uAttnCore[q][li]}}] })));
1102
+ const bgResidAttn=[0,1].map(li=>device.createBindGroup({ layout:pResid.getBindGroupLayout(0), entries:[
1103
+ {binding:8,resource:{buffer:smBuf}},
1104
+ {binding:1,resource:{buffer:x768Buf}},{binding:2,resource:{buffer:attnOutBuf}},{binding:5,resource:{buffer:uResidAttn[li]}}] }));
1105
+ const bgWi=[0,1].map(li=>bgMM(pWi,x768Buf,ffBuf,uWi[li]));
1106
+ const bgWoFfn=[0,1].map(li=>bgMM(pWoFfn,ffBuf,ffnOutBuf,uWoFfn[li]));
1107
+ const bgResidFfn=[0,1].map(li=>device.createBindGroup({ layout:pResid.getBindGroupLayout(0), entries:[
1108
+ {binding:8,resource:{buffer:smBuf}},
1109
+ {binding:1,resource:{buffer:x768Buf}},{binding:2,resource:{buffer:ffnOutBuf}},{binding:5,resource:{buffer:uResidFfn[li]}}] }));
1110
+ const bgFinalLN=device.createBindGroup({ layout:pFinalLN.getBindGroupLayout(0), entries:[
1111
+ {binding:8,resource:{buffer:smBuf}},
1112
+ {binding:1,resource:{buffer:x768Buf}},{binding:2,resource:{buffer:xnBuf}},{binding:5,resource:{buffer:uFinalLN}}] });
1113
+ const bgToLogits=Array.from({length:NUM_CODEBOOKS},(_,q)=>bgMM(pToLogits,xnBuf,logits1024Buf,uToLogits[q]));
1114
+ const bgSample=Array.from({length:NUM_CODEBOOKS},(_,q)=>device.createBindGroup({ layout:pSample.getBindGroupLayout(0), entries:[
1115
+ {binding:1,resource:{buffer:logits1024Buf}},{binding:2,resource:{buffer:noiseBuf}},
1116
+ {binding:3,resource:{buffer:tokBuf}},{binding:5,resource:{buffer:uSample[q]}}] }));
1117
+ const bgEmbed=Array.from({length:NUM_CODEBOOKS},(_,q)=>device.createBindGroup({ layout:pEmbed.getBindGroupLayout(0), entries:[
1118
+ {binding:8,resource:{buffer:smBuf}},
1119
+ {binding:1,resource:{buffer:tokBuf}},{binding:2,resource:{buffer:xinBuf}},{binding:3,resource:{buffer:uEmbed[q]}}] }));
1120
+
1121
+ const WG_ADAPTER=nWGT(D_MODEL), WG_QKV=nWGT(HD), WG_WO=nWGT(D_MODEL),
1122
+ WG_WI=nWGT(D_FF), WG_WOFFN=nWGT(D_MODEL), WG_TOLOGITS=nWGT(CODEBOOK_SIZE);
1123
+
1124
+ const adapterBGCache=new WeakMap();
1125
+
1126
+ // runDepth: step-0 input is the temporal-out GPUBuffer (GPU-resident, bound
1127
+ // directly — needs only STORAGE usage). noiseFlat COMPACT [Q*1024]. Returns
1128
+ // { codes:[12 relative], toks:[12 global] }. Single tiny readback.
1129
+ async function runDepth(temporalOutBuf, noiseFlat, temperature){
1130
+ device.queue.writeBuffer(noiseBuf,0,noiseFlat);
1131
+ for(let q=0;q<NUM_CODEBOOKS;q++){ const lo=NUM_RESERVED+q*CODEBOOK_SIZE; const buf=new ArrayBuffer(16);
1132
+ new Uint32Array(buf,0,1)[0]=lo; new Float32Array(buf,4,1)[0]=temperature;
1133
+ new Uint32Array(buf,8,1)[0]=q; new Uint32Array(buf,12,1)[0]=q*CODEBOOK_SIZE;
1134
+ device.queue.writeBuffer(uSample[q],0,buf); }
1135
+
1136
+ let bgAdapter0=adapterBGCache.get(temporalOutBuf);
1137
+ if(!bgAdapter0){ bgAdapter0=mkAdapterBG(temporalOutBuf); adapterBGCache.set(temporalOutBuf,bgAdapter0); }
1138
+
1139
+ for(let q=0;q<NUM_CODEBOOKS;q++){
1140
+ const enc=device.createCommandEncoder(); const pass=enc.beginComputePass();
1141
+ pass.setPipeline(pAdapter);
1142
+ pass.setBindGroup(0, q===0?bgAdapter0:bgAdapterXin);
1143
+ pass.dispatchWorkgroups(WG_ADAPTER);
1144
+ for(let li=0;li<NUM_LAYERS;li++){
1145
+ pass.setPipeline(pQKV); pass.setBindGroup(0,bgQKV[q][li]); pass.dispatchWorkgroups(WG_QKV);
1146
+ pass.setPipeline(pAttnCore); pass.setBindGroup(0,bgAttnCore[q][li]); pass.dispatchWorkgroups(1);
1147
+ pass.setPipeline(pWo); pass.setBindGroup(0,bgWo[li]); pass.dispatchWorkgroups(WG_WO);
1148
+ pass.setPipeline(pResid); pass.setBindGroup(0,bgResidAttn[li]); pass.dispatchWorkgroups(1);
1149
+ pass.setPipeline(pWi); pass.setBindGroup(0,bgWi[li]); pass.dispatchWorkgroups(WG_WI);
1150
+ pass.setPipeline(pWoFfn); pass.setBindGroup(0,bgWoFfn[li]); pass.dispatchWorkgroups(WG_WOFFN);
1151
+ pass.setPipeline(pResid); pass.setBindGroup(0,bgResidFfn[li]); pass.dispatchWorkgroups(1);
1152
+ }
1153
+ pass.setPipeline(pFinalLN); pass.setBindGroup(0,bgFinalLN); pass.dispatchWorkgroups(1);
1154
+ pass.setPipeline(pToLogits); pass.setBindGroup(0,bgToLogits[q]); pass.dispatchWorkgroups(WG_TOLOGITS);
1155
+ pass.setPipeline(pSample); pass.setBindGroup(0,bgSample[q]); pass.dispatchWorkgroups(1);
1156
+ if(q<NUM_CODEBOOKS-1){ pass.setPipeline(pEmbed); pass.setBindGroup(0,bgEmbed[q]); pass.dispatchWorkgroups(1); }
1157
+ pass.end(); device.queue.submit([enc.finish()]);
1158
+ }
1159
+ const enc2=device.createCommandEncoder();
1160
+ enc2.copyBufferToBuffer(tokBuf,0,tokReadBuf,0,NUM_CODEBOOKS*4);
1161
+ device.queue.submit([enc2.finish()]);
1162
+ await tokReadBuf.mapAsync(GPUMapMode.READ);
1163
+ const toksU=new Uint32Array(tokReadBuf.getMappedRange().slice(0)); tokReadBuf.unmap();
1164
+ const toks=[], codes=[];
1165
+ for(let q=0;q<NUM_CODEBOOKS;q++){ const tok=Number(toksU[q]); toks.push(tok);
1166
+ codes.push(((tok-NUM_RESERVED)%CODEBOOK_SIZE+CODEBOOK_SIZE)%CODEBOOK_SIZE); }
1167
+ return {codes, toks};
1168
+ }
1169
+ return { runDepth };
1170
+ }
1171
+
1172
+ // ── ORT tensor helpers ──
1173
+ const NR=()=>cfg.num_reserved_tokens, CB=()=>cfg.codebook_size, Q=()=>cfg.num_codebooks, D=()=>cfg.model_dims;
1174
+ const i64=(arr,dims)=>new ort.Tensor("int64",BigInt64Array.from(arr.map(x=>BigInt(x))),dims);
1175
+ const f32=(arr,dims)=>new ort.Tensor("float32",arr instanceof Float32Array?arr:Float32Array.from(arr),dims);
1176
+
1177
+ // ── conditioning -> source (ORT encoder). Returns the source as a Float32Array. ──
1178
+ async function encodeStyle(tokens){
1179
+ const off=cfg.conditioning.cond_offset;
1180
+ const vals=[...tokens, ...Array(128).fill(-1), -1, 20,10,8].map(v=>v+off);
1181
+ const {source}=await S.encoder.run({cond:i64(vals,[1,1,vals.length])});
1182
+ const data = source.data ?? await source.getData(); // CPU-location encoder output
1183
+ const srcF32 = data instanceof Float32Array ? Float32Array.from(data) : Float32Array.from(data);
1184
+ try{ source.dispose && source.dispose(); }catch(e){}
1185
+ return srcF32; // [256]
1186
+ }
1187
+
1188
+ // ── per-frame state ──
1189
+ // prevToks: the 12 global tokens from the previous frame's depth (next temporal `prev`).
1190
+ let prevToks=null, sourceF32=null, history=[], pendingStyle=null;
1191
+ function dispose(t){ try{ t && t.dispose && t.dispose(); }catch(e){} }
1192
+ function reset(){
1193
+ // temporal `prev` for the very first frame: 12 zeros (BOS), as in the ORT path.
1194
+ prevToks=Array(Q()).fill(0);
1195
+ history=[];
1196
+ if(TEMPORAL) TEMPORAL.resetKV(); // reset self/cross KV growth to length 0
1197
+ if(DSJ){ if(DSTATE) DSJ.keys.forEach((k,i)=>dispose(DSTATE["s_"+i]));
1198
+ DSTATE={}; DSJ.keys.forEach((k,i)=>{ const sh=DSJ.shapes[k]; DSTATE["s_"+i]=f32(new Float32Array(sh.reduce((a,b)=>a*b,1)),sh); }); }
1199
+ }
1200
+
1201
+ // ── per-frame generation: custom WGSL temporal → custom WGSL depth ──
1202
+ let DEC_MS=0, DEPTH_MS=0, TEMP_MS=0;
1203
+ async function genFrame(temp){
1204
+ // 1) custom WGSL temporal step. prevToks[12] global ids -> out in xBuf[1024]
1205
+ // (GPU-resident). Self/cross KV slot-appended on-device. Zero readback.
1206
+ const t0=performance.now();
1207
+ const outBuf=TEMPORAL.runTemporal(prevToks);
1208
+ TEMP_MS=performance.now()-t0;
1209
+ // 2) custom WGSL depth reads the temporal-out GPUBuffer directly (zero copy).
1210
+ const noise=Float32Array.from({length:Q()*CODEBOOK_SIZE},()=>Math.random());
1211
+ const t1=performance.now();
1212
+ const {codes,toks}=await DEPTH.runDepth(outBuf, noise, temp);
1213
+ DEPTH_MS=performance.now()-t1;
1214
+ prevToks=toks; // next temporal `prev` = the 12 global tokens
1215
+ if(window.__LOG){ try{ const _d=await TEMPORAL.debugReadOut(); window.__FN=(window.__FN||0)+1;
1216
+ console.log('f'+window.__FN, 'tmpAbs='+_d.absmax.toFixed(2), 'mean='+_d.mean.toFixed(3), 'std='+_d.std.toFixed(2), 'f4=['+_d.first4.map(x=>x.toFixed(2)).join(',')+']', (_d.hasNaN?'NaN!':''), 'tlen='+TEMPORAL.kvLen(), 'codes=['+codes.join(',')+']'); }catch(e){console.warn('log',e);} }
1217
+ return codes; // 12 relative codes for decode
1218
+ }
1219
+
1220
+ // codes [F,12] -> embeddings [1,F,256] (gather+sum over 12 levels)
1221
+ function codesToEmb(frames){ const F=frames.length, dd=256, out=new Float32Array(F*dd);
1222
+ for(let t=0;t<F;t++) for(let q=0;q<12;q++){ const c=frames[t][q], o=(q*1024+c)*dd;
1223
+ for(let i=0;i<dd;i++) out[t*dd+i]+=QUANT[o+i]; } return f32(out,[1,F,dd]); }
1224
+ // stateful streaming decode (GPU-resident conv-state caches; decodes only NEW frames)
1225
+ async function streamDecode(frames){
1226
+ const emb=codesToEmb(frames);
1227
+ const feed={embeddings:emb}; DSJ.keys.forEach((k,i)=>feed["s_"+i]=DSTATE["s_"+i]);
1228
+ const r=await S.decoder.run(feed);
1229
+ DSJ.keys.forEach((k,i)=>{ dispose(DSTATE["s_"+i]); DSTATE["s_"+i]=r["ns_"+i]; });
1230
+ dispose(emb);
1231
+ return r.waveform;
1232
+ }
1233
+
1234
+ // ── load ──
1235
+ $("load").onclick=async()=>{
1236
+ $("load").disabled=true; $("prog").style.display="block"; setBar(0);
1237
+ $("stat").textContent=`loading ${sz} · webgpu · custom WGSL temporal + WGSL depth…`;
1238
+ const base=REPO;
1239
+ try{
1240
+ cfg=await fetchJSON(base+"/config.json");
1241
+ presets=await fetchJSON(base+"/presets.json");
1242
+ DSJ=await fetchJSON(DEC_STATE_URL);
1243
+ $("prompt").innerHTML=Object.keys(presets).map(p=>`<option>${p}</option>`).join("");
1244
+ const ep=["webgpu"];
1245
+ HIFLUSH={extra:{"ep.webgpuexecutionprovider.maxPendingDispatches":"100000"}};
1246
+ // ORT graphs: encoder (-> source) + fp32 streaming decoder. Temporal + depth are WGSL.
1247
+ const g={encoder:"encoder",decoder:"spectrostream_decoder"};
1248
+ const extMap=cfg.external_data||{};
1249
+ const items=[];
1250
+ for(const k in g){
1251
+ const fn = k==="decoder" ? "spectrostream_stream.onnx" : `${g[k]}.q4.onnx`;
1252
+ items.push({id:"g_"+k, url: k==="decoder" ? DEC_URL : `${base}/onnx/${fn}`});
1253
+ const df=extMap[fn]; if(df) items.push({id:"d_"+k, path:df, url:`${base}/onnx/${df}`}); }
1254
+ items.push({id:"emb", url:base+"/onnx/token_embedding_fp16.bin"});
1255
+ items.push({id:"quant", url:base+"/onnx/quantizer_fp16.bin"});
1256
+ // WGSL temporal weights (q4: packed nibbles + scales + small fp32 params)
1257
+ items.push({id:"temp_layout", url:TEMP_BASE+"temporal_q4_ort_layout.json", json:true});
1258
+ items.push({id:"temp_bin", url:TEMP_BASE+"temporal_q4_ort.bin"});
1259
+ // WGSL depth weights (q4)
1260
+ items.push({id:"depth_layout", url:DEPTH_BASE+"depth_q4_ort_layout.json", json:true});
1261
+ items.push({id:"depth_bin", url:DEPTH_BASE+"depth_q4_ort.bin"});
1262
+ const N=items.length, bufs={};
1263
+ for(let i=0;i<N;i++){ const it=items[i], name=it.url.split("/").pop();
1264
+ if(it.json){ bufs[it.id]=await fetchJSON(it.url); setBar((i+1)/N); continue; }
1265
+ bufs[it.id]=await fetchBuf(it.url, f=>{ setBar((i+f)/N); $("stat").textContent=`downloading ${name} — ${(f*100).toFixed(0)}% (${i+1}/${N})`; }); }
1266
+ setBar(1); $("stat").textContent="compiling ORT graphs…";
1267
+ for(const k in g){ const opts={executionProviders:ep}, d=items.find(x=>x.id==="d_"+k);
1268
+ if(d) opts.externalData=[{path:d.path, data:bufs["d_"+k]}];
1269
+ if(k==="decoder"){ opts.preferredOutputLocation={}; DSJ.keys.forEach((_,i)=>opts.preferredOutputLocation["ns_"+i]="gpu-buffer"); }
1270
+ S[k]=await ort.InferenceSession.create(bufs["g_"+k], opts); }
1271
+ EMB=f16decode(bufs.emb); QUANT=f16decode(bufs.quant);
1272
+
1273
+ // build BOTH custom WGSL engines on ORT's SAME WebGPU device (zero-copy handoff)
1274
+ const ortDevice = ort.env.webgpu.device;
1275
+ if(!ortDevice) throw new Error("ort.env.webgpu.device is null — WebGPU EP not initialized");
1276
+ // capture any GPU validation/out-of-memory errors that would otherwise be
1277
+ // silently swallowed (pipelines/bind groups invalid on ORT's shared device
1278
+ // -> garbage out). Surfaced via window.__DBG for headless verification.
1279
+ const __dbgErrs=[];
1280
+ try{ ortDevice.addEventListener("uncapturederror",e=>{ __dbgErrs.push(String(e.error&&e.error.message||e.error||e)); }); }catch(e){}
1281
+ window.__DBG = { ready:false, errors:__dbgErrs };
1282
+ $("stat").textContent="building WGSL temporal on ORT device…";
1283
+ TEMPORAL = await buildTemporal(ortDevice, bufs.temp_layout, bufs.temp_bin);
1284
+ $("stat").textContent="building WGSL depth on ORT device…";
1285
+ DEPTH = await buildDepth(ortDevice, bufs.depth_layout, bufs.depth_bin);
1286
+ // record layout/blob fingerprints so a hosted-vs-local byte mismatch is visible.
1287
+ const fp=(l,bin)=>({packed_byte_off:l.packed_byte_off,scale_byte_off:l.scale_byte_off,small_byte_off:l.small_byte_off,
1288
+ packed_words:l.packed_words,scale_floats:l.scale_floats,small_floats:l.small_floats,embed_scale:l.embed_scale,
1289
+ binBytes:bin.byteLength,nq4:Object.keys(l.q4||{}).length,nsmall:Object.keys(l.small||{}).length});
1290
+ window.__DBG = Object.assign(window.__DBG||{},{ tempLayout:fp(bufs.temp_layout,bufs.temp_bin), depthLayout:fp(bufs.depth_layout,bufs.depth_bin) });
1291
+
1292
+ // warm up: compile WebGPU shaders (temporal + depth) across the KV-growth range
1293
+ $("stat").textContent="warming up (compiling shaders)…"; setBar(0);
1294
+ try{ reset(); sourceF32=await encodeStyle(presets[$("prompt").value]); TEMPORAL.setSource(sourceF32);
1295
+ const W=(cfg.temporal&&cfg.temporal.max_past?cfg.temporal.max_past:T_KV_CAP)+4;
1296
+ for(let w=0;w<W;w++){ const wt=performance.now(); const c=await genFrame(1.1); history.push(c); const ms=performance.now()-wt;
1297
+ setBar((w+1)/W); $("stat").textContent=`warming up ${w+1}/${W} · ${ms.toFixed(0)} ms/frame (temporal ${TEMP_MS.toFixed(1)} · depth ${DEPTH_MS.toFixed(1)} ms)`;
1298
+ await new Promise(r=>setTimeout(r)); }
1299
+ // ---- debug hook: after warmup, capture temporal-out + first depth output ----
1300
+ try{
1301
+ reset(); TEMPORAL.setSource(sourceF32);
1302
+ TEMPORAL.runTemporal(prevToks); // one temporal step (BOS prev)
1303
+ const t=await TEMPORAL.debugReadOut(); // read temporal out[1024]
1304
+ const noise=Float32Array.from({length:Q()*CODEBOOK_SIZE},()=>Math.random());
1305
+ const {codes,toks}=await DEPTH.runDepth(TEMPORAL.outBuf, noise, 1.1);
1306
+ window.__DBG = Object.assign(window.__DBG||{}, {
1307
+ ready:true,
1308
+ tempOutAbsmax:t.absmax, tempOutHasNaN:t.hasNaN, tempOutFirst4:t.first4,
1309
+ depthCodes:codes, depthToks:toks, errors:__dbgErrs,
1310
+ });
1311
+ console.log("__DBG", window.__DBG);
1312
+ }catch(e){ window.__DBG = Object.assign(window.__DBG||{}, { ready:false, dbgError:String(e), errors:__dbgErrs }); console.warn("dbg:",e); }
1313
+ if(history.length>=10){ const w=await streamDecode(history.slice(-10)); dispose(w); }
1314
+ reset(); }catch(e){ console.warn("warmup:",e); window.__DBG=Object.assign(window.__DBG||{},{warmupError:String(e)}); }
1315
+ $("prog").style.display="none"; $("play").disabled=false;
1316
+ $("stat").innerHTML=`ready · <code>webgpu</code> · <code>WGSL temporal + WGSL depth</code> — warmed, press Play`;
1317
+ }catch(e){ $("prog").style.display="none"; $("stat").textContent="load failed: "+e.message; $("load").disabled=false; console.error(e); }
1318
+ };
1319
+
1320
+ // ── Web Audio streaming ──
1321
+ let actx=null,analyser=null,nextT=0,playing=false,freq=null;
1322
+ function playSamples(data,start,end){ const n=end-start; if(n<1)return;
1323
+ const buf=actx.createBuffer(2,n,48000), L=buf.getChannelData(0), R=buf.getChannelData(1);
1324
+ for(let i=0;i<n;i++){ L[i]=data[(start+i)*2]; R[i]=data[(start+i)*2+1]; }
1325
+ const s=actx.createBufferSource(); s.buffer=buf; s.connect(analyser);
1326
+ if(nextT<actx.currentTime+0.05)nextT=actx.currentTime+0.15; s.start(nextT); nextT+=n/48000; }
1327
+ function viz(){ const c=$("viz"),g=c.getContext("2d"),w=c.width,h=c.height; g.clearRect(0,0,w,h);
1328
+ if(analyser){ analyser.getByteFrequencyData(freq); const bw=w/48;
1329
+ for(let i=0;i<48;i++){ const v=freq[i*2]/255; g.fillStyle=`hsl(${70-v*40},85%,${45+v*15}%)`; g.fillRect(i*bw,h-v*h,bw-1,v*h);} }
1330
+ requestAnimationFrame(viz); } viz();
1331
+
1332
+ $("play").onclick=async()=>{
1333
+ actx=new AudioContext({sampleRate:48000}); await actx.resume(); nextT=actx.currentTime+0.2;
1334
+ analyser=actx.createAnalyser(); analyser.fftSize=128; analyser.connect(actx.destination); freq=new Uint8Array(analyser.frequencyBinCount);
1335
+ $("play").disabled=true; $("stop").disabled=false; playing=true;
1336
+ reset(); sourceF32=await encodeStyle(presets[$("prompt").value]); TEMPORAL.setSource(sourceF32);
1337
+ const CHUNK=10; let done=0, firstChunk=true; const t0=performance.now();
1338
+ // running averages for the breakdown line
1339
+ let aT=0,aD=0,aC=0,nT=0;
1340
+ while(playing){
1341
+ if(pendingStyle){ const old=sourceF32; sourceF32=await encodeStyle(presets[pendingStyle]); TEMPORAL.setSource(sourceF32); pendingStyle=null; }
1342
+ const nf=[];
1343
+ for(let i=0;i<CHUNK&&playing;i++){ const c=await genFrame(1.1); history.push(c); nf.push(c); done++;
1344
+ aT+=TEMP_MS; aD+=DEPTH_MS; nT++; }
1345
+ if(nf.length===CHUNK){
1346
+ const dt=performance.now();
1347
+ const wav=await streamDecode(nf);
1348
+ const data=wav.data ?? await wav.getData(); DEC_MS=performance.now()-dt;
1349
+ aC+=DEC_MS;
1350
+ const start=firstChunk?1920:0; firstChunk=false;
1351
+ playSamples(data, start, wav.dims[1]); dispose(wav);
1352
+ }
1353
+ const sec=done/cfg.frames_per_second, rt=sec/((performance.now()-t0)/1000);
1354
+ $("rt").textContent=`${rt.toFixed(2)}× realtime`;
1355
+ $("stat").textContent=`generating · ${sec.toFixed(1)}s · ${rt.toFixed(2)}× realtime`;
1356
+ // per-frame breakdown (decode is per-10-frame chunk -> /CHUNK to show per-frame)
1357
+ const chunks=Math.max(1,Math.round(nT/CHUNK));
1358
+ $("brk").textContent=`temporal ${(aT/Math.max(1,nT)).toFixed(1)} ms · depth ${(aD/Math.max(1,nT)).toFixed(1)} ms · decode ${(aC/Math.max(1,chunks)).toFixed(1)} ms/chunk`;
1359
+ }
1360
+ };
1361
+ $("stop").onclick=()=>{ playing=false; if(actx)actx.suspend(); $("play").disabled=false; $("stop").disabled=true; $("stat").textContent="stopped"; };
1362
+ $("prompt").onchange=()=>{ if(playing) pendingStyle=$("prompt").value; };
1363
+ </script>
1364
+ </body>
1365
+ </html>