Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: estimate the prompt's time left from how the cost per token grows, not the rate so far (#16450)
oobaboogaac7229860e39
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 3c342630ec5..8947f99a351 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -7226,6 +7226,8 @@ class _PrefillProgressSignal:"total": total,"cached": min(cached, processed) if cached is not None else None,"tok_per_s": _live_rate(rate),+ # Server time avoids poll-arrival quantization.+ "time_ms": _live_count(progress.get("time_ms")),}def _record_decode(self, sample: dict) -> None:diff --git a/studio/backend/tests/test_live_generation_progress.py b/studio/backend/tests/test_live_generation_progress.pyindex f1d31a8ac5b..8ff0c82ba26 100644--- a/studio/backend/tests/test_live_generation_progress.py+++ b/studio/backend/tests/test_live_generation_progress.py@@ -47,6 +47,7 @@ def test_prefill_samples_become_frames_once_each():"total": 5316,"cached": 0,"tok_per_s": 1365.3,+ "time_ms": 1500,}# Sent once; the stall loop polls far more often than llama-server reports a batch.assert signal.live_frame() is None@@ -64,6 +65,7 @@ def test_prefill_counts_are_clamped_and_bad_rates_dropped():assert frame["processed"] == 100assert frame["cached"] == 100assert frame["tok_per_s"] is None+ assert frame["time_ms"] is None, "an older llama-server without time_ms"def test_decode_frames_are_throttled(monkeypatch):diff --git a/studio/frontend/src/features/chat/lib/generation-progress.ts b/studio/frontend/src/features/chat/lib/generation-progress.tsindex 8ef980b2ddf..1ccaf5b86b2 100644--- a/studio/frontend/src/features/chat/lib/generation-progress.ts+++ b/studio/frontend/src/features/chat/lib/generation-progress.ts@@ -5,6 +5,7 @@ import type {LiveDecodeProgress,LiveGenerationProgress,LivePrefillProgress,+ LivePrefillFit,} from "../stores/chat-runtime-store";import { formatEta } from "../utils/format-transfer";@@ -41,6 +42,8 @@ export function readGenerationProgress(total: total || null,cached: count(f.cached),tokPerS: rate(f.tok_per_s),+ elapsedMs: count(f.time_ms),+ fit: null,},};}@@ -84,14 +87,97 @@ export function formatPrefillDetails(}const MIN_TOKENS_FOR_PREFILL_RATE = 512;+const MIN_SAMPLES_FOR_PREFILL_FIT = 4;+const FIT_FULL_AT_READ = 0.3;const PREFILL_LABEL_MIN_SECONDS = 2;-/** Seconds left at the rate so far, or null while llama.cpp's first sample (a few tokens in, before- * the first batch) is all there is, since its rate is noise. */-function prefillSecondsLeft(prefill: LivePrefillProgress): number | null {- if (!prefill.total || prefill.tokPerS === null) return null;- if (prefill.processed - (prefill.cached ?? 0) < MIN_TOKENS_FOR_PREFILL_RATE) return null;- return (prefill.total - prefill.processed) / prefill.tokPerS;+function samePrefillPass(+ previous: LiveGenerationProgress | undefined,+ prefill: LivePrefillProgress,+): previous is LiveGenerationProgress & { prefill: LivePrefillProgress } {+ return (+ previous?.prefill != null &&+ previous.decode === null &&+ previous.prefill.total === prefill.total &&+ previous.prefill.processed <= prefill.processed+ );+}++function timedSample(prefill: LivePrefillProgress): { done: number; elapsedMs: number } | null {+ const done = prefill.processed - (prefill.cached ?? 0);+ return done >= MIN_TOKENS_FOR_PREFILL_RATE && prefill.elapsedMs+ ? { done, elapsedMs: prefill.elapsedMs }+ : null;+}++export function withPrefillFit(+ previous: LiveGenerationProgress | undefined,+ prefill: LivePrefillProgress,+): LivePrefillProgress {+ const kept = samePrefillPass(previous, prefill) ? previous.prefill.fit : null;+ const now = timedSample(prefill);+ if (now === null || (kept !== null && now.done <= kept.done)) {+ return { ...prefill, fit: kept };+ }+ const x = now.done / 1000;+ const y = now.elapsedMs / 1000;+ const terms = [1, x, x * x, x ** 3, x ** 4, y, x * y, x * x * y];+ const sums = terms.map((term, i) => (kept?.sums[i] ?? 0) + term);+ return { ...prefill, fit: { first: kept?.first ?? now.done, done: now.done, sums } };+}++function det3(m: number[][]): number {+ return (+ m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) -+ m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) ++ m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])+ );+}++// Fit c + a*x + b*x²; cap extrapolation at the observed span so one slow batch cannot dominate.+function fittedSeconds(fit: LivePrefillFit, from: number, to: number): number | null {+ const [n, sx, sx2, sx3, sx4, sy, sxy, sx2y] = fit.sums;+ if (n < MIN_SAMPLES_FOR_PREFILL_FIT) return null;+ const normal = [+ [n, sx, sx2],+ [sx, sx2, sx3],+ [sx2, sx3, sx4],+ ];+ const d = det3(normal);+ if (d > 0) {+ const withColumn = (column: number) =>+ det3(normal.map((row, i) => row.map((v, j) => (j === column ? [sy, sxy, sx2y][i] : v))));+ const a = withColumn(1) / d;+ const b = withColumn(2) / d;+ if (b > 0 && a + 2 * b * from > 0) {+ const cap = Math.min(to, from + (from - fit.first / 1000));+ const grown = a * (cap - from) + b * (cap * cap - from * from);+ return grown + (a + 2 * b * cap) * (to - cap);+ }+ }+ const slope = (n * sxy - sx * sy) / (n * sx2 - sx * sx);+ return Number.isFinite(slope) && slope > 0 ? slope * (to - from) : null;+}++export function prefillSecondsLeft(prefill: LivePrefillProgress): number | null {+ if (!prefill.total) return null;+ const cached = prefill.cached ?? 0;+ const now = timedSample(prefill);+ const rateSoFar =+ prefill.tokPerS !== null && prefill.processed - cached >= MIN_TOKENS_FOR_PREFILL_RATE+ ? (prefill.total - prefill.processed) / prefill.tokPerS+ : null;+ if (now !== null && prefill.fit !== null) {+ const todo = prefill.total - cached;+ const fitted = fittedSeconds(prefill.fit, now.done / 1000, todo / 1000);+ if (fitted !== null) {+ if (rateSoFar === null) return fitted;+ const samples = prefill.fit.sums[0];+ const weight = Math.min(1, now.done / todo / FIT_FULL_AT_READ, (samples - 3) / 3);+ return rateSoFar + weight * (fitted - rateSoFar);+ }+ }+ return rateSoFar;}/** Whether "Processing prompt" shows after this sample. Only a pass expected to keep it up for@@ -101,17 +187,12 @@ export function prefillLabelShown(previous: LiveGenerationProgress | undefined,prefill: LivePrefillProgress,): boolean {- const samePass =- previous?.prefill != null &&- previous.decode === null &&- previous.prefill.total === prefill.total &&- previous.prefill.processed <= prefill.processed;- if (samePass && previous.prefillShown) return true;+ if (samePrefillPass(previous, prefill) && previous.prefillShown) return true;const left = prefillSecondsLeft(prefill);return left !== null && left >= PREFILL_LABEL_MIN_SECONDS;}-/** "12s left" at the rate so far, like the load toast; null without a trusted rate or under a second. */+/** "12s left", like the load toast; null without a trusted rate or under a second. */export function formatPrefillTimeLeft(prefill: LivePrefillProgress): string | null {const left = prefillSecondsLeft(prefill);return left !== null && left >= 1 ? `${formatEta(left)} left` : null;diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.tsindex 1f362a7dc37..627eeb9b3c6 100644--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts@@ -129,7 +129,7 @@ import {type ModelLifecyclePhase,} from "../utils/model-lifecycle-gate";import { shouldAdvanceQueuedSettingsEpoch } from "../utils/queued-settings-epoch";-import { prefillLabelShown } from "../lib/generation-progress";+import { prefillLabelShown, withPrefillFit } from "../lib/generation-progress";import { adoptFirstTurnConfirmations } from "../utils/adopt-first-turn-confirmations";import type { MmprojFallbackReason } from "../types/api";import type {@@ -426,11 +426,15 @@ export type LoadedPlacement = {/** Set when every routed expert is in RAM with a GPU cache of the busiest (--moe-cache-mib auto). */expertCacheMib: number | null;};+// x = uncached kilotokens, y = server seconds; sums: n, x, x², x³, x⁴, y, xy, x²y.+export type LivePrefillFit = { first: number; done: number; sums: readonly number[] };export type LivePrefillProgress = {processed: number;total: number | null;cached: number | null;tokPerS: number | null;+ elapsedMs: number | null;+ fit: LivePrefillFit | null;};export type LiveDecodeProgress = {tokens: number;@@ -5965,7 +5969,9 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({setLivePrefill: (threadId, prefill) =>set((state) => {const key = threadId || "__default";- const prefillShown = prefillLabelShown(state.liveGenerationByThreadId[key], prefill);+ const previous = state.liveGenerationByThreadId[key];+ prefill = withPrefillFit(previous, prefill);+ const prefillShown = prefillLabelShown(previous, prefill);// A new prompt pass (the next round of a tool loop) starts over, so its decode figures go too.return {liveGenerationByThreadId: {diff --git a/studio/frontend/tests/generation-details.test.ts b/studio/frontend/tests/generation-details.test.tsindex 870d1ed25e9..264d86687bc 100644--- a/studio/frontend/tests/generation-details.test.ts+++ b/studio/frontend/tests/generation-details.test.ts@@ -16,6 +16,8 @@ const {formatPrefillTimeLeft,prefillLabelShown,prefillPercent,+ prefillSecondsLeft,+ withPrefillFit,readGenerationProgress,} = await import("../src/features/chat/lib/generation-progress.ts");const { describePlacement, loadedPlacementFrom } = await import(@@ -31,6 +33,10 @@ const { generationChunkCountsTowardTiming } = await import("../src/features/chat/utils/chat-generation-recovery.ts");+const prefill = (+ fields: Omit<LivePrefillProgress, "elapsedMs" | "fit"> & Partial<LivePrefillProgress>,+): LivePrefillProgress => ({ elapsedMs: null, fit: null, ...fields });+test("prefill frames read into store shape, clamped, and give a whole percent", () => {const update = readGenerationProgress({type: "generation_progress",@@ -39,29 +45,127 @@ test("prefill frames read into store shape, clamped, and give a whole percent",total: 5316,cached: 7000,tok_per_s: 1326.4,+ time_ms: 3950,});assert.equal(update?.phase, "prefill");if (update?.phase !== "prefill") return;- assert.deepEqual(update.prefill, { processed: 5316, total: 5316, cached: 7000, tokPerS: 1326.4 });- assert.equal(prefillPercent({ processed: 2048, total: 5316, cached: 0, tokPerS: null }), 38);- assert.equal(prefillPercent({ processed: 10, total: null, cached: null, tokPerS: null }), null);+ assert.deepEqual(update.prefill, prefill({ processed: 5316, total: 5316, cached: 7000, tokPerS: 1326.4, elapsedMs: 3950 }));+ assert.equal(prefillPercent(prefill({ processed: 2048, total: 5316, cached: 0, tokPerS: null })), 38);+ assert.equal(prefillPercent(prefill({ processed: 10, total: null, cached: null, tokPerS: null })), null);});test("a follow-up in a long chat counts only the part the cache did not cover", () => {// 29,000 of 30,000 tokens reused: halfway through the new 1,000, not 98% of the whole prompt.- const followUp = { processed: 29500, total: 30000, cached: 29000, tokPerS: 1000 };+ const followUp = prefill({ processed: 29500, total: 30000, cached: 29000, tokPerS: 1000 });assert.equal(prefillPercent(followUp), 50);assert.equal(formatPrefillDetails(followUp, "en-US"), "500 / 1,000 tokens · 1,000 tok/s");// llama.cpp evaluates at least one token, but a cache that covers it all is done, not NaN.- assert.equal(prefillPercent({ processed: 30000, total: 30000, cached: 30000, tokPerS: null }), 100);+ assert.equal(prefillPercent(prefill({ processed: 30000, total: 30000, cached: 30000, tokPerS: null })), 100);});test("the time left follows the rate so far and drops out under a second", () => {- assert.equal(formatPrefillTimeLeft({ processed: 4118, total: 18880, cached: 0, tokPerS: 1401.2 }), "11s left");- assert.equal(formatPrefillTimeLeft({ processed: 5000, total: 200000, cached: 0, tokPerS: 1500 }), "2m 10s left");+ assert.equal(formatPrefillTimeLeft(prefill({ processed: 4118, total: 18880, cached: 0, tokPerS: 1401.2 })), "11s left");+ assert.equal(formatPrefillTimeLeft(prefill({ processed: 5000, total: 200000, cached: 0, tokPerS: 1500 })), "2m 10s left");// The first sample's rate is noise, and at the end there is nothing worth counting down.- assert.equal(formatPrefillTimeLeft({ processed: 22, total: 18844, cached: 0, tokPerS: 242 }), null);- assert.equal(formatPrefillTimeLeft({ processed: 18500, total: 18880, cached: 0, tokPerS: 1400 }), null);+ assert.equal(formatPrefillTimeLeft(prefill({ processed: 22, total: 18844, cached: 0, tokPerS: 242 })), null);+ assert.equal(formatPrefillTimeLeft(prefill({ processed: 18500, total: 18880, cached: 0, tokPerS: 1400 })), null);+});++// llama-server's own [processed, time_ms] samples for two prompts. The first, 30,382 tokens through+// llama-server directly, ended at 34,847 ms; the second, 27,268 tokens through Studio, ended at+// 18,229 ms and its first batch was slow (warm-up), which a fit through the first sample misreads.+const LONG_PROMPTS = [+ {+ total: 30382,+ endMs: 34847,+ samples: [+ [0, 0], [1, 6], [2049, 1230], [4097, 2643], [6145, 4180], [8193, 5911], [10241, 7781],+ [12289, 9807], [14337, 11955], [16385, 14277], [18433, 16762], [20481, 19450], [22529, 22273],+ [24577, 25239], [26625, 28324], [28673, 31509], [29866, 33929],+ ],+ },+ {+ total: 27268,+ endMs: 18229,+ samples: [+ [1, 2], [2049, 1122], [4097, 2033], [6145, 3026], [8193, 4029], [10241, 5119], [12289, 6341],+ [14337, 7784], [16385, 9124], [18433, 10551], [20481, 12066], [22529, 13665], [24577, 15436],+ [26625, 17363],+ ],+ },+];++test("the time left allows for later prompt tokens costing more than earlier ones", () => {+ for (const { total, endMs, samples } of LONG_PROMPTS) {+ let previous: { prefill: LivePrefillProgress; prefillShown: boolean; decode: null } | undefined;+ const errors: number[] = [];+ const rateSoFar: number[] = [];+ for (const [processed, time_ms] of samples) {+ const tok_per_s = time_ms > 0 ? (processed / time_ms) * 1000 : 0;+ const update = readGenerationProgress({ phase: "prefill", processed, total, cached: 0, tok_per_s, time_ms });+ assert.equal(update?.phase, "prefill");+ if (update?.phase !== "prefill") return;+ const current = withPrefillFit(previous, update.prefill);+ previous = { prefill: current, prefillShown: false, decode: null };+ const left = prefillSecondsLeft(current);+ const actual = (endMs - time_ms) / 1000;+ if (left === null || processed < 0.3 * total || actual < 3) continue;+ const rateError = ((total - processed) / tok_per_s - actual) / actual;+ const error = (left - actual) / actual;+ rateSoFar.push(rateError);+ assert.ok(Math.abs(error) <= Math.abs(rateError) + 0.01, `${processed}: ${error} vs ${rateError}`);+ if (processed >= 0.45 * total) errors.push(error);+ }+ assert.ok(errors.length >= 6);+ assert.ok(rateSoFar.every((e) => e < -0.3), String(rateSoFar));+ assert.ok(errors.every((e) => Math.abs(e) < 0.2), String(errors));+ }+});++test("one slow batch early in a long prompt does not read as a slowdown for the rest of it", () => {+ for (const total of [32768, 131072]) {+ let previous: { prefill: LivePrefillProgress; prefillShown: boolean; decode: null } | undefined;+ let elapsed = 0;+ const totalMs = (total / 2048) * 500 + 250;+ for (let batch = 1; batch * 2048 <= total; batch++) {+ elapsed += 500 + (batch === 4 ? 250 : 0);+ const processed = batch * 2048;+ const update = readGenerationProgress({+ phase: "prefill", processed, total, cached: 0, tok_per_s: (processed / elapsed) * 1000, time_ms: elapsed,+ });+ if (update?.phase !== "prefill") return;+ const current = withPrefillFit(previous, update.prefill);+ previous = { prefill: current, prefillShown: false, decode: null };+ const left = prefillSecondsLeft(current);+ const actual = (totalMs - elapsed) / 1000;+ if (left === null || actual < 2) continue;+ assert.ok(left < actual * 1.6, `${total} at ${processed}: ${left.toFixed(1)} s shown for ${actual.toFixed(1)} s left`);+ }+ }+});++test("the time-left fit sums a pass's timed samples and starts over with the next pass", () => {+ const at = (processed: number, elapsedMs: number, total = 30382) =>+ prefill({ processed, total, cached: 0, tokPerS: 1000, elapsedMs });+ const pass = (p: LivePrefillProgress) => ({ prefill: p, prefillShown: false, decode: null });+ const first = withPrefillFit(undefined, at(1, 6));+ assert.equal(first.fit, null);+ const second = withPrefillFit(pass(first), at(2049, 1230));+ const third = withPrefillFit(pass(second), at(4097, 2643));+ assert.equal(third.fit?.sums[0], 2);+ assert.equal(prefillSecondsLeft(third), (30382 - 4097) / 1000);+ assert.equal(withPrefillFit(pass(third), at(4097, 2643)).fit?.sums[0], 2);+ const fourth = withPrefillFit(pass(third), at(6145, 4180));+ assert.equal(prefillSecondsLeft(fourth), (30382 - 6145) / 1000);+ const fifth = withPrefillFit(pass(fourth), at(8193, 5911));+ assert.equal(fifth.fit?.sums[0], 4);+ assert.equal(fifth.fit?.first, 2049, "the span the curve may be extended by starts at the first timed sample");+ assert.notEqual(prefillSecondsLeft(fifth), (30382 - 8193) / 1000);+ const untimed = prefill({ processed: 4097, total: 30382, cached: 0, tokPerS: 1000 });+ assert.equal(withPrefillFit(undefined, untimed).fit, null);+ const decode = { tokens: 9, tokPerS: 50, draftN: null, draftAccepted: null };+ assert.equal(withPrefillFit({ ...pass(fifth), decode }, at(4097, 900)).fit?.sums[0], 1);+ assert.equal(withPrefillFit(pass(fifth), at(4097, 900, 40000)).fit?.sums[0], 1);});test("malformed frames are dropped rather than drawn as NaN", () => {@@ -80,19 +184,15 @@ test("decode frames keep draft acceptance only when both counts are there", () =test("the prefill details give the rate when there is one", () => {assert.equal(- formatPrefillDetails({ processed: 4118, total: 18880, cached: 0, tokPerS: 1401.2 }, "en-US"),+ formatPrefillDetails(prefill({ processed: 4118, total: 18880, cached: 0, tokPerS: 1401.2 }), "en-US"),"4,118 / 18,880 tokens · 1,401 tok/s",);- assert.equal(formatPrefillDetails({ processed: 900, total: null, cached: null, tokPerS: null }, "en-US"), "900 tokens");+ assert.equal(formatPrefillDetails(prefill({ processed: 900, total: null, cached: null, tokPerS: null }), "en-US"), "900 tokens");});test("the prefill label shows only for a pass expected to keep it up, then stays for that pass", () => {- const sample = (processed: number, total: number, tokPerS: number | null, cached = 0) => ({- processed,- total,- cached,- tokPerS,- });+ const sample = (processed: number, total: number, tokPerS: number | null, cached = 0) =>+ prefill({ processed, total, cached, tokPerS });const after = (prefill: LivePrefillProgress, prefillShown: boolean, decode: LiveDecodeProgress | null = null) => ({prefill,prefillShown,