aienos.com
Source of www.aienos.com, served from my own hardware
Brought by drakestapleton
aienos.com / public / js / aien-speed.js
| 1 | (() => { |
| 2 | 'use strict'; |
| 3 | /* AienSpeed: a live inference speed test, mounted into any element with |
| 4 | window.AienSpeed.mount(el, options) and removed with unmount(). Every number |
| 5 | comes from the gateway's own stream: tok.t is the gateway clock in ms since |
| 6 | the run started, so the graph shows what the server measured, counted raw in |
| 7 | BUCKET_MS windows and never smoothed. The client first token is this page's |
| 8 | clock, from the Run press to the first tok event. Text reaches the page only |
| 9 | through textContent and text nodes. Nothing loads from outside. */ |
| 10 | const PRESETS = ['short', 'medium', 'long']; |
| 11 | const PRESET_NAMES = { short: 'Short', medium: 'Medium', long: 'Long' }; |
| 12 | const MAX_TOKENS = [64, 256, 512, 1024, 2048, 4096]; |
| 13 | const MAX_DEFAULT = 256; |
| 14 | const PARALLEL_MAX = 1024; |
| 15 | const STREAMS = [1, 2, 3, 4]; |
| 16 | const SWEEP_SIZES = [4096, 8192, 16384, 32768]; |
| 17 | const BUCKET_MS = 250; |
| 18 | const HISTORY_MAX = 50; |
| 19 | const PROMPT_BYTES = 49152; |
| 20 | const DEFAULTS = { |
| 21 | api: '/aien/api', |
| 22 | model: '', |
| 23 | server: "Drake's GB10 (DGX Spark)", |
| 24 | historyKey: 'aien.speed', |
| 25 | share: true, |
| 26 | }; |
| 27 | const OWN_COMMAND = 'cd aienos.com && python3 scripts/allen/allen_infer.py bench http://127.0.0.1:8000 --model <your-model>'; |
| 28 | const SHARE_ADDRESS = /^#r=([A-Za-z0-9_-]{1,65536})$/; |
| 29 | const OFFLINE_TEXT = 'The model is offline right now. The speed test is back when it is.'; |
| 30 | const OFFLINE_POLL_MS = 60000; |
| 31 | let lab = null; |
| 32 | let serial = 0; |
| 33 | function h(tag, props, ...kids) { |
| 34 | const node = document.createElement(tag); |
| 35 | if (props) { |
| 36 | for (const [key, value] of Object.entries(props)) { |
| 37 | if (value === undefined || value === null || value === false) continue; |
| 38 | if (key === 'class') node.className = value; |
| 39 | else if (key === 'text') node.textContent = value; |
| 40 | else if (key === 'hidden') node.hidden = true; |
| 41 | else node.setAttribute(key, value === true ? '' : String(value)); |
| 42 | } |
| 43 | } |
| 44 | for (const kid of kids) if (kid !== null && kid !== undefined && kid !== false) node.append(kid); |
| 45 | return node; |
| 46 | } |
| 47 | function setText(node, value) { |
| 48 | if (node && node.textContent !== value) node.textContent = value; |
| 49 | } |
| 50 | function cut(text, max) { |
| 51 | if (text.length <= max) return text; |
| 52 | const head = text.slice(0, max); |
| 53 | return /[\ud800-\udbff]$/.test(head) ? head.slice(0, -1) : head; |
| 54 | } |
| 55 | function retryAfter(response, body) { |
| 56 | const value = Number(body && body.retry_after !== undefined ? body.retry_after : response.headers.get('Retry-After')); |
| 57 | return Number.isFinite(value) && value > 0 ? Math.ceil(value) : 0; |
| 58 | } |
| 59 | async function copyText(source, node) { |
| 60 | if (node.dataset.label === undefined) node.dataset.label = node.textContent; |
| 61 | try { |
| 62 | await navigator.clipboard.writeText(source); |
| 63 | setText(node, 'Copied'); |
| 64 | } catch (_) { |
| 65 | setText(node, 'Copy blocked'); |
| 66 | } |
| 67 | setTimeout(() => setText(node, node.dataset.label), 1500); |
| 68 | } |
| 69 | /* Incremental server-sent events: a chunk may end anywhere, even inside a line. */ |
| 70 | function sse(onEvent) { |
| 71 | let carry = ''; |
| 72 | let name = ''; |
| 73 | let data = []; |
| 74 | function line(text) { |
| 75 | if (text === '') { |
| 76 | if (data.length) onEvent(name || 'message', data.join('\n')); |
| 77 | name = ''; |
| 78 | data = []; |
| 79 | return; |
| 80 | } |
| 81 | if (text.startsWith(':')) return; |
| 82 | const colon = text.indexOf(':'); |
| 83 | const field = colon < 0 ? text : text.slice(0, colon); |
| 84 | let value = colon < 0 ? '' : text.slice(colon + 1); |
| 85 | if (value.startsWith(' ')) value = value.slice(1); |
| 86 | if (field === 'event') name = value; |
| 87 | else if (field === 'data') data.push(value); |
| 88 | } |
| 89 | return { |
| 90 | feed(chunk) { |
| 91 | carry += chunk; |
| 92 | let start = 0; |
| 93 | for (;;) { |
| 94 | const end = carry.indexOf('\n', start); |
| 95 | if (end < 0) break; |
| 96 | line(carry.slice(start, end).replace(/\r$/, '')); |
| 97 | start = end + 1; |
| 98 | } |
| 99 | carry = carry.slice(start); |
| 100 | }, |
| 101 | end() { |
| 102 | if (carry) line(carry.replace(/\r$/, '')); |
| 103 | carry = ''; |
| 104 | line(''); |
| 105 | }, |
| 106 | }; |
| 107 | } |
| 108 | function choices(values, selected, label) { |
| 109 | return values.map((value) => h('option', { value: String(value), selected: value === selected, text: label ? label(value) : String(value) })); |
| 110 | } |
| 111 | function build(host, options) { |
| 112 | serial += 1; |
| 113 | const id = (name) => `aien-speed-${serial}-${name}`; |
| 114 | const presetButtons = PRESETS.map((name) => h('button', { type: 'button', class: 'sp-preset', 'data-preset': name, 'aria-pressed': 'false' }, |
| 115 | h('span', { class: 'sp-preset-name', text: PRESET_NAMES[name] }), |
| 116 | h('span', { class: 'sp-preset-n', text: 'max tokens set by the server' }))); |
| 117 | const radio = (value, text, checked) => h('label', { class: 'sp-mode' }, |
| 118 | h('input', { type: 'radio', name: id('mode'), value, checked }), ' ', h('span', { text })); |
| 119 | const streams = h('select', { 'aria-label': 'Streams' }, ...choices(STREAMS, 4)); |
| 120 | const sweep = h('select', { 'aria-label': 'Largest prompt' }, ...choices(SWEEP_SIZES, 4096, (size) => `${size / 1024}k`)); |
| 121 | const modes = h('fieldset', { class: 'sp-modes' }, |
| 122 | h('legend', { text: 'Mode' }), |
| 123 | radio('single', 'Single', true), radio('concurrent', 'Parallel', false), radio('sweep', 'Context sweep', false), |
| 124 | h('label', { class: 'sp-opt', 'data-for': 'concurrent', hidden: true }, 'Streams ', streams), |
| 125 | h('label', { class: 'sp-opt', 'data-for': 'sweep', hidden: true }, 'Up to ', sweep, ' prompt tokens')); |
| 126 | const prompt = h('textarea', { id: id('prompt'), rows: 3, maxlength: PROMPT_BYTES, autocomplete: 'off', placeholder: 'Or write your own prompt. An empty box runs the last preset.' }); |
| 127 | const max = h('select', { 'aria-label': 'Max tokens' }, ...choices(MAX_TOKENS, MAX_DEFAULT)); |
| 128 | const run = h('button', { type: 'button', class: 'sp-run', text: 'Run' }); |
| 129 | const halt = h('button', { type: 'button', class: 'sp-stop', text: 'Stop', disabled: true }); |
| 130 | const status = h('p', { class: 'sp-status', role: 'status', 'aria-live': 'polite' }); |
| 131 | const heroNumber = h('span', { class: 'sp-hero-n', text: '-' }); |
| 132 | const heroText = h('span', { class: 'sp-hero-t' }); |
| 133 | const canvas = h('canvas', { width: 940, height: 240, role: 'img', 'aria-label': 'Tokens per second since the start of the run' }); |
| 134 | const caption = h('figcaption', {}); |
| 135 | const outputs = h('div', { class: 'sp-outputs' }); |
| 136 | const verify = h('p', { class: 'sp-verify', hidden: true }); |
| 137 | const results = h('dl', { class: 'sp-results' }); |
| 138 | const label = h('p', { class: 'sp-label' }); |
| 139 | const share = h('button', { type: 'button', class: 'sp-tool', text: 'Copy share link', disabled: true }); |
| 140 | const clear = h('button', { type: 'button', class: 'sp-tool', text: 'Clear' }); |
| 141 | const history = h('table', {}, |
| 142 | h('thead', {}, h('tr', {}, ...['When', 'Mode', 'TTFT ms', 'Prefill tok/s', 'Decode tok/s', 'Aggregate tok/s', 'Tokens out', 'In flight', 'Load'] |
| 143 | .map((text) => h('th', { scope: 'col', text })))), |
| 144 | h('tbody', {})); |
| 145 | const own = h('code', { text: OWN_COMMAND }); |
| 146 | const ownCopy = h('button', { type: 'button', class: 'sp-tool', text: 'Copy' }); |
| 147 | const panel = h('section', { class: 'sp-panel', 'aria-label': 'Live speed test', 'data-mode': 'single', 'data-state': 'idle' }, |
| 148 | h('div', { class: 'sp-presets', role: 'group', 'aria-label': 'Presets: one press runs a test' }, ...presetButtons), |
| 149 | modes, |
| 150 | h('p', { class: 'sp-note', 'data-for': 'single concurrent', text: 'A preset runs at once, with a fixed prompt and token limit, so runs compare. Run sends your own prompt, or the last preset when the box is empty.' }), |
| 151 | h('p', { class: 'sp-note', 'data-for': 'concurrent', hidden: true, text: `Parallel sends the same prompt as 1 to 4 streams at once, each capped at ${PARALLEL_MAX} tokens, and adds up their speed.` }), |
| 152 | h('p', { class: 'sp-note', 'data-for': 'sweep', hidden: true, text: 'A sweep doubles the prompt from 512 tokens up to the size you pick and asks for 8 tokens each step. Every step is a cold prefill (nothing cached), so a 32k sweep takes minutes. Presets and your prompt do not apply.' }), |
| 153 | h('div', { class: 'sp-compose' }, |
| 154 | h('label', { class: 'sp-sr', for: id('prompt'), text: 'Your own prompt' }), |
| 155 | prompt, |
| 156 | h('div', { class: 'sp-actions' }, h('label', { class: 'sp-max' }, 'Max tokens ', max), run, halt)), |
| 157 | h('div', { class: 'sp-readout' }, status, h('p', { class: 'sp-hero', 'aria-hidden': 'true' }, heroNumber, heroText)), |
| 158 | h('figure', { class: 'sp-graph' }, canvas, caption), |
| 159 | outputs, |
| 160 | h('section', { class: 'sp-box', 'aria-label': 'Result of the run' }, |
| 161 | h('h3', { class: 'sp-h', text: 'Result' }), verify, results, label, h('p', { class: 'sp-share' }, share)), |
| 162 | h('section', { class: 'sp-box', 'aria-label': 'Your runs' }, |
| 163 | h('h3', { class: 'sp-h' }, 'Your runs ', clear), |
| 164 | h('div', { class: 'sp-table' }, history), |
| 165 | h('p', { class: 'sp-note', text: `Kept only in this browser, newest first, at most ${HISTORY_MAX} runs. Clear removes them.` })), |
| 166 | h('section', { class: 'sp-box', 'aria-label': 'Run this on your own GPU' }, |
| 167 | h('h3', { class: 'sp-h', text: 'Run this on your own GPU' }), |
| 168 | h('div', { class: 'sp-cmd' }, own, ownCopy), |
| 169 | h('p', { class: 'sp-note', text: 'From a copy of the aienos.com repository, which is moving to Interplane (downloads are not open yet). Same presets and the same measurement code as this page, against any OpenAI-compatible server.' }))); |
| 170 | host.classList.add('aien-speed'); |
| 171 | host.replaceChildren(panel); |
| 172 | return { |
| 173 | host, options, panel, presetButtons, modes, prompt, max, run, halt, streams, sweep, status, heroNumber, heroText, canvas, |
| 174 | caption, outputs, verify, results, label, share, clear, history, own, ownCopy, |
| 175 | routes: { infer: `${options.api}/infer`, verify: `${options.api}/infer-verify`, info: `${options.api}/infer-info` }, |
| 176 | preset: 'short', info: null, active: null, view: null, shared: null, link: '', timer: 0, frame: 0, |
| 177 | offline: false, poll: 0, off: [], |
| 178 | }; |
| 179 | } |
| 180 | function labNumber(value) { |
| 181 | return typeof value === 'number' && Number.isFinite(value) ? value : NaN; |
| 182 | } |
| 183 | function labRate(value) { |
| 184 | const number = labNumber(value); |
| 185 | return Number.isNaN(number) ? '-' : number.toFixed(1); |
| 186 | } |
| 187 | function labMs(value) { |
| 188 | const number = labNumber(value); |
| 189 | return Number.isNaN(number) ? '-' : String(Math.round(number)); |
| 190 | } |
| 191 | function labWord(value, size) { |
| 192 | return typeof value === 'string' || typeof value === 'number' ? String(value).slice(0, size) : '-'; |
| 193 | } |
| 194 | function labModeName(mode) { |
| 195 | return { single: 'Single', concurrent: 'Parallel', sweep: 'Context sweep' }[mode] || 'Unknown'; |
| 196 | } |
| 197 | function labList(result) { |
| 198 | const list = Array.isArray(result.streams_out) ? result.streams_out : []; |
| 199 | return list.filter((item) => item && typeof item === 'object').slice(0, 64); |
| 200 | } |
| 201 | function labEach(list, key, format) { |
| 202 | return list.length ? list.map((item) => format(item[key])).join(' / ') : '-'; |
| 203 | } |
| 204 | function labSlots() { |
| 205 | return lab.info && Number.isSafeInteger(lab.info.slots) ? lab.info.slots : 4; |
| 206 | } |
| 207 | function labSize(tokens) { |
| 208 | return tokens >= 1024 && tokens % 1024 === 0 ? `${tokens / 1024}k` : String(tokens); |
| 209 | } |
| 210 | function labSay(text, wait) { |
| 211 | clearInterval(lab.timer); |
| 212 | if (!wait) { |
| 213 | setText(lab.status, text); |
| 214 | return; |
| 215 | } |
| 216 | let left = wait; |
| 217 | const show = () => setText(lab.status, left > 0 ? `${text}: busy, try again in ${left} s.` : `${text}. You can try again now.`); |
| 218 | show(); |
| 219 | lab.timer = setInterval(() => { |
| 220 | left -= 1; |
| 221 | show(); |
| 222 | if (left <= 0) clearInterval(lab.timer); |
| 223 | }, 1000); |
| 224 | } |
| 225 | function labRefusal(status, reply) { |
| 226 | const code = reply && typeof reply.error === 'string' ? reply.error : ''; |
| 227 | const limits = lab.info && lab.info.limits && typeof lab.info.limits === 'object' ? lab.info.limits : {}; |
| 228 | if (code === 'offline') return OFFLINE_TEXT; |
| 229 | if (status === 503 || code === 'busy') return 'Every test slot is taken'; |
| 230 | if (status === 429 || code === 'rate') { |
| 231 | const runs = Number.isSafeInteger(limits.runs_per_min) ? limits.runs_per_min : 6; |
| 232 | const heavy = Number.isSafeInteger(limits.heavy_per_10min) ? limits.heavy_per_10min : 3; |
| 233 | return `That is more runs than the limit (${runs} a minute, ${heavy} heavy tests in 10 minutes)`; |
| 234 | } |
| 235 | if (status === 409 || code === 'one_at_a_time') return 'You already have a test running, maybe in another tab. Let it finish first'; |
| 236 | if (status === 413 || code === 'too_long') return 'That prompt is too long: at most 48 KiB and about 32768 tokens'; |
| 237 | if (status === 400 || code === 'bad_request') return `The gateway could not read that request${reply && typeof reply.message === 'string' ? `: ${reply.message.slice(0, 200)}` : ''}`; |
| 238 | return `The speed test is not answering right now (HTTP ${status})`; |
| 239 | } |
| 240 | function labIdle() { |
| 241 | const info = lab.info; |
| 242 | if (!info || lab.active || lab.shared || lab.offline) return; |
| 243 | const busy = Number.isSafeInteger(info.tests_in_flight) ? info.tests_in_flight : 0; |
| 244 | const queue = Number.isSafeInteger(info.queue) ? info.queue : 0; |
| 245 | labSay(`Ready. ${busy} of ${labSlots()} test slots busy${queue ? `, ${queue} in line` : ''}. Press a preset.`); |
| 246 | } |
| 247 | function labLabel(source) { |
| 248 | const model = typeof source.model === 'string' && source.model ? source.model.slice(0, 80) : lab.options.model; |
| 249 | const flight = source.server_in_flight; |
| 250 | let text = `Live shared server: ${lab.options.server}${model ? `, ${model}` : ''}. Numbers vary with load`; |
| 251 | if (Number.isSafeInteger(flight)) text += `; ${flight} ${flight === 1 ? 'request was' : 'requests were'} in flight on the server when this run started`; |
| 252 | if (!Number.isNaN(labNumber(source.load1))) text += `, host load ${source.load1}`; |
| 253 | setText(lab.label, `${text}.`); |
| 254 | } |
| 255 | function labCaption(sweep) { |
| 256 | setText(lab.caption, sweep |
| 257 | ? 'Prefill tokens per second against prompt tokens (log2 scale), one point per step, from the server count: raw, no smoothing.' |
| 258 | : `Tokens per second against seconds since the start, one line per stream: raw, ${BUCKET_MS} ms buckets, no smoothing.`); |
| 259 | lab.canvas.setAttribute('aria-label', sweep ? 'Prefill tokens per second for each prompt size' : 'Tokens per second since the start of the run'); |
| 260 | } |
| 261 | function labMode() { |
| 262 | const pick = lab.modes.querySelector('input[type="radio"]:checked'); |
| 263 | return pick ? pick.value : 'single'; |
| 264 | } |
| 265 | function labModeShow() { |
| 266 | const mode = labMode(); |
| 267 | lab.panel.dataset.mode = mode; |
| 268 | for (const node of lab.panel.querySelectorAll('[data-for]')) node.hidden = !node.dataset.for.split(' ').includes(mode); |
| 269 | for (const option of lab.max.options) option.disabled = mode === 'concurrent' && Number(option.value) > PARALLEL_MAX; |
| 270 | if (mode === 'concurrent' && Number(lab.max.value) > PARALLEL_MAX) lab.max.value = String(PARALLEL_MAX); |
| 271 | lab.max.disabled = mode === 'sweep' || Boolean(lab.active); |
| 272 | lab.prompt.disabled = mode === 'sweep'; |
| 273 | for (const item of lab.presetButtons) item.disabled = Boolean(lab.active) || lab.offline || mode === 'sweep'; |
| 274 | lab.run.disabled = Boolean(lab.active) || lab.offline; |
| 275 | } |
| 276 | function labBusy(on) { |
| 277 | lab.panel.dataset.state = on ? 'running' : lab.offline ? 'offline' : 'idle'; |
| 278 | lab.halt.disabled = !on; |
| 279 | for (const input of lab.modes.querySelectorAll('input, select')) input.disabled = on; |
| 280 | labModeShow(); |
| 281 | } |
| 282 | /* While the model is down, infer-info says server_ok false: the pane says so, |
| 283 | turns its run controls off, and asks again every OFFLINE_POLL_MS. */ |
| 284 | function labOffline(on) { |
| 285 | lab.offline = on; |
| 286 | clearTimeout(lab.poll); |
| 287 | lab.poll = on ? setTimeout(labInfo, OFFLINE_POLL_MS) : 0; |
| 288 | if (!lab.active) labBusy(false); |
| 289 | if (on && !lab.shared) labSay(OFFLINE_TEXT); |
| 290 | labPaint(); |
| 291 | } |
| 292 | async function labInfo() { |
| 293 | const mine = lab; |
| 294 | try { |
| 295 | const response = await fetch(mine.routes.info, { cache: 'no-store', credentials: 'omit' }); |
| 296 | if (!response.ok) return; |
| 297 | const info = await response.json(); |
| 298 | if (lab !== mine || !info || typeof info !== 'object') return; |
| 299 | lab.info = info; |
| 300 | const presets = info.presets && typeof info.presets === 'object' ? info.presets : {}; |
| 301 | for (const item of lab.presetButtons) { |
| 302 | const preset = presets[item.dataset.preset]; |
| 303 | if (!preset || typeof preset !== 'object') continue; |
| 304 | if (Number.isSafeInteger(preset.max_tokens)) setText(item.querySelector('.sp-preset-n'), `${preset.max_tokens} tokens`); |
| 305 | if (typeof preset.prompt === 'string') item.title = cut(preset.prompt, 300); |
| 306 | } |
| 307 | if (info.server_ok === false) { |
| 308 | labOffline(true); |
| 309 | return; |
| 310 | } |
| 311 | if (lab.offline) labOffline(false); |
| 312 | labIdle(); |
| 313 | } catch (_) { |
| 314 | /* The presets still run with the server's own numbers. */ |
| 315 | } |
| 316 | } |
| 317 | function labView(mode) { |
| 318 | return { |
| 319 | mode, click: performance.now(), first: NaN, start: null, done: null, yielded: null, |
| 320 | outcome: '', tokens: 0, series: [], lanes: [], marks: [], steps: [], stepAt: 0, |
| 321 | }; |
| 322 | } |
| 323 | function labLaneName(view, index) { |
| 324 | if (view.mode === 'sweep') { |
| 325 | const size = view.steps[index]; |
| 326 | return `Step ${index + 1}${Number.isSafeInteger(size) ? `: ${labSize(size)} prompt tokens` : ''}`; |
| 327 | } |
| 328 | return view.mode === 'single' ? 'Output' : `Stream ${index + 1}`; |
| 329 | } |
| 330 | function labLane(view, index) { |
| 331 | while (view.lanes.length <= index) { |
| 332 | const number = view.lanes.length; |
| 333 | const tally = h('span', { class: 'sp-out-tally' }); |
| 334 | const text = h('pre', { class: 'sp-text' }); |
| 335 | const stats = h('p', { class: 'sp-out-stats' }); |
| 336 | lab.outputs.append(h('div', { class: view.mode === 'sweep' ? 'sp-step' : 'sp-out', 'data-lane': number % 4 }, |
| 337 | h('p', { class: 'sp-out-head' }, h('span', { class: 'sp-out-name', text: labLaneName(view, number) }), tally), |
| 338 | text, stats)); |
| 339 | view.lanes.push({ text, tally, stats, buf: '', shown: 0, count: 0, stat: null }); |
| 340 | } |
| 341 | return view.lanes[index]; |
| 342 | } |
| 343 | function labStat(stat, mode) { |
| 344 | const parts = []; |
| 345 | if (mode === 'sweep') parts.push(`${labWord(stat.prompt_tokens, 12)} prompt tokens`); |
| 346 | parts.push(`first token ${labMs(stat.ttft_ms)} ms`); |
| 347 | parts.push(`prefill ${labRate(stat.prefill_tps)} tok/s`); |
| 348 | if (mode !== 'sweep') parts.push(`decode ${labRate(stat.decode_tps)} tok/s`); |
| 349 | parts.push(`${labWord(stat.completion_tokens, 12)} tokens out in ${labMs(stat.total_ms)} ms`); |
| 350 | if (typeof stat.finish === 'string') parts.push(`finish ${stat.finish.slice(0, 24)}`); |
| 351 | return parts.join(', '); |
| 352 | } |
| 353 | function labRows(result, view) { |
| 354 | const list = labList(result); |
| 355 | const streams = Number.isSafeInteger(result.streams) && result.streams > 1 ? `, ${result.streams} streams` : ''; |
| 356 | const max = Number.isSafeInteger(result.max_tokens) && result.mode !== 'sweep' ? `, max ${result.max_tokens} tokens` : ''; |
| 357 | let client = 'not in a shared link'; |
| 358 | if (view) client = Number.isNaN(view.first) ? '-' : `${Math.round(view.first - view.click)} ms`; |
| 359 | const rows = [ |
| 360 | ['Mode', `${labModeName(result.mode)}${streams}${max}${result.yielded === true ? ', yielded to a live chat' : ''}`], |
| 361 | ['First token, server (ms)', labEach(list, 'ttft_ms', labMs)], |
| 362 | ['First token, from Run', client], |
| 363 | ['Prefill tok/s', labEach(list, 'prefill_tps', labRate)], |
| 364 | ['Decode tok/s', labEach(list, 'decode_tps', labRate)], |
| 365 | ['Total (ms)', `${labEach(list, 'total_ms', labMs)}${Number.isNaN(labNumber(result.wall_ms)) ? '' : `, wall ${labMs(result.wall_ms)}`}`], |
| 366 | ['Tokens in / out', list.length ? list.map((item) => `${labWord(item.prompt_tokens, 12)} / ${labWord(item.completion_tokens, 12)}`).join(', ') : '-'], |
| 367 | ]; |
| 368 | if (result.mode === 'concurrent') rows.push(['Aggregate tok/s', labRate(result.aggregate_tps)]); |
| 369 | rows.push(['Server requests in flight at start', labWord(result.server_in_flight, 12)]); |
| 370 | rows.push(['Test slots in use', `${labWord(result.tests_in_flight, 12)} of ${labSlots()}`]); |
| 371 | rows.push(['Host load (1 min)', labWord(result.load1, 12)]); |
| 372 | if (typeof result.run === 'string' && result.run) rows.push(['Run', `${result.run.slice(0, 40)}${typeof result.utc === 'string' && result.utc ? ` at ${result.utc.slice(0, 40)}` : ''}`]); |
| 373 | return rows; |
| 374 | } |
| 375 | function labResult(result, view) { |
| 376 | lab.results.replaceChildren(...labRows(result, view).map(([name, value]) => h('div', { class: 'sp-stat' }, h('dt', { text: name }), h('dd', { text: value })))); |
| 377 | labLabel(result); |
| 378 | } |
| 379 | function labPartial(view) { |
| 380 | const start = view.start || {}; |
| 381 | return { |
| 382 | mode: view.mode, model: start.model, run: start.run, streams: start.streams, |
| 383 | max_tokens: start.max_tokens, server_in_flight: start.server_in_flight, |
| 384 | tests_in_flight: start.tests_in_flight, load1: start.load1, |
| 385 | streams_out: view.lanes.map((lane) => lane.stat).filter(Boolean), |
| 386 | }; |
| 387 | } |
| 388 | function historyRead() { |
| 389 | try { |
| 390 | const rows = JSON.parse(localStorage.getItem(lab.options.historyKey) || '[]'); |
| 391 | return Array.isArray(rows) ? rows.filter((row) => row && typeof row === 'object').slice(0, HISTORY_MAX) : []; |
| 392 | } catch (_) { |
| 393 | return []; |
| 394 | } |
| 395 | } |
| 396 | function historyWrite(rows) { |
| 397 | try { |
| 398 | localStorage.setItem(lab.options.historyKey, JSON.stringify(rows.slice(0, HISTORY_MAX))); |
| 399 | } catch (_) { |
| 400 | /* A full or blocked store keeps the table as it was. */ |
| 401 | } |
| 402 | } |
| 403 | function historyClear() { |
| 404 | try { |
| 405 | localStorage.removeItem(lab.options.historyKey); |
| 406 | } catch (_) { |
| 407 | /* Nothing stored. */ |
| 408 | } |
| 409 | historyShow(); |
| 410 | } |
| 411 | function historyAdd(result, link) { |
| 412 | const list = labList(result); |
| 413 | const streams = Number.isSafeInteger(result.streams) && result.streams > 1 ? ` x${result.streams}` : ''; |
| 414 | const out = list.reduce((sum, item) => sum + (Number.isSafeInteger(item.completion_tokens) ? item.completion_tokens : 0), 0); |
| 415 | historyWrite([{ |
| 416 | when: typeof result.utc === 'string' ? result.utc.slice(0, 40) : new Date().toISOString(), |
| 417 | mode: `${labModeName(result.mode)}${streams}${result.yielded === true ? ' (yielded)' : ''}`, |
| 418 | ttft: labEach(list, 'ttft_ms', labMs), |
| 419 | prefill: labEach(list, 'prefill_tps', labRate), |
| 420 | decode: result.mode === 'sweep' ? '-' : labEach(list, 'decode_tps', labRate), |
| 421 | agg: result.mode === 'concurrent' ? labRate(result.aggregate_tps) : '-', |
| 422 | out: String(out), |
| 423 | inflight: labWord(result.server_in_flight, 12), |
| 424 | load: labWord(result.load1, 12), |
| 425 | share: link, |
| 426 | }, ...historyRead()]); |
| 427 | historyShow(); |
| 428 | } |
| 429 | function historyShow() { |
| 430 | const body = lab.history.tBodies[0]; |
| 431 | const rows = historyRead(); |
| 432 | body.replaceChildren(...rows.map((row) => { |
| 433 | const stamp = labWord(row.when, 40).replace('T', ' ').slice(0, 19); |
| 434 | const shared = lab.options.share && typeof row.share === 'string' && /^[A-Za-z0-9_-]{1,65536}$/.test(row.share); |
| 435 | const when = h('td', {}, shared ? h('a', { href: `#r=${row.share}`, text: stamp }) : stamp); |
| 436 | return h('tr', {}, when, ...['mode', 'ttft', 'prefill', 'decode', 'agg', 'out', 'inflight', 'load'].map((key) => h('td', { text: labWord(row[key], 200) }))); |
| 437 | })); |
| 438 | if (!rows.length) body.append(h('tr', {}, h('td', { class: 'sp-empty', colspan: 9, text: 'No runs yet. Your runs appear here, kept only in this browser.' }))); |
| 439 | lab.clear.disabled = !rows.length; |
| 440 | } |
| 441 | function labPack(text) { |
| 442 | let binary = ''; |
| 443 | for (const byte of new TextEncoder().encode(text)) binary += String.fromCharCode(byte); |
| 444 | return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); |
| 445 | } |
| 446 | function labUnpack(text) { |
| 447 | const plain = text.replace(/-/g, '+').replace(/_/g, '/'); |
| 448 | const binary = atob(plain + '='.repeat((4 - (plain.length % 4)) % 4)); |
| 449 | const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0)); |
| 450 | return new TextDecoder('utf-8', { fatal: true }).decode(bytes); |
| 451 | } |
| 452 | function labVerdict(verdict) { |
| 453 | lab.verify.hidden = false; |
| 454 | lab.verify.dataset.state = verdict === true ? 'ok' : verdict === false ? 'bad' : 'unknown'; |
| 455 | setText(lab.verify, verdict === true |
| 456 | ? 'Verified: produced by this gateway' |
| 457 | : verdict === false |
| 458 | ? 'Not verified: this link was edited or is from another server' |
| 459 | : 'Not checked: the gateway did not answer. Open the link again later.'); |
| 460 | } |
| 461 | async function labShared() { |
| 462 | const match = SHARE_ADDRESS.exec(location.hash); |
| 463 | if (!lab.options.share || !match || lab.active) return; |
| 464 | const mine = lab; |
| 465 | let payload = null; |
| 466 | try { |
| 467 | payload = JSON.parse(labUnpack(match[1])); |
| 468 | } catch (_) { |
| 469 | payload = null; |
| 470 | } |
| 471 | lab.view = null; |
| 472 | lab.link = ''; |
| 473 | lab.share.disabled = true; |
| 474 | lab.outputs.replaceChildren(); |
| 475 | const readable = payload && typeof payload === 'object' && payload.result && typeof payload.result === 'object' |
| 476 | && !Array.isArray(payload.result) && typeof payload.sig === 'string' && /^[0-9a-f]{16,256}$/.test(payload.sig); |
| 477 | if (!readable) { |
| 478 | lab.shared = null; |
| 479 | lab.results.replaceChildren(); |
| 480 | labVerdict(false); |
| 481 | labSay('This share link could not be read.'); |
| 482 | labDirty(); |
| 483 | return; |
| 484 | } |
| 485 | lab.shared = payload; |
| 486 | const result = payload.result; |
| 487 | labResult(result, null); |
| 488 | labCaption(result.mode === 'sweep'); |
| 489 | labSay(`Showing a shared run${typeof result.utc === 'string' ? ` from ${result.utc.slice(0, 40)}` : ''}. Press a preset to run your own.`); |
| 490 | lab.verify.hidden = false; |
| 491 | lab.verify.dataset.state = 'checking'; |
| 492 | setText(lab.verify, 'Checking this link with the gateway.'); |
| 493 | labDirty(); |
| 494 | let verdict = null; |
| 495 | try { |
| 496 | const response = await fetch(mine.routes.verify, { |
| 497 | method: 'POST', |
| 498 | headers: { 'Content-Type': 'application/json' }, |
| 499 | body: JSON.stringify({ result, sig: payload.sig }), |
| 500 | cache: 'no-store', |
| 501 | credentials: 'omit', |
| 502 | }); |
| 503 | if (response.status < 500) { |
| 504 | const reply = await response.json().catch(() => null); |
| 505 | verdict = Boolean(response.ok && reply && reply.ok === true); |
| 506 | } |
| 507 | } catch (_) { |
| 508 | verdict = null; |
| 509 | } |
| 510 | if (lab === mine && lab.shared === payload) labVerdict(verdict); |
| 511 | } |
| 512 | function labCopyLink() { |
| 513 | if (lab.link) copyText(`${location.origin}${location.pathname}${location.search}#r=${lab.link}`, lab.share); |
| 514 | } |
| 515 | function labEvent(name, data, view) { |
| 516 | let value; |
| 517 | try { |
| 518 | value = JSON.parse(data); |
| 519 | } catch (_) { |
| 520 | return; |
| 521 | } |
| 522 | if (!value || typeof value !== 'object') return; |
| 523 | if (name === 'queue') { |
| 524 | if (value.reason === 'chat') labSay('Waiting: a live chat is running; tests yield to chat.'); |
| 525 | else labSay(`In line: position ${labWord(value.position, 6)}, ${labWord(value.tests_in_flight, 6)} of ${labWord(value.slots, 6)} test slots busy.`); |
| 526 | } else if (name === 'start') { |
| 527 | view.start = value; |
| 528 | view.steps = Array.isArray(value.steps) ? value.steps.filter(Number.isSafeInteger).slice(0, 16) : []; |
| 529 | const lanes = view.mode === 'sweep' ? view.steps.length : Number.isSafeInteger(value.streams) ? Math.min(value.streams, 4) : 1; |
| 530 | for (let index = 0; index < Math.max(lanes, 1); index += 1) labLane(view, index); |
| 531 | labResult(labPartial(view), view); |
| 532 | labSay(view.mode === 'sweep' |
| 533 | ? `Sweep running: ${view.steps.length} steps, up to ${labSize(view.steps[view.steps.length - 1] || 0)} prompt tokens.` |
| 534 | : 'Running: reading the prompt, waiting for the first token.'); |
| 535 | } else if (name === 'tok') { |
| 536 | const index = value.i; |
| 537 | const time = labNumber(value.t); |
| 538 | if (!Number.isSafeInteger(index) || index < 0 || index > 15 || Number.isNaN(time) || time < 0) return; |
| 539 | if (Number.isNaN(view.first)) { |
| 540 | view.first = performance.now(); |
| 541 | labResult(labPartial(view), view); |
| 542 | if (view.mode !== 'sweep') labSay('Streaming.'); |
| 543 | } |
| 544 | view.tokens += 1; |
| 545 | const lane = labLane(view, index); |
| 546 | if (typeof value.s === 'string') lane.buf += value.s; |
| 547 | lane.count += 1; |
| 548 | if (view.mode !== 'sweep') { |
| 549 | const bucket = Math.floor(time / BUCKET_MS); |
| 550 | const series = view.series[index] || (view.series[index] = []); |
| 551 | while (series.length <= bucket) series.push(0); |
| 552 | series[bucket] += 1; |
| 553 | } |
| 554 | labDirty(); |
| 555 | } else if (name === 'stream') { |
| 556 | const index = Number.isSafeInteger(value.i) && value.i >= 0 && value.i <= 15 ? value.i : view.lanes.length; |
| 557 | labLane(view, index).stat = value; |
| 558 | const started = labNumber(value.start_ms); |
| 559 | const total = labNumber(value.total_ms); |
| 560 | if (!Number.isNaN(started) && !Number.isNaN(total)) view.stepAt = Math.max(view.stepAt, started + total); |
| 561 | const tokens = value.prompt_tokens; |
| 562 | const rate = labNumber(value.prefill_tps); |
| 563 | if (view.mode === 'sweep' && Number.isSafeInteger(tokens) && tokens > 0 && !Number.isNaN(rate)) view.marks.push({ x: tokens, y: rate }); |
| 564 | labResult(labPartial(view), view); |
| 565 | if (view.mode === 'sweep' && view.marks.length < view.steps.length) labSay(`Step ${view.marks.length + 1} of ${view.steps.length}: prefilling.`); |
| 566 | labDirty(); |
| 567 | } else if (name === 'beat') { |
| 568 | const time = labNumber(value.t); |
| 569 | const seconds = Number.isNaN(time) ? 0 : Math.max(0, Math.round((time - view.stepAt) / 1000)); |
| 570 | labSay(view.mode === 'sweep' |
| 571 | ? `Step ${Math.min(view.marks.length + 1, view.steps.length || 1)} of ${view.steps.length || 1}: prefilling, ${seconds} s.` |
| 572 | : `Prefilling, ${seconds} s.`); |
| 573 | } else if (name === 'yielded') { |
| 574 | view.yielded = value; |
| 575 | labSay(`Yielded to a live chat after ${labWord(value.completed_steps, 6)} completed steps.`); |
| 576 | } else if (name === 'done') { |
| 577 | const result = value.result; |
| 578 | if (!result || typeof result !== 'object' || Array.isArray(result)) return; |
| 579 | view.done = value; |
| 580 | labResult(result, view); |
| 581 | lab.link = typeof value.sig === 'string' ? labPack(JSON.stringify({ result, sig: value.sig })) : ''; |
| 582 | lab.share.disabled = !lab.link || !lab.options.share; |
| 583 | historyAdd(result, lab.link); |
| 584 | } else if (name === 'error') { |
| 585 | view.outcome = `The run stopped with an error: ${labWord(value.message || value.code, 200)}`; |
| 586 | } |
| 587 | } |
| 588 | function labBody(preset) { |
| 589 | const mode = labMode(); |
| 590 | const body = { mode }; |
| 591 | if (mode === 'sweep') { |
| 592 | body.sweep_max = Number(lab.sweep.value); |
| 593 | return body; |
| 594 | } |
| 595 | const text = lab.prompt.value.trim() ? lab.prompt.value : ''; |
| 596 | if (preset || !text) { |
| 597 | body.preset = preset || lab.preset; |
| 598 | } else { |
| 599 | body.prompt = text; |
| 600 | body.max_tokens = Number(lab.max.value); |
| 601 | } |
| 602 | if (mode === 'concurrent') body.streams = Number(lab.streams.value); |
| 603 | return body; |
| 604 | } |
| 605 | async function labRun(preset) { |
| 606 | if (!lab || lab.active || lab.offline) return; |
| 607 | const body = labBody(preset); |
| 608 | if (body.prompt !== undefined) { |
| 609 | const bytes = new TextEncoder().encode(body.prompt).length; |
| 610 | if (bytes > PROMPT_BYTES) { |
| 611 | labSay(`Your prompt is ${bytes} bytes; the limit is ${PROMPT_BYTES} bytes.`); |
| 612 | return; |
| 613 | } |
| 614 | } |
| 615 | if (body.preset) lab.preset = body.preset; |
| 616 | for (const item of lab.presetButtons) item.setAttribute('aria-pressed', String(Boolean(body.preset) && item.dataset.preset === body.preset)); |
| 617 | if (SHARE_ADDRESS.test(location.hash)) history.replaceState(null, '', `${location.pathname}${location.search}`); |
| 618 | lab.shared = null; |
| 619 | lab.verify.hidden = true; |
| 620 | lab.link = ''; |
| 621 | lab.share.disabled = true; |
| 622 | lab.outputs.replaceChildren(); |
| 623 | lab.results.replaceChildren(); |
| 624 | const mine = lab; |
| 625 | const view = labView(body.mode); |
| 626 | lab.view = view; |
| 627 | const controller = new AbortController(); |
| 628 | lab.active = controller; |
| 629 | labBusy(true); |
| 630 | labCaption(body.mode === 'sweep'); |
| 631 | labSay('Sending.'); |
| 632 | labPaint(); |
| 633 | let wait = 0; |
| 634 | let offline = false; |
| 635 | try { |
| 636 | const response = await fetch(mine.routes.infer, { |
| 637 | method: 'POST', |
| 638 | headers: { 'Content-Type': 'application/json', Accept: 'text/event-stream' }, |
| 639 | body: JSON.stringify(body), |
| 640 | cache: 'no-store', |
| 641 | credentials: 'omit', |
| 642 | signal: controller.signal, |
| 643 | }); |
| 644 | const type = response.headers.get('Content-Type') || ''; |
| 645 | if (!response.ok) { |
| 646 | const reply = await response.json().catch(() => null); |
| 647 | wait = retryAfter(response, reply); |
| 648 | offline = Boolean(reply && reply.error === 'offline'); |
| 649 | view.outcome = labRefusal(response.status, reply); |
| 650 | } else if (!response.body || !type.includes('text/event-stream')) { |
| 651 | view.outcome = 'The gateway answered in a form this page does not read.'; |
| 652 | } else { |
| 653 | const reader = response.body.getReader(); |
| 654 | const decoder = new TextDecoder(); |
| 655 | const parser = sse((name, data) => { |
| 656 | if (lab === mine) labEvent(name, data, view); |
| 657 | }); |
| 658 | for (;;) { |
| 659 | const { value, done } = await reader.read(); |
| 660 | if (done) break; |
| 661 | parser.feed(decoder.decode(value, { stream: true })); |
| 662 | } |
| 663 | parser.feed(decoder.decode()); |
| 664 | parser.end(); |
| 665 | if (!view.done && !view.outcome) view.outcome = 'The connection closed before the run finished.'; |
| 666 | } |
| 667 | } catch (_) { |
| 668 | view.outcome = controller.signal.aborted |
| 669 | ? 'Stopped. The partial output stays above; a stopped run has no signed result.' |
| 670 | : 'Could not reach the gateway. Check your connection and try again.'; |
| 671 | } |
| 672 | if (lab !== mine) return; |
| 673 | lab.active = null; |
| 674 | labBusy(false); |
| 675 | labPaint(); |
| 676 | if (offline) labOffline(true); |
| 677 | else if (view.outcome) labSay(view.outcome, wait); |
| 678 | else if (view.yielded) labSay('Yielded to a live chat: the numbers below are partial.'); |
| 679 | else labSay(lab.options.share ? 'Done. Copy the share link to show someone these exact numbers.' : 'Done.'); |
| 680 | } |
| 681 | function labDirty() { |
| 682 | if (lab && !lab.frame) lab.frame = requestAnimationFrame(labPaint); |
| 683 | } |
| 684 | function labPaint() { |
| 685 | if (!lab) return; |
| 686 | if (lab.frame) cancelAnimationFrame(lab.frame); |
| 687 | lab.frame = 0; |
| 688 | const view = lab.view; |
| 689 | if (view) { |
| 690 | for (const lane of view.lanes) { |
| 691 | if (lane.shown !== lane.buf.length) { |
| 692 | lane.text.textContent = lane.buf; |
| 693 | lane.shown = lane.buf.length; |
| 694 | lane.text.scrollTop = lane.text.scrollHeight; |
| 695 | } |
| 696 | setText(lane.tally, lane.count ? `${lane.count} ${lane.count === 1 ? 'token' : 'tokens'}` : ''); |
| 697 | if (lane.stat) setText(lane.stats, labStat(lane.stat, view.mode)); |
| 698 | } |
| 699 | } |
| 700 | labHero(); |
| 701 | labDraw(); |
| 702 | } |
| 703 | /* The big number: live tok/s over the last full second of buckets while a run |
| 704 | streams, then the run's own headline figure from the server's result. */ |
| 705 | function labHero() { |
| 706 | const view = lab.view; |
| 707 | const result = view && view.done ? view.done.result : lab.shared ? lab.shared.result : null; |
| 708 | let value = NaN; |
| 709 | let text = 'tok/s shows here as the first token lands'; |
| 710 | if (result) { |
| 711 | const list = labList(result); |
| 712 | if (result.mode === 'concurrent') { |
| 713 | value = labNumber(result.aggregate_tps); |
| 714 | text = `aggregate tok/s over ${list.length} streams`; |
| 715 | } else if (result.mode === 'sweep') { |
| 716 | value = list.reduce((most, item) => Math.max(most, Number.isNaN(labNumber(item.prefill_tps)) ? 0 : item.prefill_tps), 0) || NaN; |
| 717 | text = 'peak prefill tok/s'; |
| 718 | } else { |
| 719 | value = list.length ? labNumber(list[0].decode_tps) : NaN; |
| 720 | text = 'decode tok/s'; |
| 721 | } |
| 722 | } else if (view && view.mode === 'sweep') { |
| 723 | const mark = view.marks[view.marks.length - 1]; |
| 724 | if (mark) { |
| 725 | value = mark.y; |
| 726 | text = 'prefill tok/s, last step'; |
| 727 | } |
| 728 | } else if (view) { |
| 729 | const last = view.series.reduce((most, line) => Math.max(most, line ? line.length - 1 : 0), 0); |
| 730 | const from = Math.max(0, last - 4); |
| 731 | if (last > 0) { |
| 732 | let count = 0; |
| 733 | for (const line of view.series) if (line) for (let bucket = from; bucket < last; bucket += 1) count += line[bucket] || 0; |
| 734 | value = (count * 1000) / ((last - from) * BUCKET_MS); |
| 735 | text = view.mode === 'concurrent' ? 'tok/s right now, all streams' : 'tok/s right now'; |
| 736 | } |
| 737 | } |
| 738 | setText(lab.heroNumber, labRate(value)); |
| 739 | setText(lab.heroText, text); |
| 740 | } |
| 741 | function labStep(span, parts) { |
| 742 | const raw = span / parts; |
| 743 | const power = Math.pow(10, Math.floor(Math.log10(raw))); |
| 744 | for (const scale of [1, 2, 5]) if (scale * power >= raw) return scale * power; |
| 745 | return 10 * power; |
| 746 | } |
| 747 | function labTop(peak) { |
| 748 | const step = labStep(peak > 0 ? peak : 10, 4); |
| 749 | return { top: Math.max(step, Math.ceil(peak / step) * step), step }; |
| 750 | } |
| 751 | function labAxes(g, box, xs, ys, names, ink, faint) { |
| 752 | g.lineWidth = 1; |
| 753 | g.strokeStyle = faint; |
| 754 | g.fillStyle = ink; |
| 755 | g.textAlign = 'right'; |
| 756 | g.textBaseline = 'middle'; |
| 757 | for (const [text, y] of ys) { |
| 758 | g.beginPath(); |
| 759 | g.moveTo(box.l, y); |
| 760 | g.lineTo(box.r, y); |
| 761 | g.stroke(); |
| 762 | g.fillText(text, box.l - 6, y); |
| 763 | } |
| 764 | g.textAlign = 'center'; |
| 765 | g.textBaseline = 'top'; |
| 766 | for (const [text, x] of xs) { |
| 767 | g.beginPath(); |
| 768 | g.moveTo(x, box.b); |
| 769 | g.lineTo(x, box.b + 4); |
| 770 | g.stroke(); |
| 771 | g.fillText(text, x, box.b + 6); |
| 772 | } |
| 773 | g.fillText(names[0], (box.l + box.r) / 2, box.b + 20); |
| 774 | g.save(); |
| 775 | g.translate(11, (box.t + box.b) / 2); |
| 776 | g.rotate(-Math.PI / 2); |
| 777 | g.textBaseline = 'middle'; |
| 778 | g.fillText(names[1], 0, 0); |
| 779 | g.restore(); |
| 780 | } |
| 781 | function labEmpty(g, box, text, ink) { |
| 782 | g.fillStyle = ink; |
| 783 | g.textAlign = 'center'; |
| 784 | g.textBaseline = 'middle'; |
| 785 | g.fillText(text, (box.l + box.r) / 2, (box.t + box.b) / 2); |
| 786 | } |
| 787 | function labDraw() { |
| 788 | const canvas = lab.canvas; |
| 789 | if (!canvas.isConnected || !canvas.clientWidth) return; |
| 790 | const width = Math.max(240, Math.round(canvas.clientWidth)); |
| 791 | const height = Math.max(160, Math.round(canvas.clientHeight || 240)); |
| 792 | const ratio = Math.min(window.devicePixelRatio || 1, 2); |
| 793 | if (canvas.width !== Math.round(width * ratio)) canvas.width = Math.round(width * ratio); |
| 794 | if (canvas.height !== Math.round(height * ratio)) canvas.height = Math.round(height * ratio); |
| 795 | const g = canvas.getContext('2d'); |
| 796 | if (!g) return; |
| 797 | g.setTransform(ratio, 0, 0, ratio, 0, 0); |
| 798 | g.clearRect(0, 0, width, height); |
| 799 | const css = getComputedStyle(lab.host); |
| 800 | const color = (name) => css.getPropertyValue(name).trim() || 'gray'; |
| 801 | const colors = [color('--speed-lane-1'), color('--speed-lane-2'), color('--speed-lane-3'), color('--speed-lane-4')]; |
| 802 | g.font = `${width < 420 ? 10 : 11}px ${css.getPropertyValue('--speed-mono').trim() || 'monospace'}`; |
| 803 | const box = { l: 52, r: width - 12, t: 12, b: height - 36 }; |
| 804 | const ink = color('--speed-muted'); |
| 805 | const faint = color('--speed-line'); |
| 806 | const view = lab.view; |
| 807 | const shared = lab.shared ? lab.shared.result : null; |
| 808 | const mode = view ? view.mode : shared ? shared.mode : labMode(); |
| 809 | if (mode === 'sweep') { |
| 810 | let marks = view ? view.marks : []; |
| 811 | let steps = view ? view.steps : []; |
| 812 | if (!view && shared) { |
| 813 | const list = labList(shared); |
| 814 | marks = list.filter((item) => Number.isSafeInteger(item.prompt_tokens) && item.prompt_tokens > 0 && !Number.isNaN(labNumber(item.prefill_tps))) |
| 815 | .map((item) => ({ x: item.prompt_tokens, y: item.prefill_tps })); |
| 816 | steps = list.map((item) => item.target_tokens).filter(Number.isSafeInteger); |
| 817 | } |
| 818 | labSweepDraw(g, box, marks, steps, colors, ink, faint, color('--speed-fg')); |
| 819 | } else { |
| 820 | labRateDraw(g, box, view, colors, ink, faint, Boolean(shared)); |
| 821 | } |
| 822 | } |
| 823 | function labRateDraw(g, box, view, colors, ink, faint, shared) { |
| 824 | const series = view ? view.series : []; |
| 825 | let buckets = 0; |
| 826 | let peak = 0; |
| 827 | for (const line of series) { |
| 828 | if (!line) continue; |
| 829 | buckets = Math.max(buckets, line.length); |
| 830 | for (const value of line) peak = Math.max(peak, value); |
| 831 | } |
| 832 | const seconds = Math.max(2, Math.ceil((buckets * BUCKET_MS) / 1000)); |
| 833 | const { top, step } = labTop((peak * 1000) / BUCKET_MS); |
| 834 | const xAt = (second) => box.l + ((box.r - box.l) * second) / seconds; |
| 835 | const yAt = (rate) => box.b - ((box.b - box.t) * rate) / top; |
| 836 | const xs = []; |
| 837 | const xStep = labStep(seconds, box.r - box.l < 360 ? 4 : 8); |
| 838 | for (let second = 0; second <= seconds + 1e-9; second += xStep) xs.push([String(Math.round(second * 10) / 10), xAt(second)]); |
| 839 | const ys = []; |
| 840 | for (let rate = 0; rate <= top + 1e-9; rate += step) ys.push([String(Math.round(rate * 10) / 10), yAt(rate)]); |
| 841 | labAxes(g, box, xs, ys, ['seconds since start', 'tok/s'], ink, faint); |
| 842 | series.forEach((line, index) => { |
| 843 | if (!line || !line.length) return; |
| 844 | g.strokeStyle = colors[index % colors.length]; |
| 845 | g.lineWidth = 1.6; |
| 846 | g.beginPath(); |
| 847 | g.moveTo(xAt(0), yAt(0)); |
| 848 | for (let bucket = 0; bucket < line.length; bucket += 1) { |
| 849 | const rate = (line[bucket] * 1000) / BUCKET_MS; |
| 850 | g.lineTo(xAt((bucket * BUCKET_MS) / 1000), yAt(rate)); |
| 851 | g.lineTo(xAt(((bucket + 1) * BUCKET_MS) / 1000), yAt(rate)); |
| 852 | } |
| 853 | g.stroke(); |
| 854 | }); |
| 855 | if (series.filter(Boolean).length > 1) { |
| 856 | g.textAlign = 'left'; |
| 857 | g.textBaseline = 'middle'; |
| 858 | series.forEach((line, index) => { |
| 859 | const x = box.r - 70; |
| 860 | const y = box.t + 8 + index * 15; |
| 861 | g.fillStyle = colors[index % colors.length]; |
| 862 | g.fillRect(x, y - 2, 12, 4); |
| 863 | g.fillText(`Stream ${index + 1}`, x + 16, y); |
| 864 | }); |
| 865 | } |
| 866 | if (!buckets) labEmpty(g, box, shared ? 'A shared link carries the result, not the token timeline.' : lab.offline ? 'Offline: the graph fills in when the model is back.' : 'Press a preset: each token is drawn as it arrives.', ink); |
| 867 | } |
| 868 | function labSweepDraw(g, box, marks, steps, colors, ink, faint, fg) { |
| 869 | const sizes = [...new Set([...steps, ...marks.map((mark) => mark.x)].filter((size) => size > 0))].sort((a, b) => a - b); |
| 870 | const low = Math.log2(sizes.length ? sizes[0] : 512) - 0.5; |
| 871 | const high = Math.log2(sizes.length ? sizes[sizes.length - 1] : Number(lab.sweep.value)) + 0.5; |
| 872 | const peak = marks.reduce((most, mark) => Math.max(most, mark.y), 0); |
| 873 | const { top, step } = labTop(peak); |
| 874 | const xAt = (size) => box.l + ((box.r - box.l) * (Math.log2(size) - low)) / (high - low); |
| 875 | const yAt = (rate) => box.b - ((box.b - box.t) * rate) / top; |
| 876 | const ticks = sizes.length ? sizes.filter((size) => steps.includes(size) || !steps.length) : [512, 1024, 2048, 4096]; |
| 877 | const xs = ticks.map((size) => [labSize(size), xAt(size)]); |
| 878 | const ys = []; |
| 879 | for (let rate = 0; rate <= top + 1e-9; rate += step) ys.push([String(Math.round(rate * 10) / 10), yAt(rate)]); |
| 880 | labAxes(g, box, xs, ys, ['prompt tokens (log2 scale)', 'prefill tok/s'], ink, faint); |
| 881 | g.textAlign = 'center'; |
| 882 | g.textBaseline = 'bottom'; |
| 883 | for (const mark of marks) { |
| 884 | const x = xAt(mark.x); |
| 885 | const y = yAt(mark.y); |
| 886 | g.fillStyle = colors[0]; |
| 887 | g.beginPath(); |
| 888 | g.arc(x, y, 4, 0, Math.PI * 2); |
| 889 | g.fill(); |
| 890 | g.fillStyle = fg; |
| 891 | g.fillText(mark.y.toFixed(1), x, y - 6); |
| 892 | } |
| 893 | if (!marks.length) labEmpty(g, box, 'Each finished step adds one point: prompt size against prefill speed.', ink); |
| 894 | } |
| 895 | function listen(target, type, handler) { |
| 896 | target.addEventListener(type, handler); |
| 897 | lab.off.push(() => target.removeEventListener(type, handler)); |
| 898 | } |
| 899 | function settings(given) { |
| 900 | const options = { ...DEFAULTS }; |
| 901 | if (given && typeof given === 'object') { |
| 902 | if (typeof given.api === 'string' && /^(\/|https:\/\/)[^\s]*$/.test(given.api)) options.api = given.api.replace(/\/+$/, ''); |
| 903 | for (const key of ['model', 'server', 'historyKey']) if (typeof given[key] === 'string' && given[key]) options[key] = given[key].slice(0, 120); |
| 904 | if (typeof given.share === 'boolean') options.share = given.share; |
| 905 | } |
| 906 | return options; |
| 907 | } |
| 908 | function mount(host, given) { |
| 909 | if (!(host instanceof Element)) throw new TypeError('AienSpeed.mount needs an element'); |
| 910 | unmount(); |
| 911 | lab = build(host, settings(given)); |
| 912 | for (const item of lab.presetButtons) listen(item, 'click', () => labRun(item.dataset.preset)); |
| 913 | listen(lab.run, 'click', () => labRun('')); |
| 914 | listen(lab.halt, 'click', () => { |
| 915 | if (lab.active) lab.active.abort(); |
| 916 | }); |
| 917 | listen(lab.prompt, 'keydown', (event) => { |
| 918 | if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) { |
| 919 | event.preventDefault(); |
| 920 | labRun(''); |
| 921 | } |
| 922 | }); |
| 923 | listen(lab.modes, 'change', () => { |
| 924 | labModeShow(); |
| 925 | if (!lab.active && !lab.shared) { |
| 926 | lab.view = null; |
| 927 | lab.outputs.replaceChildren(); |
| 928 | labCaption(labMode() === 'sweep'); |
| 929 | labDirty(); |
| 930 | } |
| 931 | }); |
| 932 | listen(lab.clear, 'click', historyClear); |
| 933 | listen(lab.share, 'click', labCopyLink); |
| 934 | listen(lab.ownCopy, 'click', () => copyText(lab.own.textContent, lab.ownCopy)); |
| 935 | listen(window, 'resize', labDirty); |
| 936 | listen(window, 'hashchange', () => { |
| 937 | if (SHARE_ADDRESS.test(location.hash)) labShared(); |
| 938 | }); |
| 939 | if (typeof ResizeObserver === 'function') { |
| 940 | const watch = new ResizeObserver(() => labDirty()); |
| 941 | watch.observe(lab.canvas); |
| 942 | lab.off.push(() => watch.disconnect()); |
| 943 | } |
| 944 | if (!lab.options.share) lab.share.hidden = true; |
| 945 | labCaption(false); |
| 946 | labModeShow(); |
| 947 | historyShow(); |
| 948 | labShared(); |
| 949 | labInfo(); |
| 950 | labPaint(); |
| 951 | return true; |
| 952 | } |
| 953 | function unmount() { |
| 954 | if (!lab) return false; |
| 955 | const gone = lab; |
| 956 | lab = null; |
| 957 | if (gone.active) gone.active.abort(); |
| 958 | clearInterval(gone.timer); |
| 959 | clearTimeout(gone.poll); |
| 960 | if (gone.frame) cancelAnimationFrame(gone.frame); |
| 961 | for (const off of gone.off) off(); |
| 962 | gone.host.replaceChildren(); |
| 963 | gone.host.classList.remove('aien-speed'); |
| 964 | return true; |
| 965 | } |
| 966 | window.AienSpeed = Object.freeze({ mount, unmount }); |
| 967 | })(); |