Spaces:
Runtime error
Runtime error
File size: 8,706 Bytes
0310320 de9b734 0310320 de9b734 0310320 de9b734 0310320 de9b734 0310320 0a2c317 0310320 0a2c317 0310320 de9b734 0310320 0a2c317 0310320 0a2c317 0310320 0a2c317 0310320 0a2c317 0310320 de9b734 0310320 0a2c317 0310320 0a2c317 0310320 0a2c317 0310320 0a2c317 0310320 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 |
import { EventEmitter } from "events";
import { BenchmarkResult } from "../core/types.js";
import { logger } from "../core/logger.js";
export interface BenchmarkRequest {
id: string;
platform: "node" | "web";
modelId: string;
task: string;
mode: "warm" | "cold";
repeats: number;
dtype?: string;
batchSize: number;
device?: string;
browser?: string;
headed?: boolean;
timestamp: number;
}
export interface QueuedBenchmark extends BenchmarkRequest {
status: "pending" | "running" | "completed" | "failed";
result?: BenchmarkResult;
error?: string;
startedAt?: number;
completedAt?: number;
}
export class BenchmarkQueue extends EventEmitter {
private queue: QueuedBenchmark[] = [];
private isProcessing = false;
addBenchmark(request: BenchmarkRequest): void {
const queued: QueuedBenchmark = {
...request,
status: "pending",
};
this.queue.push(queued);
this.emit("added", queued);
this.processQueue();
}
getBenchmark(id: string): QueuedBenchmark | undefined {
return this.queue.find((b) => b.id === id);
}
getAllBenchmarks(): QueuedBenchmark[] {
return [...this.queue];
}
getQueueStatus() {
return {
total: this.queue.length,
pending: this.queue.filter((b) => b.status === "pending").length,
running: this.queue.filter((b) => b.status === "running").length,
completed: this.queue.filter((b) => b.status === "completed").length,
failed: this.queue.filter((b) => b.status === "failed").length,
};
}
private async processQueue() {
if (this.isProcessing) return;
const pending = this.queue.find((b) => b.status === "pending");
if (!pending) return;
this.isProcessing = true;
pending.status = "running";
pending.startedAt = Date.now();
this.emit("started", pending);
try {
const result = await this.runBenchmark(pending);
pending.status = "completed";
pending.result = result;
pending.completedAt = Date.now();
this.emit("completed", pending);
} catch (error) {
pending.status = "failed";
// Capture detailed error information
if (error instanceof Error) {
pending.error = error.message;
// Log full error details to console
logger.error(`\n❌ Benchmark ${pending.id} failed:`);
logger.error(` Message: ${error.message}`);
if (error.stack) {
logger.error(` Stack trace:\n${error.stack}`);
}
} else {
pending.error = String(error);
logger.error(`\n❌ Benchmark ${pending.id} failed: ${pending.error}`);
}
pending.completedAt = Date.now();
this.emit("failed", pending);
} finally {
// Ensure isProcessing is always reset
this.isProcessing = false;
// Process next item
setImmediate(() => this.processQueue());
}
}
private async runBenchmark(request: BenchmarkRequest): Promise<BenchmarkResult> {
const BENCHMARK_TIMEOUT = parseInt(process.env.BENCHMARK_TIMEOUT || String(10 * 60 * 1000), 10); // 10 minutes default
if (request.platform === "node") {
// Use spawn instead of dynamic import to avoid import.meta.url issues
const { spawn } = await import("child_process");
// Build command args
const args = [
"src/node/index.ts",
request.modelId,
request.task,
`--mode=${request.mode}`,
`--repeats=${request.repeats}`,
`--batch-size=${request.batchSize}`,
];
if (request.dtype) args.push(`--dtype=${request.dtype}`);
logger.log(`\n[Queue] Dispatching node benchmark with command: tsx ${args.join(' ')}`);
return new Promise((resolve, reject) => {
const proc = spawn("tsx", args, { cwd: process.cwd() });
let stdout = "";
let stderr = "";
let isResolved = false;
// Timeout handler
const timeoutId = setTimeout(() => {
if (!isResolved) {
isResolved = true;
logger.error(`[Queue] Benchmark ${request.id} timed out after ${BENCHMARK_TIMEOUT / 1000}s`);
proc.kill('SIGTERM');
// Give it 5 seconds to clean up, then force kill
setTimeout(() => proc.kill('SIGKILL'), 5000);
reject(new Error(`Benchmark timed out after ${BENCHMARK_TIMEOUT / 1000}s`));
}
}, BENCHMARK_TIMEOUT);
proc.stdout.on("data", (data) => {
stdout += data.toString();
});
proc.stderr.on("data", (data) => {
stderr += data.toString();
});
// Error handler for spawn failures
proc.on("error", (error) => {
if (!isResolved) {
isResolved = true;
clearTimeout(timeoutId);
reject(new Error(`Failed to spawn process: ${error.message}`));
}
});
proc.on("close", (code, signal) => {
if (!isResolved) {
isResolved = true;
clearTimeout(timeoutId);
if (signal) {
reject(new Error(`Benchmark killed by signal ${signal}`));
return;
}
if (code !== 0) {
reject(new Error(`Benchmark failed with code ${code}: ${stderr}`));
return;
}
// Extract JSON from stdout (last JSON object)
const jsonMatch = stdout.match(/\{[\s\S]*"platform"[\s\S]*\}/);
if (jsonMatch) {
try {
const result = JSON.parse(jsonMatch[0]);
resolve(result);
} catch (e) {
reject(new Error(`Failed to parse benchmark result: ${e}`));
}
} else {
reject(new Error("No benchmark result found in output"));
}
}
});
});
} else {
// For web benchmarks, we'll use the CLI approach with Playwright
const { spawn } = await import("child_process");
// Build command args
const args = [
"src/web/cli.ts",
request.modelId,
request.task,
`--mode=${request.mode}`,
`--repeats=${request.repeats}`,
`--device=${request.device || "webgpu"}`,
`--batch-size=${request.batchSize}`,
];
if (request.dtype) args.push(`--dtype=${request.dtype}`);
if (request.browser) args.push(`--browser=${request.browser}`);
if (request.headed) args.push(`--headed=true`);
logger.log(`\n[Queue] Dispatching web benchmark with command: tsx ${args.join(' ')}`);
return new Promise((resolve, reject) => {
const proc = spawn("tsx", args, { cwd: process.cwd() });
let stdout = "";
let stderr = "";
let isResolved = false;
// Timeout handler
const timeoutId = setTimeout(() => {
if (!isResolved) {
isResolved = true;
logger.error(`[Queue] Benchmark ${request.id} timed out after ${BENCHMARK_TIMEOUT / 1000}s`);
proc.kill('SIGTERM');
// Give it 5 seconds to clean up, then force kill
setTimeout(() => proc.kill('SIGKILL'), 5000);
reject(new Error(`Benchmark timed out after ${BENCHMARK_TIMEOUT / 1000}s`));
}
}, BENCHMARK_TIMEOUT);
proc.stdout.on("data", (data) => {
stdout += data.toString();
});
proc.stderr.on("data", (data) => {
stderr += data.toString();
});
// Error handler for spawn failures
proc.on("error", (error) => {
if (!isResolved) {
isResolved = true;
clearTimeout(timeoutId);
reject(new Error(`Failed to spawn process: ${error.message}`));
}
});
proc.on("close", (code, signal) => {
if (!isResolved) {
isResolved = true;
clearTimeout(timeoutId);
if (signal) {
reject(new Error(`Benchmark killed by signal ${signal}`));
return;
}
if (code !== 0) {
reject(new Error(`Benchmark failed with code ${code}: ${stderr}`));
return;
}
// Extract JSON from stdout (last JSON object)
const jsonMatch = stdout.match(/\{[\s\S]*"platform"[\s\S]*\}/);
if (jsonMatch) {
try {
const result = JSON.parse(jsonMatch[0]);
resolve(result);
} catch (e) {
reject(new Error(`Failed to parse benchmark result: ${e}`));
}
} else {
reject(new Error("No benchmark result found in output"));
}
}
});
});
}
}
}
|