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: harden diffusion adapters, quant scales, prompt LoRA tags, Hub clips, short audio and restyle uploads (#17396)
Daniel Han422eb7fd1b8c
diff --git a/studio/backend/core/inference/diffusion_fp8_dequant.py b/studio/backend/core/inference/diffusion_fp8_dequant.pyindex 5fcf53f82d7..7bb3b38f84f 100644--- a/studio/backend/core/inference/diffusion_fp8_dequant.py+++ b/studio/backend/core/inference/diffusion_fp8_dequant.py@@ -125,6 +125,13 @@ def dequant_rows(``widen`` maps a row slice to its exact float32 values; ``fmt`` names the fp8 bits (None: integer codes)."""import torch+ rows = codes.shape[0]+ scale = scale.reshape(-1)+ # A per-tensor (one-element) scale is valid: broadcast it, since the kernel and the row chunks read scale[row].+ if scale.numel() == 1 and rows != 1:+ scale = scale.expand(rows)+ if scale.numel() != rows:+ raise ValueError(f"weight scale has {scale.numel()} values for {rows} rows")if triton_ok:# Triton launches on the current device's current stream and the capture probe reads that stream too:# both must be the operand's device, not whichever GPU the caller left current.@@ -139,7 +146,6 @@ def dequant_rows(except Exception as exc: # noqa: BLE001 - no Triton / launch failure: chunked torch below_triton_failed(exc)del out- rows = codes.shape[0]cols = codes.numel() // max(1, rows)step = chunk_rows(rows, cols, codes.device, 8 if codes.device.type == "mps" else 4)if not step:diff --git a/studio/backend/core/inference/diffusion_lora.py b/studio/backend/core/inference/diffusion_lora.pyindex 059da986646..afebbf8e49d 100644--- a/studio/backend/core/inference/diffusion_lora.py+++ b/studio/backend/core/inference/diffusion_lora.py@@ -20,6 +20,7 @@ from utils.paths.storage_roots import account_pathfrom .diffusion_content import ROLE_LORA, inspect_checkpointfrom .diffusion_families import DIFFUSION_CANCELLED_MSG+from .sd_cpp_args import strip_lora_tagsfrom utils.paths.path_utils import is_appledouble_metadata_ALL_EXTS = (".safetensors", ".gguf")@@ -628,13 +629,9 @@ def materialize_native_dir(return out-_TAG_RE = re.compile(r"<lora:([^:>]+):([^>]+)>")--def inject_prompt_tags(prompt: str, resolved: list[ResolvedLora]) -> str:"""Strips all user <lora:...> tags first so the validated weight wins over any typed weight."""- cleaned = _TAG_RE.sub("", prompt)- cleaned = re.sub(r"[ \t]{2,}", " ", cleaned).strip()+ cleaned = re.sub(r"[ \t]{2,}", " ", strip_lora_tags(prompt)).strip()tags = [f"<lora:{r.alias}:{_fmt_weight(r.weight)}>" for r in resolved]if not tags:return cleaneddiff --git a/studio/backend/core/inference/diffusion_lora_files.py b/studio/backend/core/inference/diffusion_lora_files.pyindex 16a7a03592e..b27629fb8eb 100644--- a/studio/backend/core/inference/diffusion_lora_files.py+++ b/studio/backend/core/inference/diffusion_lora_files.py@@ -306,6 +306,21 @@ class KronAdapter:setattr(parent, attr, wrapper.base_layer)+# A Kronecker factor is never larger than the layer it builds (16384 x 16384), so a low-rank pair whose product is+# bigger is malformed: refuse it before multiplying, as a ~400 KB pair can otherwise ask for tens of GB.+_MAX_KRON_FACTOR_ELEMENTS = 1 << 28+++def _low_rank_product(a: Any, b: Any, stem: str) -> Any:+ if a.dim() != 2 or b.dim() != 2 or a.shape[1] != b.shape[0]:+ raise ValueError(f"LoKR factors {stem}_a / {stem}_b do not multiply")+ if int(a.shape[0]) * int(b.shape[1]) > _MAX_KRON_FACTOR_ELEMENTS:+ raise ValueError(+ f"LoKR factor {stem} is {int(a.shape[0])} x {int(b.shape[1])}, larger than any layer"+ )+ return a.float() @ b.float()++def _kron_factors(parts: dict) -> tuple[Any, Any, float]:"""``(w1, w2, alpha_scale)`` like the reference runtime: a factor stored as a low-rank pair is its product, and``alpha / rank`` applies only when one is (rank = that pair's inner size)."""@@ -314,13 +329,13 @@ def _kron_factors(parts: dict) -> tuple[Any, Any, float]:dim = Nonew1 = parts.get("lokr_w1")if w1 is None:- w1 = parts["lokr_w1_a"].float() @ parts["lokr_w1_b"].float()+ w1 = _low_rank_product(parts["lokr_w1_a"], parts["lokr_w1_b"], "lokr_w1")dim = int(parts["lokr_w1_b"].shape[0])w2 = parts.get("lokr_w2")if w2 is None:if "lokr_t2" in parts:raise ValueError("a LoKR convolution (lokr_t2) cannot apply to a Linear layer")- w2 = parts["lokr_w2_a"].float() @ parts["lokr_w2_b"].float()+ w2 = _low_rank_product(parts["lokr_w2_a"], parts["lokr_w2_b"], "lokr_w2")dim = int(parts["lokr_w2_b"].shape[0])if w1.dim() != 2 or w2.dim() != 2:raise ValueError("only Linear LoKR modules are supported")diff --git a/studio/backend/core/inference/sd_cpp_args.py b/studio/backend/core/inference/sd_cpp_args.pyindex 6a2628ebc93..86674a21aea 100644--- a/studio/backend/core/inference/sd_cpp_args.py+++ b/studio/backend/core/inference/sd_cpp_args.py@@ -8,6 +8,7 @@ from __future__ import annotationsimport functoolsimport os+import refrom collections.abc import Iterable, Mapping, Sequencefrom dataclasses import dataclass, fieldfrom typing import Optional@@ -846,6 +847,22 @@ def offload_flags(return out+# sd-cli's own <lora:NAME:W> pattern; it loads an absolute NAME from anywhere, whatever --lora-model-dir says.+_LORA_TAG_RE = re.compile(r"<lora:([^:>]+):([^>]+)>")+++def strip_lora_tags(prompt: str) -> str:+ """Removes every tag sd-cli would parse, to a fixed point so a split tag cannot reassemble, plus any dangling+ ``<lora:`` that could pair with a tag appended after it."""+ out, prev = prompt, None+ while prev != out:+ prev = out+ out = _LORA_TAG_RE.sub("", out).replace("<lora:", "")+ if out == prompt:+ return prompt+ return re.sub(r"[ \t]{2,}", " ", out).strip()++def build_sd_cpp_command(binary: str,files: SdCppModelFiles,@@ -880,7 +897,9 @@ def build_sd_cpp_command(if value:cmd += [flag, value]- cmd += ["--prompt", params.prompt]+ # Tags are only honoured against a lora_dir the caller filled with validated adapters.+ prompt = params.prompt if params.lora_dir else strip_lora_tags(params.prompt)+ cmd += ["--prompt", prompt]if params.negative_prompt:cmd += ["--negative-prompt", params.negative_prompt]if params.init_img:@@ -1001,7 +1020,8 @@ def build_sd_cpp_video_command(cmd += ["--ref-audio", ref]cmd += ["--prompt",- params.prompt,+ # Video has no LoRA selection, so no prompt tag is legitimate.+ strip_lora_tags(params.prompt),"--cfg-scale",_fmt_float(params.cfg_scale),"--width",diff --git a/studio/backend/core/inference/stt_mtmd_sidecar.py b/studio/backend/core/inference/stt_mtmd_sidecar.pyindex fe124773e9f..8e7e1f0ec2b 100644--- a/studio/backend/core/inference/stt_mtmd_sidecar.py+++ b/studio/backend/core/inference/stt_mtmd_sidecar.py@@ -37,6 +37,7 @@ from core.inference.stt_sidecar import (SttContextSizeError,SttIncompleteTranscriptionError,SttLoadCancelledError,+ SttAudioDecodeError,SttModelBusyError,SttModelIdError,SttModelNotDownloadedError,@@ -1175,6 +1176,9 @@ class MtmdSttSidecar:decoded_audio = _decode_audio_bounded(audio, cancel_event)if cancel_event is not None and cancel_event.is_set():raise SttTranscriptionCancelledError("Transcription cancelled.")+ # llama-server aborts (mtmd GGML_ASSERT) on a one-sample clip.+ if len(decoded_audio) < _TARGET_SAMPLE_RATE // 1000:+ raise SttAudioDecodeError("Audio is too short (min 1 ms).")wav_bytes = _pcm_to_wav_bytes(decoded_audio)audio_seconds = (len(decoded_audio) / _TARGET_SAMPLE_RATE) if len(decoded_audio) else Noneself.load(diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 0bdeb541ce5..56b371d430d 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -9633,6 +9633,16 @@ async def _preflight_audio_for_switch(audio_preflight: dict, target_is_gguf: boostatus_code = 413,detail = _audio_too_long_detail(),) from None+ except _AudioTooShortError:+ raise HTTPException(+ status_code = 400,+ detail = openai_error_body(+ _AUDIO_TOO_SHORT_DETAIL,+ status = 400,+ code = "invalid_value",+ param = "audio_base64",+ ),+ ) from Noneexcept Exception:raise HTTPException(status_code = 400,@@ -26903,12 +26913,21 @@ _MAX_DECODE_BLOCK_SAMPLES = 1 << 20_RESAMPLE_SLICE_SAMPLES = 1 << 18_WAV_HEADER_BYTES = 44_MIN_TRANSCODE_AUDIO_SAMPLE_RATE = 8000+# llama-server aborts (mtmd GGML_ASSERT) on audio that resamples to one sample.+_MIN_AUDIO_SECONDS = 0.001class _DecodedAudioTooLongError(ValueError):"""Decoded audio crossed the duration cap before it could be buffered."""+class _AudioTooShortError(ValueError):+ """A clip too short for llama-server to decode without aborting."""+++_AUDIO_TOO_SHORT_DETAIL = "Audio is too short (min 1 ms)."++# (seconds, samples) the current decode may use: what earlier clips in the request left over._AUDIO_BUDGET_LEFT: "contextvars.ContextVar[Optional[tuple[int, int]]]" = contextvars.ContextVar("_AUDIO_BUDGET_LEFT", default = None@@ -27515,6 +27534,8 @@ def _prepare_audio_clips_for_llama(clips: list[str]) -> list[tuple[str, str]]:decoded[index] = (arr, sr)samples_held += len(arr)seconds = len(arr) / float(sr) if sr else 0.0+ if seconds < _MIN_AUDIO_SECONDS:+ raise _AudioTooShortError(_AUDIO_TOO_SHORT_DETAIL)total_seconds += secondsif total_seconds > _MAX_AUDIO_SECONDS:raise _DecodedAudioTooLongError(@@ -32388,6 +32409,8 @@ async def produce_openai_chat_completions(# A valid but over-long file reports the duration limit like the non-GGUF path, not corrupt audio.logger.info("Audio rejected at the duration limit: %s", e)raise _reject(413, _audio_too_long_detail())+ except _AudioTooShortError:+ raise _reject(400, _AUDIO_TOO_SHORT_DETAIL)except Exception as e:logger.warning("Audio decode failed: %s", e, exc_info = True)raise _reject(400, "Could not decode the provided audio file.")diff --git a/studio/backend/routes/video_restyle.py b/studio/backend/routes/video_restyle.pyindex 7aa097c1813..1b6f06437bb 100644--- a/studio/backend/routes/video_restyle.py+++ b/studio/backend/routes/video_restyle.py@@ -87,6 +87,9 @@ async def preview_restyle(request: Request, current_subject: str = Depends(get_casync def start_restyle(request: Request, current_subject: str = Depends(get_current_subject)):if account_access.managed_account():await asyncio.to_thread(account_access.require_model_allowed, video_restyle.MODEL_ID)+ # Receive the upload before reserving: a reservation holds the GPU, so a slow or stalled body+ # must not keep every model load and training start refused while it trickles in.+ upload = await _read_upload(request)try:reservation = video_restyle.runner.reserve(current_account_id())except RestyleBusy as exc:@@ -95,7 +98,7 @@ async def start_restyle(request: Request, current_subject: str = Depends(get_cur# a cancelled request must not free a reservation that start() is still about to use.lease = {"route": True}try:- return await _start_reserved(request, reservation, lease)+ return await _start_reserved(upload, reservation, lease)finally:if lease["route"]:video_restyle.runner.release(reservation)@@ -172,8 +175,8 @@ def _take_the_gpu(mode: Optional[str] = None) -> None:gpu_arbiter.restyle_handoff.reset(handoff)-async def _start_reserved(request: Request, reservation: str, lease: dict):- fields, files = await _read_upload(request)+async def _start_reserved(upload: tuple, reservation: str, lease: dict):+ fields, files = uploadseed: Optional[int] = Noneif fields.get("seed"):try:diff --git a/studio/backend/tests/test_diffusion_fp8_dequant.py b/studio/backend/tests/test_diffusion_fp8_dequant.pyindex edd175296c0..0738a11f54f 100644--- a/studio/backend/tests/test_diffusion_fp8_dequant.py+++ b/studio/backend/tests/test_diffusion_fp8_dequant.py@@ -508,3 +508,29 @@ def test_the_triton_widen_of_a_layer_on_a_non_current_gpu(monkeypatch, fmt):assert launches and fd._TRITON_STATE["failed"] is None, fd._TRITON_STATE["failed"]assert got.device == torch.device("cuda", 1)_assert_bitwise(got.cpu(), _old(codes, scale, torch.bfloat16, fmt))+++def test_one_element_scale_broadcasts_on_kernel_and_chunked_paths(monkeypatch):+ # A per-tensor scale (ComfyUI scaled checkpoints) must reach the kernel as one value per row, since it reads+ # scale[row]; a 1-element buffer there would be read out of bounds on CUDA / ROCm.+ import core.inference.diffusion_fp8_dequant as fd++ codes = torch.randint(-127, 127, (6, 5), dtype = torch.int8)+ scale = torch.tensor([0.5], dtype = torch.float32)+ want = (codes.float() * 0.5).to(torch.bfloat16)+ seen = []++ def fake_launch(codes_, scale_, out, fmt):+ seen.append(scale_.numel())+ out.copy_((codes_.float() * scale_[: codes_.shape[0], None]).to(out.dtype))++ monkeypatch.setattr(fd, "_triton_ok", lambda *a: True)+ monkeypatch.setattr(fd, "launch_triton", fake_launch)+ got = fd.dequant_rows(codes, scale, torch.bfloat16, lambda c: c.float())+ assert seen == [6] and torch.equal(got, want)++ monkeypatch.setattr(fd, "chunk_rows", lambda *a, **k: 2)+ got = fd.dequant_rows(codes, scale, torch.bfloat16, lambda c: c.float(), triton_ok = False)+ assert torch.equal(got, want)+ with pytest.raises(ValueError):+ fd.dequant_rows(codes, torch.ones(3), torch.bfloat16, lambda c: c.float(), triton_ok = False)diff --git a/studio/backend/tests/test_diffusion_lora_files.py b/studio/backend/tests/test_diffusion_lora_files.pyindex dd821d1f0a4..1e083a49602 100644--- a/studio/backend/tests/test_diffusion_lora_files.py+++ b/studio/backend/tests/test_diffusion_lora_files.py@@ -626,3 +626,15 @@ def test_the_folded_scale_covers_the_lora_b_bias(source):out = lf.normalize_lora(state, "krea-2", meta)assert torch.allclose(out[f"{stem}.lora_B.weight"], b * 4.0)assert torch.allclose(out[f"{stem}.lora_B.bias"], bias * 4.0)+++def test_kron_factor_pair_larger_than_any_layer_is_refused_before_multiplying():+ # ~400 KB on disk, a 100000 x 100000 fp32 product (40 GB) once multiplied; meta tensors keep the test free.+ a = torch.empty(100_000, 1, dtype = torch.bfloat16, device = "meta")+ b = torch.empty(1, 100_000, dtype = torch.bfloat16, device = "meta")+ for name in ("w1", "w2"):+ parts = {"lokr_w1": torch.randn(2, 2), "lokr_w2": torch.randn(3, 3)}+ parts.pop("lokr_" + name)+ parts.update({f"lokr_{name}_a": a, f"lokr_{name}_b": b})+ with pytest.raises(ValueError, match = "larger than any layer"):+ lf._kron_factors(parts)diff --git a/studio/backend/tests/test_hub_clip_playlist.py b/studio/backend/tests/test_hub_clip_playlist.pynew file mode 100644index 00000000000..0eb138dc331--- /dev/null+++ b/studio/backend/tests/test_hub_clip_playlist.py@@ -0,0 +1,92 @@+# 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 Hub dataset clip that is really a playlist must never reach FFmpeg as a local file."""++import uuid++import pytest++MP4_HEAD = b"\x00\x00\x00\x20ftypisom\x00\x00\x02\x00isomiso2avc1mp41"+++def _patch_hub(monkeypatch, tmp_path, body):+ import huggingface_hub++ class Api:+ def list_repo_files(+ self,+ repo_id,+ repo_type = None,+ revision = None,+ ):+ return ["videos/clip00.mp4"]++ def download(repo_id, filename, **kw):+ path = tmp_path / filename+ path.parent.mkdir(parents = True, exist_ok = True)+ path.write_bytes(body)+ return str(path)++ monkeypatch.setattr(huggingface_hub, "HfApi", Api)+ monkeypatch.setattr(huggingface_hub, "hf_hub_download", download)+++def _resolved(rows_or_messages, **kw):+ from utils.datasets.format_conversion import own_message_videos++ # A fresh repo name per call: conversions are cached per dataset.+ out = own_message_videos(+ rows_or_messages, dataset_name = f"someone/clips{uuid.uuid4().hex}", **kw+ )+ return [+ part["video"]+ for row in out+ for message in row["messages"]+ for part in message["content"]+ if part.get("type") == "video"+ ]+++def _messages():+ return [{"messages": [{"role": "user", "content": [{"type": "video", "video": "clip00.mp4"}]}]}]+++ "body",+ [+ b"#EXTM3U\n#EXT-X-TARGETDURATION:1\n#EXTINF:1,\nhttp://169.254.169.254/latest/meta-data/\n",+ b"ffconcat version 1.0\nfile 'http://127.0.0.1:8888/'\n",+ b'<?xml version="1.0"?><MPD></MPD>',+ ],+)+def test_a_hub_clip_that_is_a_playlist_is_refused(monkeypatch, tmp_path, body):+ _patch_hub(monkeypatch, tmp_path, body)+ with pytest.raises(ValueError, match = "playlist"):+ _resolved(_messages())+++def test_a_real_hub_clip_still_resolves(monkeypatch, tmp_path):+ _patch_hub(monkeypatch, tmp_path, MP4_HEAD)+ assert _resolved(_messages()) == [str(tmp_path / "videos/clip00.mp4")]+++def test_flat_rows_refuse_a_playlist_clip(monkeypatch, tmp_path):+ from utils.datasets.format_conversion import convert_video_to_vlm_format++ _patch_hub(monkeypatch, tmp_path, b"#EXTM3U\nhttp://169.254.169.254/\n")+ rows = [{"video": "videos/clip00.mp4", "answer": "a"}]+ try:+ out = convert_video_to_vlm_format(+ rows, "video", "answer", dataset_name = f"someone/clips{uuid.uuid4().hex}"+ )+ except ValueError:+ return+ paths = [+ p["video"]+ for r in out+ for m in r["messages"]+ for p in m["content"]+ if p.get("type") == "video"+ ]+ assert str(tmp_path / "videos/clip00.mp4") not in pathsdiff --git a/studio/backend/tests/test_llama_audio_attachment_container.py b/studio/backend/tests/test_llama_audio_attachment_container.pyindex 08724997cff..7c25c018d43 100644--- a/studio/backend/tests/test_llama_audio_attachment_container.py+++ b/studio/backend/tests/test_llama_audio_attachment_container.py@@ -34,7 +34,7 @@ def test_aac_and_mp2_are_transcoded_instead_of_forwarded_as_mp3(monkeypatch):monkeypatch.setattr(inference_route,"_decode_audio_mono",- lambda raw: (decoded.append(raw) or np.zeros(0, np.float32), 16_000),+ lambda raw: (decoded.append(raw) or np.zeros(16_000, np.float32), 16_000),)monkeypatch.setattr(inference_route,@@ -663,6 +663,48 @@ def test_a_forwarded_wav_is_bounded_by_its_own_header(monkeypatch):assert base64.b64decode(encoded) == short_wav+def test_a_one_sample_wav_is_refused_before_llama_server(monkeypatch):+ """mtmd aborts llama-server on a clip that decodes to one sample, so it never leaves here."""+ one_sample = _wav_header(16_000, 1, 16, 2) + b"\x00\x00"+ assert len(one_sample) == 46+ # three samples at 48 kHz resample to one at 16 kHz+ three_at_48k = _wav_header(48_000, 1, 16, 6) + bytes(6)+ for wav in (one_sample, three_at_48k):+ with pytest.raises(inference_route._AudioTooShortError):+ inference_route._prepare_audio_for_llama(base64.b64encode(wav).decode())++ ten_ms = _wav_header(16_000, 1, 16, 320) + bytes(320)+ encoded, container = inference_route._prepare_audio_clips_for_llama(+ [base64.b64encode(ten_ms).decode(), base64.b64encode(ten_ms).decode()]+ )[1]+ assert container == "wav"+ assert base64.b64decode(encoded) == ten_ms+++def test_a_transcoded_clip_that_decodes_to_one_sample_is_refused(monkeypatch):+ monkeypatch.setattr(+ inference_route, "_decode_audio_mono", lambda raw: (np.zeros(1, np.float32), 16_000)+ )+ with pytest.raises(inference_route._AudioTooShortError):+ inference_route._prepare_audio_for_llama(base64.b64encode(b"OggS tiny").decode())+++def test_a_switch_preflight_names_too_short_audio(monkeypatch):+ import asyncio++ from fastapi import HTTPException++ one_sample = _wav_header(16_000, 1, 16, 2) + b"\x00\x00"+ with pytest.raises(HTTPException) as caught:+ asyncio.run(+ inference_route._preflight_audio_for_switch(+ {"clips": [base64.b64encode(one_sample).decode()]}, True+ )+ )+ assert caught.value.status_code == 400+ assert inference_route._AUDIO_TOO_SHORT_DETAIL in str(caught.value.detail)++def test_an_inflated_block_align_cannot_shorten_a_forwarded_wav():wav = bytearray(_wav_header(16_000, 1, 16, 32_000) + bytes(32_000))# nBlockAlign, which the decoder ignoresdiff --git a/studio/backend/tests/test_sd_cpp_lora_prompt_tags.py b/studio/backend/tests/test_sd_cpp_lora_prompt_tags.pynew file mode 100644index 00000000000..9a38040af2b--- /dev/null+++ b/studio/backend/tests/test_sd_cpp_lora_prompt_tags.py@@ -0,0 +1,90 @@+# 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 <lora:...> tag typed into a prompt must never reach sd-cli unless the account selected that adapter."""++from __future__ import annotations++import re++import pytest++from core.inference import diffusion_lora as dl+from core.inference.sd_cpp_args import (+ SdCppGenParams,+ SdCppModelFiles,+ SdCppVideoGenParams,+ build_sd_cpp_command,+ build_sd_cpp_video_command,+)++_SDCLI_RE = re.compile(r"<lora:([^:>]+):([^>]+)>")++_TAGS = [+ "<lora:/victim/bob-private:1>",+ "<lora:|high_noise|/victim/bob-private:1>",+ "<lora:../../victim/bob-private:1>",+ # Split tags that reassemble after a single-pass strip.+ "<lo<lora:x:1>ra:/victim/bob-private:1>",+ "<lora<lora:x:1>:/victim/bob-private:1>",+]+++def _sdcli_lora_names(prompt: str) -> list[str]:+ """Mirrors sd-cli's extract_and_remove_lora: search, record, drop the first match, repeat."""+ names = []+ while (m := _SDCLI_RE.search(prompt)) is not None:+ names.append(m.group(1))+ prompt = _SDCLI_RE.sub("", prompt, count = 1)+ return names+++def _prompt_arg(cmd: list[str]) -> str:+ return cmd[cmd.index("--prompt") + 1]+++def _video_cmd(prompt: str) -> list[str]:+ files = SdCppModelFiles(+ diffusion_model = "/m/h3.gguf", vae = "/m/vae.safetensors", llm = "/m/te.gguf"+ )+ params = SdCppVideoGenParams(+ prompt = prompt, width = 512, height = 512, num_frames = 25, ref_audios = ("/s/a.wav",)+ )+ return build_sd_cpp_video_command("sd-cli", files, params, output_path = "/s/out.webm")+++def _image_cmd(prompt: str, lora_dir = None) -> list[str]:+ params = SdCppGenParams(prompt = prompt, lora_dir = lora_dir)+ return build_sd_cpp_command(+ "sd-cli", SdCppModelFiles(diffusion_model = "/m/z.gguf"), params, output_path = "/s/o.png"+ )++[email protected]("tag", _TAGS)+def test_video_argv_drops_prompt_lora_tags(tag):+ assert _sdcli_lora_names(_prompt_arg(_video_cmd(f"a cat {tag} running"))) == []++[email protected]("tag", _TAGS)+def test_image_argv_without_selected_lora_drops_prompt_tags(tag):+ assert _sdcli_lora_names(_prompt_arg(_image_cmd(f"a cat {tag} running"))) == []++[email protected]("tag", _TAGS)+def test_selected_lora_keeps_only_the_validated_tag(tag):+ r = dl.ResolvedLora("style", "style", "/x/style.safetensors", "safetensors", 0.8)+ prompt = dl.inject_prompt_tags(f"a cat {tag}", [r])+ cmd = _image_cmd(prompt, lora_dir = "/tmp/run/loras")+ assert _sdcli_lora_names(_prompt_arg(cmd)) == ["style"]+ assert cmd[cmd.index("--lora-model-dir") + 1] == "/tmp/run/loras"+++def test_dangling_tag_opener_cannot_pair_with_the_injected_tag():+ r = dl.ResolvedLora("style", "style", "/x/style.safetensors", "safetensors", 1.0)+ assert _sdcli_lora_names(dl.inject_prompt_tags("a cat <lora:/victim/x", [r])) == ["style"]+++def test_tag_free_prompt_passes_through_unchanged():+ prompt = " a cat: <b>bold</b> lora "+ assert _prompt_arg(_video_cmd(prompt)) == prompt+ assert _prompt_arg(_image_cmd(prompt)) == promptdiff --git a/studio/backend/tests/test_stt_mtmd_sidecar.py b/studio/backend/tests/test_stt_mtmd_sidecar.pyindex a12a7cee4b8..4899a1aa506 100644--- a/studio/backend/tests/test_stt_mtmd_sidecar.py+++ b/studio/backend/tests/test_stt_mtmd_sidecar.py@@ -1336,3 +1336,23 @@ def test_requested_language_reaches_the_decoder(assert progress, "prefilled responses still need to publish transcription progress"assert progress[-1] == {"text": "Hello world"}assert all("language " not in event["text"] for event in progress)+++def test_a_one_sample_recording_never_reaches_llama_server(monkeypatch):+ """mtmd aborts llama-server on a one-sample clip; refuse it before the sidecar loads."""+ import numpy as np+ from core.inference.stt_sidecar import SttAudioDecodeError++ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)+ monkeypatch.setattr(mtmd_mod, "ensure_engine_available", lambda: "/bin/llama-server")+ monkeypatch.setattr(+ MtmdSttSidecar, "_ensure_model_downloaded", lambda self, model_id: ("m.gguf", "p.gguf")+ )+ monkeypatch.setattr(+ mtmd_mod, "_decode_audio_bounded", lambda audio, cancel_event = None: np.zeros(1, np.float32)+ )+ loads = []+ monkeypatch.setattr(MtmdSttSidecar, "load", lambda self, *a, **k: loads.append(a))+ with pytest.raises(SttAudioDecodeError, match = "too short"):+ sidecar.transcribe(b"RIFF", model = "qwen3-asr-0.6b")+ assert loads == []diff --git a/studio/backend/tests/test_video_restyle.py b/studio/backend/tests/test_video_restyle.pyindex 38084edba67..5d3aacd85a8 100644--- a/studio/backend/tests/test_video_restyle.py+++ b/studio/backend/tests/test_video_restyle.py@@ -1252,3 +1252,32 @@ def test_the_video_claim_idle_check_runs_under_the_arbiter_lock(weights, monkeypmonkeypatch.setattr(arb, "_drop_resident", lambda owner: None)vr.RestyleRunner()._release_video_claim()assert held == [True]+++def test_upload_is_received_before_the_gpu_is_reserved(weights, monkeypatch):+ # A reservation refuses every model load and training start, so a slow or stalled upload must not hold one.+ from fastapi import FastAPI+ from fastapi.testclient import TestClient++ from auth.authentication import get_current_subject+ from routes import video_restyle as route++ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))+ monkeypatch.setattr(vr, "runner", runner)+ held_while_reading = []+ real_read = route._read_upload++ async def watching_read(request):+ held_while_reading.append(runner.holds_gpu())+ return await real_read(request)++ monkeypatch.setattr(route, "_read_upload", watching_read)+ monkeypatch.setattr(vr, "frames_from_video", lambda data: _frames(5))+ app = FastAPI()+ app.include_router(route.router, prefix = "/api/inference")+ app.dependency_overrides[get_current_subject] = lambda: "owner"+ files = [("video", ("a.mp4", b"x", "video/mp4"))]+ res = TestClient(app).post("/api/inference/video/restyle", data = {"prompt": ""}, files = files)+ assert res.status_code == 400+ assert held_while_reading == [False]+ runner.release(runner.reserve())diff --git a/studio/backend/utils/datasets/format_conversion.py b/studio/backend/utils/datasets/format_conversion.pyindex 017f9b5e9f0..315e193ac3a 100644--- a/studio/backend/utils/datasets/format_conversion.py+++ b/studio/backend/utils/datasets/format_conversion.py@@ -893,6 +893,22 @@ def convert_to_vlm_format(return converted_list+# A real video container never starts like this. A playlist / manifest saved as clip.mp4 would make+# FFmpeg open the URLs inside it itself, outside the guarded remote-media fetch.+_PLAYLIST_HEADS = (b"#EXTM3U", b"<", b"ffconcat", b"\xef\xbb\xbf", b" ", b"\t", b"\r", b"\n")+++def _refuse_hub_playlist(local_path, name):+ try:+ with open(local_path, "rb") as handle:+ head = handle.read(64)+ except OSError:+ return local_path # unreadable: the decoder reports it+ if head.startswith(_PLAYLIST_HEADS):+ raise ValueError(f"Video '{name}' is a playlist or text document, not a video file.")+ return local_path++class _HubClips:"""Repo-relative clip names of a Hub dataset, resolved by download the way bare image filenames are."""@@ -944,7 +960,7 @@ class _HubClips:return None# Offline: an exact repo path may still be in the cache.try:- return hf_hub_download(+ cached = hf_hub_download(self.repo,path,repo_type = "dataset",@@ -954,17 +970,21 @@ class _HubClips:)except Exception: # noqa: BLE001 -- not cached: the path stays localreturn None+ return _refuse_hub_playlist(cached, path)if isinstance(self.files[path], list):raise ValueError(f"Video '{path}' matches several files in {self.repo} ({', '.join(self.files[path])}); ""use the repo-relative path.")- return hf_hub_download(- self.repo,- self.files[path],- repo_type = "dataset",- revision = self.revision,- cache_dir = active_hf_hub_cache(),+ return _refuse_hub_playlist(+ hf_hub_download(+ self.repo,+ self.files[path],+ repo_type = "dataset",+ revision = self.revision,+ cache_dir = active_hf_hub_cache(),+ ),+ path,)