Taylor commited on
Commit
699a27f
·
1 Parent(s): 4dda1bd

feat: Aether engine speed dustoff -- PyTorch vs WASM-SIMD

Browse files

Same model (SmolLM2-360M-Instruct Q8_0). Same prompt. Same tokens.
Pure engine comparison. No training differences, no decoder tricks.

PyTorch: ~2.8GB runtime, C++/CUDA/MKL, Python bindings
Aether: 14KB WASM binary + JS, SIMD128, zero ML dependencies

Both run in parallel. Whichever finishes first shows first.
Cyan accent.

Files changed (6) hide show
  1. Dockerfile +17 -0
  2. README.md +6 -5
  3. aether-server.mjs +393 -0
  4. app.py +209 -0
  5. requirements.txt +7 -0
  6. simd-kernels.wasm +3 -0
Dockerfile ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ RUN apt-get update && apt-get install -y curl && \
4
+ curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \
5
+ apt-get install -y nodejs && \
6
+ rm -rf /var/lib/apt/lists/*
7
+
8
+ WORKDIR /app
9
+
10
+ COPY requirements.txt .
11
+ RUN pip install --no-cache-dir --extra-index-url https://download.pytorch.org/whl/cpu -r requirements.txt
12
+
13
+ COPY app.py aether-server.mjs simd-kernels.wasm ./
14
+
15
+ RUN mkdir -p /tmp/hf_cache
16
+ EXPOSE 7860
17
+ CMD ["python", "app.py"]
README.md CHANGED
@@ -1,10 +1,11 @@
1
  ---
2
- title: Aether
3
- emoji: 😻
4
  colorFrom: blue
5
  colorTo: blue
6
  sdk: docker
7
- pinned: false
 
 
 
8
  ---
9
-
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Aether - Engine Speed Comparison
3
+ emoji: "\u26A1"
4
  colorFrom: blue
5
  colorTo: blue
6
  sdk: docker
7
+ app_port: 7860
8
+ pinned: true
9
+ models:
10
+ - bartowski/SmolLM2-360M-Instruct-GGUF
11
  ---
 
 
aether-server.mjs ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Aether Inference Server
3
+ *
4
+ * SmolLM2-360M inference using WASM SIMD kernels.
5
+ * Zero external ML dependencies. Pure JS + 14KB WASM binary.
6
+ */
7
+
8
+ import { createServer } from 'http';
9
+ import { readFileSync, existsSync } from 'fs';
10
+ import { execSync } from 'child_process';
11
+ import { fileURLToPath } from 'url';
12
+ import { dirname, join } from 'path';
13
+
14
+ const __dirname = dirname(fileURLToPath(import.meta.url));
15
+ const PORT = parseInt(process.env.AETHER_PORT || '7861');
16
+
17
+ // ─── SmolLM2-360M Config ────────────────────────────────────────────────────
18
+ const C = {
19
+ hiddenDim: 960, numLayers: 32, numHeads: 15, numKvHeads: 5,
20
+ headDim: 64, intermediateSize: 2560, vocabSize: 49152,
21
+ ropeTheta: 100000.0, rmsNormEps: 1e-5, eosToken: 2,
22
+ };
23
+ const kvDim = C.numKvHeads * C.headDim; // 320
24
+ const gqaRatio = C.numHeads / C.numKvHeads; // 3
25
+
26
+ // ─── WASM SIMD ──────────────────────────────────────────────────────────────
27
+ let simd = null;
28
+
29
+ async function loadSIMD() {
30
+ const p = join(__dirname, 'simd-kernels.wasm');
31
+ if (!existsSync(p)) return null;
32
+ try {
33
+ const { instance } = await WebAssembly.instantiate(readFileSync(p), {
34
+ env: { expf: Math.exp, tanhf: Math.tanh, powf: Math.pow },
35
+ });
36
+ const w = instance.exports;
37
+ w.resetHeap(65536);
38
+ const mem = w.memory;
39
+ const hf = () => new Float32Array(mem.buffer);
40
+ const cp = (ptr, f) => hf().set(f, ptr >> 2);
41
+ const rd = (ptr, n) => hf().slice(ptr >> 2, (ptr >> 2) + n);
42
+
43
+ const wrap = (fn) => (...args) => {
44
+ const s = w.getHeapPtr();
45
+ try { return fn(s, ...args); }
46
+ finally { w.resetHeap(s); }
47
+ };
48
+
49
+ console.log('[Aether] WASM SIMD loaded');
50
+ return {
51
+ matVec: wrap((s, mat, vec, rows, cols) => {
52
+ if (mat.byteLength > 100_000_000) return matVecJS(mat, vec, rows, cols);
53
+ const mP = w.allocate(mat.byteLength); const vP = w.allocate(vec.byteLength);
54
+ const rP = w.allocate(rows * 4);
55
+ cp(mP, mat); cp(vP, vec);
56
+ w.matVecSimdBatch4(mP, vP, rP, rows, cols);
57
+ return rd(rP, rows);
58
+ }),
59
+ rmsNorm: wrap((s, x, wt, eps) => {
60
+ const xP = w.allocate(x.byteLength); const wP = w.allocate(wt.byteLength);
61
+ const rP = w.allocate(x.byteLength);
62
+ cp(xP, x); cp(wP, wt);
63
+ w.rmsNormSimd(xP, wP, rP, x.length, eps);
64
+ return rd(rP, x.length);
65
+ }),
66
+ softmax: wrap((s, x) => {
67
+ const xP = w.allocate(x.byteLength); const rP = w.allocate(x.byteLength);
68
+ cp(xP, x); w.softmaxSimd(xP, rP, x.length);
69
+ return rd(rP, x.length);
70
+ }),
71
+ fusedSiluMul: wrap((s, g, u) => {
72
+ const gP = w.allocate(g.byteLength); const uP = w.allocate(u.byteLength);
73
+ const rP = w.allocate(g.byteLength);
74
+ cp(gP, g); cp(uP, u);
75
+ w.fusedSiluMul(gP, uP, rP, g.length);
76
+ return rd(rP, g.length);
77
+ }),
78
+ add: wrap((s, a, b) => {
79
+ const aP = w.allocate(a.byteLength); const bP = w.allocate(b.byteLength);
80
+ const rP = w.allocate(a.byteLength);
81
+ cp(aP, a); cp(bP, b);
82
+ w.addSimd(aP, bP, rP, a.length);
83
+ return rd(rP, a.length);
84
+ }),
85
+ };
86
+ } catch (e) { console.warn('[Aether] WASM failed:', e.message); return null; }
87
+ }
88
+
89
+ // ─── JS Fallbacks ───────────────────────────────────────────────────────────
90
+ function matVecJS(m, v, rows, cols) {
91
+ const o = new Float32Array(rows);
92
+ for (let r = 0; r < rows; r++) { let s = 0; const off = r * cols; for (let c = 0; c < cols; c++) s += m[off+c]*v[c]; o[r] = s; }
93
+ return o;
94
+ }
95
+ function rmsNormJS(x, w, eps) {
96
+ let ss = 0; for (let i = 0; i < x.length; i++) ss += x[i]*x[i];
97
+ ss = 1.0/Math.sqrt(ss/x.length+eps);
98
+ const o = new Float32Array(x.length); for (let i = 0; i < x.length; i++) o[i] = x[i]*ss*w[i]; return o;
99
+ }
100
+ function softmaxJS(x) {
101
+ let mx = -Infinity; for (let i = 0; i < x.length; i++) if (x[i]>mx) mx=x[i];
102
+ const o = new Float32Array(x.length); let s=0;
103
+ for (let i = 0; i < x.length; i++) { o[i]=Math.exp(x[i]-mx); s+=o[i]; }
104
+ for (let i = 0; i < x.length; i++) o[i]/=s; return o;
105
+ }
106
+ function fusedSiluMulJS(g, u) {
107
+ const o = new Float32Array(g.length);
108
+ for (let i = 0; i < g.length; i++) { const v=g[i]; o[i]=(v/(1+Math.exp(-v)))*u[i]; } return o;
109
+ }
110
+ function addJS(a, b) {
111
+ const o = new Float32Array(a.length); for (let i = 0; i < a.length; i++) o[i]=a[i]+b[i]; return o;
112
+ }
113
+
114
+ const op = () => ({
115
+ matVec: simd?.matVec || matVecJS, rmsNorm: simd?.rmsNorm || rmsNormJS,
116
+ softmax: simd?.softmax || softmaxJS, fusedSiluMul: simd?.fusedSiluMul || fusedSiluMulJS,
117
+ add: simd?.add || addJS,
118
+ });
119
+
120
+ // ─── Q8_0 Dequant ───────────────────────────────────────────────────────────
121
+ function fp16(lo, hi) {
122
+ const h = lo|(hi<<8), s=(h>>15)&1, e=(h>>10)&0x1f, f=h&0x3ff;
123
+ if (e===0) return f===0?0:(s?-1:1)*(f/1024)*Math.pow(2,-14);
124
+ if (e===31) return 0;
125
+ return (s?-1:1)*Math.pow(2,e-15)*(1+f/1024);
126
+ }
127
+ function dequantQ8(data, n) {
128
+ const o = new Float32Array(n), nb = Math.ceil(n/32);
129
+ for (let b=0;b<nb;b++) { const off=b*34, sc=fp16(data[off],data[off+1]);
130
+ const cnt=Math.min(32,n-b*32);
131
+ for (let i=0;i<cnt;i++) { const v=data[off+2+i]; o[b*32+i]=(v>127?v-256:v)*sc; }
132
+ } return o;
133
+ }
134
+ function dequantF32(data, n) { return new Float32Array(data.buffer, data.byteOffset, n); }
135
+
136
+ function dequantByType(data, n, type) {
137
+ if (type === 0) return dequantF32(data, n);
138
+ if (type === 8) return dequantQ8(data, n);
139
+ if (type === 1) { const o=new Float32Array(n); for(let i=0;i<n;i++) o[i]=fp16(data[i*2],data[i*2+1]); return o; }
140
+ return dequantQ8(data, n); // fallback
141
+ }
142
+
143
+ // ─── GGUF Parser ────────────────────────────────────────────────────────────
144
+ const MAGIC=0x46554747;
145
+ const BSZ={2:32,3:32,6:32,7:32,8:32,9:32,10:256,11:256,12:256,13:256,14:256,15:256};
146
+ const BBY={2:18,3:20,6:22,7:24,8:34,9:36,10:84,11:110,12:144,13:176,14:210,15:292};
147
+ const TSZ={0:4,1:2,16:1,17:2,18:4,19:8,20:8};
148
+ function csz(d,t){let n=1n;for(const x of d)n*=x;const b=BSZ[t];if(b&&BBY[t])return Math.ceil(Number(n)/b)*BBY[t];return Math.ceil(Number(n)*(TSZ[t]??4));}
149
+ function rs(b,o){const l=Number(b.readBigUInt64LE(o));return{v:b.subarray(o+8,o+8+l).toString('utf8'),o:o+8+l};}
150
+ function rv(b,o,t){switch(t){
151
+ case 0:return{v:b.readUInt8(o),o:o+1};case 1:return{v:b.readInt8(o),o:o+1};
152
+ case 2:return{v:b.readUInt16LE(o),o:o+2};case 3:return{v:b.readInt16LE(o),o:o+2};
153
+ case 4:return{v:b.readUInt32LE(o),o:o+4};case 5:return{v:b.readInt32LE(o),o:o+4};
154
+ case 6:return{v:b.readFloatLE(o),o:o+4};case 7:return{v:b.readUInt8(o)!==0,o:o+1};
155
+ case 8:{const r=rs(b,o);return{v:r.v,o:r.o};}
156
+ case 10:return{v:b.readBigUInt64LE(o),o:o+8};case 11:return{v:b.readBigInt64LE(o),o:o+8};
157
+ case 12:return{v:b.readDoubleLE(o),o:o+8};
158
+ case 9:{const at=b.readUInt32LE(o),al=Number(b.readBigUInt64LE(o+4));let co=o+12;const a=[];
159
+ for(let i=0;i<al;i++){const r=rv(b,co,at);a.push(r.v);co=r.o;}return{v:a,o:co};}
160
+ default:throw new Error(`Unknown GGUF type ${t}`);
161
+ }}
162
+ function parseGGUF(buf){
163
+ let o=0;if(buf.readUInt32LE(o)!==MAGIC)throw new Error('Not GGUF');o+=4;o+=4;
164
+ const tc=Number(buf.readBigUInt64LE(o));o+=8;const kc=Number(buf.readBigUInt64LE(o));o+=8;
165
+ let align=32;for(let i=0;i<kc;i++){const{v:k,o:o1}=rs(buf,o);o=o1;const vt=buf.readUInt32LE(o);o+=4;
166
+ const{v,o:o2}=rv(buf,o,vt);o=o2;if(k==='general.alignment')align=Number(v);}
167
+ const tensors=[];for(let i=0;i<tc;i++){const{v:name,o:o1}=rs(buf,o);o=o1;const nd=buf.readUInt32LE(o);o+=4;
168
+ const dims=[];for(let d=0;d<nd;d++){dims.push(buf.readBigUInt64LE(o));o+=8;}const type=buf.readUInt32LE(o);o+=4;
169
+ const offset=buf.readBigUInt64LE(o);o+=8;
170
+ tensors.push({name,dims,type,offset,size:csz(dims,type),numElements:Number(dims.reduce((a,b)=>a*b,1n))});}
171
+ return{tensors,dataOffset:Math.ceil(o/align)*align};
172
+ }
173
+
174
+ // ─── BPE Tokenizer ──────────────────────────────────────────────────────────
175
+ class Tok {
176
+ constructor(j){const m=j.model||{};this.vocab=m.vocab||{};this.rev={};
177
+ for(const[t,id]of Object.entries(this.vocab))this.rev[id]=t;
178
+ this.mr={};for(const[i,mg]of(m.merges||[]).entries())this.mr[mg]=i;
179
+ this.added={};if(j.added_tokens)for(const t of j.added_tokens)this.added[t.content]=t.id;}
180
+ encode(text){const sp=/<\|[^|]+\|>/g;const parts=[];let last=0,m;
181
+ while((m=sp.exec(text))!==null){if(m.index>last)parts.push({t:text.slice(last,m.index),s:false});
182
+ parts.push({t:m[0],s:true});last=m.index+m[0].length;}
183
+ if(last<text.length)parts.push({t:text.slice(last),s:false});
184
+ const tokens=[];for(const p of parts){
185
+ if(p.s){const id=this.added[p.t]??this.vocab[p.t];if(id!==undefined)tokens.push(id);continue;}
186
+ const words=p.t.match(/\S+|\s+/g)||[];for(const w of words){let syms=[];
187
+ for(const ch of w){if(this.vocab[ch]!==undefined)syms.push(ch);
188
+ else for(const b of Buffer.from(ch,'utf8'))syms.push(`<0x${b.toString(16).toUpperCase().padStart(2,'0')}>`)}
189
+ while(syms.length>1){let best=Infinity,bi=-1;
190
+ for(let i=0;i<syms.length-1;i++){const r=this.mr[`${syms[i]} ${syms[i+1]}`];if(r!==undefined&&r<best){best=r;bi=i;}}
191
+ if(bi===-1)break;syms.splice(bi,2,syms[bi]+syms[bi+1]);}
192
+ for(const s of syms){const id=this.vocab[s]??this.added[s];if(id!==undefined)tokens.push(id);}}}
193
+ return tokens;}
194
+ decode(tokens){const p=[];for(const t of tokens){const s=this.rev[t];
195
+ if(s&&s.startsWith('<0x')&&s.endsWith('>'))p.push(String.fromCharCode(parseInt(s.slice(3,-1),16)));
196
+ else if(s&&!s.startsWith('<|'))p.push(s);}
197
+ return p.join('').replace(/Ġ/g,' ').replace(/Ċ/g,'\n');}
198
+ }
199
+
200
+ // ─── RoPE (LLaMA style: ADJACENT pairs) ─────────────────────────────────────
201
+ // CRITICAL: SmolLM2/LLaMA pairs (x[i], x[i+1]), NOT (x[k], x[k+half])
202
+ function applyRoPE(x, headDim, position, theta) {
203
+ for (let i = 0; i < headDim; i += 2) {
204
+ const freqIdx = i / 2;
205
+ const freq = 1.0 / Math.pow(theta, (2 * freqIdx) / headDim);
206
+ const angle = position * freq;
207
+ const cos = Math.cos(angle), sin = Math.sin(angle);
208
+ const x0 = x[i], x1 = x[i + 1];
209
+ x[i] = x0 * cos - x1 * sin;
210
+ x[i + 1] = x0 * sin + x1 * cos;
211
+ }
212
+ }
213
+
214
+ // ─── Model ──────────────────────────────────────────────────────────────────
215
+ let model = null;
216
+
217
+ function loadModel(ggufPath, tokPath) {
218
+ const t0 = Date.now();
219
+ const buf = readFileSync(ggufPath);
220
+ const parsed = parseGGUF(buf);
221
+ console.log(`[Aether] Parsed ${parsed.tensors.length} tensors in ${Date.now()-t0}ms`);
222
+
223
+ const tokenizer = new Tok(JSON.parse(readFileSync(tokPath, 'utf8')));
224
+ const byName = {}; for (const t of parsed.tensors) byName[t.name] = t;
225
+
226
+ function get(name) {
227
+ const t = byName[name]; if (!t) return null;
228
+ const raw = new Uint8Array(buf.buffer, buf.byteOffset + parsed.dataOffset + Number(t.offset), t.size);
229
+ return dequantByType(raw, t.numElements, t.type);
230
+ }
231
+
232
+ console.log('[Aether] Dequantizing...');
233
+ const tokenEmbd = get('token_embd.weight');
234
+ const layers = [];
235
+ for (let i = 0; i < C.numLayers; i++) {
236
+ if (i % 8 === 0) console.log(`[Aether] Layer ${i}/${C.numLayers}`);
237
+ layers.push({
238
+ an: get(`blk.${i}.attn_norm.weight`), fn: get(`blk.${i}.ffn_norm.weight`),
239
+ qw: get(`blk.${i}.attn_q.weight`), kw: get(`blk.${i}.attn_k.weight`),
240
+ vw: get(`blk.${i}.attn_v.weight`), ow: get(`blk.${i}.attn_output.weight`),
241
+ gw: get(`blk.${i}.ffn_gate.weight`), uw: get(`blk.${i}.ffn_up.weight`),
242
+ dw: get(`blk.${i}.ffn_down.weight`),
243
+ });
244
+ }
245
+ const outNorm = get('output_norm.weight');
246
+ let outWeight = get('output.weight');
247
+ if (!outWeight) { console.log('[Aether] Tied embeddings'); outWeight = tokenEmbd; }
248
+
249
+ console.log(`[Aether] Loaded in ${((Date.now()-t0)/1000).toFixed(1)}s`);
250
+ model = { tokenEmbd, layers, outNorm, outWeight, tokenizer, loadTime: Date.now()-t0 };
251
+ }
252
+
253
+ // ─── Inference ──────────────────────────────────────────────────────────────
254
+ function generate(prompt, maxTokens = 8192) {
255
+ const t0 = performance.now();
256
+ const o = op();
257
+
258
+ const chatPrompt = `<|im_start|>user\n${prompt}<|im_end|>\n<|im_start|>assistant\n`;
259
+ const inputTokens = model.tokenizer.encode(chatPrompt);
260
+ const allTokens = [...inputTokens];
261
+
262
+ const kvCache = Array.from({ length: C.numLayers }, () => ({ k: [], v: [] }));
263
+ const tokenTimes = [];
264
+
265
+ for (let step = 0; step < inputTokens.length + maxTokens - 1; step++) {
266
+ const tStart = performance.now();
267
+ const pos = step, tid = allTokens[step];
268
+
269
+ // Embed
270
+ const x0 = model.tokenEmbd.slice(tid * C.hiddenDim, (tid + 1) * C.hiddenDim);
271
+ let x = x0;
272
+
273
+ for (let l = 0; l < C.numLayers; l++) {
274
+ const ly = model.layers[l];
275
+
276
+ // Attention: norm → QKV → RoPE → attention → O → residual
277
+ const normed = o.rmsNorm(x, ly.an, C.rmsNormEps);
278
+ const q = o.matVec(ly.qw, normed, C.hiddenDim, C.hiddenDim);
279
+ const k = o.matVec(ly.kw, normed, kvDim, C.hiddenDim);
280
+ const v = o.matVec(ly.vw, normed, kvDim, C.hiddenDim);
281
+
282
+ // RoPE per head -- LLaMA style (adjacent pairs)
283
+ for (let h = 0; h < C.numHeads; h++)
284
+ applyRoPE(q.subarray(h * C.headDim, (h+1) * C.headDim), C.headDim, pos, C.ropeTheta);
285
+ for (let h = 0; h < C.numKvHeads; h++)
286
+ applyRoPE(k.subarray(h * C.headDim, (h+1) * C.headDim), C.headDim, pos, C.ropeTheta);
287
+
288
+ kvCache[l].k.push(new Float32Array(k));
289
+ kvCache[l].v.push(new Float32Array(v));
290
+
291
+ // Multi-head attention with GQA
292
+ const seqLen = kvCache[l].k.length;
293
+ const attnOut = new Float32Array(C.hiddenDim);
294
+ for (let h = 0; h < C.numHeads; h++) {
295
+ const kvH = Math.floor(h / gqaRatio);
296
+ const qH = q.subarray(h * C.headDim, (h+1) * C.headDim);
297
+ const scores = new Float32Array(seqLen);
298
+ for (let s = 0; s < seqLen; s++) {
299
+ const kH = kvCache[l].k[s].subarray(kvH * C.headDim, (kvH+1) * C.headDim);
300
+ let dot = 0; for (let d = 0; d < C.headDim; d++) dot += qH[d] * kH[d];
301
+ scores[s] = dot / Math.sqrt(C.headDim);
302
+ }
303
+ const w = softmaxJS(scores);
304
+ for (let s = 0; s < seqLen; s++) {
305
+ const vH = kvCache[l].v[s].subarray(kvH * C.headDim, (kvH+1) * C.headDim);
306
+ const wt = w[s];
307
+ for (let d = 0; d < C.headDim; d++) attnOut[h * C.headDim + d] += wt * vH[d];
308
+ }
309
+ }
310
+
311
+ const projected = o.matVec(ly.ow, attnOut, C.hiddenDim, C.hiddenDim);
312
+ const postAttn = o.add(x, projected);
313
+
314
+ // FFN: norm → gate/up → fusedSiluMul → down → residual
315
+ const ffnIn = o.rmsNorm(postAttn, ly.fn, C.rmsNormEps);
316
+ const gate = o.matVec(ly.gw, ffnIn, C.intermediateSize, C.hiddenDim);
317
+ const up = o.matVec(ly.uw, ffnIn, C.intermediateSize, C.hiddenDim);
318
+ const activated = o.fusedSiluMul(gate, up);
319
+ const down = o.matVec(ly.dw, activated, C.hiddenDim, C.intermediateSize);
320
+ x = o.add(postAttn, down);
321
+ }
322
+
323
+ if (step >= inputTokens.length - 1) {
324
+ const finalNormed = o.rmsNorm(x, model.outNorm, C.rmsNormEps);
325
+ const logits = o.matVec(model.outWeight, finalNormed, C.vocabSize, C.hiddenDim);
326
+
327
+ for (let i = 0; i < logits.length; i++) logits[i] /= 0.7;
328
+ const probs = o.softmax(logits);
329
+
330
+ const indexed = Array.from(probs).map((p, i) => ({ p, i })).sort((a, b) => b.p - a.p);
331
+ let cumP = 0, chosen = indexed[0].i;
332
+ const r = Math.random();
333
+ for (const { p, i } of indexed) { cumP += p; if (r < cumP) { chosen = i; break; } if (cumP > 0.9) break; }
334
+
335
+ tokenTimes.push(performance.now() - tStart);
336
+ if (chosen === C.eosToken) break;
337
+ allTokens.push(chosen);
338
+ }
339
+ }
340
+
341
+ const totalTime = performance.now() - t0;
342
+ const genTokens = allTokens.slice(inputTokens.length);
343
+ const avgMs = tokenTimes.length > 0 ? tokenTimes.reduce((a, b) => a + b, 0) / tokenTimes.length : 0;
344
+
345
+ return {
346
+ text: model.tokenizer.decode(genTokens), tokens: genTokens.length,
347
+ totalTimeMs: Math.round(totalTime), avgTokenMs: Math.round(avgMs),
348
+ engine: `Aether ${simd ? 'WASM-SIMD' : 'JS'}`, simd: !!simd,
349
+ };
350
+ }
351
+
352
+ // ─── HTTP Server ────────────────────────────────────────────────────────────
353
+ const server = createServer((req, res) => {
354
+ if (req.method === 'POST' && req.url === '/generate') {
355
+ let body = '';
356
+ req.on('data', c => body += c);
357
+ req.on('end', () => {
358
+ try {
359
+ const { prompt, max_tokens } = JSON.parse(body);
360
+ const result = generate(prompt, max_tokens || 256);
361
+ res.writeHead(200, { 'Content-Type': 'application/json' });
362
+ res.end(JSON.stringify(result));
363
+ } catch (e) {
364
+ console.error('[Aether] Error:', e);
365
+ res.writeHead(500, { 'Content-Type': 'application/json' });
366
+ res.end(JSON.stringify({ error: e.message, stack: e.stack }));
367
+ }
368
+ });
369
+ } else if (req.url === '/health') {
370
+ res.writeHead(200, { 'Content-Type': 'application/json' });
371
+ res.end(JSON.stringify({ status: 'ok', model: model ? 'loaded' : 'not loaded', simd: !!simd, loadTime: model?.loadTime }));
372
+ } else { res.writeHead(404); res.end(); }
373
+ });
374
+
375
+ // ─── Main ───────────────────────────────────────────────────────────────────
376
+ const ggufPath = '/tmp/hf_cache/smollm2-360m-q8_0.gguf';
377
+ const tokPath = '/tmp/hf_cache/tokenizer.json';
378
+
379
+ async function main() {
380
+ simd = await loadSIMD();
381
+ if (!existsSync(ggufPath)) {
382
+ console.log('[Aether] Downloading base SmolLM2-360M Q8_0...');
383
+ execSync(`python3 -c "from huggingface_hub import hf_hub_download; hf_hub_download('bartowski/SmolLM2-360M-Instruct-GGUF', 'SmolLM2-360M-Instruct-Q8_0.gguf', cache_dir='/tmp/hf_cache', local_dir='/tmp/hf_cache'); import shutil; shutil.move('/tmp/hf_cache/SmolLM2-360M-Instruct-Q8_0.gguf', '${ggufPath}')"`, { stdio: 'inherit' });
384
+ }
385
+ if (!existsSync(tokPath)) {
386
+ console.log('[Aether] Downloading tokenizer...');
387
+ execSync(`python3 -c "from huggingface_hub import hf_hub_download; hf_hub_download('HuggingFaceTB/SmolLM2-360M-Instruct', 'tokenizer.json', cache_dir='/tmp/hf_cache', local_dir='/tmp/hf_cache')"`, { stdio: 'inherit' });
388
+ }
389
+ loadModel(ggufPath, tokPath);
390
+ server.listen(PORT, '127.0.0.1', () => console.log(`[Aether] http://127.0.0.1:${PORT} (SIMD: ${!!simd})`));
391
+ }
392
+
393
+ main().catch(e => { console.error('[Aether] Fatal:', e); process.exit(1); });
app.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Aether -- Pure Engine Speed Comparison
3
+ Same model. Same prompt. Same tokens. Different engine.
4
+ PyTorch CPU vs Aether WASM-SIMD. Let the ms/tok speak.
5
+ """
6
+
7
+ import gradio as gr
8
+ import torch
9
+ import json
10
+ import time
11
+ import subprocess
12
+ import urllib.request
13
+ import urllib.error
14
+ import select
15
+ from concurrent.futures import ThreadPoolExecutor, as_completed
16
+ from transformers import AutoModelForCausalLM, AutoTokenizer
17
+
18
+ print("[Aether] Starting Aether sidecar...", flush=True)
19
+ aether_proc = subprocess.Popen(
20
+ ["node", "aether-server.mjs"],
21
+ env={**__import__('os').environ, "AETHER_PORT": "7861"},
22
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
23
+ )
24
+
25
+ print("[Aether] Loading PyTorch model...", flush=True)
26
+ tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-360M-Instruct")
27
+ pytorch_model = AutoModelForCausalLM.from_pretrained(
28
+ "HuggingFaceTB/SmolLM2-360M-Instruct",
29
+ torch_dtype=torch.float32, device_map="cpu",
30
+ )
31
+ print("[Aether] PyTorch ready.", flush=True)
32
+
33
+ print("[Aether] Waiting for Aether engine...", flush=True)
34
+ for attempt in range(180):
35
+ try:
36
+ req = urllib.request.Request("http://127.0.0.1:7861/health")
37
+ resp = urllib.request.urlopen(req, timeout=2)
38
+ health = json.loads(resp.read())
39
+ if health.get("status") == "ok" and health.get("model") == "loaded":
40
+ print(f"[Aether] Engine ready ({health.get('loadTime')}ms, SIMD: {health.get('simd')})", flush=True)
41
+ break
42
+ except Exception:
43
+ pass
44
+ if aether_proc.stdout and select.select([aether_proc.stdout], [], [], 0)[0]:
45
+ line = aether_proc.stdout.readline()
46
+ if line: print(f" {line.decode().strip()}", flush=True)
47
+ time.sleep(1)
48
+
49
+
50
+ def gen_pytorch(prompt, max_tokens):
51
+ messages = [{"role": "user", "content": prompt}]
52
+ text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
53
+ inputs = tokenizer(text, return_tensors="pt")
54
+ t0 = time.perf_counter()
55
+ with torch.no_grad():
56
+ outputs = pytorch_model.generate(
57
+ **inputs, max_new_tokens=max_tokens, temperature=0.7, top_p=0.9,
58
+ do_sample=True, pad_token_id=tokenizer.eos_token_id,
59
+ )
60
+ elapsed = time.perf_counter() - t0
61
+ n = outputs.shape[1] - inputs["input_ids"].shape[1]
62
+ text = tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True).strip()
63
+ return text, elapsed, n, (elapsed * 1000 / n) if n > 0 else 0
64
+
65
+
66
+ def gen_aether(prompt, max_tokens):
67
+ try:
68
+ data = json.dumps({"prompt": prompt, "max_tokens": max_tokens}).encode()
69
+ req = urllib.request.Request("http://127.0.0.1:7861/generate", data=data,
70
+ headers={"Content-Type": "application/json"})
71
+ resp = urllib.request.urlopen(req, timeout=600)
72
+ r = json.loads(resp.read())
73
+ return r["text"], r["totalTimeMs"] / 1000, r["tokens"], r["avgTokenMs"]
74
+ except urllib.error.HTTPError as e:
75
+ body = e.read().decode() if e.fp else str(e)
76
+ try: detail = json.loads(body).get("error", body[:300])
77
+ except Exception: detail = body[:300]
78
+ return f"[Error: {detail}]", 0, 0, 0
79
+ except Exception as e:
80
+ return f"[Error: {e}]", 0, 0, 0
81
+
82
+
83
+ def compare(prompt, max_tokens):
84
+ empty = ("", "", "", "")
85
+ if not prompt or not prompt.strip():
86
+ yield empty
87
+ return
88
+
89
+ max_tokens = int(max_tokens)
90
+ pt_result = [None]
91
+ ae_result = [None]
92
+
93
+ def run_pt():
94
+ pt_result[0] = gen_pytorch(prompt, max_tokens)
95
+ def run_ae():
96
+ ae_result[0] = gen_aether(prompt, max_tokens)
97
+
98
+ def fmt(r):
99
+ if not r: return "running..."
100
+ return f"{r[2]} tokens in {r[1]:.1f}s ({r[3]:.0f}ms/tok)"
101
+
102
+ def build():
103
+ pt, ae = pt_result[0], ae_result[0]
104
+ return (
105
+ pt[0] if pt else "generating...",
106
+ ae[0] if ae else "generating...",
107
+ fmt(pt), fmt(ae),
108
+ )
109
+
110
+ with ThreadPoolExecutor(max_workers=2) as pool:
111
+ futures = {pool.submit(run_pt): "pt", pool.submit(run_ae): "ae"}
112
+ for future in as_completed(futures):
113
+ future.result()
114
+ yield build()
115
+ yield build()
116
+
117
+
118
+ CSS = """
119
+ .gradio-container { max-width: 1060px !important; margin: 0 auto !important; }
120
+ .gradio-container, .dark { background: #09090b !important; }
121
+ #hero { text-align: center; padding: 2rem 0 1rem; }
122
+ #hero h1 { font-size: 2.5rem; font-weight: 300; letter-spacing: -0.02em; color: #fafafa; margin: 0; }
123
+ #hero .accent { color: #06b6d4; }
124
+ #hero .subtitle { color: #71717a; font-size: 0.95rem; margin-top: 0.5rem; }
125
+ .response-card { background: #0c0c0f !important; border: 1px solid #1f1f23 !important; border-radius: 8px !important; }
126
+ .response-card textarea { background: #0c0c0f !important; border: none !important; color: #e4e4e7 !important; font-size: 0.95rem !important; line-height: 1.6 !important; }
127
+ .pt-label { color: #71717a !important; font-size: 0.8rem !important; text-transform: uppercase !important; letter-spacing: 0.05em !important; font-weight: 500 !important; }
128
+ .ae-label { color: #06b6d4 !important; font-size: 0.8rem !important; text-transform: uppercase !important; letter-spacing: 0.05em !important; font-weight: 500 !important; }
129
+ .stats-text { font-family: 'SF Mono', 'Fira Code', monospace !important; font-size: 0.85rem !important; color: #52525b !important; }
130
+ #prompt-input > label > span { display: none !important; }
131
+ #prompt-input textarea { background: #111114 !important; border: 1px solid #1f1f23 !important; border-radius: 8px !important; color: #fafafa !important; font-size: 1rem !important; padding: 1rem !important; }
132
+ #prompt-input textarea:focus { border-color: #06b6d4 !important; }
133
+ #gen-btn { background: #06b6d4 !important; border: none !important; border-radius: 8px !important; font-weight: 500 !important; font-size: 0.9rem !important; padding: 0.75rem 2rem !important; color: #09090b !important; }
134
+ .prompt-chip { background: #111114 !important; border: 1px solid #1f1f23 !important; border-radius: 6px !important; color: #a1a1aa !important; font-size: 0.85rem !important; }
135
+ .prompt-chip:hover { border-color: #06b6d4 !important; color: #fafafa !important; }
136
+ #footer { text-align: center; padding: 2rem 0; border-top: 1px solid #1f1f23; margin-top: 2rem; }
137
+ #footer p { color: #52525b; font-size: 0.8rem; }
138
+ #footer a { color: #06b6d4; text-decoration: none; }
139
+ footer.svelte-1ax1toq { display: none !important; }
140
+ .built-with { display: none !important; }
141
+ """
142
+
143
+ with gr.Blocks(css=CSS, theme=gr.themes.Base(primary_hue="cyan", neutral_hue="zinc"), title="Aether") as demo:
144
+
145
+ gr.HTML("""
146
+ <div id="hero">
147
+ <h1><span class="accent">Aether</span></h1>
148
+ <p class="subtitle">Pure engine speed comparison. Same model (SmolLM2-360M-Instruct). Same prompt. Same tokens.<br/>
149
+ Left: PyTorch CPU (2.8GB runtime, CUDA/MKL optimized).<br/>
150
+ Right: Aether (14KB WASM binary, pure JS + SIMD128, zero ML dependencies).<br/>
151
+ Both generate in parallel. Whichever finishes first shows first.</p>
152
+ </div>
153
+ """)
154
+
155
+ with gr.Row():
156
+ prompt = gr.Textbox(elem_id="prompt-input", placeholder="What is the shape of failure?", lines=2, label="Prompt", show_label=False, interactive=True, scale=4)
157
+ max_tok = gr.Slider(minimum=8, maximum=8192, value=64, step=1, label="Max tokens", scale=1)
158
+
159
+ btn = gr.Button("Generate", elem_id="gen-btn", variant="primary")
160
+
161
+ with gr.Row(equal_height=True):
162
+ with gr.Column():
163
+ gr.HTML('<p class="pt-label">PyTorch CPU (standard)</p>')
164
+ pt_out = gr.Textbox(lines=10, show_label=False, interactive=False, elem_classes=["response-card"])
165
+ pt_stats = gr.HTML('<p class="stats-text">--</p>')
166
+ with gr.Column(min_width=30):
167
+ gr.HTML('<p style="color:#27272a; text-align:center; padding-top:4rem; font-size:0.75rem; letter-spacing:0.1em;">VS</p>')
168
+ with gr.Column():
169
+ gr.HTML('<p class="ae-label">Aether WASM-SIMD (14KB)</p>')
170
+ ae_out = gr.Textbox(lines=10, show_label=False, interactive=False, elem_classes=["response-card"])
171
+ ae_stats = gr.HTML('<p class="stats-text">--</p>')
172
+
173
+ outputs = [pt_out, ae_out, pt_stats, ae_stats]
174
+ inputs = [prompt, max_tok]
175
+
176
+ def run(p, mt):
177
+ for pt, ae, ps, aes in compare(p, mt):
178
+ yield pt, ae, f'<p class="stats-text">{ps}</p>', f'<p class="stats-text">{aes}</p>'
179
+
180
+ btn.click(run, inputs, outputs)
181
+ prompt.submit(run, inputs, outputs)
182
+
183
+ gr.HTML('<p style="color:#52525b; font-size:0.8rem; margin-top:1.5rem; margin-bottom:0.5rem;">Try these:</p>')
184
+ with gr.Row():
185
+ for p in ["hello", "What is the shape of failure?", "Write a haiku about parallel universes.", "Explain entropy to a five-year-old."]:
186
+ gr.Button(p, size="sm", elem_classes=["prompt-chip"]).click(
187
+ fn=lambda x=p: x, outputs=[prompt]
188
+ ).then(fn=run, inputs=inputs, outputs=outputs)
189
+
190
+ gr.HTML("""
191
+ <div id="footer">
192
+ <p style="color:#a1a1aa; font-size:0.85rem; margin-bottom:0.5rem;">
193
+ SmolLM2-360M-Instruct &middot; Q8_0 GGUF &middot; Same weights, different engines
194
+ </p>
195
+ <p>
196
+ PyTorch: ~2.8GB runtime, C++/CUDA/MKL optimized, Python bindings<br/>
197
+ Aether: 14KB WASM + JS, SIMD128 vectorized, zero dependencies, runs anywhere
198
+ </p>
199
+ <p style="margin-top:1rem;">
200
+ <a href="https://forkracefold.com/">Whitepaper</a> &middot;
201
+ <a href="https://huggingface.co/spaces/forkjoin-ai/glossolalia">Glossolalia</a> &middot;
202
+ <a href="https://huggingface.co/spaces/forkjoin-ai/metacog">Metacog</a> &middot;
203
+ <a href="https://huggingface.co/spaces/forkjoin-ai/five-bules">Five Bules</a>
204
+ </p>
205
+ </div>
206
+ """)
207
+
208
+ if __name__ == "__main__":
209
+ demo.launch(server_name="0.0.0.0", server_port=7860)
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ torch>=2.1.0
2
+ transformers>=4.46.0
3
+ huggingface-hub>=0.26.0
4
+ sentencepiece>=0.2.0
5
+ accelerate>=1.0.0
6
+ gguf>=0.10.0
7
+ gradio>=5.0.0,<6.0.0
simd-kernels.wasm ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a05084c8998119797c6e80927678ce007e3285b78c6e7e8feee223ca4bb13636
3
+ size 14553