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.

Unsloth Studio: show why a video generation failed instead of only "Video generation failed." (#16744)

Leo Borcherding92c76b346241
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 53becb3191a..9e910c94be9 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -5080,8 +5080,34 @@ _NATIVE_CRASH_NEEDLES = (
)
+_FAILURE_REASON_MAX_CHARS = 120
+_PATH_START = r"(?:file://)?(?:~[\\/]|/|[A-Za-z]:[\\/]|\\\\)"
+# Absolute paths (quoted ones may hold spaces); URLs are left for redact_log_text.
+_FAILURE_PATH_RE = re.compile(
+ r"(?P<url>\b(?:https?|wss?|ftp)://[^\s\"'`,;]+)"
+ rf"|(?P<q>['\"`]){_PATH_START}[^\n]*?(?P=q)"
+ rf"|(?<![\w/~]){_PATH_START}[^\s\"'`,;]+"
+)
+
+
+def _failure_reason(exc: BaseException) -> str:
+ """Exception class and first message line, without credentials or filesystem paths."""
+ from utils.log_redaction import redact_log_text
+
+ lines = str(exc).strip().splitlines()
+ text = redact_log_text(lines[0] if lines else "")
+ text = _FAILURE_PATH_RE.sub(lambda m: m["url"] or f"{m['q'] or ''}<path>{m['q'] or ''}", text)
+ text = " ".join(text.split())
+ reason = f"{type(exc).__name__}: {text}" if text else type(exc).__name__
+ if len(reason) > _FAILURE_REASON_MAX_CHARS:
+ cut = reason[: _FAILURE_REASON_MAX_CHARS - 3]
+ reason = (cut.rsplit(" ", 1)[0] if " " in cut else cut).rstrip(" ,;:") + "..."
+ return reason
+
+
def video_failure_detail(exc: BaseException, request_shape: Optional[dict[str, Any]] = None) -> str:
- """A user-facing reason for a failed generation, built only from fixed text."""
+ """A user-facing reason for a failed generation: fixed text for known classes, else the
+ redacted exception class and first line."""
try:
from .video_minimax_h3 import H3NativeMemoryRefusal
@@ -5100,17 +5126,18 @@ def video_failure_detail(exc: BaseException, request_shape: Optional[dict[str, A
_probe_target(request_shape), request_shape.get("attention_head_dims")
)
):
- return f"{VIDEO_GENERATION_FAILED_MSG} {SDPA_MATH_ONLY_MESSAGE}"
+ return (
+ f"{VIDEO_GENERATION_FAILED_MSG} Out of memory: this device has no fused attention "
+ "kernel. Lower the resolution or frame count."
+ )
return (
- f"{VIDEO_GENERATION_FAILED_MSG} The device ran out of memory. Try a smaller "
- "resolution, fewer frames, or fewer steps."
+ f"{VIDEO_GENERATION_FAILED_MSG} Out of memory. Try a smaller resolution, fewer "
+ "frames or fewer steps."
)
text = str(exc).lower()
if any(needle in text for needle in _NATIVE_CRASH_NEEDLES):
- return (
- f"{VIDEO_GENERATION_FAILED_MSG} The renderer stopped unexpectedly. See the "
- "server log in Settings > Logs for its output."
- )
+ return f"{VIDEO_GENERATION_FAILED_MSG} The renderer crashed. See Settings > Logs."
+ return f"{VIDEO_GENERATION_FAILED_MSG} {_failure_reason(exc)}"
except Exception: # noqa: BLE001 -- diagnostics never mask the real failure
pass
return VIDEO_GENERATION_FAILED_MSG
@@ -12648,8 +12675,8 @@ class VideoBackend:
video_id: Optional[str] = None,
**gen_kwargs: Any,
) -> None:
- """Worker for begin_generate; unexpected errors are logged, the client gets only a generic
- message."""
+ """Worker for begin_generate; unexpected errors are logged in full, the client gets
+ video_failure_detail's redacted reason."""
from . import video_gallery
def _record_outcome(error: Optional[str] = None) -> None:
diff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.py
index fdc17a2b1c0..101145087c0 100644
--- a/studio/backend/routes/video.py
+++ b/studio/backend/routes/video.py
@@ -2282,7 +2282,7 @@ async def _start_openai_video(
maybe_auto_switch_media_model,
resident_answers_media_request,
)
- from core.inference.video import get_video_backend
+ from core.inference.video import get_video_backend, video_failure_detail
from core.inference.video_families import (
VIDEO_GENERATION_BUSY_MSG,
VIDEO_MODEL_CHANGED_MSG,
@@ -2410,7 +2410,7 @@ async def _start_openai_video(
continue
raise _openai_video_error(409, msg, code = "model_changed", param = "model")
logger.error("openai_videos.generate_failed: %s", exc, exc_info = True)
- raise HTTPException(status_code = 500, detail = "Video generation failed.")
+ raise HTTPException(status_code = 500, detail = video_failure_detail(exc))
break
_note_generation_account()
diff --git a/studio/backend/tests/test_h3_native_memory_fit.py b/studio/backend/tests/test_h3_native_memory_fit.py
index 06c65229884..3745c03a4d6 100644
--- a/studio/backend/tests/test_h3_native_memory_fit.py
+++ b/studio/backend/tests/test_h3_native_memory_fit.py
@@ -449,7 +449,7 @@ def test_a_recovered_capacity_warning_is_not_a_capacity_failure():
crash = (
"sd-cli exited -11. Last output:\n" + _RECOVERED_CAPACITY_WARNING + "Segmentation fault\n"
)
- assert "renderer stopped unexpectedly" in video_failure_detail(RuntimeError(crash))
+ assert "renderer crashed" in video_failure_detail(RuntimeError(crash))
def test_a_bare_device_loss_is_explained_as_likely_memory():
@@ -463,12 +463,12 @@ def test_an_unrelated_native_crash_keeps_its_old_text():
detail = video_failure_detail(
RuntimeError("sd-cli exited -11. Last output:\nSegmentation fault")
)
- assert "renderer stopped unexpectedly" in detail
+ assert "renderer crashed" in detail
def test_a_torch_oom_keeps_its_old_text():
detail = video_failure_detail(RuntimeError("CUDA out of memory. Tried to allocate 2.00 GiB"))
- assert "smaller resolution, fewer frames, or fewer steps" in detail
+ assert "smaller resolution, fewer frames or fewer steps" in detail
_V1_SWAP_ROOM = {
diff --git a/studio/backend/tests/test_openai_videos_route.py b/studio/backend/tests/test_openai_videos_route.py
index f078f231d7f..0ed8ea51030 100644
--- a/studio/backend/tests/test_openai_videos_route.py
+++ b/studio/backend/tests/test_openai_videos_route.py
@@ -392,6 +392,24 @@ def test_a_failed_job_reports_its_error_and_keeps_it_after_the_next_job(client,
assert client.get(f"/v1/videos/{job['id']}").status_code == 404
+def test_a_pipeline_exception_names_its_cause_in_the_job_error(client, backend, monkeypatch):
+ def _mismatch(**kwargs):
+ raise RuntimeError(
+ "Input type (CPUBFloat16Type) and weight type (CUDABFloat16Type) should be the same\n"
+ ' File "/home/u/.venv/diffusers/autoencoder_kl_wan.py", line 597'
+ )
+
+ monkeypatch.setattr(backend, "generate", _mismatch)
+ job = _create(client, {"prompt": "a car"}).json()
+ failed = _wait_terminal(client, job["id"])
+ assert failed["status"] == "failed"
+ assert failed["error"] == {
+ "code": "video_generation_failed",
+ "message": "Video generation failed. RuntimeError: Input type (CPUBFloat16Type) and "
+ "weight type (CUDABFloat16Type) should be the same",
+ }
+
+
def test_an_unpolled_failure_keeps_its_error_after_the_next_job(client, backend):
backend.fail_with = "Prompt rejected before polling."
failed_job = _create(client, {"prompt": "bad"}).json()
diff --git a/studio/backend/tests/test_video_routes.py b/studio/backend/tests/test_video_routes.py
index d536b50cf5a..46ee0f18342 100644
--- a/studio/backend/tests/test_video_routes.py
+++ b/studio/backend/tests/test_video_routes.py
@@ -600,12 +600,12 @@ def test_generate_pipeline_error_reports_sanitized_failure(client, monkeypatch):
monkeypatch.setattr(backend, "generate", _oom)
progress = _shared_setup_4(client)
assert progress["error"].startswith("Video generation failed.")
- assert "ran out of memory" in progress["error"]
+ assert "Out of memory" in progress["error"]
assert "CUDA" not in progress["error"]
assert "40.00 GiB" not in progress["error"]
-def test_generate_unclassified_error_keeps_the_bare_fallback(client, monkeypatch):
+def test_generate_unclassified_error_names_the_cause_without_the_path(client, monkeypatch):
backend = video_module.get_video_backend()
backend.loaded = True
@@ -614,10 +614,86 @@ def test_generate_unclassified_error_keeps_the_bare_fallback(client, monkeypatch
monkeypatch.setattr(backend, "generate", _odd)
progress = _shared_setup_4(client)
- assert progress["error"] == "Video generation failed."
+ assert progress["error"] == (
+ "Video generation failed. RuntimeError: something went sideways in <path>"
+ )
assert "secret.safetensors" not in progress["error"]
+def test_generate_pipeline_exception_reaches_the_progress_error(client, monkeypatch):
+ # diffusers 0.40.0 on Cosmos3 Edge: the page showed only "Video generation failed."
+ backend = video_module.get_video_backend()
+ backend.loaded = True
+ cause = (
+ "Input type (CPUBFloat16Type) and weight type (CUDABFloat16Type) should be the same "
+ "or input should be a MKLDNN tensor and weight is a dense tensor"
+ )
+
+ def _mismatch(**kwargs):
+ raise RuntimeError(cause)
+
+ monkeypatch.setattr(backend, "generate", _mismatch)
+ progress = _shared_setup_4(client)
+ assert progress["error"] == (
+ "Video generation failed. RuntimeError: Input type (CPUBFloat16Type) and weight type "
+ "(CUDABFloat16Type) should be the same or input should be..."
+ )
+
+
+def test_generate_failure_reason_is_redacted_and_bounded(client, monkeypatch):
+ import os
+
+ backend = video_module.get_video_backend()
+ backend.loaded = True
+ home = os.path.expanduser("~")
+ token = "hf_" + "A1b2C3d4E5" * 3
+
+ def _leaky(**kwargs):
+ raise OSError(
+ f"cannot read {home}/.cache/huggingface/token with hf_token={token} "
+ f"or {token} from ~/models and C:\\Users\\leo\\w.bin " + "x" * 400 + "\n"
+ ' File "/usr/lib/python3/site-packages/diffusers/pipe.py", line 9, in __call__'
+ )
+
+ monkeypatch.setattr(backend, "generate", _leaky)
+ error = _shared_setup_4(client)["error"]
+ assert error.startswith("Video generation failed. OSError: cannot read <path> with")
+ for leaked in (home, token, "~/models", "Users", "w.bin", "site-packages", "File "):
+ assert leaked not in error
+ assert len(error) <= len("Video generation failed. ") + 120
+ assert error.endswith("...")
+
+
+def test_generate_failure_reason_hides_a_quoted_path_with_spaces(client, monkeypatch):
+ backend = video_module.get_video_backend()
+ backend.loaded = True
+
+ def _missing(**kwargs):
+ raise FileNotFoundError(
+ 2, "No such file or directory", "C:\\Users\\Jo Ann\\models\\w.safetensors"
+ )
+
+ monkeypatch.setattr(backend, "generate", _missing)
+ error = _shared_setup_4(client)["error"]
+ assert error == (
+ "Video generation failed. FileNotFoundError: [Errno 2] No such file or directory: '<path>'"
+ )
+
+
+def test_generate_failure_reason_hides_a_double_quoted_path_with_an_apostrophe(client, monkeypatch):
+ backend = video_module.get_video_backend()
+ backend.loaded = True
+
+ def _missing(**kwargs):
+ raise FileNotFoundError(2, "No such file or directory", "/models/O'Brien/w.safetensors")
+
+ monkeypatch.setattr(backend, "generate", _missing)
+ error = _shared_setup_4(client)["error"]
+ assert error == (
+ 'Video generation failed. FileNotFoundError: [Errno 2] No such file or directory: "<path>"'
+ )
+
+
def test_generate_native_crash_points_at_the_log(client, monkeypatch):
backend = video_module.get_video_backend()
backend.loaded = True
diff --git a/studio/frontend/src/features/video/generation-failure.ts b/studio/frontend/src/features/video/generation-failure.ts
new file mode 100644
index 00000000000..9ce24553001
--- /dev/null
+++ b/studio/frontend/src/features/video/generation-failure.ts
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Same text as the backend's VIDEO_GENERATION_FAILED_MSG, so the "View logs" action matches it.
+const VIDEO_GENERATION_FAILED = "Video generation failed.";
+
+export interface VideoFailureToast {
+ title: string;
+ errorType: string | null;
+ detail: string | null;
+}
+
+/** Toast parts for a failed generation, or null for the user's own Cancel. */
+export function videoFailureToast(error: string | null | undefined): VideoFailureToast | null {
+ const msg = error?.trim() || VIDEO_GENERATION_FAILED;
+ if (!msg.startsWith(VIDEO_GENERATION_FAILED)) {
+ if (msg.toLowerCase().includes("cancelled")) return null;
+ return { title: msg, errorType: null, detail: null };
+ }
+ // Past the prefix it is the exception's own text, which can say "cancelled".
+ const reason = msg.slice(VIDEO_GENERATION_FAILED.length).trim();
+ if (!reason) return { title: VIDEO_GENERATION_FAILED, errorType: null, detail: null };
+ // "Type: first line" or a bare "Type"; fixed backend text has a space before any colon.
+ const named = /^([A-Za-z_][\w.]*)(?::\s*([\s\S]*))?$/.exec(reason);
+ if (named) {
+ return { title: VIDEO_GENERATION_FAILED, errorType: named[1], detail: named[2]?.trim() || null };
+ }
+ return { title: VIDEO_GENERATION_FAILED, errorType: null, detail: reason };
+}
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index fd70bd27530..123577f479c 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -225,6 +225,7 @@ import { loadGalleryUntil } from "@/lib/gallery-deep-link";
import { subscribeModelEjected } from "@/lib/model-lifecycle-events";
import { BlobUrlCache } from "@/lib/blob-url-cache";
+import { videoFailureToast } from "./generation-failure";
import { keyframeSupport, matchedCanvas } from "./keyframe-canvas";
import { hasReferenceCapacity } from "./reference-budget";
import {
@@ -285,6 +286,28 @@ function useVideoModels(
);
}
+const FAILURE_WITH_REASON_TOAST_MS = 10_000;
+
+/** False for the user's own Cancel, which is not an error. */
+function showVideoFailureToast(error: string | null | undefined): boolean {
+ const failure = videoFailureToast(error);
+ if (!failure) return false;
+ const { title, errorType, detail } = failure;
+ const hasReason = Boolean(errorType || detail);
+ toast.error(title, {
+ description: hasReason ? (
+ <span className="[overflow-wrap:anywhere]">
+ {errorType && <code className="font-mono">{errorType}</code>}
+ {errorType && detail ? ": " : null}
+ {detail}
+ </span>
+ ) : undefined,
+ duration: hasReason ? FAILURE_WITH_REASON_TOAST_MS : undefined,
+ action: generationFailureLogsAction(title),
+ });
+ return true;
+}
+
// Per-model generation defaults (steps + guidance), matched by repo-id substring, most specific first. The id is
// normalized like the backend's family matcher (separator runs become "-", plus a trailing "-"), so "Wan2_1-T2V-14B"
// and "wan2.1_t2v_14b" hit the same row.
@@ -2636,10 +2659,8 @@ function VideoGenerator({
void ensureSrc(clip);
}
} else if (p.phase === "failed") {
- const msg = p.error || "Video generation failed";
// The user's own Cancel surfaces as the cancelled sentinel; not an error.
- if (!msg.toLowerCase().includes("cancelled"))
- toast.error(msg, { action: generationFailureLogsAction(msg) });
+ showVideoFailureToast(p.error);
}
return;
}
@@ -2698,9 +2719,7 @@ function VideoGenerator({
}
} else if (g.phase === "failed") {
// Kept until the next job, so a reload still shows the failure.
- const msg = g.error || "Video generation failed";
- if (!msg.toLowerCase().includes("cancelled"))
- toast.error(msg, { action: generationFailureLogsAction(msg) });
+ showVideoFailureToast(g.error);
}
} catch {
// Resume is best-effort; a failed probe just leaves the idle view.
@@ -3675,8 +3694,9 @@ function VideoGenerator({
});
} catch (err) {
if (!isMounted.current) return;
- const refusal = err instanceof Error ? err.message : "Video generation failed";
- toast.error(refusal, { action: generationFailureLogsAction(refusal) });
+ const refusal = err instanceof Error ? err.message : null;
+ // A refusal is never the user's own Cancel, so one that mentions "cancelled" still shows.
+ if (!showVideoFailureToast(refusal) && refusal) toast.error(refusal);
setBusy(null);
setGenStep(null);
// The refusal can be "No video model is loaded"; re-read status.
diff --git a/studio/frontend/tests/video-generate-refusal-resync.test.ts b/studio/frontend/tests/video-generate-refusal-resync.test.ts
index 5904a76e3cf..a7e15a2f2ba 100644
--- a/studio/frontend/tests/video-generate-refusal-resync.test.ts
+++ b/studio/frontend/tests/video-generate-refusal-resync.test.ts
@@ -19,7 +19,7 @@ const RESYNC = VIDEO.slice(
test("a refused generation re-reads the model status", () => {
const generateCatch = VIDEO.slice(
VIDEO.indexOf(
- 'const refusal = err instanceof Error ? err.message : "Video generation failed";',
+ "const refusal = err instanceof Error ? err.message : null;",
),
).slice(0, 600);
assert.match(generateCatch, /void resyncAfterGenerateRefusal\(\);/);
diff --git a/studio/frontend/tests/video-generation-failure-toast.test.ts b/studio/frontend/tests/video-generation-failure-toast.test.ts
new file mode 100644
index 00000000000..b8ad1adb00a
--- /dev/null
+++ b/studio/frontend/tests/video-generation-failure-toast.test.ts
@@ -0,0 +1,66 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// A failed generation's toast shows the backend's reason, the exception class and first line.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { readSrc } from "./helpers/kit.ts";
+
+const MISMATCH =
+ "Video generation failed. RuntimeError: Input type (CPUBFloat16Type) and weight type " +
+ "(CUDABFloat16Type) should be the same";
+
+test("the backend's failure reason becomes the toast description", async () => {
+ const { videoFailureToast } = await import("../src/features/video/generation-failure.ts");
+ assert.deepEqual(videoFailureToast(MISMATCH), {
+ title: "Video generation failed.",
+ errorType: "RuntimeError",
+ detail: "Input type (CPUBFloat16Type) and weight type (CUDABFloat16Type) should be the same",
+ });
+ assert.deepEqual(videoFailureToast("Video generation failed. KeyError"), {
+ title: "Video generation failed.",
+ errorType: "KeyError",
+ detail: null,
+ });
+});
+
+test("fixed backend text and an empty error keep the logged-failure title", async () => {
+ const { videoFailureToast } = await import("../src/features/video/generation-failure.ts");
+ const oom =
+ "Video generation failed. The renderer crashed. See Settings > Logs.";
+ assert.deepEqual(videoFailureToast(oom), {
+ title: "Video generation failed.",
+ errorType: null,
+ detail: "The renderer crashed. See Settings > Logs.",
+ });
+ for (const empty of [null, undefined, "", " "]) {
+ assert.deepEqual(videoFailureToast(empty), {
+ title: "Video generation failed.",
+ errorType: null,
+ detail: null,
+ });
+ }
+});
+
+test("a failure whose cause mentions cancelled still shows", async () => {
+ const { videoFailureToast } = await import("../src/features/video/generation-failure.ts");
+ const failure = videoFailureToast(
+ "Video generation failed. CancelledError: the offload stream was cancelled",
+ );
+ assert.equal(failure?.errorType, "CancelledError");
+});
+
+test("the user's own Cancel stays silent", async () => {
+ const { videoFailureToast } = await import("../src/features/video/generation-failure.ts");
+ assert.equal(videoFailureToast("Video generation was cancelled."), null);
+});
+
+test("every failure toast on the Video page goes through one helper", () => {
+ const page = readSrc("features/video/video-page.tsx");
+ assert.equal(page.match(/showVideoFailureToast\([pg]\.error\);/g)?.length, 2);
+ assert.match(page, /if \(!showVideoFailureToast\(refusal\) && refusal\) toast\.error\(refusal\);/);
+ assert.match(page, /action: generationFailureLogsAction\(title\)/);
+ assert.doesNotMatch(page, /if \(!msg\.toLowerCase\(\)\.includes\("cancelled"\)\)/);
+});