Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/gpu-head-to-head/blob/main/bench/bench-node.mjs # gpu-head-to-head aien-dev/gpu-head-to-head Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `gpu-head-to-head / bench / bench-node.mjs` 142 lines ยท 7959 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 2 // Verification-only HTTP/SSE instrument, derived from bench.py's request contract. 3 // Records raw monotonic nanoseconds. Rates and statistics belong in Wolfram. 4 import http from 'node:http'; 5 import fs from 'node:fs'; 6 import {StringDecoder} from 'node:string_decoder'; 7 import {randomUUID} from 'node:crypto'; 8 import {pathToFileURL} from 'node:url'; 9 import {setTimeout as delay} from 'node:timers/promises'; 10 11 export async function oneRequest({port, model, prompt, maxTokens, timeoutMs=`1800000`}) { 12 const row = {time_unit:'nanoseconds', clock:'process.hrtime.bigint', 13 t_send_ns:null, t_first_ns:null, t_last_ns:null, chunks:0, text:'', 14 usage:null, finish_reason:null, error:null, http_status:null, busy_retries:0}; 15 const body = JSON.stringify({model, messages:[{role:'user',content:prompt}], 16 stream:true, stream_options:{include_usage:true}, temperature:0, top_p:1, 17 max_tokens:maxTokens, seed:0, chat_template_kwargs:{enable_thinking:false}}); 18 const controller = new AbortController(); 19 const timer = setTimeout(() => controller.abort(), timeoutMs); 20 const signal = controller.signal; 21 const connect = () => new Promise((resolve,reject) => { 22 const req = http.request({host:'127.0.0.1',port,path:'/v1/chat/completions', 23 method:'POST',agent:false,signal,headers:{'Content-Type':'application/json', 24 Accept:'text/event-stream'}}, resolve); 25 req.on('error',reject); 26 req.end(body); 27 }); 28 try { 29 row.t_send_ns = process.hrtime.bigint().toString(); 30 let response; 31 while (true) { 32 response = await connect(); 33 row.http_status = response.statusCode; 34 if (![429,503].includes(response.statusCode)) break; 35 response.resume(); 36 response.destroy(); 37 row.busy_retries++; 38 await delay(50,undefined,{signal}); 39 } 40 if (response.statusCode !== 200) { 41 response.destroy(); 42 throw new Error('HTTP '+response.statusCode); 43 } 44 const decoder = new StringDecoder('utf8'); 45 let pending = '', done = false; 46 try { 47 stream: for await (const chunk of response) { 48 pending += decoder.write(chunk); 49 while (pending.includes('\n')) { 50 const boundary = pending.indexOf('\n'); 51 const line = pending.slice(0,boundary).trim(); 52 pending = pending.slice(boundary+1); 53 if (!line.startsWith('data:')) continue; 54 const payload = line.slice(5).trim(); 55 if (payload === '[DONE]') { done=true; break stream; } 56 let event; 57 try { event=JSON.parse(payload); } 58 catch { throw new Error('malformed SSE JSON'); } 59 if (event.error) throw new Error('server error event'); 60 const now = process.hrtime.bigint().toString(); 61 if (event.usage) row.usage=event.usage; 62 for (const choice of event.choices || []) { 63 const delta=choice.delta || {}; 64 for(const key of ['content','reasoning_content']) 65 if(delta[key]!=null && typeof delta[key]!=='string') 66 throw new Error('invalid text delta'); 67 const piece=(delta.content || '')+(delta.reasoning_content || ''); 68 if (typeof piece !== 'string') throw new Error('invalid text delta'); 69 if (piece) { 70 if (row.t_first_ns === null) row.t_first_ns=now; 71 row.t_last_ns=now; 72 row.chunks++; 73 row.text+=piece; 74 } 75 if (choice.finish_reason) row.finish_reason=choice.finish_reason; 76 } 77 } 78 } 79 } finally { response.destroy(); } 80 if (!done) throw new Error('stream ended without DONE'); 81 if (row.t_first_ns === null) throw new Error('no content received'); 82 if (!row.finish_reason) throw new Error('missing finish reason'); 83 if (!Number.isInteger(row.usage?.prompt_tokens) || !Number.isInteger(row.usage?.completion_tokens)) 84 throw new Error('missing token usage'); 85 } catch (error) { row.error=error.message; } 86 finally { clearTimeout(timer); } 87 return row; 88 } 89 90 async function main() { 91 const args={}; 92 const flags=new Set(['port','model','arm','round','metric','prompts','select','concurrency', 93 'max-tokens','warmup','reps','out','cell-run']); 94 for (let i=2;ix.trim()).map(JSON.parse); 109 if(args.select) prompts=args.select.split(',').map(id=>{ 110 const p=prompts.find(p=>p.id===id); if(!p) throw new Error('missing prompt '+id); return p; 111 }); 112 if(!prompts.length || prompts.some(p=>typeof p.id!=='string'||typeof p.text!=='string')) 113 throw new Error('invalid prompt file'); 114 const output=fs.openSync(args.out,'wx'); // Preserve all prior runs; never silently append. 115 let failed=false; 116 try { 117 for(let k=0;kprompts[(k*args.concurrency+i)%prompts.length]); 120 const batchId=randomUUID(); 121 const before=fs.readFileSync('/proc/loadavg','utf8').trim(); 122 const wallUtc=new Date().toISOString(); 123 const rows=await Promise.all(selected.map(p=>oneRequest({port:args.port,model:args.model, 124 prompt:(args.nonce?'Request id '+randomUUID().replaceAll('-','')+'. Ignore this line.\n':'')+p.text, 125 maxTokens:args['max-tokens']}))); 126 const after=fs.readFileSync('/proc/loadavg','utf8').trim(); 127 for(let i=0;i{console.error(error.message);process.exitCode=1;});