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: show image generation time (#16462)

AAFI MALEK7603b8072c13
diff --git a/.github/workflows/studio-ui-smoke.yml b/.github/workflows/studio-ui-smoke.yml
index 3732fa2548d..34e7afd921a 100644
--- a/.github/workflows/studio-ui-smoke.yml
+++ b/.github/workflows/studio-ui-smoke.yml
@@ -549,6 +549,13 @@ jobs:
mkdir -p logs/playwright_image_footprint
python tests/studio/playwright_image_model_footprint.py
+ - name: Image generation time regression (Playwright)
+ if: matrix.shard == 'extra'
+ env:
+ BASE_URL: http://127.0.0.1:18894
+ STUDIO_PW: ${{ env.STUDIO_EXTRA_NEW_PW }}
+ run: python tests/studio/playwright_images_generation_time.py
+
- name: Image staged-download cancel/retry regression (Playwright)
if: matrix.shard == 'extra'
env:
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 6155d610807..9dd37f57659 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -5561,6 +5561,13 @@ class GalleryImage(BaseModel):
batch_size: int = Field(
1, description = "Batch size used; with batch_index it lets restore replay this image"
)
+ generation_seconds: Optional[float] = Field(
+ None,
+ description = "Elapsed generation seconds until images are ready to save, shared by the request",
+ )
+ generation_count: Optional[int] = Field(
+ None, description = "Number of images in the timed request; absent on older records"
+ )
model: Optional[str] = Field(None, description = "Model repo id that produced it")
# The load-time BUILD. The repo id alone does not identify a pipeline (quant choice, torchao scheme, baked adapters), so without these a recipe cannot be rebuilt.
engine: Optional[str] = Field(
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 81aac3ad9a6..210358ed04d 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -49023,6 +49023,7 @@ async def _external_image_generation(
timeout = 600.0,
)
owner = current_account_id()
+ generation_started = time.perf_counter()
task = asyncio.create_task(
client.create_images(
prompt = body.prompt,
@@ -49066,6 +49067,7 @@ async def _external_image_generation(
status_code = 502, detail = "The image endpoint did not return a usable image."
) from exc
+ generation_seconds = time.perf_counter() - generation_started
created_at = time.time()
def _persist() -> list[dict]:
@@ -49082,6 +49084,8 @@ async def _external_image_generation(
"seed": body.seed or 0,
"batch_index": index,
"batch_size": body.batch_size,
+ "generation_seconds": generation_seconds,
+ "generation_count": len(images),
"model": external_model,
"model_kind": "connection",
"created_at": created_at,
@@ -49221,6 +49225,7 @@ async def _generate_diffusion_image_run(
else None
)
submitted = request
+ generation_started = time.perf_counter()
# FLUX.3 prompt upsampling runs ahead of the run, so the sidecar can leave the VRAM before the DiT denoises.
enhancement = await _enhance_generate_prompts(backend, request)
if enhancement.status != "applied":
@@ -49364,6 +49369,7 @@ async def _generate_diffusion_image_run(
_diffusion_persist_active -= 1
raise
+ generation_seconds = time.perf_counter() - generation_started
# Persist each image with its full recipe. BOTH engines batch with a distinct seed per image, returned in ``seeds``, so each is individually reproducible.
created_at = time.time()
per_image_seeds = result.get("seeds")
@@ -49406,6 +49412,8 @@ async def _generate_diffusion_image_run(
"batch_index": index,
# The batch shares one seed, so reproducing a batch_index>0 image needs the original batch_size.
"batch_size": 1 if list_driven else request.batch_size,
+ "generation_seconds": generation_seconds,
+ "generation_count": len(result["images"]),
"model": result.get("repo_id"),
**({"engine": result["engine"]} if result.get("engine") else {}),
# The BUILD the image came off, not just the repo id: a GGUF repo holds many quants, a dense load may be torchao-
@@ -51246,6 +51254,7 @@ async def _generate_openai_images(
openai_errors = True,
hf_token = hf_token,
)
+ generation_started = time.perf_counter()
# Use the active engine (diffusers OR native sd.cpp), the same accessor /images/generate uses.
backend = get_active_diffusion_engine()
@@ -51329,6 +51338,7 @@ async def _generate_openai_images(
logger.error("openai_images.generate_failed: %s", exc)
raise HTTPException(status_code = 500, detail = _generate_failure_detail(str(exc)))
+ generation_seconds = time.perf_counter() - generation_started
# A local-directory load puts the host path in repo_id, and the monitor row is tunnelled.
_served_repo = str(result.get("repo_id") or "")
api_monitor.relabel(monitor_id, public_model_id(_served_repo) or _served_repo)
@@ -51345,6 +51355,8 @@ async def _generate_openai_images(
"guidance": guidance,
# The batch shares one base seed, so restoring a batch_index>0 sibling needs the original batch_size.
"batch_size": body.n,
+ "generation_seconds": generation_seconds,
+ "generation_count": len(result["images"]),
"model": result.get("repo_id"),
# Same build record as /images/generate, so the gallery entry can name the GGUF quant and precision.
"model_kind": result.get("model_kind"),
diff --git a/studio/backend/tests/test_diffusion_routes.py b/studio/backend/tests/test_diffusion_routes.py
index eb95c03d2ac..e63f7a8ff73 100644
--- a/studio/backend/tests/test_diffusion_routes.py
+++ b/studio/backend/tests/test_diffusion_routes.py
@@ -508,6 +508,29 @@ def test_generate_batch_size_persists_each_image(client):
assert len(client.get("/api/inference/images/gallery").json()["images"]) == 3
+def test_gallery_records_generation_time_for_the_whole_batch(client, monkeypatch):
+ import time
+
+ backend = diffusion_module.get_diffusion_backend()
+ generate = backend.generate
+
+ def _slow_generate(**kwargs):
+ time.sleep(0.03)
+ return generate(**kwargs)
+
+ monkeypatch.setattr(backend, "generate", _slow_generate)
+ _post_load(client, model_path = "x/z-image", gguf_filename = "q.gguf")
+ response = _post_generate(client, prompt = "p", batch_size = 2, seed = 5)
+ assert response.status_code == 200
+ images = response.json()["images"]
+ assert len(images) == 2
+ assert images[0]["generation_seconds"] >= 0.03
+ assert images[1]["generation_seconds"] == images[0]["generation_seconds"]
+ assert [image["generation_count"] for image in images] == [2, 2]
+ listed = client.get("/api/inference/images/gallery").json()["images"]
+ assert all(image["generation_seconds"] == images[0]["generation_seconds"] for image in listed)
+
+
def test_generate_batch_persists_through_one_save_many(client, monkeypatch):
batches = []
real = gallery_module.save_many
@@ -2163,6 +2186,8 @@ def test_recipe_records_the_conditioned_workflow_settings(client, monkeypatch):
assert gen.status_code == 200
img = gen.json()["images"][0]
assert img["workflow"] == "inpaint"
+ assert img["generation_seconds"] >= 0
+ assert img["generation_count"] == 1
assert img["strength"] == 0.42
plain = client.post("/api/inference/images/generate", json = {"prompt": "a sloth", "seed": 7})
assert plain.status_code == 200
@@ -3060,6 +3085,9 @@ def test_external_connection_generates_without_a_local_model_and_saves_to_galler
assert [(i["prompt"], i["model"], i["width"], i["height"]) for i in images] == [
("a sloth", "qwen-image", 512, 256)
] * 2
+ assert images[0]["generation_seconds"] >= 0
+ assert images[1]["generation_seconds"] == images[0]["generation_seconds"]
+ assert [image["generation_count"] for image in images] == [2, 2]
assert len(client.get("/api/inference/images/gallery").json()["images"]) == 2
assert sent == [
(
diff --git a/studio/backend/tests/test_image_gallery.py b/studio/backend/tests/test_image_gallery.py
index c3c2896d44f..571c575974d 100644
--- a/studio/backend/tests/test_image_gallery.py
+++ b/studio/backend/tests/test_image_gallery.py
@@ -61,6 +61,18 @@ def test_save_embeds_recipe_and_round_trips():
assert listed[0]["prompt"] == "a sloth" and listed[0]["seed"] == 7
+def test_generation_time_round_trips_and_old_images_remain_readable():
+ from models.inference import GalleryImage
+
+ gallery.save(_img(), _meta(prompt = "new", generation_seconds = 1.25, generation_count = 2))
+ gallery.save(_img(), _meta(prompt = "old"))
+ images = {image["prompt"]: GalleryImage(**image) for image in gallery.list_images()}
+ assert images["new"].generation_seconds == 1.25
+ assert images["new"].generation_count == 2
+ assert images["old"].generation_seconds is None
+ assert images["old"].generation_count is None
+
+
def test_listing_reads_the_recipe_without_decoding_pixels(monkeypatch):
from PIL import PngImagePlugin
diff --git a/studio/backend/tests/test_openai_images_generations_route.py b/studio/backend/tests/test_openai_images_generations_route.py
index fbc53ceef0b..3ac8f729987 100644
--- a/studio/backend/tests/test_openai_images_generations_route.py
+++ b/studio/backend/tests/test_openai_images_generations_route.py
@@ -368,6 +368,9 @@ def test_batch_persists_batch_size(monkeypatch):
records = sorted(store.values(), key = lambda r: r["batch_index"])
assert [r["batch_index"] for r in records] == [0, 1, 2]
assert all(r["batch_size"] == 3 for r in records)
+ assert records[0]["generation_seconds"] >= 0
+ assert all(r["generation_seconds"] == records[0]["generation_seconds"] for r in records)
+ assert all(r["generation_count"] == 3 for r in records)
def test_uses_active_engine_not_diffusers_singleton(monkeypatch):
diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.ts
index 05bce080484..92d6076a5d1 100644
--- a/studio/frontend/src/features/images/api.ts
+++ b/studio/frontend/src/features/images/api.ts
@@ -315,6 +315,8 @@ export interface GalleryImage {
batch_seed?: number | null;
batch_index: number;
batch_size: number;
+ generation_seconds?: number | null;
+ generation_count?: number | null;
model: string | null;
// The load-time build. The repo id alone does not identify a pipeline (quant choice, torchao
// scheme, baked adapters), so these are what a recipe needs once the model is unloaded.
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index 0e2e9acdc4e..bbb564ef768 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -1293,16 +1293,19 @@ function RecipeRow({
value,
wrap,
mono,
+ title,
}: {
label: string;
value: string;
wrap?: boolean;
mono?: boolean;
+ title?: string;
}) {
return (
<div className={cn("grid grid-cols-[72px_1fr] gap-2", wrap ? "items-start" : "items-center")}>
<span className="text-muted-foreground">{label}</span>
<span
+ title={title}
className={cn(
"min-w-0 text-foreground",
wrap ? "whitespace-pre-wrap break-words" : "truncate",
@@ -1427,6 +1430,13 @@ function RecipePopover({
/>
) : null}
<RecipeRow label="Size" value={`${image.width} × ${image.height}`} />
+ {image.generation_seconds != null ? (
+ <RecipeRow
+ label="Time"
+ value={`${image.generation_seconds.toFixed(image.generation_seconds < 1 ? 2 : 1)} s${(image.generation_count ?? 1) > 1 ? ` (batch of ${image.generation_count})` : ""}`}
+ title="Elapsed time until images are ready to save; may include waiting and processing"
+ />
+ ) : null}
{!viaConnection && <RecipeRow label="Steps" value={String(image.steps)} />}
{!viaConnection && <RecipeRow label="Guidance" value={String(image.guidance)} />}
{samplerRecipeLabel(image.sampler, image.schedule_type) ? (
diff --git a/studio/frontend/src/features/images/lib/image-metadata.ts b/studio/frontend/src/features/images/lib/image-metadata.ts
index 50e63e54287..c85e36362d7 100644
--- a/studio/frontend/src/features/images/lib/image-metadata.ts
+++ b/studio/frontend/src/features/images/lib/image-metadata.ts
@@ -1029,6 +1029,8 @@ export const INFO_RECIPE_KEYS = [
"controlnet_guidance",
"batch_index",
"created_at",
+ "generation_seconds",
+ "generation_count",
"engine",
"generator",
"schema_version",
diff --git a/studio/frontend/tests/image-metadata.test.ts b/studio/frontend/tests/image-metadata.test.ts
index efca23cc998..139daa03ad6 100644
--- a/studio/frontend/tests/image-metadata.test.ts
+++ b/studio/frontend/tests/image-metadata.test.ts
@@ -679,6 +679,7 @@ test("a newer recipe loads what this build knows and names what it does not", ()
assert.equal(newerRecipeSchema(recipe), true);
// Every key today's recipe writes is known, so a current image reports nothing.
assert.deepEqual(unknownRecipeKeys(JSON.parse(RECIPE)), []);
+ assert.deepEqual(unknownRecipeKeys({ prompt: "p", generation_seconds: 1.25, generation_count: 2 }), []);
assert.equal(
new Set([...APPLIED_RECIPE_KEYS, ...INFO_RECIPE_KEYS, ...PENDING_RECIPE_KEYS]).size,
APPLIED_RECIPE_KEYS.length + INFO_RECIPE_KEYS.length + PENDING_RECIPE_KEYS.length,
diff --git a/tests/studio/playwright_images_generation_time.py b/tests/studio/playwright_images_generation_time.py
new file mode 100644
index 00000000000..1203f7bb207
--- /dev/null
+++ b/tests/studio/playwright_images_generation_time.py
@@ -0,0 +1,77 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import os
+from urllib.parse import parse_qs, urlparse
+
+from playwright.sync_api import Route, expect, sync_playwright
+
+from playwright_image_model_footprint import BASE_URL, _api_payload, _json
+
+
+def main() -> None:
+ common = {
+ "negative_prompt": None,
+ "width": 64,
+ "height": 64,
+ "steps": 1,
+ "guidance": 1,
+ "seed": 1,
+ "batch_index": 0,
+ "batch_size": 1,
+ "model": None,
+ "created_at": 100,
+ "pinned": False,
+ "archived": False,
+ }
+ images = [
+ {
+ **common,
+ "id": "new",
+ "url": "/image-new",
+ "prompt": "New image",
+ "generation_seconds": 2.25,
+ "generation_count": 2,
+ },
+ {**common, "id": "old", "url": "/image-old", "prompt": "Old image"},
+ ]
+ errors = []
+ with sync_playwright() as playwright:
+ browser = playwright.chromium.launch(
+ headless = True, executable_path = os.environ.get("PW_CHROME")
+ )
+ context = browser.new_context(viewport = {"width": 1440, "height": 900})
+ context.add_init_script("localStorage.setItem('unsloth_auth_token', 'rendered-ui-test');")
+
+ def route_request(route: Route) -> None:
+ parsed = urlparse(route.request.url)
+ if parsed.netloc == "huggingface.co":
+ _json(route, [])
+ elif parsed.path == "/api/inference/images/gallery":
+ _json(route, {"images": images, "has_more": False})
+ elif parsed.path.startswith("/api/"):
+ _json(
+ route, _api_payload(parsed.path, parse_qs(parsed.query), full_footprint = False)
+ )
+ else:
+ route.continue_()
+
+ context.route("**/*", route_request)
+ page = context.new_page()
+ page.on("pageerror", lambda error: errors.append(str(error)))
+ page.goto(f"{BASE_URL}/images", wait_until = "domcontentloaded")
+ tiles = page.locator("[data-image-id] > button")
+ expect(tiles).to_have_count(2, timeout = 30_000)
+ page.get_by_role("button", name = "Recipe", exact = True).click()
+ expect(page.get_by_text("2.3 s (batch of 2)")).to_be_visible()
+ page.keyboard.press("Escape")
+ tiles.nth(1).click()
+ page.get_by_role("button", name = "Recipe", exact = True).click()
+ expect(page.get_by_text("Time", exact = True)).to_have_count(0)
+ assert not errors, errors
+ browser.close()
+ print("PASS image generation duration and legacy gallery records")
+
+
+if __name__ == "__main__":
+ main()