interplane.Get Omega
Read in your language

aienos.com

Source of www.aienos.com, served from my own hardware

Brought by drakestapleton

branch main Branches Tags History

aienos.com / om / lab-page / client.om

31 lines · 11922 bytes Raw Blame History
1note /lab/ browser glue authored and emitted by seeded Omega: lab.js on fd 1, the run worker on fd 3.
2text j0 "'use strict';\n(() => {\n /* /lab/: compile Omega on the shared gateway, run the wasm in a worker in this\n tab, check its checksum against an independent reference. Every number here is measured in this\n tab or read from /lab/record.tsv, which record.sh wrote on the Spark. */\n const $ = (id) => document.getElementById(id);\n const src = $('lab-src');\n if (!src) return;\n const ORIGINAL = src.value;\n const LINE = 'ret add mul a x y';\n const API = '/aien/api/omega';\n const LIMIT_MS = 15000;\n const fmt = (x) => Number(x).toLocaleString('en-US');\n const ms = (x) => `${x < 10 ? x.toFixed(2) : x < 100 ? x.toFixed(1) : Math.round(x)} ms`;\n const state = { bytes: null, recorded: '', worker: null, timer: 0, label: 'prebuilt' };\n const status = (text, kind) => {\n const box = $('lab-status');\n box.textContent = text;\n box.dataset.kind = kind || '';\n };\n async function sha256(bytes) {\n if (!crypto.subtle) return '';\n const d = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes));\n return Array.from(d, (b) => b.toString(16).padStart(2, '0')).join('');\n }\n function hexdump(bytes) {\n const rows = [];\n for (let i = 0; i < Math.min(bytes.length, 1024); i += 16) {\n const row = Array.from(bytes.subarray(i, i + 16), (b) => b.toString(16).padStart(2, '0')).join(' ');\n rows.push(`${i.toString(16).padStart(4, '0')} ${row}`);\n }\n if (bytes.length > 1024) rows.push(`... ${fmt(bytes.length - 1024)} more bytes`);\n return rows.join('\\n');\n }\n function worker() {\n if (state.worker) return state.worker;\n state.worker = new Worker('/js/lab-worker.js');\n return state.worker;\n }\n function stop() {\n clearTimeout(state.timer);\n if (state.worker) state.worker.terminate();\n state.worker = null;\n state.bytes = null;\n }\n function ask(message) {\n return new Promise((resolve) => {\n const w = worker();\n state.timer = setTimeout(() => {\n stop();\n resolve({ type: 'error', message: `Stopped after ${LIMIT_MS / 1000} s. The worker was ended, so this tab stays responsive.` });\n }, LIMIT_MS);\n w.onmessage = (event) => { clearTimeout(state.timer); resolve(event.data); };\n w.onerror = (event) => { clearTimeout(state.timer); stop(); resolve({ type: 'error', message: event.message || 'worker failed' }); };\n w.postMessage(message);\n });\n }\n async function show(reply, label) {\n if (reply.type !== 'loaded') { status(reply.message, 'fail'); return false; }\n state.bytes = reply.bytes;\n state.label = label;\n const hash = await sha256(reply.bytes);\n const same = hash && hash === state.recorded;\n $('lab-wasm').textContent = hexdump(reply.bytes);\n $('lab-wasm-meta').textContent = `${label}: ${fmt(reply.bytes.length)} bytes, ${reply.imports} imports, exports ${reply.exports.join(', ')}. sha256 ${hash || 'unavailable'}${same ? ', byte for byte the file record.sh built on the Spark' : ''}.`;\n return true;\n }\n async function prebuilt() {\n stop();\n return show(await ask({ type: 'prebuilt' }), 'prebuilt /lab/axpy.wasm');\n }\n function choice() {\n const a = Math.max(1, Math.min(1000, Math.round(Number($('lab-a').value) || 3)));\n const n = Number($('lab-n').value);\n $('lab-a').value = a;\n return { a, n };\n }\n async function run() {\n if (!state.bytes && !(await prebuilt())) return;\n const { a, n } = choice();\n status(`Running ${fmt(n)} elements three times in a worker...`, 'wait');\n $('lab-run').disabled = true;\n const reply = await ask({ type: 'run', a, n });\n $('lab-run').disabled = false;\n if (reply.type !== 'ran') { status(reply.message, 'fail'); return; }\n const match = reply.sum === reply.ref;\n $('lab-r-sum').textContent = fmt(reply.sum);\n $('lab-r-wasm').textContent = `${ms(reply.wasm)} (${reply.wasmMs.map(ms).join(', ')})`;\n $('lab-r-rate').textContent = `${fmt(Math.round(n / reply.wasm / 1000))} million elements per second`;\n $('lab-verdict').textContent = match\n ? `MATCH. ${fmt(n)} elements, a = ${a}, ${state.label}.`\n : `MISMATCH. The kernel and the reference disagree. ${state.label}.`;\n $('lab-verdict').dataset.kind = match ? 'pass' : 'fail';\n for (const cell of document.querySelectorAll('[data-live]')) {\n const key = cell.dataset.live;\n cell.textContent = key === 'n' ? fmt(n) : key === 'time' ? ms(reply.wasm) : match ? 'MATCH' : 'MISMATCH';\n }\n status(match ? 'Checked: every element went into the checksum.' : 'The check caught a wrong kernel.', match ? 'pass' : 'fail');\n }\n async function compile(label) {\n const source = src.value;\n status('Compiling on the gateway: omc check, IR, irwasm...', 'wait');\n $('lab-compile').disabled = true;\n stop();\n const reply = await ask({ type: 'compile', source });\n $('lab-compile').disabled = false;\n if (reply.trip !== undefined) $('lab-c-trip').textContent = ms(reply.trip);\n if (reply.type === 'refused') {\n const where = reply.line ? `line ${reply.line}: ` : '';\n status(`${reply.stage ? `${reply.stage} ` : ''}${reply.code ? `error ${reply.code} ` : ''}${where}${reply.message || 'compile failed'}${reply.hint ? `. ${reply.hint}` : ''}`, 'fail');\n if (reply.line) {\n const lines = source.split('\\n');\n const start = lines.slice(0, reply.line - 1).join('\\n').length + (reply.line > 1 ? 1 : 0);\n src.focus();\n src.setSelectionRange(start, start + (lines[reply.line - 1] || '').length);\n }\n return false;\n }\n if (reply.type === 'loaded') {\n $('lab-c-server').textContent = `${fmt(reply.compileMs)} ms`;\n $('lab-c-pin').textContent = `omc ${String(reply.omc || '').slice(0, 12)}, irwasm ${String(reply.irwasm || '').slice(0, 12)}`;\n }\n const ok = await show(reply, label || 'your compile');\n if (ok) await run();\n return ok;\n }\n async function start() {\n $('lab-run').addEventListener('click', run);\n $('lab-compile').addEventListener('click', () => compile('your compile'));\n $('lab-break').addEventListener('click', () => {\n if (!src.value.includes(LINE)) src.value = ORIGINAL;\n src.value = src.value.replace(LINE, 'ret sub mul a x y');\n compile('broken on purpose: add changed to sub');\n });\n $('lab-reset').addEventListener('click', () => { src.value = ORIGINAL; status('Source reset. Compile or run.', ''); });\n const copy = $('lab-copy');\n if (copy) copy.addEventListener('click', async () => {\n try { await navigator.clipboard.writeText($('lab-home-cmd').textContent); copy.textContent = 'Copied'; } catch { copy.textContent = 'Select and copy'; }\n setTimeout(() => { copy.textContent = 'Copy'; }, 2000);\n });\n try {\n const tsv = await (await fetch('/lab/record.tsv', { cache: 'no-cache' })).text();\n"
3text j1 " const rec = Object.fromEntries(tsv.trim().split('\\n').map((l) => l.split('\\t')));\n state.recorded = rec.wasm_sha256 || '';\n for (const cell of document.querySelectorAll('[data-us]')) if (rec[cell.dataset.us]) cell.textContent = ms(Number(rec[cell.dataset.us]) / 1000);\n for (const cell of document.querySelectorAll('[data-bytes]')) if (rec[cell.dataset.bytes]) cell.textContent = `${fmt(rec[cell.dataset.bytes])} bytes`;\n } catch { /* the cells keep their link to record.tsv */ }\n try {\n if (await prebuilt()) status('Ready. Run uses the prebuilt kernel; Compile builds your edit on the gateway.', 'pass');\n } catch (err) {\n status(`Could not load the prebuilt kernel: ${err.message}`, 'fail');\n }\n }\n start();\n})();\n"
4text w0 "'use strict';\n/* Runs the compiled Omega kernel off the main thread. The page can stop this\n worker at any time, so a kernel that loops for a long time never freezes the tab.\n The worker only executes wasm it fetched itself: the prebuilt /lab/axpy.wasm or\n the reply of the compile gateway. Messages carry Omega source text and numbers,\n never code. The wasm has no imports: it cannot touch the page, the network or storage. */\nconst API = '/aien/api/omega';\nconst BLOCK = 999999;\nlet kernel = null;\nfunction median(xs) { const s = xs.slice().sort((p, q) => p - q); return s[(s.length - 1) >> 1]; }\nasync function install(bytes) {\n const module = await WebAssembly.compile(bytes);\n const imports = WebAssembly.Module.imports(module).length;\n if (imports) throw new Error(`This module asks for ${imports} imports; the lab runs only self-contained kernels.`);\n kernel = await WebAssembly.instantiate(module, {});\n return { type: 'loaded', bytes, imports, exports: WebAssembly.Module.exports(module).map((e) => e.name) };\n}\nasync function compile(source) {\n const t = performance.now();\n let reply;\n try {\n const response = await fetch(API, { method: 'POST', credentials: 'omit', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ source }) });\n reply = (response.headers.get('content-type') || '').includes('json') ? await response.json() : { ok: false, message: `HTTP ${response.status}` };\n } catch (err) {\n reply = { ok: false, message: `The compile service is unreachable (${err.message}). The prebuilt kernel still runs.` };\n }\n const trip = performance.now() - t;\n if (!reply.ok) return { type: 'refused', trip, stage: reply.stage, code: reply.code, line: reply.line, message: reply.message, hint: reply.hint };\n const loaded = await install(Uint8Array.from(atob(reply.wasm), (c) => c.charCodeAt(0)));\n return Object.assign(loaded, { trip, compileMs: reply.compile_ms, omc: reply.omc_sha256, irwasm: reply.irwasm_sha256 });\n}\nfunction run(a, n) {\n if (!kernel || typeof kernel.exports.run !== 'function') {\n return { type: 'error', message: 'This module has no run export. Keep fn run a long lo long hi long to long.' };\n }\n const go = kernel.exports.run;\n const big = BigInt(a);\n const wasmMs = [];\n const jsMs = [];\n let sum = 0n;\n let ref = 0;\n for (let rep = 0; rep < 3; rep++) {\n let t = performance.now();\n let s = 0n;\n for (let lo = 0; lo < n; lo += BLOCK) s += go(big, BigInt(lo), BigInt(Math.min(n, lo + BLOCK)));\n wasmMs.push(performance.now() - t);\n sum = s;\n t = performance.now();\n let r = 0;\n for (let i = 0; i < n; i++) r += a * i + (2 * i + 1);\n jsMs.push(performance.now() - t);\n ref = r;\n }\n return { type: 'ran', sum: sum.toString(), ref: BigInt(ref).toString(), wasmMs, jsMs, wasm: median(wasmMs), js: median(jsMs) };\n}\nself.onmessage = async (event) => {\n const job = event.data || {};\n try {\n if (job.type === 'prebuilt') self.postMessage(await install(new Uint8Array(await (await fetch('/lab/axpy.wasm')).arrayBuffer())));\n else if (job.type === 'compile') self.postMessage(await compile(String(job.source)));\n else if (job.type === 'run') self.postMessage(run(Math.max(1, Math.min(1000, Math.round(Number(job.a)) || 3)), Math.max(1, Math.min(4194304, Math.round(Number(job.n)) || 1))));\n } catch (err) {\n const message = String((err && err.message) || err);\n self.postMessage({ type: 'error', message: err instanceof WebAssembly.RuntimeError ? `The kernel trapped: ${message}. Omega stops on integer overflow instead of wrapping.` : message });\n }\n};\n"
5fn main to int
6pos = ulong 0
7while lt pos len j0 bound 65536
8n = write 1 j0 pos sub len j0 pos
9if le n 0
10ret 1
11end
12pos = add pos ulong n
13end
14pos = ulong 0
15while lt pos len j1 bound 65536
16n = write 1 j1 pos sub len j1 pos
17if le n 0
18ret 1
19end
20pos = add pos ulong n
21end
22pos = ulong 0
23while lt pos len w0 bound 65536
24n = write 3 w0 pos sub len w0 pos
25if le n 0
26ret 1
27end
28pos = add pos ulong n
29end
30ret 0
31end