interplane.Get Omega
Read in your language

gpu-head-to-head

aien-dev/gpu-head-to-head

Brought by drakestapleton

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.
4import http from 'node:http';
5import fs from 'node:fs';
6import {StringDecoder} from 'node:string_decoder';
7import {randomUUID} from 'node:crypto';
8import {pathToFileURL} from 'node:url';
9import {setTimeout as delay} from 'node:timers/promises';
10
11export 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
90async 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;i<process.argv.length;i++) {
95 const name=process.argv[i].replace(/^--/,'');
96 if(name==='nonce') { args.nonce=true; continue; }
97 if(!flags.has(name) || process.argv[i+1]===undefined) throw new Error('invalid option '+name);
98 args[name]=process.argv[++i];
99 }
100 for(const name of ['port','model','arm','round','metric','prompts','max-tokens','out'])
101 if(!args[name]) throw new Error('missing option '+name);
102 for(const [name,value] of Object.entries({concurrency:1,warmup:2,reps:3}))
103 args[name]=Number(args[name] ?? value);
104 args.port=Number(args.port); args['max-tokens']=Number(args['max-tokens']);
105 for(const name of ['port','concurrency','warmup','reps','max-tokens'])
106 if(!Number.isInteger(args[name]) || args[name]<0) throw new Error('invalid integer '+name);
107 if(!args.port || !args.concurrency || !args.reps || !args['max-tokens']) throw new Error('zero size');
108 let prompts=fs.readFileSync(args.prompts,'utf8').split('\n').filter(x=>x.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;k<args.warmup+args.reps;k++) {
118 const warmup=k<args.warmup, rep=warmup?k:k-args.warmup;
119 const selected=Array.from({length:args.concurrency},(_,i)=>prompts[(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<rows.length;i++) {
128 const row={...rows[i],arm:args.arm,round:args.round,metric:args.metric,rep,warmup,
129 concurrency:args.concurrency,stream_index:i,batch_id:batchId,
130 loadavg_start:before,loadavg_end:after,wall_utc:wallUtc,
131 max_tokens:args['max-tokens'],prompt_id:selected[i].id,cell_run:args['cell-run']||'',
132 server_cpus:process.env.H2H_SRV_CPUS||null,client_cpus:process.env.H2H_CLI_CPUS||null,
133 client:'node-sse-v1',node_version:process.version};
134 fs.writeSync(output,JSON.stringify(row)+'\n');
135 if(row.error) failed=true;
136 }
137 }
138 } finally { fs.closeSync(output); }
139 if(failed) process.exitCode=1;
140}
141if(process.argv[1] && import.meta.url===pathToFileURL(process.argv[1]).href)
142 main().catch(error=>{console.error(error.message);process.exitCode=1;});