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 video: run LTX-2.5 FP8 on a 24 GB card by streaming the hosted fp8 DiT instead of refusing it (#17238)
Daniel Han1c15fc37a3ba
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex c27d54336ab..06e877fe6f6 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -154,6 +154,7 @@ from .diffusion_memory import (normalize_memory_mode,plan_diffusion_memory,plan_keeps_transformer_resident,+ prequant_seed_device,raise_on_unified_memory_shortfall,scoped_allow_oversized_load,unified_memory_refusal_code,@@ -4282,17 +4283,55 @@ def _video_seed_stays_resident(hf_token: Optional[str] = None,ltx25_dev: bool = False,device_memory_reader: Optional[Callable[[], Any]] = None,+ plan_out: Optional[list] = None,) -> bool:"""True when an artifact-sized plan keeps the denoiser resident (text encoders may stream).``scheme=None`` sizes the released bf16 DiT instead, and then also requires a measured budget (see``_auto_keeps_resident_bf16``). ``device_memory_reader`` lets one planner call settle the card once- for both checks; it must return the raw settled snapshot (reclaimable is applied here)."""+ for both checks; it must return the raw settled snapshot (reclaimable is applied here). ``plan_out`` (a+ list) receives the plan judged, so a caller can place an offloaded seed on it without a second settle."""+ planned = _video_seed_plan(+ fam,+ target = target,+ scheme = scheme,+ memory_mode = memory_mode,+ text_encoder_quant = text_encoder_quant,+ base_repo = base_repo,+ reclaimable_mib = reclaimable_mib,+ hf_token = hf_token,+ ltx25_dev = ltx25_dev,+ device_memory_reader = device_memory_reader,+ )+ if planned is None:+ return scheme is not None+ if plan_out is not None:+ plan_out.append(planned)+ if scheme is None:+ return _auto_keeps_resident_bf16(planned, target)+ return plan_keeps_transformer_resident(planned)+++def _video_seed_plan(+ fam: Any,+ *,+ target: Any,+ scheme: Optional[str],+ memory_mode: Optional[str],+ text_encoder_quant: Optional[str],+ base_repo: Optional[str],+ reclaimable_mib: int = 0,+ hf_token: Optional[str] = None,+ ltx25_dev: bool = False,+ device_memory_reader: Optional[Callable[[], Any]] = None,+) -> Any:+ """The artifact-sized plan ``_video_seed_stays_resident`` judges, or None (no component sizes, or a+ scheme with no steady size: both answered by the caller)."""from .diffusion_component_sizes import video_components_gbcomponents = video_components_gb(fam, base_repo, allow_hub = True, token = hf_token, dev = ltx25_dev)if not components:- return scheme is not None+ return Noneimport torchdtype = getattr(target, "dtype", None)@@ -4308,7 +4347,7 @@ def _video_seed_stays_resident(elif factor is not None:denoiser_gb = components[0] * factorelse:- return True+ return Nonefrom .diffusion_te_prequant import te_prequant_budget_scale@@ -4352,9 +4391,67 @@ def _video_seed_stays_resident(text_encoder_dense_mib = int(text_encoder_gb * mib_per_gb),requested_mode = normalize_memory_mode(memory_mode),)- if scheme is None:- return _auto_keeps_resident_bf16(planned, target)- return plan_keeps_transformer_resident(planned)+ return planned+++# 0 restores the refusal: an explicit fp8 pipeline load whose plan moves the DiT keeps the dense shards and is declined.+VIDEO_FP8_STREAM_ENV = "UNSLOTH_VIDEO_FP8_STREAM"+# Schemes whose hosted torchao denoiser streams under group offload; int8 has its torchao-free twin there instead.+_VIDEO_TORCHAO_STREAM_SCHEMES = (TQ_FP8,)+++def video_fp8_stream_enabled() -> bool:+ raw = (os.environ.get(VIDEO_FP8_STREAM_ENV) or "").strip().lower()+ return raw not in ("0", "false", "no", "off")+++def _video_torchao_seed_placement(fam: Any, scheme: Optional[str], target: Any, plan: Any) -> Any:+ """The streaming placement a hosted torchao ``scheme`` denoiser takes under an offloaded ``plan``, else None.++ The rule the image path's seeded and single-file fp8 loads follow (``torchao_offload_plan``): group or+ streaming offload keep their placement, a whole-module plan becomes the streaming plan, sequential offload+ and a torchao, diffusers or pin budget that cannot stream it return None. Only fp8 on a card whose fp8+ GEMM passes Studio's probe (sm_89+), on a conventional pipeline load; int8 keeps its torchao-free twin."""+ if not video_fp8_stream_enabled() or scheme not in _VIDEO_TORCHAO_STREAM_SCHEMES:+ return None+ if plan is None or plan_keeps_transformer_resident(plan):+ return None+ if getattr(fam, "modular_workflow", None):+ return None+ try:+ import torch++ from .diffusion_memory import torchao_offload_plan, torchao_streaming_plan++ if (+ getattr(target, "device", None) != "cuda"+ or getattr(target, "dtype", None) is not torch.bfloat16+ ):+ return None+ if (+ select_transformer_quant_scheme(+ target, scheme, family = getattr(fam, "name", None), unproven_ok = True+ )+ != scheme+ ):+ return None+ placed = torchao_offload_plan(plan, scheme)+ if placed is not None and getattr(placed, "offload_policy", None) == OFFLOAD_MODEL:+ # Whole-module hooks move a Float8Tensor by storage swap, which it does not survive: stream instead.+ from .diffusion_memory import _torchao_stream_pinnable, torchao_scheme_streams+ placed = (+ torchao_streaming_plan(placed)+ if torchao_scheme_streams(scheme) and _torchao_stream_pinnable(placed)+ else None+ )+ except Exception: # noqa: BLE001 -- an unanswerable probe keeps today's decline+ return None+ if placed is None or getattr(placed, "offload_policy", None) not in (+ OFFLOAD_GROUP,+ OFFLOAD_STREAMING,+ ):+ return None+ return placeddef _h3_carry_by_scheduler(fam: Any, state: Any, has_step_callback: bool) -> bool:@@ -7666,6 +7763,7 @@ class VideoBackend:):# auto keeps a resident bf16 DiT, so the dense shards are what this load runs.return None+ seed_plans: list = []if not _video_seed_stays_resident(fam,target = target,@@ -7677,7 +7775,20 @@ class VideoBackend:hf_token = hf_token,ltx25_dev = ltx25_dev,device_memory_reader = _settled_once,+ plan_out = seed_plans,):+ seed_plan = seed_plans[0] if seed_plans else None+ streamed = _video_torchao_seed_placement(fam, scheme, target, seed_plan)+ if streamed is not None:+ logger.info(+ "video.denoiser_prequant: an artifact-sized plan for %s offloads on this "+ "card ('%s'), and its torchao weights stream there, so the hosted "+ "checkpoint is seeded and streamed ('%s')",+ scheme,+ _video_plan_label(seed_plan),+ _video_plan_label(streamed),+ )+ return schemehosted = _video_native_hosted_scheme(fam, scheme, target)if native_hosted is not None and hosted is not None:native_hosted.append(hosted)@@ -9770,7 +9881,21 @@ class VideoBackend:plan, bf16_plan, quant_replanned = _plan_for_te_scale(te_scale, log = True, denoiser_gb = denoiser_seed_gb)- if denoiser_seed_scheme is not None and not plan_keeps_transformer_resident(plan):+ seed_streamed = (+ _video_torchao_seed_placement(fam, denoiser_seed_scheme, target, plan)+ if denoiser_seed_scheme is not None+ else None+ )+ if seed_streamed is not None:+ logger.info(+ "video.denoiser_prequant: the %s denoiser is offloaded ('%s') on this card, and its "+ "torchao weights stream there, so the hosted checkpoint is seeded as '%s'",+ denoiser_seed_scheme,+ _video_plan_label(plan),+ _video_plan_label(seed_streamed),+ )+ plan = seed_streamed+ elif denoiser_seed_scheme is not None and not plan_keeps_transformer_resident(plan):logger.info("video.denoiser_prequant: the %s denoiser would have to be offloaded ('%s') on this ""card, so the hosted checkpoint is not seeded",@@ -9965,7 +10090,14 @@ class VideoBackend:plan, bf16_plan, quant_replanned = _plan_for_te_scale(settled_te_scale, log = False, denoiser_gb = denoiser_seed_gb)- if denoiser_seed_scheme is not None and not plan_keeps_transformer_resident(plan):+ seed_streamed = (+ _video_torchao_seed_placement(fam, denoiser_seed_scheme, target, plan)+ if seed_streamed is not None+ else None+ )+ if seed_streamed is not None:+ plan = seed_streamed+ elif denoiser_seed_scheme is not None and not plan_keeps_transformer_resident(plan):denoiser_seed_scheme = Nonedenoiser_seed_gb = Noneplan, bf16_plan, quant_replanned = _plan_for_te_scale(settled_te_scale, log = False)@@ -9983,6 +10115,12 @@ class VideoBackend:scheme = denoiser_seed_scheme,dtype = dtype,device = device,+ # a streamed seed is built on the host: on the card first it OOMs a 16 GiB budget+ placement_device = (+ prequant_seed_device(plan, device, denoiser_seed_scheme)+ if seed_streamed is not None+ else None+ ),hf_token = hf_token,target = target,local_files_only = local_files_only,diff --git a/studio/backend/core/inference/video_denoiser_prequant.py b/studio/backend/core/inference/video_denoiser_prequant.pyindex 1768a21fb94..e7e0dc239ba 100644--- a/studio/backend/core/inference/video_denoiser_prequant.py+++ b/studio/backend/core/inference/video_denoiser_prequant.py@@ -108,8 +108,11 @@ def denoiser_prequant_pipe_kwargs(local_files_only: bool = False,cache_dir: Optional[str] = None,logger: Any = None,+ placement_device: Optional[str] = None,) -> dict[str, Any]:- """Component overrides for pipeline assembly, or ``{}`` (not seeded whole: re-plan memory at bf16)."""+ """Component overrides for pipeline assembly, or ``{}`` (not seeded whole: re-plan memory at bf16).+ ``placement_device`` (default ``device``): where the modules are materialised; a streamed seed stays on the host+ (``prequant_seed_device``), as the offload hooks move it block by block."""try:import gc@@ -143,6 +146,7 @@ def denoiser_prequant_pipe_kwargs(base_repo,source,device = device,+ placement_device = placement_device,dtype = dtype,hf_token = hf_token,scheme = scheme,diff --git a/studio/backend/tests/test_video_fp8_stream.py b/studio/backend/tests/test_video_fp8_stream.pynew file mode 100644index 00000000000..790686a36cd--- /dev/null+++ b/studio/backend/tests/test_video_fp8_stream.py@@ -0,0 +1,211 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Explicit fp8 on a conventional video pipeline whose plan moves the DiT: the hosted torchao fp8 denoiser is seeded+and streamed through group offload (``_video_torchao_seed_placement``), as the image path does, instead of the load+being refused. CPU only: the placement rule and both planner call sites, with the plan and the fp8 probe spoofed."""++import types++import pytest+import torch++import core.inference.diffusion_memory as dm+import core.inference.video as vid+from core.inference.video_families import detect_video_family++LTX25 = "Lightricks/LTX-2.5-Diffusers"+CUDA_BF16 = types.SimpleNamespace(device = "cuda", dtype = torch.bfloat16, ordinal = 0)+++def _plan(policy, **kw):+ return types.SimpleNamespace(+ offload_policy = policy,+ stream_transformer = kw.pop("stream_transformer", policy != "none"),+ stream_text_encoders = kw.pop("stream_text_encoders", True),+ reasons = (),+ **kw,+ )+++def fam():+ return detect_video_family(LTX25)+++def fp8_gemm(monkeypatch):+ """A card whose fp8 probe passes (sm_89+) unless a test flips ``state["ok"]``."""+ state = {"ok": True}+ monkeypatch.setattr(+ vid,+ "select_transformer_quant_scheme",+ lambda target, scheme, family = None, **kw: scheme if state["ok"] else None,+ )+ monkeypatch.setattr(+ vid, "plan_keeps_transformer_resident", lambda p: p.offload_policy == "none"+ )+ return state+++ "policy, placed_policy, want",+ [+ ("group", "group", "group"), # the L4 whole-card plan: denoiser and text encoders streamed+ ("streaming", "streaming", "streaming"),+ (+ "model",+ "model",+ "streaming",+ ), # whole-module hooks cannot move a Float8Tensor: stream instead+ (+ "model",+ "streaming",+ "streaming",+ ), # the quantised parts do not fit whole (torchao_offload_plan)+ ("sequential", None, None), # never measured with torchao+ ("group", None, None), # torchao / diffusers too old, or no up-front pin budget+ ],+)+def test_placement_follows_torchao_offload_plan(+ monkeypatch, fam, fp8_gemm, policy, placed_policy, want+):+ plan = _plan(policy)+ seen = []++ def offload_plan(p, scheme):+ seen.append(scheme)+ return (+ None+ if placed_policy is None+ else (p if placed_policy == policy else _plan(placed_policy))+ )++ monkeypatch.setattr(dm, "torchao_offload_plan", offload_plan)+ monkeypatch.setattr(dm, "torchao_scheme_streams", lambda scheme, **kw: True)+ monkeypatch.setattr(dm, "_torchao_stream_pinnable", lambda p, reclaimable_host_mib = 0: True)+ monkeypatch.setattr(dm, "torchao_streaming_plan", lambda p: _plan("streaming"))+ got = vid._video_torchao_seed_placement(fam, "fp8", CUDA_BF16, plan)+ assert seen == ["fp8"]+ assert (None if got is None else got.offload_policy) == want+++def test_whole_module_plan_without_a_pin_budget_is_not_streamed(monkeypatch, fam, fp8_gemm):+ monkeypatch.setattr(dm, "torchao_offload_plan", lambda p, s: p)+ monkeypatch.setattr(dm, "torchao_scheme_streams", lambda scheme, **kw: True)+ monkeypatch.setattr(dm, "_torchao_stream_pinnable", lambda p, reclaimable_host_mib = 0: False)+ assert vid._video_torchao_seed_placement(fam, "fp8", CUDA_BF16, _plan("model")) is None+++ "case",+ ["int8", "resident", "no_plan", "kill_switch", "no_fp8_gemm", "fp16", "cpu", "modular"],+)+def test_placement_declines(monkeypatch, fam, fp8_gemm, case):+ """int8 keeps its torchao-free twin; a resident plan needs nothing; no fp8 GEMM (A100), a non-bf16 or non-CUDA+ target, the kill switch and the modular workflow (MiniMax-H3 places its own denoiser) keep today's decline."""+ calls = []+ monkeypatch.setattr(dm, "torchao_offload_plan", lambda p, s: calls.append(s) or p)+ scheme, target, plan = "fp8", CUDA_BF16, _plan("group")+ if case == "int8":+ scheme = "int8"+ elif case == "resident":+ plan = _plan("none")+ elif case == "no_plan":+ plan = None+ elif case == "kill_switch":+ monkeypatch.setenv(vid.VIDEO_FP8_STREAM_ENV, "0")+ elif case == "no_fp8_gemm":+ fp8_gemm["ok"] = False+ elif case == "fp16":+ target = types.SimpleNamespace(device = "cuda", dtype = torch.float16, ordinal = 0)+ elif case == "cpu":+ target = types.SimpleNamespace(device = "cpu", dtype = torch.bfloat16, ordinal = None)+ elif case == "modular":+ fam = types.SimpleNamespace(name = "minimax-h3", modular_workflow = "t2v")+ assert vid._video_torchao_seed_placement(fam, scheme, target, plan) is None+ assert calls == []+++def _planner(monkeypatch, fam, *, resident, placement):+ backend = vid.VideoBackend()+ backend._state = types.SimpleNamespace(pipe = None)+ monkeypatch.setattr(vid, "_video_auto_denoiser_scheme", lambda fam, **kw: "fp8")+ monkeypatch.setattr(vid, "_pipeline_device_mib", lambda pipe, ordinal = None: 0)+ monkeypatch.setattr(vid, "resolve_diffusion_device_target", lambda **_k: CUDA_BF16)+ judged = _plan("group")++ def stays(fam, **kw):+ if kw.get("plan_out") is not None:+ kw["plan_out"].append(judged)+ return resident++ monkeypatch.setattr(vid, "_video_seed_stays_resident", stays)+ seen = []+ monkeypatch.setattr(+ vid,+ "_video_torchao_seed_placement",+ lambda fam, scheme, target, plan: seen.append((scheme, plan)) or placement,+ )+ monkeypatch.setattr(vid, "_video_native_hosted_scheme", lambda fam, scheme, target: None)+ native: list = []+ got = backend._video_planned_auto_denoiser_scheme(+ fam,+ base = LTX25,+ kind = "pipeline",+ transformer_quant = "fp8",+ speed_mode = None,+ native_hosted = native,+ )+ return got, seen, judged+++def test_planner_seeds_the_hosted_fp8_when_it_streams(monkeypatch, fam):+ got, seen, judged = _planner(monkeypatch, fam, resident = False, placement = _plan("group"))+ assert got == "fp8"+ assert seen == [("fp8", judged)] # judged on the same artifact-sized plan, no second settle+++def test_planner_still_declines_when_it_cannot_stream(monkeypatch, fam):+ got, seen, _ = _planner(monkeypatch, fam, resident = False, placement = None)+ assert got == vid.DENOISER_SEED_DECLINED+ assert seen+++def test_planner_resident_seed_skips_the_streaming_check(monkeypatch, fam):+ got, seen, _ = _planner(monkeypatch, fam, resident = True, placement = None)+ assert got == "fp8"+ assert seen == []+++def test_stays_resident_hands_back_the_plan_it_judged(monkeypatch, fam):+ planned = _plan("group")+ monkeypatch.setattr(vid, "_video_seed_plan", lambda fam, **kw: planned)+ monkeypatch.setattr(vid, "plan_keeps_transformer_resident", lambda p: False)+ out: list = []+ assert (+ vid._video_seed_stays_resident(+ fam,+ target = CUDA_BF16,+ scheme = "fp8",+ memory_mode = None,+ text_encoder_quant = None,+ base_repo = LTX25,+ plan_out = out,+ )+ is False+ )+ assert out == [planned]+ # no sizes: unchanged answer (a scheme counts as resident), nothing handed back+ monkeypatch.setattr(vid, "_video_seed_plan", lambda fam, **kw: None)+ out.clear()+ assert vid._video_seed_stays_resident(+ fam,+ target = CUDA_BF16,+ scheme = "fp8",+ memory_mode = None,+ text_encoder_quant = None,+ base_repo = LTX25,+ plan_out = out,+ )+ assert out == []diff --git a/studio/backend/tests/test_video_quantised_offload.py b/studio/backend/tests/test_video_quantised_offload.pyindex 959f97a7d2f..a1cbcd1300c 100644--- a/studio/backend/tests/test_video_quantised_offload.py+++ b/studio/backend/tests/test_video_quantised_offload.py@@ -122,12 +122,13 @@ def _spoof(monkeypatch.setattr(tq, "native_quant_host", lambda t: False)monkeypatch.setattr(tq, "native_offload_host", lambda t: True)monkeypatch.setattr(V, "stored_denoiser_precision", lambda *a, **k: None)- spy = types.SimpleNamespace(plans = [], quant = [], speed = [], seeded = [])+ spy = types.SimpleNamespace(plans = [], quant = [], speed = [], seeded = [], seed_kw = [])import core.inference.video_denoiser_prequant as vdpdef _seed(fam, base, *, scheme, **kw):spy.seeded.append(scheme)+ spy.seed_kw.append(kw)return {"transformer": object()}monkeypatch.setattr(vdp, "denoiser_prequant_pipe_kwargs", _seed)@@ -245,12 +246,54 @@ def test_auto_seeds_the_hosted_artifact_only_where_it_would_quantise(assert status["transformer_quant"] == "int8"+def _streaming_supported(monkeypatch):+ """torchao / diffusers versions and host RAM decide streaming; pin them so the host's install does not."""+ import core.inference.diffusion_memory as dm++ monkeypatch.setattr(dm, "torchao_scheme_streams", lambda scheme, **kw: True)+ monkeypatch.setattr(dm, "_torchao_stream_pinnable", lambda plan, reclaimable_host_mib = 0: True)++def test_explicit_fp8_refused_with_reason_when_the_dit_must_move(fake_runtime, monkeypatch):+ """UNSLOTH_VIDEO_FP8_STREAM=0 restores the refusal of an fp8 DiT the plan moves."""+ _streaming_supported(monkeypatch)+ monkeypatch.setenv("UNSLOTH_VIDEO_FP8_STREAM", "0")_spoof(monkeypatch, tier_gib = 16)with pytest.raises(RuntimeError, match = r"moves the DiT .*int8 runs torchao-free"):VideoBackend().load_pipeline(FAMILIES["wan2.2-ti2v-5b"], transformer_quant = "fp8")+def test_explicit_fp8_refused_where_the_card_has_no_fp8_gemm(fake_runtime, monkeypatch):+ """Without Studio's fp8 GEMM (sm_80) a moved DiT cannot stream torchao fp8 weights: still refused."""+ _streaming_supported(monkeypatch)+ monkeypatch.setitem(SUPPORTED, (8, 0), {"int8"})+ _spoof(monkeypatch, tier_gib = 16, cap = (8, 0))+ with pytest.raises(RuntimeError):+ VideoBackend().load_pipeline(FAMILIES["wan2.2-ti2v-5b"], transformer_quant = "fp8")+++def test_explicit_fp8_streams_the_hosted_torchao_dit_when_the_dit_must_move(+ fake_runtime, monkeypatch+):+ """sm_89+: the hosted fp8 checkpoint is seeded and streamed (torchao_offload_plan), not refused, and the dense+ shards are not quantised at load."""+ _streaming_supported(monkeypatch)+ spy = _spoof(monkeypatch, tier_gib = 16, cap = (8, 9))+ status = VideoBackend().load_pipeline(FAMILIES["wan2.2-ti2v-5b"], transformer_quant = "fp8")+ assert status["transformer_quant"] == "fp8"+ assert spy.seeded == ["fp8"]+ assert not spy.quant+ assert spy.plans[-1].offload_policy in ("group", "streaming")+ # built on the host: the offload hooks move it block by block (on the card first it OOMed a 16 GiB budget)+ assert spy.seed_kw[0]["placement_device"] == "cpu"+++def test_resident_fp8_seed_is_built_on_the_card(fake_runtime, monkeypatch):+ spy = _spoof(monkeypatch, tier_gib = 24)+ VideoBackend().load_pipeline(FAMILIES["wan2.2-ti2v-5b"], transformer_quant = "fp8")+ assert spy.seed_kw[0]["placement_device"] is None++def test_explicit_int8_under_streamed_dit_is_torchao_free(fake_runtime, monkeypatch):spy = _spoof(monkeypatch, tier_gib = 24)status = VideoBackend().load_pipeline(FAMILIES["ltx-2"], transformer_quant = "int8")