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: size the hosted H3 text encoder before the unified-memory guard (#15474)
Daniel Hana45de19fdef0
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex b9a6915481a..43a95b1c691 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -129,6 +129,7 @@ from .diffusion_multigpu import (with_load_selection,)from .diffusion_memory import (+ DeviceMemory,commit_load_budget_fraction,release_load_budget_fraction,vram_budget_scope,@@ -10163,6 +10164,8 @@ class VideoBackend:device: str,memory_mode: Optional[str],scheme: Optional[str],+ te_scheme: Optional[str] = None,+ device_memory: Optional[DeviceMemory] = None,) -> None:"""Refuse H3 modular loads that cannot fit unified memory; best-effort, skipped if no table/device."""components = getattr(fam, "bf16_components_gb", None)@@ -10180,10 +10183,16 @@ class VideoBackend:transformer_gb = float(measured)elif factor is not None:transformer_gb *= factor+ # The hosted conditioner stays INT8 in memory; price the same artifact the loader seeds.+ text_encoder_gb = h3_te_resident_gb(te_scheme, bf16_gb = text_encoder_gb)mib_per_gb = 1000.0**3 / (1024.0 * 1024.0)plan = plan_diffusion_memory(target = target,- device_memory = settled_snapshot_device_memory(target),+ device_memory = (+ device_memory+ if device_memory is not None+ else settled_snapshot_device_memory(target)+ ),model_dense_mib = int((transformer_gb + text_encoder_gb + vae_gb) * dtype_scale * mib_per_gb),@@ -10348,7 +10357,17 @@ class VideoBackend:f"no hosted pre-quantized {scheme} checkpoint for {fam.name} {workflow}")scheme = None- # Unified memory: CPU offload frees nothing, so H3's 144.2 GB set must be refused before any load.+ te_scheme = self._h3_te_quant_scheme(fam, text_encoder_quant, base, umem_target)+ te_index_source = self._h3_te_index_source(pipe) if te_scheme is not None else None+ te_index_declined = False+ if te_scheme is not None:+ if te_index_source is None or _h3_te_canonical(te_index_source) != _h3_te_canonical(+ fam.base_repo+ ):+ te_scheme = None+ te_index_declined = True+ # Keep the pre-seed free pool: re-reading after seeding double-counts hosted components.+ preseed_memory = settled_snapshot_device_memory(umem_target)self._raise_on_modular_unified_shortfall(fam,target = umem_target,@@ -10356,6 +10375,8 @@ class VideoBackend:device = device,memory_mode = memory_mode,scheme = comfy_scheme or scheme,+ te_scheme = te_scheme,+ device_memory = preseed_memory,)if comfy_scan is not None:from .video_minimax_h3_comfy import load_h3_comfy_transformer@@ -10489,24 +10510,11 @@ class VideoBackend:# Seed the hosted conditioner: a runtime cast peaks at bf16 and would download 62 GB dense.text_encoder_quant_engaged: Optional[str] = Nonetext_encoder_quant_reason = "released bfloat16 components"- # Base-gated by the plan's resolver: a derivative base with its own conditioner never gets this one.- te_scheme = self._h3_te_quant_scheme(fam, text_encoder_quant, base, umem_target)- # From here the request is the NORMALISED scheme (None once "none" pins dense); reasons assume it.text_encoder_quant = (None if text_encoder_quant_is_auto else normalize_te_quant(text_encoder_quant))if text_encoder_quant_is_auto and te_scheme is not None:text_encoder_quant_reason = f"auto: hosted quantized {te_scheme} conditioner"- # Second gate: the modular index names the conditioner's true source; unanswerable is a refusal.- te_index_source = self._h3_te_index_source(pipe) if te_scheme is not None else None- te_index_declined = False- if te_scheme is not None:- # Exact match: the tolerant _same_base_model would accept someone/MiniMax-H3.- if te_index_source is None or _h3_te_canonical(te_index_source) != _h3_te_canonical(- fam.base_repo- ):- te_scheme = None- te_index_declined = Trueif text_encoder_quant is not None and te_scheme is None:# Valid request, no hosted artifact for this workflow or conditioner: say which; keep the request.if te_index_declined:@@ -10583,15 +10591,19 @@ class VideoBackend:))# Pass the token again or gated components load anonymously; workflow= narrows names, not blocks.- if scheme is not None and transformer_quant_engaged is None:- # Seeding may fall back to the dense 66.3 GB denoiser: re-check unified memory first or the OS kills.+ if (scheme is not None and transformer_quant_engaged is None) or (+ te_scheme is not None and text_encoder_quant_engaged is None+ ):+ # Either hosted component can fall back to dense; re-check the components that actually landed.self._raise_on_modular_unified_shortfall(fam,target = umem_target,dtype = dtype,device = device,memory_mode = memory_mode,- scheme = None,+ scheme = transformer_quant_engaged,+ te_scheme = text_encoder_quant_engaged,+ device_memory = preseed_memory,)# Without cache_dir components resolve against the import-time HF_HUB_CACHE.from .diffusion_offline_source import offline_component_sourcesdiff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.pyindex f51a1bd94c9..bc611c83e2b 100644--- a/studio/backend/tests/test_video_backend.py+++ b/studio/backend/tests/test_video_backend.py@@ -13633,3 +13633,208 @@ def test_a_layer_split_fallback_moves_the_compile_below_the_offload_hooks(_load_gguf(backend, tmp_path)assert speed_offload and set(speed_offload) == {not split_expected}assert (seen == [backend._state.pipe]) if moved else (seen == [])++[email protected]("te_scheme, encoder_gb", [(None, 66.8), ("int8", 27.2)])+def test_h3_unified_guard_prices_the_hosted_conditioner(+ fake_runtime, monkeypatch, te_scheme, encoder_gb+):+ import core.inference.video as video_mod+ from core.inference.video_families import detect_video_family++ seen = {}++ def capture(**kwargs):+ seen.update(kwargs)+ return object()++ monkeypatch.setattr(video_mod, "plan_diffusion_memory", capture)+ monkeypatch.setattr(video_mod, "settled_snapshot_device_memory", lambda _target: None)+ monkeypatch.setattr(video_mod, "raise_on_unified_memory_shortfall", lambda *_a, **_kw: None)+ fam = detect_video_family("MiniMaxAI/MiniMax-H3")+ VideoBackend._raise_on_modular_unified_shortfall(+ fam,+ target = None,+ dtype = sys.modules["torch"].bfloat16,+ device = "cuda",+ memory_mode = None,+ scheme = "fp8",+ te_scheme = te_scheme,+ )+ assert seen["model_dense_mib"] == int((20.3 + encoder_gb + 11.1) * 1000**3 / 1024**2)+++ "te_request, source, encoder_gb",+ [+ (None, "MiniMaxAI/MiniMax-H3", 27.2),+ ("int8", "MiniMaxAI/MiniMax-H3", 27.2),+ ("none", "MiniMaxAI/MiniMax-H3", 66.8),+ ("int8", "someone/MiniMax-H3", 66.8),+ ("int8", None, 66.8),+ ],+)+def test_h3_unified_preflight_uses_the_seeded_encoder_provenance(+ fake_runtime, monkeypatch, te_request, source, encoder_gb+):+ import core.inference.video as video_mod++ class ReachedPreflight(Exception):+ pass++ seen = {}++ def capture(**kwargs):+ seen.update(kwargs)+ raise ReachedPreflight++ pipe = types.SimpleNamespace(+ get_component_spec = lambda _name: types.SimpleNamespace(+ pretrained_model_name_or_path = source+ ),+ )+ diffusers = types.SimpleNamespace(+ ComponentsManager = lambda: object(),+ ModularPipeline = types.SimpleNamespace(from_pretrained = lambda *_a, **_kw: pipe),+ )+ monkeypatch.setattr(video_mod, "_h3_auto_precision_ok", lambda _target: True)+ monkeypatch.setattr(video_mod, "plan_diffusion_memory", capture)+ monkeypatch.setattr(video_mod, "settled_snapshot_device_memory", lambda _target: None)+ fam = _detect_load_family("MiniMaxAI/MiniMax-H3", None, "minimax-h3")+ with pytest.raises(ReachedPreflight):+ VideoBackend()._load_h3_modular_pipeline(+ diffusers = diffusers,+ torch = sys.modules["torch"],+ fam = fam,+ repo_id = fam.base_repo,+ base = fam.base_repo,+ kind = "pipeline",+ dtype = sys.modules["torch"].bfloat16,+ device = "cuda",+ hf_token = None,+ memory_mode = None,+ transformer_quant = "fp8",+ text_encoder_quant = te_request,+ target = types.SimpleNamespace(device = "cuda"),+ )+ assert seen["model_dense_mib"] == int((20.3 + encoder_gb + 11.1) * 1000**3 / 1024**2)+++def test_h3_unified_quantized_components_still_refuse_a_spark_sized_pool(fake_runtime, monkeypatch):+ import core.inference.video as video_mod+ from core.inference.diffusion_memory import DeviceMemory++ fam = _detect_load_family("MiniMaxAI/MiniMax-H3", None, "minimax-h3")+ memory = DeviceMemory("cuda", "cuda", "unified_memory", 45 * 1024, 54 * 1024)+ monkeypatch.setattr(video_mod, "settled_snapshot_device_memory", lambda _target: memory)+ with pytest.raises(RuntimeError, match = "unified memory") as exc:+ VideoBackend._raise_on_modular_unified_shortfall(+ fam,+ target = types.SimpleNamespace(device = "cuda", supports_model_cpu_offload = True),+ dtype = sys.modules["torch"].bfloat16,+ device = "cuda",+ memory_mode = None,+ scheme = "fp8",+ te_scheme = "int8",+ )+ assert "57 GB" in str(exc.value)+ # A larger unified pool can load the quantized pair even though the old 93 GiB estimate refused it.+ monkeypatch.setattr(video_mod, "settled_snapshot_device_memory", _unified_snapshot(128))+ VideoBackend._raise_on_modular_unified_shortfall(+ fam,+ target = types.SimpleNamespace(device = "mps", supports_model_cpu_offload = True),+ dtype = sys.modules["torch"].bfloat16,+ device = "mps",+ memory_mode = None,+ scheme = "fp8",+ te_scheme = "int8",+ )++[email protected]("total_gib, fallback_fits", [(128, False), (160, True)])+def test_h3_unified_guard_reruns_before_a_failed_hosted_encoder_goes_dense(+ fake_runtime, monkeypatch, total_gib, fallback_fits+):+ import core.inference.video as video_mod+ import core.inference.diffusion_prequant as prequant_mod+ import core.inference.video_minimax_h3_te as te_mod+ from core.inference.diffusion_memory import DeviceMemory++ calls = []+ snapshots = []+ initial_memory = _unified_snapshot(total_gib)(None)+ free_mib = initial_memory.free_mib++ def snapshot(_target):+ memory = DeviceMemory("mps", "mps", "unified_memory", free_mib, initial_memory.total_mib)+ snapshots.append(memory)+ return memory++ def seed_transformer(*_a, **_kw):+ nonlocal free_mib+ free_mib -= int(20.3 * 1000**3 / 1024**2)+ return object()++ class ReachedComponents(Exception):+ pass++ real = VideoBackend._raise_on_modular_unified_shortfall++ def spy(fam, **kwargs):+ calls.append((kwargs["scheme"], kwargs["te_scheme"], kwargs["device_memory"]))+ return real(fam, **kwargs)++ class Pipe:+ def get_component_spec(self, _name):+ return types.SimpleNamespace(pretrained_model_name_or_path = "MiniMaxAI/MiniMax-H3")++ def update_components(self, **kwargs):+ for name, value in kwargs.items():+ setattr(self, name, value)++ def load_components(self, **kwargs):+ if not fallback_fits:+ pytest.fail("dense components must not be opened before the fallback memory check")+ raise ReachedComponents++ diffusers = types.SimpleNamespace(+ ComponentsManager = lambda: object(),+ ModularPipeline = types.SimpleNamespace(from_pretrained = lambda *_a, **_kw: Pipe()),+ MiniMaxH3Transformer3DModel = object,+ )+ monkeypatch.setattr(VideoBackend, "_raise_on_modular_unified_shortfall", staticmethod(spy))+ monkeypatch.setattr(video_mod, "settled_snapshot_device_memory", snapshot)+ monkeypatch.setattr(video_mod, "precision_fallback_allowed", lambda: True)+ monkeypatch.setattr(+ prequant_mod,+ "resolve_prequant_source",+ lambda *_a, **_kw: types.SimpleNamespace(location = "unsloth/MiniMax-H3-FP8"),+ )+ monkeypatch.setattr(prequant_mod, "load_prequantized_transformer", seed_transformer)+ monkeypatch.setattr(te_mod, "load_h3_quantized_text_encoder", lambda *_a, **_kw: None)+ fam = _detect_load_family("MiniMaxAI/MiniMax-H3", None, "minimax-h3")+ expected = (+ pytest.raises(ReachedComponents)+ if fallback_fits+ else pytest.raises(RuntimeError, match = "unified memory")+ )+ with expected:+ VideoBackend()._load_h3_modular_pipeline(+ diffusers = diffusers,+ torch = sys.modules["torch"],+ fam = fam,+ repo_id = fam.base_repo,+ base = fam.base_repo,+ kind = "pipeline",+ dtype = sys.modules["torch"].bfloat16,+ device = "mps",+ hf_token = None,+ memory_mode = None,+ transformer_quant = "fp8",+ text_encoder_quant = "int8",+ target = types.SimpleNamespace(device = "mps", supports_model_cpu_offload = True),+ )+ # Seeded weights reduce current free RAM, but both checks price the FULL model against the original pool.+ assert free_mib < initial_memory.free_mib+ assert snapshots == [initial_memory]+ assert calls == [("fp8", "int8", initial_memory), ("fp8", None, initial_memory)]