Skip to content

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.

studio: report prompt speed in tokens per second for safetensors chat (#8647)

Maheswar Kumare7c1a13a528c
diff --git a/studio/backend/core/inference/generation_timing.py b/studio/backend/core/inference/generation_timing.py
new file mode 100644
index 00000000000..3cf6c6b0354
--- /dev/null
+++ b/studio/backend/core/inference/generation_timing.py
@@ -0,0 +1,140 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Prefill/decode timing for the safetensors generate paths.
+
+Transformers reports no timings of its own, so the prompt and generation speeds the
+chat UI reads off llama-server's ``timings`` object have to be measured here. The
+split point is the first logits-processor call, which transformers makes once the
+prefill forward pass has produced its logits, before the first token is sampled.
+
+Reaching that callback only means the kernels were queued, so each stamp waits for the
+device first. Without the wait a 2048-token prefill on an RTX 3080 reads as 28 ms
+instead of 77 ms, inflating prompt throughput 2.7x and charging the rest to decode.
+
+Kept in a dependency-light leaf module (torch + transformers only, no unsloth / peft)
+so the arithmetic can be unit-tested without loading a model, matching
+``core.inference.presence_penalty``.
+"""
+
+import time
+
+import torch
+
+
+def _wait_for_device(device):
+ """Drain queued work so a wall-clock stamp reflects finished compute, not dispatch."""
+ if device is None or device.type == "cpu":
+ return
+ synchronize = getattr(getattr(torch, device.type, None), "synchronize", None)
+ if synchronize is None:
+ return
+ try:
+ try:
+ synchronize(device)
+ except TypeError: # torch.mps.synchronize takes no device argument
+ synchronize()
+ except Exception:
+ # An async device fault surfaces here as a RuntimeError. It belongs to generate(), whose
+ # caller reports it; a timing stamp must not pre-empt that or skip the cleanup after it.
+ pass
+
+
+class GenerationTimer:
+ """Monotonic prefill/decode split around one ``model.generate()`` call."""
+
+ def __init__(self):
+ self.started_at = None
+ self.prefill_ended_at = None
+ self.ended_at = None
+ self._device = None
+
+ def start(self):
+ self.started_at = time.monotonic()
+
+ def mark_prefill_end(self, device = None):
+ """Stamp the end of prefill; later decode steps must not move the boundary."""
+ if self.started_at is None or self.prefill_ended_at is not None:
+ return
+ _wait_for_device(device)
+ # latched for finish(), which has no tensor of its own to read a device off
+ self._device = device
+ self.prefill_ended_at = time.monotonic()
+
+ def finish(self):
+ if self.started_at is None or self.ended_at is not None:
+ return
+ _wait_for_device(self._device)
+ self.ended_at = time.monotonic()
+
+ @property
+ def prompt_ms(self):
+ """Prefill wall time, or None when generation never reached its first logits."""
+ if self.started_at is None or self.prefill_ended_at is None:
+ return None
+ return max(0.0, (self.prefill_ended_at - self.started_at) * 1000.0)
+
+ @property
+ def predicted_ms(self):
+ """Decode wall time, or None when the prefill boundary or the end is unknown."""
+ if self.prefill_ended_at is None or self.ended_at is None:
+ return None
+ return max(0.0, (self.ended_at - self.prefill_ended_at) * 1000.0)
+
+
+def with_prefill_boundary_processor(logits_processor, timer):
+ """Prepend a prefill-boundary stamp to ``logits_processor`` (which may be None).
+
+ The stamp runs first within this custom list, so the presence-penalty processor sharing it
+ cannot be charged to prefill. transformers still runs its own default processors (min length,
+ repetition penalty, temperature, top-k/top-p/min-p) before the whole custom list, since
+ ``_merge_criteria_processor_list`` appends the custom one to the defaults.
+ """
+ from transformers import LogitsProcessor, LogitsProcessorList
+
+ class _PrefillBoundaryLogitsProcessor(LogitsProcessor):
+ def __call__(self, input_ids, scores):
+ # scores is the prefill output, so its device is the one to wait on
+ timer.mark_prefill_end(scores.device)
+ return scores
+
+ processors = LogitsProcessorList([_PrefillBoundaryLogitsProcessor()])
+ if logits_processor:
+ processors.extend(logits_processor)
+ return processors
+
+
+def build_generation_timings(
+ *,
+ prompt_n,
+ predicted_n,
+ prompt_ms,
+ predicted_ms,
+ cached_n = 0,
+):
+ """Map a measured prefill/decode split onto the timings shape llama-server emits.
+
+ Returns None when the split was never measured. A rate is omitted rather than
+ reported as zero when its window or token count is empty, so the UI falls back to
+ its client-side metrics instead of showing an invented speed.
+ """
+ if prompt_ms is None or predicted_ms is None:
+ return None
+ prompt_n = int(prompt_n or 0)
+ predicted_n = int(predicted_n or 0)
+ prompt_ms = float(prompt_ms)
+ predicted_ms = float(predicted_ms)
+ timings = {
+ "prompt_n": prompt_n,
+ "prompt_ms": prompt_ms,
+ "predicted_n": predicted_n,
+ "predicted_ms": predicted_ms,
+ "cache_n": int(cached_n or 0),
+ }
+ if prompt_n > 0 and prompt_ms > 0:
+ timings["prompt_per_token_ms"] = prompt_ms / prompt_n
+ timings["prompt_per_second"] = prompt_n / (prompt_ms / 1000.0)
+ if predicted_n > 0 and predicted_ms > 0:
+ timings["predicted_per_token_ms"] = predicted_ms / predicted_n
+ timings["predicted_per_second"] = predicted_n / (predicted_ms / 1000.0)
+ return timings
diff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.py
index 46137fd1bbc..9e556b5db92 100644
--- a/studio/backend/core/inference/inference.py
+++ b/studio/backend/core/inference/inference.py
@@ -43,6 +43,11 @@ from core.inference.chat_template_helpers import (
trailing_assistant_text,
)
from core.inference.presence_penalty import _make_presence_penalty_processor
+from core.inference.generation_timing import (
+ GenerationTimer,
+ build_generation_timings,
+ with_prefill_boundary_processor,
+)
from io import StringIO
import structlog
from loggers import get_logger
@@ -1419,10 +1424,13 @@ class InferenceBackend:
# Presence penalty (GGUF parity) for VLM chat.
_vision_input_ids = inputs.get("input_ids") if hasattr(inputs, "get") else None
prompt_len = int(_vision_input_ids.shape[1]) if _vision_input_ids is not None else None
- if _vision_input_ids is not None:
- _pp = _make_presence_penalty_processor(presence_penalty, prompt_len)
- if _pp is not None:
- generation_kwargs["logits_processor"] = _pp
+ _pp = (
+ _make_presence_penalty_processor(presence_penalty, prompt_len)
+ if _vision_input_ids is not None
+ else None
+ )
+ timer = GenerationTimer()
+ generation_kwargs["logits_processor"] = with_prefill_boundary_processor(_pp, timer)
stopping_criteria = self._cancel_stopping_criteria(cancel_event)
if stopping_criteria is not None:
generation_kwargs["stopping_criteria"] = stopping_criteria
@@ -1434,6 +1442,8 @@ class InferenceBackend:
def generate_fn():
with self._generation_lock:
try:
+ # Started inside the lock so a queued request's wait is not billed as prefill.
+ timer.start()
# See generate_stream: only the returned sequences carry
# an exact generated-token count.
gen_outputs["sequences"] = model.generate(**generation_kwargs)
@@ -1443,6 +1453,7 @@ class InferenceBackend:
streamer.abort()
logger.error(f"Vision generation error in thread: {e}")
finally:
+ timer.finish()
try:
streamer.end()
except Exception:
@@ -1522,6 +1533,7 @@ class InferenceBackend:
),
cancelled = not generation_complete
or (cancel_event is not None and cancel_event.is_set()),
+ timer = timer,
)
if err.get("msg"):
@@ -1627,6 +1639,8 @@ class InferenceBackend:
_audio_input_ids = inputs.get("input_ids") if hasattr(inputs, "get") else None
prompt_len = int(_audio_input_ids.shape[1]) if _audio_input_ids is not None else None
+ timer = GenerationTimer()
+ generation_kwargs["logits_processor"] = with_prefill_boundary_processor(None, timer)
active_stop_token_ids = self._generation_stop_token_ids(model, generation_kwargs)
err: dict[str, str] = {}
@@ -1638,6 +1652,8 @@ class InferenceBackend:
# As in the text path: apply under the lock so Base-vs-LoRA
# compare doesn't run the adapter on both sides (None = no-op).
self._apply_adapter_state(use_adapter)
+ # Started after the adapter swap so only model.generate() is timed.
+ timer.start()
# See generate_stream: only the returned sequences carry
# an exact generated-token count.
gen_outputs["sequences"] = model.generate(**generation_kwargs)
@@ -1645,6 +1661,7 @@ class InferenceBackend:
err["msg"] = str(e)
logger.error(f"Audio input generation error in thread: {e}")
finally:
+ timer.finish()
try:
streamer.end()
except Exception:
@@ -1694,6 +1711,7 @@ class InferenceBackend:
gen_outputs["sequences"], active_stop_token_ids
),
cancelled = not generation_complete,
+ timer = timer,
)
if err.get("msg"):
@@ -1906,8 +1924,8 @@ class InferenceBackend:
prompt_len = int(inputs["input_ids"].shape[1])
# Presence penalty (GGUF parity); prompt_len excludes prompt tokens.
_pp = _make_presence_penalty_processor(presence_penalty, prompt_len)
- if _pp is not None:
- generation_kwargs["logits_processor"] = _pp
+ timer = GenerationTimer()
+ generation_kwargs["logits_processor"] = with_prefill_boundary_processor(_pp, timer)
stopping_criteria = self._cancel_stopping_criteria(cancel_event)
if stopping_criteria is not None:
generation_kwargs["stopping_criteria"] = stopping_criteria
@@ -1917,6 +1935,8 @@ class InferenceBackend:
try:
if _adapter_state is not None:
self._apply_adapter_state(_adapter_state)
+ # Started after the adapter swap so only model.generate() is timed.
+ timer.start()
# Only the returned sequences carry an exact token count;
# the streamer sees decoded text.
gen_outputs["sequences"] = model.generate(**generation_kwargs)
@@ -1926,6 +1946,7 @@ class InferenceBackend:
streamer.abort()
logger.error(f"Generation error: {e}")
finally:
+ timer.finish()
try:
streamer.end()
except Exception:
@@ -2009,6 +2030,7 @@ class InferenceBackend:
),
cancelled = not generation_complete
or (cancel_event is not None and cancel_event.is_set()),
+ timer = timer,
)
if err.get("msg"):
@@ -2704,18 +2726,21 @@ class InferenceBackend:
max_new_tokens,
ended_on_stop_token: bool = False,
cancelled: bool = False,
+ timer = None,
) -> None:
- """Latch usage + budget exhaustion for the worker's gen_done stats channel.
+ """Latch usage, timings and budget exhaustion for the worker's gen_done stats channel.
Left at None when the token count is unknown, so a path that cannot count
reports what it did before. ``truncated`` becomes finish_reason "length";
a cancelled run stopped by request, not at the cap, so it never sets it.
+ ``timer`` carries the prefill/decode split behind the prompt and generation
+ speeds; a path that does not measure one reports usage alone.
"""
if completion_tokens is None:
return
completion_tokens = int(completion_tokens)
prompt_tokens = int(prompt_tokens or 0)
- self.last_generation_stats = {
+ stats = {
"usage": {
"prompt_tokens": prompt_tokens,
"completion_tokens": completion_tokens,
@@ -2728,6 +2753,15 @@ class InferenceBackend:
and completion_tokens >= int(max_new_tokens)
),
}
+ timings = build_generation_timings(
+ prompt_n = prompt_tokens,
+ predicted_n = completion_tokens,
+ prompt_ms = timer.prompt_ms if timer is not None else None,
+ predicted_ms = timer.predicted_ms if timer is not None else None,
+ )
+ if timings is not None:
+ stats["timings"] = timings
+ self.last_generation_stats = stats
def _cancel_stopping_criteria(self, cancel_event):
"""Build a Transformers stopping criteria list for user cancellation."""
diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.py
index 559af125a03..9702f5babce 100644
--- a/studio/backend/core/inference/worker.py
+++ b/studio/backend/core/inference/worker.py
@@ -648,8 +648,8 @@ def _handle_generate(backend, cmd: dict, resp_queue: Any, cancel_event) -> None:
{
"type": "gen_done",
"request_id": request_id,
- # usage/timings from MLX, usage + "truncated" from safetensors
- # (None for a backend that reports neither).
+ # usage/timings from MLX and safetensors, plus "truncated" from
+ # safetensors (None for a backend that reports neither).
"stats": getattr(backend, "last_generation_stats", None),
},
)
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 762bcce189e..1a502467df5 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -15088,7 +15088,7 @@ async def openai_chat_completions(
_sf_finish = "stop" if cancel_event.is_set() else _stats_finish_reason(_stats)
yield _chat_final_chunk(completion_id, created, model_name, _sf_finish)
# Reuse the reason already sent to the client. Outside the stats block
- # below: only MLX reports stats.
+ # below: a run whose token count is unknown reports no stats.
api_monitor.set_perf(monitor_id, stop_reason = _sf_finish)
if _stats:
usage_line = _openai_stream_usage_chunk(
@@ -15209,7 +15209,7 @@ async def openai_chat_completions(
api_monitor.set_reply(monitor_id, _visible_text)
_stats = _sf_stats_holder.get("stats")
# Reuse the reason this response carries. Outside the stats block below:
- # only MLX reports stats.
+ # a run whose token count is unknown reports no stats.
_sf_json_finish = "stop" if cancel_event.is_set() else _stats_finish_reason(_stats)
api_monitor.set_perf(monitor_id, stop_reason = _sf_json_finish)
if _stats:
@@ -15565,7 +15565,7 @@ async def openai_chat_completions(
)
yield _chat_final_chunk(completion_id, created, model_name, _finish)
# Reuse the reason already sent to the client. Outside the stats block
- # below: only MLX reports stats.
+ # below: a run whose token count is unknown reports no stats.
api_monitor.set_perf(monitor_id, stop_reason = _finish)
if _stats:
usage_line = _openai_stream_usage_chunk(
@@ -15752,8 +15752,8 @@ async def openai_chat_completions(
f"[tool_calls] {_calls_text}" if _calls_text else ""
)
api_monitor.set_reply(monitor_id, _monitor_reply)
- # Reuse the response's finish_reason. Outside the stats block: only
- # MLX reports stats.
+ # Reuse the response's finish_reason. Outside the stats block: a run
+ # whose token count is unknown reports no stats.
api_monitor.set_perf(monitor_id, stop_reason = _finish)
_stats = stats_holder.get("stats")
if _stats:
diff --git a/studio/backend/tests/test_generation_timing.py b/studio/backend/tests/test_generation_timing.py
new file mode 100644
index 00000000000..1e3806a62b7
--- /dev/null
+++ b/studio/backend/tests/test_generation_timing.py
@@ -0,0 +1,258 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Prompt/generation speed for the safetensors path.
+
+Transformers reports no timings, so the chat UI showed a prompt and generation speed
+for GGUF and MLX but nothing for safetensors. These tests pin the measurement: the
+prefill boundary is stamped once (at the first logits-processor call, not at every
+decode step), each stamp waits for the accelerator so it times compute rather than
+kernel dispatch, the emitted object matches llama-server's ``timings`` shape, and an
+unmeasurable rate is omitted rather than reported as zero.
+"""
+
+import pytest
+import torch
+
+from core.inference.generation_timing import (
+ GenerationTimer,
+ build_generation_timings,
+ with_prefill_boundary_processor,
+)
+from core.inference.presence_penalty import _make_presence_penalty_processor
+
+try:
+ # core.inference.inference imports unsloth at module scope, which requires
+ # unsloth_zoo. The dependency-light backend CI matrix job does not install it,
+ # so the _record_generation_stats check runs only when the stack is importable.
+ from core.inference.inference import InferenceBackend
+except ImportError:
+ InferenceBackend = None
+
+
+def test_windows_are_none_until_generation_is_measured():
+ timer = GenerationTimer()
+ assert timer.prompt_ms is None
+ assert timer.predicted_ms is None
+
+ timer.start()
+ assert timer.prompt_ms is None # prefill has not produced logits yet
+
+ timer.mark_prefill_end()
+ assert timer.prompt_ms is not None
+ assert timer.predicted_ms is None # generation has not returned yet
+
+ timer.finish()
+ assert timer.predicted_ms is not None
+
+
+def test_prefill_boundary_stamps_once_so_decode_steps_do_not_move_it():
+ timer = GenerationTimer()
+ timer.start()
+ timer.mark_prefill_end()
+ boundary = timer.prefill_ended_at
+ for _ in range(5):
+ timer.mark_prefill_end()
+ assert timer.prefill_ended_at == boundary
+
+
+def test_both_stamps_wait_for_the_accelerator(monkeypatch):
+ """A queued forward pass has not run yet, so stamping on the callback alone times
+ dispatch, not prefill. Measured on an RTX 3080: a 2048-token prefill reads as 28ms
+ unsynchronized against 77ms synchronized, a 2.7x overstated prompt speed."""
+ synced = []
+ monkeypatch.setattr(torch.cuda, "synchronize", lambda device = None: synced.append(device))
+
+ cuda = torch.device("cuda", 0)
+ timer = GenerationTimer()
+ timer.start()
+ timer.mark_prefill_end(cuda)
+ assert synced == [cuda]
+ timer.finish() # reuses the latched device: no tensor is in scope by then
+ assert synced == [cuda, cuda]
+
+
+def test_a_faulting_device_wait_still_produces_timings(monkeypatch):
+ """An async CUDA fault surfaces at the next synchronize, which is inside the stamp. The call
+ sites stamp in a finally and only then end the streamer, so a raise here would strand the
+ stream and kill the worker thread on a traceback that belongs to generate()."""
+
+ def _boom(device = None):
+ raise RuntimeError("CUDA error: device-side assert triggered")
+
+ monkeypatch.setattr(torch.cuda, "synchronize", _boom)
+
+ cuda = torch.device("cuda", 0)
+ timer = GenerationTimer()
+ timer.start()
+ timer.mark_prefill_end(cuda)
+ timer.finish()
+ assert timer.prompt_ms is not None
+ assert timer.predicted_ms is not None
+
+
+def test_a_cpu_run_has_nothing_to_wait_for(monkeypatch):
+ monkeypatch.setattr(
+ torch.cuda, "synchronize", lambda device = None: pytest.fail("cpu run synchronized")
+ )
+ timer = GenerationTimer()
+ timer.start()
+ timer.mark_prefill_end(torch.device("cpu"))
+ timer.finish()
+ assert timer.prompt_ms is not None
+
+
+def test_a_run_that_never_reached_prefill_reports_no_prompt_window():
+ timer = GenerationTimer()
+ timer.start()
+ timer.finish() # generate() raised before producing logits
+ assert timer.prompt_ms is None
+ assert timer.predicted_ms is None
+
+
+def test_timings_carry_llama_server_field_names_and_rates():
+ timings = build_generation_timings(
+ prompt_n = 400,
+ predicted_n = 50,
+ prompt_ms = 200.0,
+ predicted_ms = 2000.0,
+ )
+ assert timings["prompt_n"] == 400
+ assert timings["prompt_ms"] == pytest.approx(200.0)
+ assert timings["prompt_per_second"] == pytest.approx(2000.0)
+ assert timings["prompt_per_token_ms"] == pytest.approx(0.5)
+ assert timings["predicted_n"] == 50
+ assert timings["predicted_ms"] == pytest.approx(2000.0)
+ assert timings["predicted_per_second"] == pytest.approx(25.0)
+ assert timings["predicted_per_token_ms"] == pytest.approx(40.0)
+ assert timings["cache_n"] == 0
+
+
+def test_unmeasured_split_reports_no_timings_at_all():
+ assert (
+ build_generation_timings(
+ prompt_n = 10,
+ predicted_n = 5,
+ prompt_ms = None,
+ predicted_ms = 12.0,
+ )
+ is None
+ )
+
+
+ "prompt_n, prompt_ms",
+ [
+ (0, 30.0), # a run whose prompt length was never measured
+ (10, 0.0), # a window too short to have a rate
+ ],
+)
+def test_unratable_prompt_window_omits_the_rate_instead_of_reporting_zero(prompt_n, prompt_ms):
+ timings = build_generation_timings(
+ prompt_n = prompt_n,
+ predicted_n = 5,
+ prompt_ms = prompt_ms,
+ predicted_ms = 100.0,
+ )
+ assert "prompt_per_second" not in timings
+ assert "prompt_per_token_ms" not in timings
+ assert timings["predicted_per_second"] == pytest.approx(50.0)
+
+
+def test_processor_stamps_the_boundary_and_keeps_the_penalty_processor():
+ timer = GenerationTimer()
+ timer.start()
+ penalty = _make_presence_penalty_processor(1.0, prompt_len = 2)
+ processors = with_prefill_boundary_processor(penalty, timer)
+ assert len(processors) == 2
+
+ input_ids = torch.tensor([[0, 1, 3]])
+ scores = processors(input_ids, torch.zeros(1, 5))
+ assert timer.prompt_ms is not None
+ # the wrapped penalty still ran: the one distinct completion token lost 1.0
+ assert scores[0, 3].item() == pytest.approx(-1.0)
+
+
+def test_boundary_lands_after_the_prompt_forward_pass_in_a_real_generate():
+ """The whole split rests on transformers calling the processor once per step,
+ the first time with the prompt still unextended. Pinned against a real
+ ``generate`` so a change in that contract fails here, not in a wrong tok/s."""
+ from transformers import GPT2Config, GPT2LMHeadModel
+
+ torch.manual_seed(0)
+ model = GPT2LMHeadModel(
+ GPT2Config(vocab_size = 64, n_positions = 128, n_embd = 32, n_layer = 2, n_head = 2)
+ ).eval()
+
+ seen_lengths = []
+
+ class _RecordingProcessor:
+ def __call__(self, input_ids, scores):
+ seen_lengths.append(int(input_ids.shape[1]))
+ return scores
+
+ prompt_len = 20
+ timer = GenerationTimer()
+ processors = with_prefill_boundary_processor(None, timer)
+ processors.append(_RecordingProcessor())
+
+ timer.start()
+ outputs = model.generate(
+ input_ids = torch.randint(0, 64, (1, prompt_len)),
+ max_new_tokens = 8,
+ do_sample = False,
+ logits_processor = processors,
+ pad_token_id = 0,
+ )
+ timer.finish()
+
+ assert seen_lengths[0] == prompt_len # first call sees the prompt alone: prefill
+ assert seen_lengths == list(range(prompt_len, prompt_len + 8))
+ timings = build_generation_timings(
+ prompt_n = prompt_len,
+ predicted_n = int(outputs.shape[1]) - prompt_len,
+ prompt_ms = timer.prompt_ms,
+ predicted_ms = timer.predicted_ms,
+ )
+ assert timings["predicted_n"] == 8
+ assert timings["prompt_per_second"] > 0
+ assert timings["predicted_per_second"] > 0
+
+
+def test_processor_wraps_a_zero_penalty_run_that_has_no_processor_of_its_own():
+ timer = GenerationTimer()
+ timer.start()
+ processors = with_prefill_boundary_processor(None, timer)
+ scores = torch.zeros(1, 5)
+ out = processors(torch.tensor([[0, 1, 3]]), scores)
+ assert timer.prompt_ms is not None
+ assert torch.equal(out, scores)
+
+
[email protected](InferenceBackend is None, reason = "unsloth stack not installed")
+def test_recorded_stats_carry_timings_only_when_a_run_was_timed():
+ timer = GenerationTimer()
+ timer.start()
+ timer.mark_prefill_end()
+ timer.finish()
+
+ backend = InferenceBackend.__new__(InferenceBackend)
+ InferenceBackend._record_generation_stats(
+ backend,
+ prompt_tokens = 64,
+ completion_tokens = 16,
+ max_new_tokens = 256,
+ timer = timer,
+ )
+ stats = backend.last_generation_stats
+ assert stats["usage"] == {"prompt_tokens": 64, "completion_tokens": 16, "total_tokens": 80}
+ assert stats["timings"]["prompt_n"] == 64
+ assert stats["timings"]["predicted_n"] == 16
+
+ InferenceBackend._record_generation_stats(
+ backend,
+ prompt_tokens = 64,
+ completion_tokens = 16,
+ max_new_tokens = 256,
+ )
+ assert "timings" not in backend.last_generation_stats
diff --git a/studio/frontend/src/components/assistant-ui/message-response-details-sheet.tsx b/studio/frontend/src/components/assistant-ui/message-response-details-sheet.tsx
index 48b9d193795..8549e9af4dc 100644
--- a/studio/frontend/src/components/assistant-ui/message-response-details-sheet.tsx
+++ b/studio/frontend/src/components/assistant-ui/message-response-details-sheet.tsx
@@ -323,6 +323,12 @@ export const MessageResponseDetailsSheet: FC<{
(promptTokens != null && completionTokens != null
? promptTokens + completionTokens
: undefined);
+ // Same gate as the timing tooltip: a one-token prompt or a missing rate has no speed to show.
+ const promptRate = asNumber(serverTimings?.prompt_per_second);
+ const promptSpeed =
+ (asNumber(serverTimings?.prompt_n) ?? 0) > 1 && (promptRate ?? 0) > 0
+ ? promptRate
+ : undefined;
const totalTime =
responseDetails?.durationMs ?? timing?.totalStreamTime ?? undefined;
const summaryLabel =
@@ -427,6 +433,11 @@ export const MessageResponseDetailsSheet: FC<{
value={formatMs(asNumber(serverTimings?.prompt_ms))}
mono
/>
+ <DetailRow
+ label="Prompt speed"
+ value={formatRate(promptSpeed)}
+ mono
+ />
<DetailRow
label="Generation"
value={formatMs(asNumber(serverTimings?.predicted_ms))}
diff --git a/studio/frontend/src/components/assistant-ui/message-timing.tsx b/studio/frontend/src/components/assistant-ui/message-timing.tsx
index e0a111820bd..9d8b1438c17 100644
--- a/studio/frontend/src/components/assistant-ui/message-timing.tsx
+++ b/studio/frontend/src/components/assistant-ui/message-timing.tsx
@@ -26,8 +26,9 @@ const formatRate = (r: number | undefined): string => {
/**
* Shows streaming stats as a badge with hover tooltip.
- * When server timings are available (GGUF), shows prompt eval, generation,
- * speed, tokens, and cache hits. Falls back to client-side metrics otherwise.
+ * When server timings are available (GGUF, MLX, safetensors), shows prompt eval,
+ * prompt speed, generation, speed, tokens, and cache hits. Falls back to
+ * client-side metrics otherwise.
*/
export const MessageTiming: FC<{
className?: string;
@@ -196,7 +197,7 @@ export const MessageTiming: FC<{
</>
) : (
<>
- {/* Server-side metrics (GGUF) */}
+ {/* Server-side metrics (GGUF, MLX, safetensors) */}
{st?.prompt_ms != null && (
<div className="flex items-center justify-between gap-4">
<span className="text-muted-foreground">Prompt eval</span>
@@ -205,7 +206,9 @@ export const MessageTiming: FC<{
</span>
</div>
)}
- {(st?.prompt_n ?? 0) > 1 && st?.prompt_per_second != null && (
+ {(st?.prompt_n ?? 0) > 1 &&
+ st?.prompt_per_second != null &&
+ st.prompt_per_second > 0 && (
<div className="flex items-center justify-between gap-4">
<span className="text-muted-foreground">Prompt speed</span>
<span className="font-mono tabular-nums">
@@ -294,7 +297,7 @@ export const MessageTiming: FC<{
)
) : (
<>
- {/* Client-side metrics (safetensors + external provider fallback) */}
+ {/* Client-side metrics (external provider fallback) */}
{timing.firstTokenTime !== undefined && (
<div className="flex items-center justify-between gap-4">
<span className="text-muted-foreground">First token</span>