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
MiniMax-H3: fall back to the hosted int8 denoiser when the released one cannot stay resident (#8347)
Daniel Han738690de13f7
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex de2d897e9b9..5d76eeaa9a7 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -626,6 +626,69 @@ def _h3_dense_denoiser_resident_bytes(return None+def _h3_planned_denoiser_bytes(+ fam: Any, *, te_scheme: Optional[str], dtype: Any+) -> Optional[tuple[int, int]]:+ """The same ``(denoiser_bytes, everything_else_bytes)`` split, PREDICTED from the family table.++ The measured helper above needs the built denoiser, and the seeding decision this feeds has to+ be made before ``load_components`` builds anything -- after it, the dense 66.3 GB module has+ already been fetched, which is the cost the decision exists to avoid. So the denoiser is priced+ from the released bf16 table entry rather than a module, and everything else is computed by the+ identical arithmetic, so the pre-load prediction and the post-load pin agree about the same+ load instead of drifting apart."""+ components = getattr(fam, "bf16_components_gb", None)+ if not components:+ return None+ try:+ import torch++ scale = 2.0 if dtype is torch.float32 else 1.0+ denoiser_bytes = int(components[0] * scale * 1000.0**3)+ text_encoder_gb = h3_te_resident_gb(te_scheme, bf16_gb = components[1])+ headroom_bytes = (+ estimate_video_runtime_mib(+ width = fam.resolution_presets[0][0],+ height = fam.resolution_presets[0][1],+ num_frames = fam.default_num_frames,+ )+ * 1024+ * 1024+ )+ others = int((text_encoder_gb + components[2]) * scale * 1000.0**3) + headroom_bytes+ return denoiser_bytes, others+ except Exception: # noqa: BLE001 -- an unanswerable estimate keeps the released denoiser+ return None+++def _h3_free_device_bytes(device: str) -> Optional[int]:+ """Live free VRAM, or None when it cannot be read. None means "cannot tell", never zero."""+ if device != "cuda":+ return None+ try:+ import torch+ return int(torch.cuda.mem_get_info()[0])+ except Exception: # noqa: BLE001 -- an unreadable card decides nothing+ return None+++def _h3_device_capacity_bytes(device: str) -> Optional[int]:+ """TOTAL VRAM on the card, or None when it cannot be read.++ The reading for a decision made before the download, where the free one lies: the resident+ pipeline is not torn down until ``load_pipeline`` runs, so a free reading taken while the plan+ is being built describes the OLD model's occupancy, not this load's. Capacity cannot -- it is+ an upper bound on any later free reading, so "does not fit in the whole card" still holds when+ the loader asks again against live free memory."""+ if device != "cuda":+ return None+ try:+ import torch+ return int(torch.cuda.mem_get_info()[1])+ except Exception: # noqa: BLE001 -- an unreadable card decides nothing+ return None++def _h3_dense_denoiser_fits(sizes: Optional[tuple[int, int]], free_bytes: Optional[int]) -> bool:"""Whether the released denoiser can come OUT of the offload rotation and stay resident.@@ -639,6 +702,92 @@ def _h3_dense_denoiser_fits(sizes: Optional[tuple[int, int]], free_bytes: Optionreturn int(free_bytes) >= int(denoiser_bytes) + int(others_bytes)+# The scheme an UNSET transformer_quant falls back to when the released denoiser cannot stay+# resident. int8 rather than fp8: the two are the same 20.3 GB resident and neither is a faster+# GEMM, but int8 scored closer to the released denoiser (SSIM 0.49 against 0.43) and, unlike fp8,+# needs no per-row scale support from the card.+H3_AUTO_FALLBACK_SCHEME = "int8"+++def _h3_auto_denoiser_scheme(+ fam: Any,+ *,+ target: Any,+ dtype: Any,+ device: str,+ te_scheme: Optional[str],+ task: Optional[str],+ base_repo: Optional[str],+ speed_mode: Optional[str] = None,+ free_reader: Any = None,+) -> Optional[str]:+ """The hosted scheme an UNSET ``transformer_quant`` resolves to, or None to keep bfloat16.++ None whenever the released denoiser can stay resident, so a card with room gets exactly what+ it got before: the released weights, bit-identical output, and the pin plus regional compile+ that make it fast.++ The fallback exists because the alternative on a smaller card is not "a bit slower". A denoiser+ that does not fit stays in the CPU-offload rotation, and a module that moves cannot be compiled+ either, so the regional compile is dropped with it: 194 s against 23.7 s on the same 8-step job,+ every step paying 66.3 GB across the bus. The hosted checkpoint is 20.3 GB resident, which pins,+ which restores the compile.++ The cost is real and is why this is a fallback rather than the default everywhere: the hosted+ denoisers RE-ROLL the sample (mean SSIM 0.49 against the released weights, where that config+ against itself scores 0.99). Different is not worse -- no NaN, no black frames, no visible+ degradation at the model's own 30-step schedule -- but it is not the same picture, so it is+ taken only when the choice is against a configuration nobody would pick knowingly.++ ``free_reader`` is how the device is measured: live free memory by default, and CAPACITY for+ the pre-download decision, which runs while the previous pipeline is still resident.++ Never raises, and every unanswerable question keeps the released denoiser."""+ # An explicit speed_mode="off" is a bit-exact contract, and a re-rolled sample is not bit-exact.+ # The conventional loader rewrites an unset precision to "off" under it for exactly this reason;+ # this workflow returns above that rewrite, so it applies the same rule itself.+ if speed_mode is not None and str(speed_mode).strip().lower() == SPEED_OFF:+ return None+ if not _h3_auto_precision_ok(target):+ return None+ # The hosted checkpoint is a quantization of MiniMaxAI/MiniMax-H3's OWN denoiser, so the+ # substitution is only equivalent-modulo-precision against that base. Exact identity, not the+ # tolerant tail compare the availability lookup below applies: someone/MiniMax-H3 is a+ # different repo with different weights, and installing the upstream denoiser over a+ # derivative's is not a precision choice, it is a different model. An EXPLICIT request is+ # unaffected; this gate is on the substitution nobody asked for. Same bar, and the same+ # helper, as the conditioner's index gate in the loader.+ canonical = getattr(fam, "base_repo", None)+ if not base_repo or not canonical:+ return None+ if _h3_te_canonical(base_repo) != _h3_te_canonical(canonical):+ return None+ sizes = _h3_planned_denoiser_bytes(fam, te_scheme = te_scheme, dtype = dtype)+ free_bytes = (free_reader or _h3_free_device_bytes)(device)+ if sizes is None or free_bytes is None:+ # No reading is not evidence of a shortfall, and guessing wrong here changes the picture a+ # user gets. Keep the released denoiser, which is what happens today.+ return None+ if _h3_dense_denoiser_fits(sizes, free_bytes):+ return None+ if not video_family_prequant_available(+ fam, H3_AUTO_FALLBACK_SCHEME, task = task, base_repo = base_repo+ ):+ # Asked per (scheme, PARTITION): a partition with no hosted checkpoint has no fallback, and+ # serving the other partition's would generate the wrong thing.+ return None+ # And the replacement has to fit BEFORE it is chosen. A torchao denoiser cannot ride the offload+ # rotation at all (it does not survive the mid-block move), so taking it means pinning it, which+ # turns the memory floor from a max into a sum: 20.3 GB resident PLUS whatever runs beside it.+ # Under text_encoder_quant="none" that sum is larger than the dense rotation it replaces, so a+ # card that renders today would refuse every generation afterwards. Where the replacement does+ # not fit either, the released denoiser in the rotation is the configuration that still runs.+ hosted_bytes = int(h3_transformer_resident_gb(H3_AUTO_FALLBACK_SCHEME) * 1000.0**3)+ if not _h3_dense_denoiser_fits((hosted_bytes, sizes[1]), free_bytes):+ return None+ return H3_AUTO_FALLBACK_SCHEME++def _progress(phase: Optional[str], **extra: Any) -> dict[str, Any]:return {"phase": phase, **extra}@@ -1152,13 +1301,32 @@ class VideoBackend:# the conditioner below and like the plan: this flag both REMOVES 66 GB from the pull# and is never re-checked, so an artifact that does not resolve has to keep the dense# shards rather than strand the load's own bf16 fallback with nothing to open.+ # An UNSET H3 precision can resolve to a hosted checkpoint too, and that has to be+ # settled HERE rather than only inside the loader: decided late, the pull stages the+ # dense denoiser the load never opens AND the replacement arrives inline, outside this+ # plan's progress, cancel and disk preflight.+ h3_auto_denoiser = self._h3_planned_auto_denoiser_scheme(+ fam,+ base = base,+ transformer_quant = kwargs.get("transformer_quant"),+ text_encoder_quant = kwargs.get("text_encoder_quant"),+ speed_mode = kwargs.get("speed_mode"),+ h3_task = kwargs.get("h3_task"),+ )skip_transformer_weights = self._denoiser_prequant_verified(fam,- kwargs.get("transformer_quant"),+ h3_auto_denoiser or kwargs.get("transformer_quant"),base,kwargs.get("h3_task"),kwargs.get("hf_token"),)+ # Handed to the loader only when the dense shards really are gone from the pull. Then+ # the choice is already committed and the loader must not re-take it against a reading+ # that has moved since -- there would be no dense denoiser left to fall back to. When+ # the plan kept them, this stays None and the loader decides for itself as before.+ kwargs["_h3_auto_denoiser_planned"] = (+ h3_auto_denoiser if h3_auto_denoiser and skip_transformer_weights else None+ )# And for MiniMax-H3's conditioner, whose hosted quantized artifact replaces the base# repo's 62 GB dense text_encoder/ shards outright.# Verified, not just name-matched: this scheme decides whether the base pull DROPS the@@ -1710,6 +1878,52 @@ class VideoBackend:)return repo is not None+ def _h3_planned_auto_denoiser_scheme(+ self,+ fam: Any,+ *,+ base: Optional[str],+ transformer_quant: Optional[str],+ text_encoder_quant: Optional[str],+ speed_mode: Optional[str],+ h3_task: Optional[str],+ ) -> Optional[str]:+ """The auto denoiser fallback, resolved BEFORE anything is downloaded, or None.++ The loader asks the same question against live free memory once the previous pipeline is+ torn down. Asking it there ALONE is too late for the pull: the plan still stages the+ 66.3 GB dense denoiser this load will never open, and the 20.3 GB replacement is then+ fetched inline, outside the progress plan, the cancel path and the disk preflight that+ already passed. So the plan asks it too, against the card's CAPACITY -- the one reading+ that is not polluted by the model still resident at plan time, and an upper bound on any+ later free reading, so a "does not fit" here still holds when the loader re-measures.++ None leaves the plan exactly as it was. Never raises: this runs on the planning path."""+ if not _h3_precision_unset(transformer_quant):+ return None+ try:+ if not getattr(fam, "modular_workflow", None):+ return None+ import torch++ target = resolve_diffusion_device_target()+ dtype = target.dtype+ if getattr(fam, "fp16_incompatible", False) and dtype is torch.float16:+ dtype = torch.float32+ return _h3_auto_denoiser_scheme(+ fam,+ target = target,+ dtype = dtype,+ device = target.device,+ te_scheme = self._h3_te_quant_scheme(fam, text_encoder_quant, base, target),+ task = h3_task or getattr(fam, "modular_workflow", None),+ base_repo = base,+ speed_mode = speed_mode,+ free_reader = _h3_device_capacity_bytes,+ )+ except Exception: # noqa: BLE001 -- an unanswerable probe keeps the dense shards+ return None+def _h3_te_quant_scheme_verified(self,fam: Any,@@ -2131,6 +2345,20 @@ class VideoBackend:if is_h3_native(fam, kind):return self._h3_native_download_plan(repo_id, gguf_filename or "", hf_token = hf_token)base = repo_id if kind == "pipeline" else resolve_video_base_repo(fam, base_repo)+ # The same resolution the load makes, so an H3 auto pick the loader will serve from a+ # hosted checkpoint is not staged dense here first: that is 66.3 GB the panel downloads+ # and the load never opens, and the replacement would then arrive outside this plan.+ transformer_quant = (+ self._h3_planned_auto_denoiser_scheme(+ fam,+ base = base,+ transformer_quant = transformer_quant,+ text_encoder_quant = text_encoder_quant,+ speed_mode = load_kwargs.get("speed_mode"),+ h3_task = h3_task,+ )+ or transformer_quant+ )# Only the header tells an LTX-2.3 checkpoint from 2.0 and it is not on disk yet, so narrow the base pull by NAME: a wrong guess costs an inline pull, the wide base list costs gigabytes.ltx23 = self._pick_looks_like_ltx23(fam, repo_id, gguf_filename, kind)# Keyed by repo so a 2.3 pick's checkpoint and extras stay ONE scoped job; two entries would collide on the job key.@@ -2680,6 +2908,7 @@ class VideoBackend:_load_token: Optional[int] = None,_base_local_dir: Optional[str] = None,_te_prequant_skipped: tuple[str, ...] = (),+ _h3_auto_denoiser_planned: Optional[str] = None,) -> dict[str, Any]:fam = self.validate_load_request(repo_id,@@ -2778,6 +3007,8 @@ class VideoBackend:h3_task = h3_task,_load_token = _load_token,_base_local_dir = _base_local_dir,+ # Settled before the pull when the pull acted on it; None when it did not.+ _h3_auto_denoiser_planned = _h3_auto_denoiser_planned,)# What the CALLER asked for, before the rewrite below. The record has to report this, not@@ -3459,6 +3690,7 @@ class VideoBackend:target: Any = None,_load_token: Optional[int] = None,_base_local_dir: Optional[str] = None,+ _h3_auto_denoiser_planned: Optional[str] = None,) -> dict[str, Any]:"""Load MiniMax-H3 through its official Modular Diffusers workflow.@@ -3496,21 +3728,55 @@ class VideoBackend:# ── hosted pre-quantized denoiser, BEFORE load_components builds a dense one.transformer_quant_engaged: Optional[str] = Nonetransformer_quant_reason = "released bfloat16 components"- # "auto" asks the backend to choose, and the auto ladder quantises a DENSE module on device- # -- something this workflow never materialises -- so it stays on the released denoiser.- # Only an explicit scheme takes the hosted path. Those checkpoints ARE fast (the same- # 8-step job runs 23.7 s against 194 s) and were measured before being considered as a- # default: at the model's own 30-step schedule they show no NaN, no black frames and no- # visible degradation, but they RE-ROLL the sample -- mean SSIM 0.49 (int8) / 0.43 (fp8)- # against the released denoiser, where that config against itself scores 0.99. Different- # is not worse, but nothing here can tell the two apart, so they stay opt-in and the- # default takes its speed from the resident placement + regional compile below, which- # change no weights at all.+ # "auto" asks the backend to choose. The auto LADDER is still not it -- that quantises a+ # dense module on device, which this workflow never materialises -- so the choice is+ # between the released denoiser and a hosted checkpoint, and it turns on whether the+ # released one can stay resident.+ #+ # Where it fits, auto keeps it: same weights, same picture, and the pin plus regional+ # compile below make it fast without touching a single value. Where it does not, keeping it+ # is not a smaller win but a cliff -- it rides the CPU-offload rotation, a module that moves+ # cannot be compiled, and the same 8-step job goes 23.7 s to 194 s. The hosted checkpoint is+ # 20.3 GB resident, so it pins, so the compile comes back.+ #+ # The trade is that the hosted denoisers RE-ROLL the sample: mean SSIM 0.49 (int8) / 0.43+ # (fp8) against the released weights, where that config against itself scores 0.99. No NaN,+ # no black frames, no visible degradation at the model's own 30-step schedule, but not the+ # same picture. Which is why this is a fallback and not a blanket default: it is taken only+ # against a configuration nobody would choose on purpose.scheme = (None if transformer_quant_is_auto else normalize_transformer_quant(transformer_quant))if scheme == TQ_AUTO: # defence in depth; _h3_precision_unset already caught "auto"scheme = None+ auto_fallback_scheme = None+ if transformer_quant_is_auto:+ # Already settled if the download planner acted on it -- the dense denoiser shards are+ # not on disk, so re-deciding here against a reading that has moved could ask for a+ # component this load can no longer open. Otherwise decide now, against live free+ # memory, which is the reading that describes the card once the previous pipeline is+ # gone (the plan only had the card's capacity to go on).+ auto_fallback_scheme = _h3_auto_denoiser_planned or _h3_auto_denoiser_scheme(+ fam,+ target = umem_target,+ dtype = dtype,+ device = device,+ # The conditioner precision this load WILL engage, predicted the same way the+ # encoder resolves it below, because it is part of what has to fit beside it.+ te_scheme = self._h3_te_quant_scheme(fam, text_encoder_quant, base, umem_target),+ task = workflow,+ base_repo = base,+ speed_mode = speed_mode,+ )+ if auto_fallback_scheme is not None:+ scheme = auto_fallback_scheme+ logger.info(+ "video.transformer_quant: the released bfloat16 denoiser does not fit beside "+ "the other components on this device, where it would stay in the CPU-offload "+ "rotation and lose the regional compile with it, so auto is taking the hosted "+ "%s checkpoint (ask for transformer_quant='none' to keep the released weights)",+ auto_fallback_scheme,+ )# Per (scheme, PARTITION), not per scheme: each workflow denoises against its own# checkpoint partition and they are indistinguishable once loaded, so a scheme that has an# artifact for the other one has none for this. It used to be enough to ask "is this the@@ -3601,8 +3867,18 @@ class VideoBackend:# the dense one has already been pulled and built.pipe.update_components(**{denoiser_component: transformer})transformer_quant_engaged = scheme+ # Says WHY when the caller did not ask for this. A record that reads the same+ # for a requested int8 and an automatic one leaves a user who never chose a+ # scheme with no way to see that the picture changed, or how to get the+ # released weights back.transformer_quant_reason = (f"hosted pre-quantized {scheme} denoiser checkpoint ({source.location})"+ if auto_fallback_scheme is None+ else (+ f"the released bfloat16 denoiser does not fit resident on this device, "+ f"so auto took the hosted {scheme} checkpoint ({source.location}); "+ f"transformer_quant='none' keeps the released weights"+ ))logger.info("video.transformer_quant: %s pre-quantized denoiser seeded for %s",diff --git a/studio/backend/tests/test_video_prequant.py b/studio/backend/tests/test_video_prequant.pyindex d778c628f74..035f24aed75 100644--- a/studio/backend/tests/test_video_prequant.py+++ b/studio/backend/tests/test_video_prequant.py@@ -769,3 +769,322 @@ def test_the_dense_placement_is_fenced_on_the_load_token():assert (load_components < fence < placement), "the token fence must sit between load_components and the placement it guards"+++# ── auto falls back to the hosted denoiser only where the released one cannot stay resident ──+++def _h3_family():+ from core.inference.video_families import detect_video_family+ return detect_video_family("minimax-h3")+++def test_the_planned_sizing_matches_the_measured_one_it_stands_in_for():+ """The pre-load prediction and the post-load pin have to describe the same load.++ They are separate functions for a real reason -- the seeding decision runs before any module+ exists, the pin runs after -- but if their arithmetic drifts, auto can seed a checkpoint on a+ card that would have held the released denoiser, or leave the released one on a card that+ cannot. Only the DENOISER term may differ (table vs built module); everything else must agree+ exactly."""+ import torch++ from core.inference.video import (+ _h3_dense_denoiser_resident_bytes,+ _h3_planned_denoiser_bytes,+ )++ fam = _h3_family()++ class _Dense:+ def parameters(self):+ # The released denoiser, at the size the family table quotes for it.+ n = int(fam.bf16_components_gb[0] * 1000**3 // 2)+ return [torch.zeros(n, dtype = torch.bfloat16)]++ def buffers(self):+ return []++ for te_scheme in (None, "int8"):+ planned = _h3_planned_denoiser_bytes(fam, te_scheme = te_scheme, dtype = torch.bfloat16)+ measured = _h3_dense_denoiser_resident_bytes(+ fam, denoiser = _Dense(), te_scheme = te_scheme, dtype = torch.bfloat16+ )+ assert planned is not None and measured is not None+ assert planned[1] == measured[1], f"the others term drifted for te_scheme={te_scheme}"+ # And the denoiser term agrees to within rounding on the same released weights.+ assert abs(planned[0] - measured[0]) < 1_000_000_000++ # An fp32 promotion doubles it on both sides, so the comparison is not accidentally bf16-only.+ fp32 = _h3_planned_denoiser_bytes(fam, te_scheme = None, dtype = torch.float32)+ bf16 = _h3_planned_denoiser_bytes(fam, te_scheme = None, dtype = torch.bfloat16)+ assert fp32 is not None and bf16 is not None and fp32[0] == bf16[0] * 2+++def test_auto_keeps_the_released_denoiser_on_a_card_that_can_hold_it(monkeypatch):+ """The whole point of making this conditional. A card with room gets exactly what it got+ before: the released weights and the same picture, because the pin plus the regional compile+ make it fast without changing a single value."""+ import torch++ from core.inference import video as vid++ fam = _h3_family()+ monkeypatch.setattr(vid, "_h3_auto_precision_ok", lambda target = None: True, raising = False)+ # Comfortably more free memory than the released denoiser plus everything beside it.+ monkeypatch.setattr(vid, "_h3_free_device_bytes", lambda device: 500 * 1000**3)++ assert (+ vid._h3_auto_denoiser_scheme(+ fam,+ target = None,+ dtype = torch.bfloat16,+ device = "cuda",+ te_scheme = "int8",+ task = "fl2va",+ base_repo = fam.base_repo,+ )+ is None+ )+++def test_auto_takes_the_hosted_denoiser_when_the_released_one_cannot_stay_resident(monkeypatch):+ """The bug users hit. Below the fit line the released denoiser rides the CPU-offload rotation,+ and a module that moves cannot be compiled, so the regional compile goes with it: 194 s against+ 23.7 s on the same 8-step job. Auto now takes the hosted checkpoint instead of the cliff."""+ import torch++ from core.inference import video as vid++ fam = _h3_family()+ monkeypatch.setattr(vid, "_h3_auto_precision_ok", lambda target = None: True, raising = False)+ # An 80 GB card: under the 113.5 GB the released denoiser plus its companions need, over the+ # 67.5 GB the hosted one needs, which is the band where the substitution buys anything.+ monkeypatch.setattr(vid, "_h3_free_device_bytes", lambda device: 80 * 1000**3)++ assert (+ vid._h3_auto_denoiser_scheme(+ fam,+ target = None,+ dtype = torch.bfloat16,+ device = "cuda",+ te_scheme = "int8",+ task = "fl2va",+ base_repo = fam.base_repo,+ )+ == vid.H3_AUTO_FALLBACK_SCHEME+ )+++def test_the_auto_fallback_is_declined_when_nothing_can_answer(monkeypatch):+ """Every unanswerable question keeps the released weights. A missing reading is not evidence of+ a shortfall, and guessing wrong here silently changes the picture a user gets.++ The partition gate is the same rule the explicit path applies: a task with no hosted checkpoint+ has no fallback, and serving the other partition's would generate the wrong thing."""+ import torch++ from core.inference import video as vid++ fam = _h3_family()++ def ask(**over):+ kw = dict(+ target = None,+ dtype = torch.bfloat16,+ device = "cuda",+ te_scheme = "int8",+ task = "fl2va",+ base_repo = fam.base_repo,+ )+ kw.update(over)+ return vid._h3_auto_denoiser_scheme(fam, **kw)++ monkeypatch.setattr(vid, "_h3_free_device_bytes", lambda device: 80 * 1000**3)++ # A host the hosted components were never measured on stays on the released denoiser.+ monkeypatch.setattr(vid, "_h3_auto_precision_ok", lambda target = None: False, raising = False)+ assert ask() is None++ monkeypatch.setattr(vid, "_h3_auto_precision_ok", lambda target = None: True, raising = False)+ # An unreadable card decides nothing.+ monkeypatch.setattr(vid, "_h3_free_device_bytes", lambda device: None)+ assert ask() is None+ # Neither does an unanswerable size estimate.+ monkeypatch.setattr(vid, "_h3_free_device_bytes", lambda device: 80 * 1000**3)+ monkeypatch.setattr(vid, "_h3_planned_denoiser_bytes", lambda *a, **k: None)+ assert ask() is None+ monkeypatch.undo()++ # And a partition with no hosted checkpoint for the fallback scheme keeps the released one.+ monkeypatch.setattr(vid, "_h3_auto_precision_ok", lambda target = None: True, raising = False)+ monkeypatch.setattr(vid, "_h3_free_device_bytes", lambda device: 80 * 1000**3)+ monkeypatch.setattr(+ vid, "video_family_prequant_available", lambda *a, **k: False, raising = False+ )+ assert ask() is None+++def test_an_explicit_speed_off_keeps_the_released_denoiser(monkeypatch):+ """speed_mode="off" is the bit-exact contract, and the hosted checkpoints re-roll the sample.++ The conventional loader rewrites an unset precision to "off" under speed off for exactly this+ reason; the modular workflow returns above that rewrite, so the fallback has to decline it+ itself or "off" stops meaning bit-exact on precisely the cards this fallback targets."""+ import torch++ from core.inference import video as vid++ fam = _h3_family()+ monkeypatch.setattr(vid, "_h3_auto_precision_ok", lambda target = None: True, raising = False)+ monkeypatch.setattr(vid, "_h3_free_device_bytes", lambda device: 80 * 1000**3)++ def ask(speed_mode):+ return vid._h3_auto_denoiser_scheme(+ fam,+ target = None,+ dtype = torch.bfloat16,+ device = "cuda",+ te_scheme = "int8",+ task = "fl2va",+ base_repo = fam.base_repo,+ speed_mode = speed_mode,+ )++ assert ask("off") is None+ assert ask("OFF ") is None, "the request is read the same way the conventional loader reads it"+ # Every other speed profile is the one this fallback was measured for.+ assert ask(None) == vid.H3_AUTO_FALLBACK_SCHEME+ assert ask("default") == vid.H3_AUTO_FALLBACK_SCHEME+++def test_the_automatic_substitution_needs_the_exact_base_model(monkeypatch):+ """A derivative is not a precision choice.++ ``video_family_prequant_repo`` falls back to the family default for any base it has no variant+ row for, and the checkpoint validator's base compare accepts a matching final path segment, so+ someone/MiniMax-H3 would take MiniMaxAI/MiniMax-H3's denoiser and silently generate from+ someone else's weights -- for a user who never asked for a scheme at all. Same bar as the+ conditioner's index gate: exact identity, mirrors folded, nothing else."""+ import torch++ from core.inference import video as vid++ fam = _h3_family()+ monkeypatch.setattr(vid, "_h3_auto_precision_ok", lambda target = None: True, raising = False)+ monkeypatch.setattr(vid, "_h3_free_device_bytes", lambda device: 80 * 1000**3)++ def ask(base_repo):+ return vid._h3_auto_denoiser_scheme(+ fam,+ target = None,+ dtype = torch.bfloat16,+ device = "cuda",+ te_scheme = "int8",+ task = "fl2va",+ base_repo = base_repo,+ )++ assert ask(fam.base_repo) == vid.H3_AUTO_FALLBACK_SCHEME+ assert ask("someone/MiniMax-H3") is None, "a derivative keeps its own denoiser"+ assert ask("/models/MiniMax-H3") is None, "and so does a local re-save this cannot identify"+ assert ask(None) is None+++def test_the_fallback_is_declined_when_the_hosted_denoiser_cannot_be_pinned(monkeypatch):+ """Taking the hosted checkpoint means PINNING it -- a torchao module does not survive the+ offload rotation's mid-block move -- and a pinned denoiser turns the memory floor from a max+ into a sum.++ With text_encoder_quant="none" the conditioner stays dense, so that sum is BIGGER than the+ rotation it replaces: the card renders today and would refuse every generation afterwards.+ Where the replacement does not fit either, the released denoiser in the rotation is the+ configuration that still runs, so auto keeps it."""+ import torch++ from core.inference import video as vid++ fam = _h3_family()+ monkeypatch.setattr(vid, "_h3_auto_precision_ok", lambda target = None: True, raising = False)+ monkeypatch.setattr(vid, "_h3_free_device_bytes", lambda device: 80 * 1000**3)++ def ask(te_scheme):+ return vid._h3_auto_denoiser_scheme(+ fam,+ target = None,+ dtype = torch.bfloat16,+ device = "cuda",+ te_scheme = te_scheme,+ task = "fl2va",+ base_repo = fam.base_repo,+ )++ # Dense conditioner: 107.1 GB pinned against 80 GB free, so the substitution buys a refusal.+ assert ask(None) is None+ # Quantized conditioner: 67.5 GB pinned, which is what the fallback exists for.+ assert ask("int8") == vid.H3_AUTO_FALLBACK_SCHEME+++def test_the_fallback_is_resolved_before_the_download_is_planned(monkeypatch):+ """Decided only inside the loader, the fallback is decided after the pull it exists to shrink.++ ``_denoiser_prequant_covered`` answers False for an unset request, so the plan stages the+ 66.3 GB dense denoiser this load will never open and the 20.3 GB replacement then arrives+ inline -- outside the progress plan, the cancel path and the disk preflight that just passed.+ The planner resolves the same choice up front, against the card's CAPACITY: the free reading+ is polluted at plan time (the previous pipeline is still resident) and capacity is an upper+ bound on it, so a "does not fit" here still holds when the loader re-measures."""+ import inspect+ import types++ import torch++ from core.inference import video as vid++ fam = _h3_family()+ backend = vid.VideoBackend.__new__(vid.VideoBackend)++ monkeypatch.setattr(vid, "_h3_auto_precision_ok", lambda target = None: True, raising = False)+ monkeypatch.setattr(+ vid,+ "resolve_diffusion_device_target",+ lambda *a, **k: types.SimpleNamespace(device = "cuda", dtype = torch.bfloat16),+ raising = False,+ )+ # CAPACITY, not the live free reading: an 80 GB card cannot hold the released denoiser+ # resident whatever else is or is not on it right now.+ monkeypatch.setattr(vid, "_h3_device_capacity_bytes", lambda device: 80 * 1000**3)+ monkeypatch.setattr(vid, "_h3_free_device_bytes", lambda device: None)++ def plan(**over):+ kw = dict(+ base = fam.base_repo,+ transformer_quant = None,+ text_encoder_quant = None,+ speed_mode = None,+ h3_task = "fl2va",+ )+ kw.update(over)+ return backend._h3_planned_auto_denoiser_scheme(fam, **kw)++ assert plan() == vid.H3_AUTO_FALLBACK_SCHEME+ # An explicit request is not the planner's business, in either direction.+ assert plan(transformer_quant = "none") is None+ assert plan(transformer_quant = "int8") is None+ assert plan(speed_mode = "off") is None++ # And the scheme it returns is what makes the pull drop the dense shards: the same probe+ # answers False for the unset request the planner replaces.+ assert not vid.VideoBackend._denoiser_prequant_covered(fam, None, fam.base_repo, "fl2va")+ assert vid.VideoBackend._denoiser_prequant_covered(+ fam, vid.H3_AUTO_FALLBACK_SCHEME, fam.base_repo, "fl2va"+ )++ # The wiring: the planner has to run BEFORE the verification that drops the shards, which runs+ # before the pull. Ordering is the whole point, so it is asserted rather than assumed.+ src = inspect.getsource(vid.VideoBackend._run_load)+ planned = src.index("_h3_planned_auto_denoiser_scheme")+ verified = src.index("_denoiser_prequant_verified")+ predownload = src.index("_predownload_base")+ assert planned < verified < predownload+ assert "h3_auto_denoiser or kwargs.get(\"transformer_quant\")" in src