The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat(benchmark): a brake for runaway models, and a board that says what it ranks
purpleaf3bdf3eaf42
diff --git a/src/components/models/BenchmarkView.tsx b/src/components/models/BenchmarkView.tsxindex 5b9ab41a..785fba93 100644--- a/src/components/models/BenchmarkView.tsx+++ b/src/components/models/BenchmarkView.tsx@@ -125,8 +125,11 @@ export function BenchmarkView() {</h2><div className="space-y-2">{leaderboard.map((entry, i) => {- const maxTps = leaderboard[0].avgTps- const barWidth = maxTps > 0 ? (entry.avgTps / maxTps) * 100 : 0+ // The bar follows the ranking, so the picture and the order+ // cannot disagree (issue #106: a board sorted one way and+ // drawn another is where "black box" comes from).+ const topScore = leaderboard[0].score+ const barWidth = topScore > 0 ? (entry.score / topScore) * 100 : 0return (<div key={entry.model} className="flex items-center gap-3">@@ -138,7 +141,14 @@ export function BenchmarkView() {<span className="text-[0.7rem] text-gray-800 dark:text-gray-200 truncate font-medium">{entry.model}</span><span className="text-[0.65rem] text-gray-600 dark:text-gray-400 font-mono shrink-0 ml-2 flex items-center gap-1"><Zap size={10} className="text-amber-400" />- {entry.avgTps} t/s+ <span title="Useful throughput: the average rate multiplied by how often the answer was right. This is what the board is ordered by.">+ {entry.score} t/s useful+ </span>+ {entry.score !== entry.avgTps && (+ <span className="text-gray-500" title="Raw average rate, correct answers and wrong ones counted alike">+ ({entry.avgTps} raw)+ </span>+ )}</span></div><div className="w-full h-1.5 rounded-full bg-gray-200 dark:bg-white/5 overflow-hidden">@@ -173,6 +183,11 @@ export function BenchmarkView() {{entry.truncated} cut off</span>)}+ {entry.runaway > 0 && (+ <span title="Runs stopped by the emergency brake: the model kept generating far past anything the task needs, so it was aborted and counted as wrong." className="text-red-500">+ {entry.runaway} ran away+ </span>+ )}</div></div></div>@@ -180,7 +195,9 @@ export function BenchmarkView() {})}</div><p className="text-[0.55rem] text-gray-500 mt-3">- {leaderboard.reduce((s, e) => s + e.runs, 0)} total runs across {leaderboard.length} models+ {leaderboard.reduce((s, e) => s + e.runs, 0)} total runs across {leaderboard.length} models.+ {' '}Ordered by average tokens per second multiplied by how often the answer was right,+ so a fast model that answers wrong does not outrank a slower one that answers correctly.</p></div>)}diff --git a/src/hooks/useBenchmark.ts b/src/hooks/useBenchmark.tsindex 919aeef8..e135e5de 100644--- a/src/hooks/useBenchmark.ts+++ b/src/hooks/useBenchmark.ts@@ -35,7 +35,13 @@ export function useBenchmark() {signal: abortRef.current.signal,})- const m = await measureRun(stream, prompt.check)+ // The brake aborts the request itself, not just our reading of it:+ // dropping the stream would leave the model generating into nothing,+ // still holding the GPU (ElBiggus, issue #106).+ const controller = abortRef.current+ const m = await measureRun(stream, prompt.check, {+ onLimit: () => controller.abort(),+ })store.addResult({modelName,diff --git a/src/lib/__tests__/benchmark-run.test.ts b/src/lib/__tests__/benchmark-run.test.tsindex d995423b..6b3436e8 100644--- a/src/lib/__tests__/benchmark-run.test.ts+++ b/src/lib/__tests__/benchmark-run.test.ts@@ -40,7 +40,7 @@ describe('measureRun', () => {{ done: true, finishReason: 'length', evalCount: 300, evalDurationMs: 6000 },]),check('reasoning'),- steppedClock(0, 200, 6200),+ { clock: steppedClock(0, 200, 6200) },)expect(m.correct).toBe(false) // the answer was never printedexpect(m.finishReason).toBe('length') // and this says why@@ -59,7 +59,7 @@ describe('measureRun', () => {{ done: true, finishReason: 'stop', evalCount: 40, evalDurationMs: 1000 },]),check('reasoning'),- steppedClock(0, 120, 1120),+ { clock: steppedClock(0, 120, 1120) },)expect(m.correct).toBe(true)expect(m.finishReason).toBe('stop')@@ -77,7 +77,7 @@ describe('measureRun', () => {{ done: true, finishReason: 'stop' },]),check('code'),- steppedClock(0, 100, 1100),+ { clock: steppedClock(0, 100, 1100) },)expect(m.thinkTokens).toBe(0)expect(m.totalTokens).toBe(2) // two content chunks, JS fallback (no API metrics)@@ -92,7 +92,7 @@ describe('measureRun', () => {const m = await measureRun(streamOf([{ content: 'nine' }, { done: true, finishReason: 'stop' }]),check('reasoning'),- steppedClock(0, 10, 60),+ { clock: steppedClock(0, 10, 60) },)expect(m.correct).toBe(true) // spelled-out answerexpect(m.tokensPerSec).toBeCloseTo((1 / 60) * 1000, 3)@@ -102,7 +102,7 @@ describe('measureRun', () => {const m = await measureRun(streamOf([{ content: 'partial ans' }, { done: true, finishReason: 'disconnect' }]),check('code'),- steppedClock(0, 50, 550),+ { clock: steppedClock(0, 50, 550) },)expect(m.finishReason).toBe('disconnect')expect(m.correct).toBe(false)diff --git a/src/lib/__tests__/benchmark-runaway.test.ts b/src/lib/__tests__/benchmark-runaway.test.tsnew file mode 100644index 00000000..18755d5d--- /dev/null+++ b/src/lib/__tests__/benchmark-runaway.test.ts@@ -0,0 +1,144 @@+/**+ * The emergency brake and the ranking, both from ElBiggus (issue #106, RTX+ * 5080 / Win11 25h2).+ *+ * He reported two things. `qwen3.5:9b` derails into a loop and produces two+ * orders of magnitude more tokens than the task needs, and the benchmark just+ * sits there with no way to tell a long run from a dead one. And the board is+ * ordered by tok/s alone, which reads as a black box because correctness is+ * measured and then not used for anything.+ *+ * Run: npx vitest run src/lib/__tests__/benchmark-runaway.test.ts+ */+import { describe, it, expect, vi } from 'vitest'+import { measureRun, RUNAWAY_TOKEN_CAP, RUNAWAY_MS_CAP } from '../benchmark-run'+import { getLeaderboard, rankingScore } from '../../stores/benchmarkStore'+import type { BenchmarkResult } from '../benchmark-prompts'+import type { ChatStreamChunk } from '../../api/providers/types'++/** A model that never stops. Counts what it was allowed to emit. */+function loopingStream(emitted: { n: number }): AsyncGenerator<ChatStreamChunk> {+ return (async function* () {+ for (;;) {+ emitted.n+++ yield { content: '9, ', done: false } as ChatStreamChunk+ }+ })()+}++const alwaysCorrect = () => true++describe('the emergency brake', () => {+ it('stops a looping model instead of hanging, and says why', async () => {+ const emitted = { n: 0 }+ const m = await measureRun(loopingStream(emitted), alwaysCorrect, { maxTokens: 50 })+ expect(m.finishReason).toBe('runaway')+ // Bounded, and bounded near the cap rather than some multiple of it.+ expect(emitted.n).toBeLessThanOrEqual(52)+ })++ it('a run the brake stopped counts as wrong even if the text would pass', async () => {+ // The check says true for anything here. A run that never terminated did+ // not answer the question, so scoring it correct would put a broken model+ // at the top of the board, which is the bug turned inside out.+ const m = await measureRun(loopingStream({ n: 0 }), alwaysCorrect, { maxTokens: 20 })+ expect(m.correct).toBe(false)+ })++ it('aborts the request itself, so the model stops holding the GPU', async () => {+ const onLimit = vi.fn()+ await measureRun(loopingStream({ n: 0 }), alwaysCorrect, { maxTokens: 20, onLimit })+ expect(onLimit).toHaveBeenCalledWith('runaway')+ })++ it('the wall clock catches a machine too slow to reach the token cap', async () => {+ let t = 0+ const m = await measureRun(loopingStream({ n: 0 }), alwaysCorrect, {+ maxTokens: 1_000_000,+ maxMs: 1000,+ clock: () => (t += 400),+ })+ expect(m.finishReason).toBe('timeout')+ expect(m.correct).toBe(false)+ })++ it('NEGATIVE CONTROL: an honest run is never touched by either cap', async () => {+ // Fifty numbers plus reasoning is the longest thing the prompts can ask+ // for. If the caps could reach that, the fix would be worse than the bug.+ const chunks: Partial<ChatStreamChunk>[] = []+ for (let i = 1; i <= 400; i++) chunks.push({ content: `${i}\n` })+ chunks.push({ done: true, finishReason: 'stop' })+ const m = await measureRun(+ (async function* () { for (const c of chunks) yield { content: '', done: false, ...c } as ChatStreamChunk })(),+ alwaysCorrect,+ )+ expect(m.finishReason).toBe('stop')+ expect(m.correct).toBe(true)+ })++ it('the shipped caps leave real answers room by a wide margin', () => {+ expect(RUNAWAY_TOKEN_CAP).toBeGreaterThan(4000)+ expect(RUNAWAY_MS_CAP).toBeGreaterThanOrEqual(120_000)+ })+})++function run(model: string, tps: number, correct: boolean, finishReason = 'stop'): BenchmarkResult {+ return {+ modelName: model, promptId: 'reasoning', tokensPerSec: tps,+ timeToFirstToken: 100, totalTime: 1000, totalTokens: 100,+ thinkTokens: 0, finishReason, correct, timestamp: 1,+ }+}++describe('the ranking answers "why is this one first"', () => {+ it('a fast wrong model does not outrank a slower right one', () => {+ const results = {+ fastwrong: [run('fastwrong', 100, false), run('fastwrong', 100, false)],+ slowright: [run('slowright', 60, true), run('slowright', 60, true)],+ }+ const board = getLeaderboard(results)+ expect(board[0].model).toBe('slowright')+ expect(board[0].score).toBe(60)+ expect(board[1].score).toBe(0)++ // NEGATIVE CONTROL: the old order was raw speed, which puts the model+ // that is wrong every single time on top. That is the report.+ const oldOrder = [...board].sort((a, b) => b.avgTps - a.avgTps)+ expect(oldOrder[0].model).toBe('fastwrong')+ })++ it('half the answers wrong is half the useful throughput', () => {+ const results = { m: [run('m', 80, true), run('m', 80, false)] }+ expect(getLeaderboard(results)[0].score).toBe(40)+ })++ it('runs from before correctness scoring keep their raw rate', () => {+ // Dropping them to zero would silently rewrite an old board rather than+ // admit the number is missing; the accuracy column stays empty instead.+ expect(rankingScore(42, null)).toBe(42)+ const legacy = { ...run('old', 42, true), correct: undefined }+ const board = getLeaderboard({ old: [legacy] })+ expect(board[0].accuracy).toBeNull()+ expect(board[0].score).toBe(42)+ })++ it('equal usefulness falls back to raw speed, never to insertion order', () => {+ const results = {+ slow: [run('slow', 40, true)],+ quick: [run('quick', 80, true), run('quick', 80, false)],+ }+ const board = getLeaderboard(results)+ expect(board.map((e) => e.score)).toEqual([40, 40])+ expect(board[0].model).toBe('quick') // 80 raw beats 40 raw+ })++ it('a model that ran away is counted and shown apart from an honest cut-off', () => {+ const results = {+ m: [run('m', 90, false, 'runaway'), run('m', 90, false, 'timeout'), run('m', 90, false, 'length')],+ }+ const entry = getLeaderboard(results)[0]+ expect(entry.runaway).toBe(2)+ expect(entry.truncated).toBe(1)+ expect(entry.score).toBe(0)+ })+})diff --git a/src/lib/benchmark-run.ts b/src/lib/benchmark-run.tsindex 7ea91577..5fe17262 100644--- a/src/lib/benchmark-run.ts+++ b/src/lib/benchmark-run.ts@@ -22,11 +22,42 @@ export interface RunMeasurement {correct: boolean}+/**+ * The emergency brake (ElBiggus, issue #106, RTX 5080 / Win11 25h2): a model+ * that derails into a loop emits two orders of magnitude more tokens than the+ * task needs and the benchmark simply stops moving, with no way to tell a+ * long run from a dead one. The longest honest answer here is fifty numbers+ * on their own lines plus some reasoning, so a few hundred tokens; 8000 is far+ * outside anything the three prompts can legitimately produce.+ *+ * The wall clock is the second half of the brake, for a machine so slow that+ * a runaway would still be under the token cap an hour in. It is deliberately+ * generous: a big model on CPU is slow, not broken.+ */+export const RUNAWAY_TOKEN_CAP = 8000+export const RUNAWAY_MS_CAP = 300_000++export interface MeasureOptions {+ /** Injected so a test can make timing deterministic. */+ clock?: () => number+ maxTokens?: number+ maxMs?: number+ /** Called the moment a cap trips, so the caller can abort the upstream+ * request rather than leave the model generating into a dropped stream. */+ onLimit?: (reason: 'runaway' | 'timeout') => void+}+export async function measureRun(stream: AsyncIterable<ChatStreamChunk>,check: (answer: string) => boolean,- clock: () => number = () => performance.now(),+ options: MeasureOptions = {},): Promise<RunMeasurement> {+ const {+ clock = () => performance.now(),+ maxTokens = RUNAWAY_TOKEN_CAP,+ maxMs = RUNAWAY_MS_CAP,+ onLimit,+ } = optionsconst startTime = clock()let firstTokenTime = 0let contentCount = 0@@ -60,6 +91,25 @@ export async function measureRun(if (chunk.evalDurationMs !== undefined && chunk.evalDurationMs > 0) {apiEvalDurationMs = chunk.evalDurationMs}++ // The brake. Breaking out closes the generator; onLimit fires AFTER the+ // loop, because aborting mid-iteration would race the generator's own+ // cleanup and could turn a recorded result into a thrown AbortError. The+ // run is still recorded either way: a model that ran away is a result+ // about that model, and dropping it would leave the board blank exactly+ // where the answer is "it derailed".+ const limit = contentCount + thinkCount > maxTokens+ ? 'runaway' as const+ : clock() - startTime > maxMs+ ? 'timeout' as const+ : null+ if (limit) {+ finishReason = limit+ break+ }+ }+ if (finishReason === 'runaway' || finishReason === 'timeout') {+ onLimit?.(finishReason)}const totalTime = clock() - startTime@@ -111,7 +161,8 @@ export async function measureRun(finishReason,// The answer is the visible output only. A model that reasoned its way to// the right number but never printed it fails here, which is the whole- // point of measuring correctness next to speed.- correct: check(answerText),+ // point of measuring correctness next to speed. A run the brake stopped is+ // wrong by definition, whatever happens to sit in the partial text.+ correct: finishReason === 'runaway' || finishReason === 'timeout' ? false : check(answerText),}}diff --git a/src/stores/benchmarkStore.ts b/src/stores/benchmarkStore.tsindex 9a589546..4a8864b7 100644--- a/src/stores/benchmarkStore.ts+++ b/src/stores/benchmarkStore.ts@@ -240,6 +240,16 @@ export function getTruncatedCount(results: Record<string, BenchmarkResult[]>, moreturn (results[modelName] ?? []).filter((r) => r.finishReason === 'length').length}+/**+ * Runs the emergency brake stopped: a model looping instead of answering+ * (ElBiggus, issue #106). Separate from `truncated`, which is an honest run+ * that met the token budget with the answer still coming.+ */+export function getRunawayCount(results: Record<string, BenchmarkResult[]>, modelName: string): number {+ return (results[modelName] ?? [])+ .filter((r) => r.finishReason === 'runaway' || r.finishReason === 'timeout').length+}+export interface LeaderboardEntry {model: stringavgTps: number@@ -248,20 +258,49 @@ export interface LeaderboardEntry {accuracy: number | nullthinkShare: number | nulltruncated: number+ runaway: number+ /** What the board is ordered by. See rankingScore. */+ score: number+}++/**+ * Speed weighted by how often the answer was right, in tokens per second.+ *+ * Ordering by raw tok/s alone was the second half of ElBiggus's report+ * (issue #106): it puts a model that answers wrong twice as fast above one+ * that answers correctly, and the number carries no hint that correctness was+ * even measured. Multiplying is the honest reading of "useful throughput": at+ * 50% accuracy half the tokens were wasted, so the model earns half its rate.+ *+ * A model whose runs predate correctness scoring keeps its raw rate rather+ * than being pushed to the bottom by a missing field, and the board shows the+ * accuracy column empty so the gap is visible instead of silently assumed.+ */+export function rankingScore(avgTps: number, accuracy: number | null): number {+ return Math.round(avgTps * (accuracy ?? 1) * 10) / 10}-/** Get leaderboard sorted by avg tokens/sec, with the economy stats alongside- * so speed is read next to what it cost and whether the answer was right. */+/** The leaderboard, ordered by useful throughput (rankingScore) with every+ * input to it visible alongside, so the ranking can be checked by eye rather+ * than taken on faith. */export function getLeaderboard(results: Record<string, BenchmarkResult[]>): LeaderboardEntry[] {return Object.entries(results)- .map(([model, runs]) => ({- model,- avgTps: Math.round((runs.reduce((s, r) => s + r.tokensPerSec, 0) / runs.length) * 10) / 10,- runs: runs.length,- avgTokens: getAverageTokens(results, model),- accuracy: getAccuracy(results, model),- thinkShare: getAverageThinkShare(results, model),- truncated: getTruncatedCount(results, model),- }))- .sort((a, b) => b.avgTps - a.avgTps)+ .map(([model, runs]) => {+ const avgTps = Math.round((runs.reduce((s, r) => s + r.tokensPerSec, 0) / runs.length) * 10) / 10+ const accuracy = getAccuracy(results, model)+ return {+ model,+ avgTps,+ runs: runs.length,+ avgTokens: getAverageTokens(results, model),+ accuracy,+ thinkShare: getAverageThinkShare(results, model),+ truncated: getTruncatedCount(results, model),+ runaway: getRunawayCount(results, model),+ score: rankingScore(avgTps, accuracy),+ }+ })+ // Raw speed breaks a tie, so two models with the same useful throughput+ // still sort deterministically.+ .sort((a, b) => b.score - a.score || b.avgTps - a.avgTps)}