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: run MiniMax-H3's Qwen3-VL conditioner from the hosted INT8 checkpoint (#8283)
Daniel Han587590d6a8ee
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 1e2d0e45656..7b9a5ab7a7f 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -132,8 +132,14 @@ from .video_minimax_h3 import (fit_h3_reference_image,h3_canvas_for_aspect,h3_conditioning_mode,+ h3_transformer_resident_gb,h3_transformer_task,)+from .video_minimax_h3_te import (+ H3_TE_QUANT_REPO,+ h3_te_quant_scheme,+ h3_te_resident_gb,+)from utils.hardware import clear_gpu_cache# Shared with the image backend so both pin every loader call to the same live cache root.@@ -252,6 +258,23 @@ def assert_video_precision_available(# support is consulted, and that path needs no torchao. Refusing on the raw int8# rejected loads the runtime would run and report as fell_back -- Windows ROCm,# where the torchao stub kills int8 while fp8 still works.+ # A family with a HOSTED quantized conditioner never touches the generic path this gate+ # reasons about. Studio loads that artifact itself: INT8 storage, a Hadamard rotation and an+ # ordinary F.linear, no torchao and no fp8 tensor cores. Left to the code below, the request is+ # first rewritten int8 -> fp8 by effective_te_quant (H3 has no keep-bf16 schedule) and then+ # refused for want of hardware neither the rewrite nor the real loader needs, so a supported+ # CPU load comes back as a 409. Whether the artifact suits THIS base is decided at the seed,+ # which is not a host-level impossibility and so is not this gate's question.+ # PIPELINE loads only. The hosted conditioner is a Diffusers-path artifact; the native GGUF+ # path picks its Q2/Q4 encoder off the denoiser filename and discards text_encoder_quant+ # entirely, so exempting it would let an explicit request through to a load that answers it at+ # an unrelated precision -- the very thing the fail-closed contract exists to stop.+ if (+ model_kind == "pipeline"+ and getattr(fam, "modular_workflow", None)+ and h3_te_quant_scheme(te_mode) is not None+ ):+ returnte_effective = effective_te_quant(te_mode, getattr(fam, "name", None))te_reason = Noneif te_quant_needs_resident_weights(te_effective) and not torchao_quantize_importable():@@ -456,6 +479,10 @@ class _VideoLoadState:transformer_quant: Optional[str] = None# Text-encoder quant engaged ("fp8"|"fp8_dynamic"|"int8"|"nvfp4") or None. Often the largest resident; shrunk in place.text_encoder_quant: Optional[str] = None+ # MiniMax-H3 only: the pre-quantized denoiser was PINNED to the device and taken out of the+ # offload rotation, so it is resident alongside whatever component is running. The memory+ # preflight has to know, because that turns its floor from a max into a sum.+ h3_denoiser_pinned: bool = Falseresolved: Optional[dict] = None@@ -470,6 +497,14 @@ class _VideoLoadingState:asset_repos: tuple[str, ...] = ()+def _h3_te_canonical(repo_id: Optional[str]) -> str:+ """A repo id normalised for an EXACT identity compare: mirrors folded onto the id they copy,+ then trimmed and lowercased. Deliberately no tail-segment tolerance -- ``someone/MiniMax-H3``+ is a different repo with different weights."""+ from .diffusion_families import canonical_base+ return canonical_base(repo_id).strip().lower()++def _progress(phase: Optional[str], **extra: Any) -> dict[str, Any]:return {"phase": phase, **extra}@@ -814,7 +849,8 @@ class VideoBackend:)# Reject a malformed transformer_quant cheaply, before the handoff (pipeline-kind only, matching the image backend).normalize_transformer_quant(transformer_quant)- # Reject a malformed text_encoder_quant the same way (any kind: the encoder is always dense).+ # Reject a malformed text_encoder_quant the same way. Every kind: an unsupported scheme is+ # a bad request regardless of whether this family has a hosted quantized encoder for it.normalize_te_quant(text_encoder_quant)_ensure_mp4_encoder_available()return fam@@ -932,6 +968,13 @@ class VideoBackend:skip_transformer_weights = self._denoiser_prequant_covered(fam, kwargs.get("transformer_quant"), base)+ # 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+ # dense encoder, and a derivative that the seed will decline must keep its own.+ h3_te_scheme = self._h3_te_quant_scheme_verified(+ fam, kwargs.get("text_encoder_quant"), base, kwargs.get("hf_token")+ )expected = self._estimate_download_bytes(kwargs["repo_id"],kwargs.get("gguf_filename"),@@ -940,10 +983,18 @@ class VideoBackend:kind,te_sources = te_sources,skip_transformer_weights = skip_transformer_weights,+ h3_te_scheme = h3_te_scheme,)with self._lock:if self._load_token == token and self._loading is not None:self._loading.base_repo = base+ # The conditioner artifact comes from a THIRD repo, neither repo_id nor+ # base_repo, so without this the delete-cached guard would let it be deleted+ # out from under the in-flight fetch (or out from under the assembly, while+ # the base snapshot that no longer carries a dense encoder is still coming+ # down). Same registration the native H3 path makes for its companions.+ if h3_te_scheme:+ self._loading.asset_repos = self._loading.asset_repos + (H3_TE_QUANT_REPO,)self._loading.expected_bytes = expected# Checkpoint downloads outside the lock so an unload can preempt the multi-GB pull; companions pre-download the same way.checkpoint_local: Optional[Path] = None@@ -988,6 +1039,7 @@ class VideoBackend:ltx23 = True,te_sources = te_sources,skip_transformer_weights = skip_transformer_weights,+ h3_te_scheme = h3_te_scheme,)with self._lock:if self._load_token == token and self._loading is not None:@@ -997,12 +1049,17 @@ class VideoBackend:te_sources, kwargs.get("hf_token"), cancel_event = cancel_event)kwargs["_te_prequant_skipped"] = te_skipped+ # Same rule for the H3 conditioner: the artifact has to be on disk before the base pull+ # is allowed to leave the dense encoder behind.+ h3_te_skipped = self._fetch_h3_te_quant(+ h3_te_scheme, kwargs.get("hf_token"), cancel_event = cancel_event+ )base_local = self._predownload_base(base,kwargs.get("hf_token"),kind,ltx23 = ltx23,- skip_te_components = te_skipped,+ skip_te_components = te_skipped + h3_te_skipped,skip_transformer_weights = skip_transformer_weights,cancel_event = cancel_event,)@@ -1264,6 +1321,199 @@ class VideoBackend:target = resolve_diffusion_device_target(),)+ @staticmethod+ def _h3_te_quant_scheme(+ fam: Any,+ text_encoder_quant: Optional[str],+ base: Optional[str] = None,+ ) -> Optional[str]:+ """The hosted QUANTIZED conditioner scheme this pick would load, or None.++ The one resolver the plan, the byte estimate, the pre-fetch and the load itself all ask, so+ none of them can stage an encoder another one skipped -- staging the dense conditioner for a+ quantized load wastes 62 GB, and dropping one the load actually wants costs a surprise+ mid-load pull of the same size.++ Only a modular-workflow family qualifies. Every other family casts its own dense encoder in+ place and still needs those shards.++ And only against the base the artifact was cut from. A custom derivative can keep the+ Qwen3-VL architecture and still carry different conditioner weights, and the strict load+ cannot tell the difference -- every name and shape still matches -- so it would silently+ condition on someone else's encoder. ``te_base_equivalent`` is the same test the pre-cast+ encoder path uses: the same base, or one verified to ship byte-identical component weights.+ Anything else keeps the pipeline's own dense encoder.++ Pure, never raises, never touches the network."""+ try:+ if not getattr(fam, "modular_workflow", None):+ return None+ from .diffusion_te_prequant import te_base_equivalent++ canonical = getattr(fam, "base_repo", None)+ if not canonical or not base or not te_base_equivalent(canonical, base):+ return None+ return h3_te_quant_scheme(normalize_te_quant(text_encoder_quant))+ except Exception: # noqa: BLE001 -- an unanswerable probe keeps the dense encoder+ return None++ @staticmethod+ def _h3_te_base_index_source(base: Optional[str], hf_token: Optional[str]) -> Optional[str]:+ """The text-encoder source ``base``'s own ``modular_model_index.json`` names, or None.++ The staging twin of ``_h3_te_index_source``, which can only run once the pipeline exists.+ The seed is the final authority, but by then the base snapshot has already been pulled+ WITHOUT its dense ``text_encoder/`` shards, so a decline there leaves the load to fetch+ 62 GB inline. Reading the index first makes the skip as exact as the substitution.++ A few KB, from the repo the load is about to pull anyway, pinned to the live cache root.+ None on anything unanswerable, which keeps the dense shards."""+ if not base:+ return None+ try:+ import json++ root = Path(base).expanduser()+ if root.is_dir():+ path = root / "modular_model_index.json"+ else:+ from utils.hf_xet_fallback import hf_hub_download_with_xet_fallback+ path = Path(+ hf_hub_download_with_xet_fallback(+ base,+ "modular_model_index.json",+ hf_token,+ cache_dir = hub_cache_dir(),+ )+ )+ with open(path, "r", encoding = "utf-8") as handle:+ entry = json.load(handle).get("text_encoder")+ # ["library", "ClassName", {spec}]; "repo" is the spec field's deprecated spelling.+ spec = entry[2] if isinstance(entry, (list, tuple)) and len(entry) == 3 else None+ source = (spec or {}).get("pretrained_model_name_or_path") or (spec or {}).get("repo")+ return source if isinstance(source, str) and source else None+ except Exception: # noqa: BLE001 -- unanswerable keeps the dense shards+ return None++ def _h3_te_quant_scheme_verified(+ self,+ fam: Any,+ text_encoder_quant: Optional[str],+ base: Optional[str],+ hf_token: Optional[str],+ ) -> Optional[str]:+ """``_h3_te_quant_scheme`` plus the exact index check, for the decisions that COMMIT.++ The pure resolver compares repo NAMES, which is right for a plan (it must not raise and+ must not touch the network) but not for dropping a derivative's dense encoder from the+ pull. This one is allowed the few-KB index read, so the staged snapshot and the seed agree+ on the same base."""+ scheme = self._h3_te_quant_scheme(fam, text_encoder_quant, base)+ if scheme is None:+ return None+ source = self._h3_te_base_index_source(base, hf_token)+ if source is None or _h3_te_canonical(source) != _h3_te_canonical(+ getattr(fam, "base_repo", None)+ ):+ logger.info(+ "video.h3_te_quant: %s names %s as its conditioner, not %s; keeping its dense "+ "text_encoder shards",+ base,+ source or "an unreadable index",+ getattr(fam, "base_repo", None),+ )+ return None+ return scheme++ @staticmethod+ def _h3_te_index_source(pipe: Any) -> Optional[str]:+ """The repo THIS pipeline's own modular index names as the source of its ``text_encoder``.++ ``modular_model_index.json`` records a ``pretrained_model_name_or_path`` per component, and+ diffusers has already parsed it by the time the pipeline exists, so this is free and cannot+ disagree with what ``load_components`` would have fetched. ``repo`` is the field's+ deprecated spelling; ``ComponentSpec.__post_init__`` folds it into the new name, and the+ fallback here covers a spec built by hand.++ None means the question could not be answered. The caller treats that as a refusal: not+ knowing which conditioner a pipeline uses is not a licence to substitute one."""+ try:+ spec = pipe.get_component_spec("text_encoder")+ except Exception: # noqa: BLE001 -- no spec, no substitution+ return None+ source = getattr(spec, "pretrained_model_name_or_path", None) or getattr(spec, "repo", None)+ # A list means several sources for one component; nothing here can vouch for that.+ return source if isinstance(source, str) and source else None++ @staticmethod+ def _h3_te_quant_hub_files(+ scheme: Optional[str], api: Any+ ) -> tuple[Optional[str], list[tuple[str, int]]]:+ """``(repo_id, [(rfilename, size)])`` for the hosted quantized conditioner, or ``(None, [])``.++ The conditioner mirror of ``_denoiser_prequant_hub_files``, and it earns its keep the same+ way: the base entry drops the dense ``text_encoder/`` shards whenever this resolves, so+ without it the artifact that replaces them is in no entry at all and the disk preflight+ passes on a volume that cannot hold the 27 GB it is about to pull."""+ from .video_minimax_h3_te import h3_te_quant_filename++ filename = h3_te_quant_filename(scheme)+ if filename is None:+ return None, []+ try:+ info = api.model_info(H3_TE_QUANT_REPO, files_metadata = True)+ except Exception: # noqa: BLE001 -- an unavailable artifact keeps the dense encoder+ return None, []+ files = [+ (s.rfilename, int(getattr(s, "size", 0) or 0))+ for s in (info.siblings or [])+ if s.rfilename == filename+ ]+ return (H3_TE_QUANT_REPO, files) if files else (None, [])++ def _fetch_h3_te_quant(+ self,+ scheme: Optional[str],+ hf_token: Optional[str],+ *,+ cancel_event: Optional[threading.Event] = None,+ ) -> tuple[str, ...]:+ """Pre-fetch the hosted quantized conditioner; return ``("text_encoder",)`` when it landed.++ Same contract as ``_fetch_te_prequant``: only a file already on disk earns the right to drop+ the dense shards, and the pull is cancellable and resumable like every other load download+ instead of an untracked stall inside ``from_pretrained``. A failed fetch keeps the dense+ encoder, so the load still has one to fall back to.++ A file that lands and then fails to LOAD (corrupt, or a re-upload this loader does not+ implement) is slow rather than broken: the base snapshot has no dense encoder, so+ ``load_components`` pulls it from the modular index's own repo id inline. Degrading to the+ download this skip avoided is the right failure -- the alternative is refusing the load."""+ from .video_minimax_h3_te import h3_te_quant_filename++ filename = h3_te_quant_filename(scheme)+ if filename is None:+ return ()+ cancel = cancel_event if cancel_event is not None else self._cancel_event+ from utils.hf_xet_fallback import hf_hub_download_with_xet_fallback++ try:+ hf_hub_download_with_xet_fallback(+ H3_TE_QUANT_REPO,+ filename,+ hf_token,+ cancel_event = cancel,+ cache_dir = hub_cache_dir(),+ )+ except Exception as exc: # noqa: BLE001 -- no artifact just means the dense encoder+ if cancel.is_set():+ raise+ logger.warning(+ "video.h3_te_quant_fetch_failed: %s/%s: %s", H3_TE_QUANT_REPO, filename, exc+ )+ return ()+ return ("text_encoder",)+@staticmethoddef _denoiser_prequant_covered(fam: Any, transformer_quant: Optional[str], base: Optional[str]@@ -1450,21 +1700,24 @@ class VideoBackend:ltx23: bool = False,te_sources: Optional[dict[str, Any]] = None,skip_transformer_weights: bool = False,+ h3_te_scheme: Optional[str] = None,) -> Optional[int]:"""Total bytes this load will pull (checkpoint + companions), or None.Dense encoder shards covered by an available pre-cast checkpoint are excluded, sincethe pull below skips them too, and so are the dense denoiser shards a hosted- pre-quantized checkpoint replaces (``skip_transformer_weights``). Neither hosted- checkpoint's own bytes are added: the progress bar counts cached bytes for the checkpoint- and base repos only, so a third repo in the total would leave the bar permanently short- of 100%."""+ pre-quantized checkpoint replaces (``skip_transformer_weights``) and H3's dense+ ``text_encoder/`` under ``h3_te_scheme``. None of those hosted checkpoints' own bytes are+ added: the progress bar counts cached bytes for the checkpoint and base repos only, so a+ third repo in the total would leave the bar permanently short of 100%."""try:from huggingface_hub import HfApitotal = 0api = HfApi(token = hf_token or None)skip_te_components = tuple(self._te_prequant_hub_files(te_sources or {}, api))+ if self._h3_te_quant_hub_files(h3_te_scheme, api)[1]:+ skip_te_components = skip_te_components + ("text_encoder",)if gguf_filename and not Path(repo_id).expanduser().exists():info = api.model_info(repo_id, files_metadata = True)for sibling in info.siblings or []:@@ -1588,6 +1841,18 @@ class VideoBackend:dq_repo, dq_files = self._denoiser_prequant_hub_files(fam, transformer_quant, base, api)if dq_repo:total += add(dq_repo, dq_files)+ # And H3's quantized conditioner, which replaces the base repo's dense text_encoder/.+ # VERIFIED, like the load: this entry both ADDS 27 GB and REMOVES the dense encoder+ # from the base entry below, so a name match that the load will decline gets the plan+ # and the disk preflight wrong in both directions at once -- 27 GB staged and never+ # used, 62 GB needed and never advertised. This function is already the network-bound+ # one (it is nothing but model_info calls, wrapped in the try below), so the few-KB+ # index read is in keeping.+ h3_te_repo, h3_te_files = self._h3_te_quant_hub_files(+ self._h3_te_quant_scheme_verified(fam, text_encoder_quant, base, hf_token), api+ )+ if h3_te_repo:+ total += add(h3_te_repo, h3_te_files)if base and not Path(base).expanduser().exists():info = api.model_info(base, files_metadata = True)total += add(@@ -1596,7 +1861,9 @@ class VideoBackend:info,kind,ltx23 = ltx23,- skip_te_components = tuple(te_files),+ skip_te_components = (+ tuple(te_files) + (("text_encoder",) if h3_te_repo else ())+ ),skip_transformer_weights = self._denoiser_prequant_covered(fam, transformer_quant, base),@@ -1960,6 +2227,9 @@ class VideoBackend:# than moving the dispatch past a block written for the conventional path (its# speed_mode/auto-ladder defaulting means nothing to a modular workflow).transformer_quant = normalize_transformer_quant(transformer_quant),+ # Same reason as transformer_quant above: the conventional path normalises the+ # encoder request below this dispatch, which the modular branch never reaches.+ text_encoder_quant = normalize_te_quant(text_encoder_quant),h3_task = h3_task,_load_token = _load_token,_base_local_dir = _base_local_dir,@@ -2632,6 +2902,7 @@ class VideoBackend:hf_token: Optional[str],memory_mode: Optional[str],transformer_quant: Optional[str] = None,+ text_encoder_quant: Optional[str] = None,h3_task: Optional[str] = None,target: Any = None,_load_token: Optional[int] = None,@@ -2639,9 +2910,9 @@ class VideoBackend:) -> dict[str, Any]:"""Load MiniMax-H3 through its official Modular Diffusers workflow.- ``transformer_quant`` is an ALREADY-normalised scheme (or None / "auto"). A scheme with a- hosted pre-quantized denoiser checkpoint is built here and pre-seeded into the pipeline;- anything else keeps the released bfloat16 components."""+ ``transformer_quant`` and ``text_encoder_quant`` are ALREADY-normalised schemes (or None /+ "auto"). A scheme with a hosted pre-quantized checkpoint is built here and pre-seeded into+ the pipeline; anything else keeps the released bfloat16 components."""# Defence in depth: validate_load_request now refuses a single_file modular pick outright,# so this is unreachable from the routes. It stays because this method is also reachable# directly, and by the time it runs the resident pipeline has already been torn down.@@ -2750,6 +3021,118 @@ class VideoBackend:scheme,fam.name,)+ # ── hosted quantized conditioner, for the same reason and in the same place.+ #+ # Under enable_auto_cpu_offload the VRAM floor is the LARGEST resident component, so the+ # 66.7 GB Qwen3-VL conditioner -- not the denoiser -- is what has been pinning it. Seeding+ # here rather than casting after load_components is the entire point: a runtime cast has to+ # materialise the dense encoder first, so its PEAK is the bfloat16 size it was meant to+ # avoid, and on this workflow it would also have to download the 62 GB dense component.+ text_encoder_quant_engaged: Optional[str] = None+ text_encoder_quant_reason = "released bfloat16 components"+ # Base-gated, through the same resolver the plan and the pre-fetch use, so a derivative+ # base that keeps its own conditioner can never be handed this one.+ te_scheme = self._h3_te_quant_scheme(fam, text_encoder_quant, base)+ # And gated a second time, on the identity the base NAME cannot establish. That resolver+ # compares repo ids, so a derivative stored under a directory (or repo) whose last segment+ # is also MiniMax-H3 passes it. This pipeline's own modular index names the repo its+ # conditioner would have come from, which is the actual question: a derivative that+ # retrained the encoder ships it under its own id and says so here, while one that reuses+ # the released encoder still points at it, and quantizing exactly those weights is what+ # the hosted artifact IS. Free, and it cannot disagree with the load, because it reads what+ # diffusers already parsed for it. Unanswerable is a refusal, not a pass.+ 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 here, unlike the plan-side comparison. te_base_equivalent falls through to+ # _same_base_model, which accepts a matching final path segment, and that tolerance is+ # the hole this gate exists to close: someone/MiniMax-H3 is a different repo with+ # different weights and would have passed it. canonical_base still folds a known mirror+ # onto the id it copies, so mirrors are not collateral. A pipeline re-saved locally+ # names local paths here and is refused, which costs the optimisation, not correctness.+ 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+ if text_encoder_quant is not None and te_scheme is None:+ # A valid request this workflow has no hosted artifact for, or one it has but not for+ # THIS pipeline's conditioner. Say which; do NOT erase the request.+ if te_index_declined:+ text_encoder_quant_reason = (+ f"this pipeline's conditioner comes from "+ f"{te_index_source or 'a source that could not be read'}, not {fam.base_repo}, "+ f"so the hosted quantized {text_encoder_quant} conditioner is not its "+ f"quantization; loaded this pipeline's own bfloat16 encoder instead"+ )+ elif h3_te_quant_scheme(text_encoder_quant) is not None:+ text_encoder_quant_reason = (+ f"the hosted quantized {text_encoder_quant} conditioner is cut from "+ f"{fam.base_repo}, not {base}; loaded this pipeline's own bfloat16 encoder "+ f"instead"+ )+ else:+ text_encoder_quant_reason = (+ f"no hosted quantized {text_encoder_quant} conditioner for {fam.name}; "+ f"loaded the released bfloat16 encoder instead"+ )+ if te_scheme is not None:+ from .video_minimax_h3_te import load_h3_quantized_text_encoder+ text_encoder = load_h3_quantized_text_encoder(+ base,+ te_scheme,+ dtype = dtype,+ hf_token = hf_token,+ # Pin the live cache root, exactly as the denoiser fetch above does.+ cache_dir = hub_cache_dir(),+ # The scoped pre-download keeps every component config, so the staged snapshot+ # already holds text_encoder/config.json: read it from there rather than sending+ # the config resolution back to the hub.+ local_base = _base_local_dir,+ logger = logger,+ )+ if text_encoder is None:+ # Best-effort by contract, like the denoiser: a missing / unreadable / mismatched+ # artifact continues dense rather than failing after the teardown.+ text_encoder_quant_reason = (+ f"hosted quantized {te_scheme} conditioner unusable; "+ f"loaded the released bfloat16 encoder instead"+ )+ else:+ pipe.update_components(text_encoder = text_encoder)+ text_encoder_quant_engaged = te_scheme+ text_encoder_quant_reason = (+ f"hosted quantized {te_scheme} conditioner ({H3_TE_QUANT_REPO})"+ )+ logger.info(+ "video.text_encoder_quant: %s quantized conditioner seeded for %s",+ te_scheme,+ fam.name,+ )+ # Fail closed, exactly as the conventional path does for the same request: an explicit+ # encoder precision that engaged NOTHING leaves a dense bf16 encoder the caller did not ask+ # for, and a render that succeeds at an unrequested precision quietly invalidates whatever+ # it was measuring. Covers all three ways this can end up dense -- no hosted artifact for+ # the scheme, an artifact that is not this pipeline's conditioner, and one that failed to+ # load -- because the caller cannot tell them apart from the result.+ #+ # Raised HERE, before load_components, so the refusal costs nothing rather than arriving+ # after every component has been built. precision_fallback_allowed() is the documented+ # escape hatch, and it lands the dense encoder with the reason recorded as before.+ if (+ text_encoder_quant is not None+ and text_encoder_quant_engaged is None+ and not precision_fallback_allowed()+ ):+ raise RuntimeError(+ precision_refusal_message(+ "text_encoder_quant",+ text_encoder_quant,+ text_encoder_quant_reason,+ off_label = "leave it unset to keep the dense bf16 encoder",+ auto_available = False,+ )+ )# The token above only opens the modular index. Every component's own from_pretrained runs# here, against the repos that index names, so it has to be passed again or a gated/private# component load goes out anonymously (load_components only WARNS on a failed component).@@ -2835,7 +3218,14 @@ class VideoBackend:transformer_quant_engaged or "off",transformer_quant_reason,),- "text_encoder_quant": (None, "off", "released bfloat16 components"),+ # The REQUEST on the left, not None: a declined or failed request has to read as a+ # fallback in the resolved record, never disappear into a bare "off" that looks+ # like the caller never asked.+ "text_encoder_quant": (+ text_encoder_quant,+ text_encoder_quant_engaged or "off",+ text_encoder_quant_reason,+ ),})with self._lock:@@ -2861,13 +3251,19 @@ class VideoBackend:# records it: status() reports this field, and a dense fallback must not claim a# quant the resident denoiser does not have.transformer_quant = transformer_quant_engaged,+ # Ditto for the conditioner: the memory preflight reads this field back to size the+ # resident encoder, so a dense fallback recorded as int8 would under-state the floor+ # by 39 GB and let a doomed generation start.+ text_encoder_quant = text_encoder_quant_engaged,+ h3_denoiser_pinned = denoiser_pinned,resolved = resolved,)logger.info(- "video.loaded: %s (%s, modular diffusers, transformer_quant=%s)",+ "video.loaded: %s (%s, modular diffusers, transformer_quant=%s, text_encoder_quant=%s)",repo_id,fam.name,transformer_quant_engaged or "off",+ text_encoder_quant_engaged or "off",)return self.status()@@ -3228,6 +3624,7 @@ class VideoBackend:if state.engine == "diffusers" and fam.modular_workflow and state.device != "cpu":from .video_minimax_h3 import (+ H3_TEXT_ENCODER_BF16_GB,estimate_h3_diffusers_host_ram_gb,estimate_h3_diffusers_vram_gb,)@@ -3242,7 +3639,20 @@ class VideoBackend:else 0)available_vram_gb = (free_bytes + reserved_bytes) / 1_000_000_000- required_vram_gb = estimate_h3_diffusers_vram_gb(width, height, frames)+ # Size the floor from the components this load ACTUALLY holds, not from+ # the released bfloat16 pair. Both fields are the ENGAGED schemes (a+ # declined or failed request is recorded as None at load), so a dense+ # fallback keeps the dense floor.+ required_vram_gb = estimate_h3_diffusers_vram_gb(+ width,+ height,+ frames,+ text_encoder_gb = h3_te_resident_gb(+ state.text_encoder_quant, bf16_gb = H3_TEXT_ENCODER_BF16_GB+ ),+ transformer_gb = h3_transformer_resident_gb(state.transformer_quant),+ transformer_pinned = bool(getattr(state, "h3_denoiser_pinned", False)),+ )if available_vram_gb + 0.25 < required_vram_gb:raise RuntimeError(f"MiniMax-H3 needs about {required_vram_gb:.1f} GB available "@@ -3257,7 +3667,16 @@ class VideoBackend:host_capacity_gb = (psutil.virtual_memory().available + process_rss) / 1_000_000_000- required_host_gb = estimate_h3_diffusers_host_ram_gb(available_vram_gb)+ # Same engaged components as the VRAM floor above. Sizing one from what+ # the load holds and the other from the released pair refuses exactly the+ # configuration the quantized components exist for.+ required_host_gb = estimate_h3_diffusers_host_ram_gb(+ available_vram_gb,+ text_encoder_gb = h3_te_resident_gb(+ state.text_encoder_quant, bf16_gb = H3_TEXT_ENCODER_BF16_GB+ ),+ transformer_gb = h3_transformer_resident_gb(state.transformer_quant),+ )if host_capacity_gb + 0.5 < required_host_gb:raise RuntimeError(f"MiniMax-H3 needs about {required_host_gb:.0f} GB available "diff --git a/studio/backend/core/inference/video_minimax_h3.py b/studio/backend/core/inference/video_minimax_h3.pyindex f3160197873..b6262d92a42 100644--- a/studio/backend/core/inference/video_minimax_h3.py+++ b/studio/backend/core/inference/video_minimax_h3.py@@ -32,18 +32,133 @@ H3_QWEN_Q4 = "qwen3vl_32b_minimax_h3-Q4_K_M.gguf"H3_DIFFUSERS_VRAM_BASE_GB = 68.5H3_DIFFUSERS_VRAM_GB_PER_MPIXEL_FRAME = 0.08+# The terms H3_DIFFUSERS_VRAM_BASE_GB is built from, so a load that shrinks one of the big+# components can rebuild the floor from what it actually holds instead of the released sizes.+#+# With everything under enable_auto_cpu_offload the base is the LARGEST SINGLE RESIDENT COMPONENT+# plus runtime overhead, not the sum: at any instant one component is on the device and the rest+# are parked on the host. That is exactly why seeding a 20 GB pre-quantized denoiser moved this+# number by nothing -- the 66.7 GB conditioner was already the larger of the two and simply took+# over as the maximum. Both have to shrink before the floor does.+#+# ONE case breaks the max, and it is the case a pre-quantized denoiser creates. A torchao module+# does not survive being moved mid-block, so _load_h3_modular_pipeline PINS it to the device and+# takes it out of the offload rotation (see pin_prequantized_module). It is then resident for the+# whole generation and the floor becomes additive: denoiser + whichever offloaded component is+# largest. Measured at 960x544x124 with the int8 denoiser pinned, torch.cuda.max_memory_allocated:+#+# bfloat16 conditioner 94.62 GB = 20.3 + 66.7 + 5.18 activations + 2.44+# int8 conditioner 55.20 GB = 20.3 + 27.1 + 5.18 activations + 2.58+#+# so 2.6 covers the pinned overhead on the conservative side of both. Note what the first row says+# about the shipped constant: a pinned denoiser and a dense conditioner really need ~95 GB, and the+# flat 68.5 under-states that by 26 GB. Rebuilding the floor from the resident components fixes+# that under-estimate in the same stroke as crediting the saving.+H3_DIFFUSERS_VRAM_OVERHEAD_GB = 1.8+H3_DIFFUSERS_VRAM_PINNED_OVERHEAD_GB = 2.6+H3_TEXT_ENCODER_BF16_GB = 66.7+H3_TRANSFORMER_BF16_GB = 66.3+# Video + audio VAE, from the family's bf16_components_gb. Only a floor for the offloaded term: it+# stops a very small conditioner from claiming a base no component rotation could actually fit in.+H3_VAE_RESIDENT_GB = 11.1+++# Resident decimal GB of each hosted pre-quantized denoiser, from the artifact sizes in+# unsloth/MiniMax-H3-FP8 (MiniMax-H3-INT8.pt 18.86 GiB, MiniMax-H3-FP8.pt 18.87 GiB). Both are the+# PRUNED (curve-form adaLN) partition, which is why they are so far under half the 66.3 GB dense+# denoiser rather than at it.+H3_TRANSFORMER_PREQUANT_GB: dict[str, float] = {"int8": 20.3, "fp8": 20.3}+-def estimate_h3_diffusers_vram_gb(width: int, height: int, num_frames: int) -> float:- """Measured available-VRAM floor for an H3 Diffusers generation."""+def h3_transformer_resident_gb(scheme: Optional[str]) -> float:+ """Resident decimal GB of the denoiser this load holds: the hosted pre-quantized size for an+ ENGAGED scheme, else the released bfloat16 one."""+ return H3_TRANSFORMER_PREQUANT_GB.get(scheme or "", H3_TRANSFORMER_BF16_GB)+++def h3_diffusers_vram_base_gb(+ *,+ text_encoder_gb: Optional[float] = None,+ transformer_gb: Optional[float] = None,+ transformer_pinned: bool = False,+) -> float:+ """The resident-weights floor for an H3 Diffusers load.++ Every argument defaults to today's behaviour -- the RELEASED bfloat16 sizes and no pinning --+ so the no-argument call reproduces ``H3_DIFFUSERS_VRAM_BASE_GB`` exactly and nothing that does+ not pass a size changes.++ ``transformer_pinned`` is the ENGAGED fact, not the request: only a denoiser that+ ``pin_prequantized_module`` actually pinned is resident alongside the offload rotation."""+ text_encoder = H3_TEXT_ENCODER_BF16_GB if text_encoder_gb is None else float(text_encoder_gb)+ transformer = H3_TRANSFORMER_BF16_GB if transformer_gb is None else float(transformer_gb)+ if transformer_pinned:+ offloaded = max(text_encoder, H3_VAE_RESIDENT_GB)+ return transformer + offloaded + H3_DIFFUSERS_VRAM_PINNED_OVERHEAD_GB+ return max(text_encoder, transformer) + H3_DIFFUSERS_VRAM_OVERHEAD_GB+++def estimate_h3_diffusers_vram_gb(+ width: int,+ height: int,+ num_frames: int,+ *,+ text_encoder_gb: Optional[float] = None,+ transformer_gb: Optional[float] = None,+ transformer_pinned: bool = False,+) -> float:+ """Measured available-VRAM floor for an H3 Diffusers generation.++ ``text_encoder_gb`` / ``transformer_gb`` are the RESIDENT sizes this load actually holds and+ ``transformer_pinned`` whether the denoiser was taken out of the offload rotation; all unset+ keeps the released-bfloat16 floor this shipped with."""volume_mpixel_frames = width * height * num_frames / 1_000_000- return H3_DIFFUSERS_VRAM_BASE_GB + (- H3_DIFFUSERS_VRAM_GB_PER_MPIXEL_FRAME * volume_mpixel_frames+ base = h3_diffusers_vram_base_gb(+ text_encoder_gb = text_encoder_gb,+ transformer_gb = transformer_gb,+ transformer_pinned = transformer_pinned,)+ return base + (H3_DIFFUSERS_VRAM_GB_PER_MPIXEL_FRAME * volume_mpixel_frames)-def estimate_h3_diffusers_host_ram_gb(available_vram_gb: float) -> float:- """Host-RAM floor for the offload tier selected at the available VRAM."""- return 85.0 if available_vram_gb >= 132.0 else 150.0+# The VRAM at which the offload tier changes, and the host floor of the tier above it. Both are+# the shipped values, unchanged: that tier is only reachable on a >= 132 GB device, where the+# component sizes below are not what stands between a load and a generation, and there is no+# measurement here to justify moving it.+H3_DIFFUSERS_HOST_RAM_TIER_VRAM_GB = 132.0+H3_DIFFUSERS_HOST_RAM_HIGH_VRAM_GB = 85.0+# The offload tier parks every component on the host, so its floor is their SUM (unlike the VRAM+# floor, which is the largest resident one). Derived, not newly measured: it is the shipped 150.0+# minus the released component sum, so the released configuration still asks for exactly 150.0 and+# only a load holding smaller components asks for less.+H3_DIFFUSERS_HOST_RAM_HEADROOM_GB = 5.9+++def estimate_h3_diffusers_host_ram_gb(+ available_vram_gb: float,+ *,+ text_encoder_gb: Optional[float] = None,+ transformer_gb: Optional[float] = None,+) -> float:+ """Host-RAM floor for the offload tier selected at the available VRAM.++ ``text_encoder_gb`` / ``transformer_gb`` are the RESIDENT sizes this load actually holds, as+ for the VRAM floor; unset keeps the released bfloat16 sizes, so the no-argument call is the+ number this shipped with.++ Sizing this from the released pair while the VRAM floor is sized from the engaged one refuses+ the exact configuration the hosted quantized components exist for: an 80 GB device holding the+ int8 conditioner and the int8 denoiser clears the VRAM check at 55 GB and is then told it needs+ 150 GB of system RAM for 47.5 GB of weights.++ A pinned denoiser is still counted here. It lives on the device during the generation, but it+ was built on the host to get there, and keeping it in the sum errs toward refusing a load that+ would have fitted rather than admitting one that will not."""+ if available_vram_gb >= H3_DIFFUSERS_HOST_RAM_TIER_VRAM_GB:+ return H3_DIFFUSERS_HOST_RAM_HIGH_VRAM_GB+ text_encoder = H3_TEXT_ENCODER_BF16_GB if text_encoder_gb is None else float(text_encoder_gb)+ transformer = H3_TRANSFORMER_BF16_GB if transformer_gb is None else float(transformer_gb)+ return text_encoder + transformer + H3_VAE_RESIDENT_GB + H3_DIFFUSERS_HOST_RAM_HEADROOM_GB# torch.autocast casts the weight and bias of these module types to the autocast dtype ondiff --git a/studio/backend/core/inference/video_minimax_h3_te.py b/studio/backend/core/inference/video_minimax_h3_te.pynew file mode 100644index 00000000000..325b385c813--- /dev/null+++ b/studio/backend/core/inference/video_minimax_h3_te.py@@ -0,0 +1,495 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Load MiniMax-H3's Qwen3-VL conditioner from a hosted QUANTIZED checkpoint.++The H3 Diffusers path runs every component under ``ComponentsManager.enable_auto_cpu_offload``,+so its VRAM floor is the LARGEST SINGLE RESIDENT COMPONENT, not their sum. The released bfloat16+conditioner is 66.7 GB and the released denoiser is 66.3 GB, which is why seeding a 20 GB+pre-quantized denoiser moved that floor by nothing at all: the encoder simply became the largest+component instead. The encoder is the only remaining lever.++``diffusion_te_prequant`` cannot serve this one. Its artifacts are layerwise-fp8 STORAGE casts of+a dense encoder saved as ``torch.load``-able state dicts, which halve the bytes but keep every+released tensor. The hosted H3 conditioner is a different artifact in two independent ways, and+both savings stack:++ 1. It carries 50 of the released 64 decoder layers, and no ``lm_head`` and no final ``norm``+ (47.97 GiB against 62.14 GiB for ``MiniMaxAI/MiniMax-H3`` ``text_encoder/``).+ 2. Those 50 layers' four attention and three MLP projections are ConvRot INT8+ (25.28 GiB, i.e. 27.14 GB resident).++Dropping the tail is LOSSLESS here, not an approximation. MiniMax-H3 conditions the transformer on+``hidden_states[50]`` of the conditioner and never touches the language-model head -- see+``diffusers/modular_pipelines/minimax_h3/modular_pipeline.py`` (``text_encoder_layer`` returns 50,+"MiniMax-H3 reads `hidden_states[50]`, not the final one") and ``.../encoders.py``+``get_qwen3vl_prompt_embeds``, which calls ``text_encoder.model(..., output_hidden_states=True)``+and returns ``outputs.hidden_states[text_encoder_layer]``. Decoder layers 51-64 and ``lm_head``+therefore cannot influence the conditioning by construction. Comparing the hosted file's tensor+names against ``MiniMaxAI/MiniMax-H3``'s own shard index confirms the artifact drops EXACTLY that+set and nothing else: 902 names that map 1:1 onto the released ones, the remainder being decoder+layers 50-63 (0-based), ``model.language_model.norm.weight`` and ``lm_head.weight``.++There is one mechanical catch, and it is the reason this module builds 51 layers rather than 50.+``output_hidden_states`` yields ``[embeddings, layer_0_out, ..., layer_{N-1}_out]`` where the LAST+entry is post-``norm``. A stack truncated to exactly 50 layers therefore returns a NORMALIZED+``hidden_states[50]``, which is not the conditioning the released weights were trained against;+diffusers refuses that case outright (``encoders.py``: "The last hidden state of a stack truncated+to exactly 50 layers is post-norm"). Building a 51st slot that passes its input through unchanged+puts ``hidden_states[50]`` back where it belongs -- the raw output after 50 real layers, bit-identical+to what the full 64-layer conditioner produces there -- for no weights and no compute, and keeps+``len(layers) == config.num_hidden_layers`` honest so the diffusers guard passes on a true statement.++Best-effort throughout, exactly like ``diffusion_prequant``: any missing / unreadable / mismatched+artifact returns None and the caller loads the released bfloat16 encoder instead. Inert with+nothing configured.+"""++from __future__ import annotations++from typing import Any, Optional++# The repo the Diffusers H3 path already pulls its VAEs from, so this adds no new dependency.+from .video_minimax_h3 import H3_COMPONENT_REPO++H3_TE_QUANT_REPO = H3_COMPONENT_REPO++# Hosted quantized conditioners, by ``text_encoder_quant`` scheme.+#+# nvfp4 (``qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors``, 14.61 GiB) is deliberately absent: it is+# an AWQ NVFP4 layout with two levels of scale and a per-tensor global scale, a different loader+# and a different kernel, and shipping it needs its own numerical verification. The table is the+# one place to add it.+H3_TE_QUANT_FILES: dict[str, str] = {+ "int8": "text_encoders/qwen3vl_32b_minimax_h3_int8_convrot.safetensors",+}++# Resident bytes of each conditioner, decimal GB, measured from the safetensors headers on the Hub+# (2026-08-09) as the end of the last tensor's data. The quantized load is storage-faithful -- INT8+# stays INT8, the per-output-channel scales stay float32, the vision tower and the embedding table+# stay bfloat16 -- so the file size IS the resident size, unlike a cast-on-load path whose peak is+# the dense encoder.+#+# qwen3vl_32b_minimax_h3_bf16.safetensors 51.51 GB (47.97 GiB)+# qwen3vl_32b_minimax_h3_int8_convrot.safetensors 27.14 GB (25.28 GiB)+#+# The bfloat16 number here is the HOSTED 50-layer file. The budget default elsewhere is the+# RELEASED 64-layer encoder (66.7 GB), which is what a load without this path actually materialises.+H3_TE_QUANT_RESIDENT_GB: dict[str, float] = {+ "int8": 27.2,+}++# Which Qwen3-VL hidden state conditions the transformer. Must stay equal to+# ``MiniMaxH3ModularPipeline.text_encoder_layer``; ``h3_te_layer_budget`` below is the only reader.+H3_TE_READ_LAYER = 50++# ConvRot group size baked into the hosted checkpoint's per-tensor ``comfy_quant`` blob. Validated+# per tensor at load rather than assumed, so a re-upload under a different group is refused instead+# of silently decoding to noise.+H3_TE_CONVROT_GROUP = 256++# The quantization format the loader below implements. Any other value in a tensor's ``comfy_quant``+# blob is a format this code has not been verified against, and is refused.+_H3_TE_EXPECTED_QUANT = {"format": "int8_tensorwise", "convrot": True}++# Tensor-name suffixes that make up one quantized linear in the hosted layout.+_SCALE_SUFFIX = ".weight_scale"+_QUANT_SUFFIX = ".comfy_quant"+++def h3_te_quant_scheme(mode: Optional[str]) -> Optional[str]:+ """The hosted-conditioner scheme for a requested ``text_encoder_quant``, or None.++ Pure and non-raising: the request has already been validated by ``normalize_te_quant`` at the+ route, and a scheme with no hosted artifact simply keeps the released bfloat16 encoder."""+ if mode is None:+ return None+ normalized = str(mode).strip().lower().replace("-", "_")+ return normalized if normalized in H3_TE_QUANT_FILES else None+++def h3_te_quant_filename(scheme: Optional[str]) -> Optional[str]:+ """The hosted checkpoint's path inside ``H3_TE_QUANT_REPO`` for ``scheme``, or None."""+ return H3_TE_QUANT_FILES.get(scheme or "")+++def h3_te_resident_gb(scheme: Optional[str], *, bf16_gb: float) -> float:+ """Resident decimal GB of the conditioner this pick loads: the hosted quantized size when one+ exists for ``scheme``, else the released bfloat16 ``bf16_gb``."""+ resolved = h3_te_quant_scheme(scheme)+ return H3_TE_QUANT_RESIDENT_GB[resolved] if resolved else bf16_gb+++# ── ConvRot INT8 ──────────────────────────────────────────────────────────────+# W_rot = W @ H_block^T offline, x_rot = x @ H_block online, and H is a NORMALIZED REGULAR+# Hadamard, which is symmetric and orthogonal, so H @ H == I exactly and+# x_rot @ W_rot^T == x @ H @ H @ W^T == x @ W^T. The rotation is what lets INT8 survive Qwen3-VL's+# per-channel activation outliers; dequantizing WITHOUT it is not an approximation, it is noise+# (measured against the hosted bfloat16 file for one projection: 0.9% relative error with the+# rotation, 137% without).+#+# This mirrors comfy-kitchen's ``_build_hadamard`` / ``_rotate_activation`` / ``_rotate_weight``+# exactly, in ~30 lines of torch, rather than taking a dependency on a wheel Studio does not ship.++_HADAMARD_CACHE: dict[tuple[int, str, Any], Any] = {}+++def build_convrot_hadamard(+ size: int,+ device: Any = "cpu",+ dtype: Any = None,+) -> Any:+ """The normalized regular Hadamard matrix ConvRot rotates by. Cached per (size, device, dtype)."""+ import math++ import torch++ if dtype is None:+ dtype = torch.float32+ key = (size, str(device), dtype)+ cached = _HADAMARD_CACHE.get(key)+ if cached is not None:+ return cached+ if size < 4 or (size & (size - 1)) != 0 or math.log(size, 4) % 1 != 0:+ raise ValueError(f"ConvRot group size must be a power of 4, got {size}")+ h4 = torch.tensor(+ [[1, 1, 1, -1], [1, 1, -1, 1], [1, -1, 1, 1], [-1, 1, 1, 1]],+ dtype = dtype,+ device = device,+ )+ h = h4+ current = 4+ while current < size:+ h = torch.kron(h, h4)+ current *= 4+ h = h / (size**0.5)+ _HADAMARD_CACHE[key] = h+ return h+++def rotate_convrot_activation(x: Any, h: Any, group_size: int) -> Any:+ """``x @ H`` blockwise over the last dimension."""+ shape = x.shape+ features = shape[-1]+ if features % group_size != 0:+ raise ValueError(f"features {features} not divisible by ConvRot group {group_size}")+ grouped = x.reshape(-1, features // group_size, group_size)+ return grouped.matmul(h.to(dtype = x.dtype, device = x.device)).reshape(shape)+++def _int8_convrot_linear_class() -> Any:+ """The ConvRot INT8 ``nn.Linear`` stand-in, built lazily so importing this module never imports torch."""+ import torch+ from torch import nn++ class Int8ConvRotLinear(nn.Module):+ """A Linear whose weight stays INT8 in the rotated basis for its whole residency.++ The parameter names are the hosted checkpoint's own (``weight``, ``weight_scale``, ``bias``)+ so the remapped state dict loads straight in under ``strict=True``.++ The forward keeps the weight quantized and dequantizes a bfloat16 view per call (at most+ 262 MB, for the 25600x5120 MLP projections) rather than holding one. That is deliberate:+ the whole point of this path is that the encoder's RESIDENT footprint is 27 GB, and a+ cached dense view would put the 51 GB back. The per-output-channel scale is applied to the+ OUTPUT, not the weight, because it factors straight out of the matmul --+ ``sum_i x_i q_oi s_o == s_o * sum_i x_i q_oi`` -- which keeps it exact in float32 over a+ tiny tensor instead of approximate in bfloat16 over a huge one. INT8 values are integers+ below 256, so the ``.to(compute dtype)`` is exact in bfloat16.++ Weight-only, unlike comfy-kitchen's W8A8 kernel, which also quantizes the activation+ per row. Same weights and the same rotation, strictly less error, and the conditioner runs+ once per generation so the dequantize is not on any hot path.+ """++ def __init__(+ self, in_features: int, out_features: int, bias: bool, group_size: int+ ) -> None:+ super().__init__()+ self.in_features = in_features+ self.out_features = out_features+ self.group_size = group_size+ self.register_buffer(+ "weight",+ torch.empty(out_features, in_features, dtype = torch.int8, device = "meta"),+ persistent = True,+ )+ self.register_buffer(+ "weight_scale",+ torch.empty(out_features, 1, dtype = torch.float32, device = "meta"),+ persistent = True,+ )+ if bias:+ self.register_buffer(+ "bias",+ torch.empty(out_features, dtype = torch.bfloat16, device = "meta"),+ persistent = True,+ )+ else:+ self.bias = None++ def forward(self, x: Any) -> Any: # noqa: D102+ h = build_convrot_hadamard(self.group_size, device = x.device, dtype = x.dtype)+ rotated = rotate_convrot_activation(x, h, self.group_size)+ out = torch.nn.functional.linear(rotated, self.weight.to(x.dtype))+ out = out * self.weight_scale.reshape(1, -1).to(dtype = out.dtype, device = out.device)+ if self.bias is not None:+ out = out + self.bias.to(out.dtype)+ return out++ def extra_repr(self) -> str: # noqa: D102+ return (+ f"in_features={self.in_features}, out_features={self.out_features}, "+ f"bias={self.bias is not None}, int8_convrot(group={self.group_size})"+ )++ return Int8ConvRotLinear+++def _terminator_layer_class() -> Any:+ """The 51st decoder slot: passes its input through untouched. See the module docstring."""+ from torch import nn++ class H3TextEncoderTerminatorLayer(nn.Module):+ """Zero-parameter stand-in for decoder layer 50 (0-based).++ MiniMax-H3 reads ``hidden_states[50]``, the input to this slot, so nothing this returns is+ ever consumed -- it exists only so the final ``norm`` lands on an entry no one reads and+ ``hidden_states[50]`` stays the raw post-layer-50 state. Holding real weights here would+ cost ~0.5 GB and change nothing."""++ def forward(self, hidden_states: Any, *args: Any, **kwargs: Any) -> Any: # noqa: D102+ return hidden_states++ return H3TextEncoderTerminatorLayer+++# ── name mapping ──────────────────────────────────────────────────────────────+# The hosted checkpoint uses the ComfyUI flattening of the Qwen3-VL tree; transformers nests the+# language model and the vision tower under ``model.``. Verified exhaustive on 2026-08-09: all 902+# hosted names map into ``MiniMaxAI/MiniMax-H3`` ``text_encoder/model.safetensors.index.json``, with+# nothing left over on this side.+++def h3_te_remap_key(key: str) -> str:+ """A hosted checkpoint tensor name in transformers' ``Qwen3VLForConditionalGeneration`` naming."""+ if key.startswith("visual."):+ return "model." + key+ if key.startswith("model."):+ return "model.language_model." + key[len("model.") :]+ return key+++def _validate_comfy_quant(blob: Any, name: str) -> None:+ """Raise unless a tensor's ``comfy_quant`` metadata is the format this loader implements."""+ import json++ meta = json.loads(blob.cpu().numpy().tobytes().decode("utf-8").rstrip("\x00"))+ for field, expected in _H3_TE_EXPECTED_QUANT.items():+ if meta.get(field) != expected:+ raise ValueError(+ f"{name}: unsupported quant metadata {field}={meta.get(field)!r} "+ f"(this loader implements {field}={expected!r})"+ )+ group = int(meta.get("convrot_groupsize", H3_TE_CONVROT_GROUP))+ if group != H3_TE_CONVROT_GROUP:+ raise ValueError(+ f"{name}: ConvRot group {group} != the {H3_TE_CONVROT_GROUP} this loader implements"+ )+++def load_h3_quantized_text_encoder(+ base: str,+ scheme: str,+ *,+ dtype: Any,+ hf_token: Optional[str] = None,+ cache_dir: Optional[str] = None,+ local_base: Optional[str] = None,+ logger: Any = None,+) -> Optional[Any]:+ """The hosted quantized Qwen3-VL conditioner for ``scheme``, on CPU, ready to seed into the+ modular pipeline; None on any problem so the caller loads the released bfloat16 encoder.++ ``base`` supplies the component CONFIG only (``<base>/text_encoder/config.json``); every weight+ comes from the hosted artifact, so the 62 GB dense encoder is never fetched. ``local_base`` is+ the already-staged snapshot of ``base`` when there is one, and it is preferred: the scoped+ pre-download keeps every component config precisely so the meta-init loaders can read them+ locally, and reading the config back out of the snapshot cannot go to the network at all.+ ``cache_dir`` pins the config resolution to the live cache root for the hub-id case, exactly as+ the artifact download above and every other loader call in this backend do -- unset, it+ resolves through huggingface_hub's import-time constant instead and can re-download into a root+ Studio no longer reads (or fail outright on an offline host that has already staged it).++ CPU on purpose: ``enable_auto_cpu_offload`` owns placement for every component, and a+ pre-placed encoder would only be moved again."""+ try:+ filename = h3_te_quant_filename(scheme)+ if filename is None:+ return None++ import torch+ import transformers+ from accelerate import init_empty_weights+ from safetensors import safe_open++ from utils.hf_xet_fallback import hf_hub_download_with_xet_fallback++ path = hf_hub_download_with_xet_fallback(+ H3_TE_QUANT_REPO, filename, hf_token, cache_dir = cache_dir+ )++ config = transformers.AutoConfig.from_pretrained(+ local_base or base,+ subfolder = "text_encoder",+ token = hf_token,+ cache_dir = cache_dir,+ )+ text_config = getattr(config, "text_config", config)+ released_layers = int(getattr(text_config, "num_hidden_layers", 0))+ if released_layers <= H3_TE_READ_LAYER:+ # A base repo whose conditioner is already at or below the read layer is not the model+ # this artifact was cut from; refuse rather than build something that reads a post-norm+ # state. Cannot happen for MiniMaxAI/MiniMax-H3 (64), but the pairing is not enforced+ # anywhere else.+ raise ValueError(+ f"{base} text_encoder has {released_layers} layers; MiniMax-H3 reads "+ f"hidden_states[{H3_TE_READ_LAYER}] and needs more than that"+ )+ # See the module docstring: one slot past the read layer, so the read lands on the raw+ # state rather than the post-norm one.+ text_config.num_hidden_layers = H3_TE_READ_LAYER + 1++ # include_buffers=False on purpose (it is also accelerate's default, but the whole load+ # turns on it): PARAMETERS go to meta and are replaced wholesale by ``assign=True`` below,+ # while BUFFERS -- the rotary inverse frequencies, which no state dict carries because they+ # are non-persistent -- are built for real on CPU. They are a few KB. Putting them on meta+ # instead would leave the encoder with meta tensors after the load and force a dense CPU+ # rebuild, i.e. the 51 GB allocation this path exists to avoid.+ with init_empty_weights(include_buffers = False):+ encoder = transformers.Qwen3VLForConditionalGeneration(config)++ language_model = encoder.model.language_model+ language_model.layers[H3_TE_READ_LAYER] = _terminator_layer_class()()+ # Neither is in the artifact and neither can reach the conditioning: ``norm`` is only ever+ # applied to the terminator's output, and the head is never called (the pipeline invokes+ # ``text_encoder.model``, not ``text_encoder``). Dropping the head alone saves 1.56 GB.+ language_model.norm = torch.nn.Identity()+ encoder.lm_head = torch.nn.Identity()++ int8_linear_cls = _int8_convrot_linear_class()+ with safe_open(path, framework = "pt", device = "cpu") as handle:+ names = set(handle.keys())+ quantized = {+ name[: -len(_SCALE_SUFFIX)] for name in names if name.endswith(_SCALE_SUFFIX)+ }+ # Swap every quantized projection for the INT8 module BEFORE loading, so the state dict+ # lands on buffers of the right dtype instead of being cast into bfloat16 Linears.+ for prefix in sorted(quantized):+ quant_key = prefix + _QUANT_SUFFIX+ if quant_key not in names:+ raise ValueError(f"{prefix}: quantized weight with no {_QUANT_SUFFIX} metadata")+ _validate_comfy_quant(handle.get_tensor(quant_key), prefix)+ target = h3_te_remap_key(prefix)+ parent_path, _, leaf = target.rpartition(".")+ parent = encoder.get_submodule(parent_path)+ existing = getattr(parent, leaf)+ slice_ = handle.get_slice(prefix + ".weight")+ out_features, in_features = slice_.get_shape()+ if (existing.out_features, existing.in_features) != (out_features, in_features):+ raise ValueError(+ f"{target}: checkpoint shape {(out_features, in_features)} != model "+ f"{(existing.out_features, existing.in_features)}"+ )+ setattr(+ parent,+ leaf,+ int8_linear_cls(+ in_features,+ out_features,+ bias = (prefix + ".bias") in names,+ group_size = H3_TE_CONVROT_GROUP,+ ),+ )++ # The INT8 payload and its float32 scales are STORAGE and keep their dtypes; everything+ # still dense (the vision tower, the embedding table, the norms) follows the pipeline's+ # compute dtype, exactly as ``load_components(dtype=...)`` would have set it had this+ # component been loaded the ordinary way. A no-op for the bfloat16 H3 runs.+ state_dict = {}+ for name in names:+ if name.endswith(_QUANT_SUFFIX):+ continue+ tensor = handle.get_tensor(name)+ if (+ not name.endswith(_SCALE_SUFFIX)+ and tensor.is_floating_point()+ and dtype is not None+ ):+ tensor = tensor.to(dtype)+ state_dict[h3_te_remap_key(name)] = tensor++ # strict=True proves the artifact and the meta-initialised skeleton describe the same 902+ # tensors, so a re-upload that renames, adds or drops one fails the load instead of+ # silently conditioning on partly random weights. It does NOT prove they are quantized:+ # a projection re-uploaded as a plain dense ``weight`` with its scale and metadata removed+ # simply drops out of the set above, leaves the original bfloat16 Linear in place, and+ # loads cleanly under strict. The load would then be recorded as engaged int8 while the+ # resident encoder crept back toward the dense 51 GB, and the VRAM preflight -- which+ # sizes the floor from the ENGAGED scheme -- would clear a generation that cannot fit.+ #+ # Checked structurally rather than against a count, so it stays true if the layer or+ # projection set ever changes: no ordinary Linear may survive inside the decoder stack.+ # The vision tower keeps its own dense Linears and is not in scope.+ dense = [+ name+ for name, module in language_model.layers.named_modules()+ if isinstance(module, torch.nn.Linear)+ ]+ if dense:+ raise ValueError(+ f"{len(dense)} decoder projection(s) are not quantized in this artifact, "+ f"e.g. {', '.join(sorted(dense)[:3])}; it is not the {scheme} checkpoint this "+ f"path budgets for"+ )+ encoder.load_state_dict(state_dict, strict = True, assign = True)+ # Nothing may be left on meta. A dense CPU rebuild is NOT an acceptable repair here (it is+ # the 51 GB allocation this path exists to avoid), so a leftover is a refusal and the caller+ # falls back to the released encoder, which at least loads correctly.+ stranded = _meta_tensor_names(encoder)+ if stranded:+ raise ValueError(+ f"{len(stranded)} tensor(s) still on the meta device after loading, "+ f"e.g. {', '.join(stranded[:3])}"+ )+ encoder.eval()+ if logger is not None:+ logger.info(+ "video.h3_te_quant: loaded the hosted %s conditioner (%s, %s), "+ "%d ConvRot INT8 projections over %d decoder layers",+ scheme,+ H3_TE_QUANT_REPO,+ filename,+ len(quantized),+ H3_TE_READ_LAYER,+ )+ return encoder+ except Exception as exc: # noqa: BLE001 -- fall back to the released bfloat16 encoder+ if logger is not None:+ logger.warning(+ "video.h3_te_quant: hosted %s conditioner unusable (%s); "+ "loading the released bfloat16 encoder instead",+ scheme,+ exc,+ )+ return None+++def _meta_tensor_names(module: Any) -> list[str]:+ """Names of every parameter and buffer still on the meta device."""+ from itertools import chain+ return [+ name+ for name, tensor in chain(module.named_parameters(), module.named_buffers())+ if getattr(tensor, "is_meta", False)+ ]diff --git a/studio/backend/tests/test_video_families.py b/studio/backend/tests/test_video_families.pyindex f968433d2fc..c2a10a5b2d8 100644--- a/studio/backend/tests/test_video_families.py+++ b/studio/backend/tests/test_video_families.py@@ -30,6 +30,27 @@ def test_h3_measured_diffusers_memory_estimates():assert estimate_h3_diffusers_host_ram_gb(132) == 85+def test_the_host_floor_tracks_the_components_the_load_holds():+ """The VRAM floor is rebuilt from the engaged components; the host floor has to be too, or an+ 80 GB device running the int8 conditioner and the int8 denoiser clears the VRAM check at 55 GB+ and is then told it needs 150 GB of system RAM for 47.5 GB of weights."""+ from core.inference.video_minimax_h3 import (+ H3_TEXT_ENCODER_BF16_GB,+ H3_TRANSFORMER_BF16_GB,+ )++ # Unset is the released pair, so the shipped number is unchanged to the decimal.+ assert estimate_h3_diffusers_host_ram_gb(+ 126, text_encoder_gb = H3_TEXT_ENCODER_BF16_GB, transformer_gb = H3_TRANSFORMER_BF16_GB+ ) == pytest.approx(150.0, abs = 0.001)+ # The hosted int8 conditioner + int8 denoiser: the sum, not the released one.+ assert estimate_h3_diffusers_host_ram_gb(+ 126, text_encoder_gb = 27.2, transformer_gb = 20.3+ ) == pytest.approx(64.5, abs = 0.001)+ # Above the tier the answer is the tier's, whatever the components.+ assert estimate_h3_diffusers_host_ram_gb(132, text_encoder_gb = 27.2, transformer_gb = 20.3) == 85++@pytest.mark.parametrize("repo_id",[diff --git a/studio/backend/tests/test_video_h3_te_quant.py b/studio/backend/tests/test_video_h3_te_quant.pynew file mode 100644index 00000000000..3c66acf2f61--- /dev/null+++ b/studio/backend/tests/test_video_h3_te_quant.py@@ -0,0 +1,679 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Hosted QUANTIZED conditioner route for MiniMax-H3's Diffusers path.++Mirrors tests/test_video_prequant.py, which covers the denoiser half of the same idea: the+resolver, the download-plan hooks that decide whether the base repo's dense ``text_encoder/``+shards are staged, the ConvRot INT8 arithmetic, and the memory floor recomputed from what the+load actually holds.++Network-free and (except for the two arithmetic tests) torch-free. The 27 GB artifact itself is+exercised end to end on a GPU, not here."""++from __future__ import annotations++import types++import pytest++from core.inference.video import VideoBackend+from core.inference.video_families import detect_video_family+from core.inference.video_minimax_h3 import (+ H3_DIFFUSERS_VRAM_BASE_GB,+ H3_TEXT_ENCODER_BF16_GB,+ H3_TRANSFORMER_BF16_GB,+ estimate_h3_diffusers_vram_gb,+ h3_diffusers_vram_base_gb,+ h3_transformer_resident_gb,+)+from core.inference.video_minimax_h3_te import (+ H3_TE_CONVROT_GROUP,+ H3_TE_QUANT_FILES,+ H3_TE_QUANT_REPO,+ H3_TE_READ_LAYER,+ h3_te_quant_filename,+ h3_te_quant_scheme,+ h3_te_remap_key,+ h3_te_resident_gb,+)++torch = pytest.importorskip("torch", reason = "the ConvRot arithmetic tests need torch")+++H3_BASE = "MiniMaxAI/MiniMax-H3"+++def _fam(+ modular_workflow = "fl2va",+ name = "minimax-h3",+ base_repo = H3_BASE,+):+ return types.SimpleNamespace(name = name, modular_workflow = modular_workflow, base_repo = base_repo)+++# ── the resolver ─────────────────────────────────────────────────────────────────+def test_only_int8_has_a_hosted_conditioner():+ assert h3_te_quant_scheme("int8") == "int8"+ assert h3_te_quant_scheme("INT8") == "int8"+ # Valid text_encoder_quant modes with no hosted H3 artifact resolve to nothing rather than+ # raising: the request is well formed, this family just cannot serve it.+ for mode in ("fp8", "fp8_dynamic", "nvfp4", "fp8-dynamic", "", None):+ assert h3_te_quant_scheme(mode) is None+++def test_the_hosted_filename_is_the_comfy_component_repo():+ # H3_TE_QUANT_REPO must stay the repo the Diffusers path already pulls its VAEs from, or this+ # adds a second component dependency nobody staged.+ from core.inference.video_minimax_h3 import H3_COMPONENT_REPO++ assert H3_TE_QUANT_REPO == H3_COMPONENT_REPO+ assert (+ h3_te_quant_filename("int8")+ == "text_encoders/qwen3vl_32b_minimax_h3_int8_convrot.safetensors"+ )+ assert h3_te_quant_filename("fp8") is None+ assert h3_te_quant_filename(None) is None+++def test_every_hosted_scheme_is_a_valid_text_encoder_quant_request():+ # A scheme this module offers but normalize_te_quant refuses could never be requested.+ from core.inference.diffusion_precision import normalize_te_quant+ for scheme in H3_TE_QUANT_FILES:+ assert normalize_te_quant(scheme) == scheme+++# ── the name mapping ─────────────────────────────────────────────────────────────+def test_remap_puts_comfy_names_into_the_transformers_tree():+ # ComfyUI flattens the Qwen3-VL tree; transformers nests both halves under model.+ assert (+ h3_te_remap_key("model.layers.0.self_attn.q_proj.weight")+ == "model.language_model.layers.0.self_attn.q_proj.weight"+ )+ assert (+ h3_te_remap_key("model.embed_tokens.weight") == "model.language_model.embed_tokens.weight"+ )+ assert h3_te_remap_key("visual.blocks.3.attn.qkv.bias") == "model.visual.blocks.3.attn.qkv.bias"+ # NOT idempotent, on purpose: re-mapping an already-transformers name produces a key no module+ # owns, so an artifact re-uploaded in transformers naming fails the strict load loudly instead+ # of half-matching.+ assert h3_te_remap_key("model.language_model.layers.0.mlp.up_proj.weight") == (+ "model.language_model.language_model.layers.0.mlp.up_proj.weight"+ )+++# ── the ConvRot arithmetic ───────────────────────────────────────────────────────+def test_the_convrot_hadamard_is_symmetric_and_its_own_inverse():+ from core.inference.video_minimax_h3_te import build_convrot_hadamard++ h = build_convrot_hadamard(H3_TE_CONVROT_GROUP)+ assert h.shape == (H3_TE_CONVROT_GROUP, H3_TE_CONVROT_GROUP)+ # Exactly, not approximately: the entries are +-1/16 and the products are sums of 256 of them.+ assert torch.equal(h, h.T)+ assert (h @ h - torch.eye(H3_TE_CONVROT_GROUP)).abs().max().item() == 0.0+ # Regular Hadamard: a power of 4 only. 128 is a power of 2 and must still be refused.+ for bad in (128, 100, 2):+ with pytest.raises(ValueError):+ build_convrot_hadamard(bad)+++def test_rotating_the_activation_undoes_the_rotation_baked_into_the_weight():+ """The load-bearing identity: x_rot @ W_rot.T == x @ W.T.++ If this were false the INT8 conditioner would decode to noise, and a load that only checked+ file sizes would never notice. Dequantizing WITHOUT the rotation is the control."""+ from core.inference.video_minimax_h3_te import (+ _int8_convrot_linear_class,+ build_convrot_hadamard,+ rotate_convrot_activation,+ )++ torch.manual_seed(0)+ group = H3_TE_CONVROT_GROUP+ out_features, in_features = 64, group * 3+ weight = torch.randn(out_features, in_features) * 0.02+ x = torch.randn(5, in_features)++ h = build_convrot_hadamard(group)+ # The offline half, exactly as the artifact was baked: W_rot = W @ H.T blockwise.+ grouped = weight.reshape(out_features, in_features // group, group)+ weight_rot = grouped.matmul(h.T).reshape(out_features, in_features)+ # Round trip through INT8 per output channel, as the hosted checkpoint stores it.+ scale = (weight_rot.abs().amax(dim = -1, keepdim = True) / 127.0).clamp(min = 1e-30)+ qdata = torch.round(weight_rot / scale).clamp(-127, 127).to(torch.int8)++ module = _int8_convrot_linear_class()(in_features, out_features, bias = False, group_size = group)+ module.load_state_dict({"weight": qdata, "weight_scale": scale}, strict = True, assign = True)+ with torch.no_grad():+ got = module(x)+ reference = torch.nn.functional.linear(x, weight)+ # Everything but the INT8 rounding is exact, so this is a quantization-error bound, not a+ # numerical-slop one.+ assert (got - reference).norm() / reference.norm() < 0.02++ # Control: skipping the activation rotation is not "slightly worse", it is unrelated.+ unrotated = torch.nn.functional.linear(x, qdata.float() * scale)+ assert (unrotated - reference).norm() / reference.norm() > 0.5+ # And the rotation itself is an involution.+ assert torch.allclose(+ rotate_convrot_activation(rotate_convrot_activation(x, h, group), h, group), x, atol = 1e-5+ )+++def test_the_int8_module_keeps_its_weight_quantized():+ """The resident footprint IS the point, so a cached dense view would defeat the whole path."""+ from core.inference.video_minimax_h3_te import _int8_convrot_linear_class++ group = H3_TE_CONVROT_GROUP+ module = _int8_convrot_linear_class()(group, 8, bias = False, group_size = group)+ module.load_state_dict(+ {+ "weight": torch.zeros(8, group, dtype = torch.int8),+ "weight_scale": torch.ones(8, 1),+ },+ strict = True,+ assign = True,+ )+ with torch.no_grad():+ module(torch.randn(2, group))+ assert module.weight.dtype is torch.int8+ assert sum(t.numel() * t.element_size() for t in module.buffers()) == 8 * group + 8 * 4+++# ── the read layer ───────────────────────────────────────────────────────────────+def test_the_read_layer_matches_the_diffusers_pipeline():+ """MiniMax-H3 conditions on hidden_states[50]. If diffusers ever moves it, the 50-layer+ artifact stops being lossless and this must fail rather than ship a silent approximation."""+ pytest.importorskip("diffusers", reason = "reads the installed pipeline's own constant")+ from diffusers.modular_pipelines.minimax_h3.modular_pipeline import MiniMaxH3ModularPipeline++ assert MiniMaxH3ModularPipeline.text_encoder_layer.fget(None) == H3_TE_READ_LAYER+++# ── the memory floor ─────────────────────────────────────────────────────────────+def test_the_default_floor_is_unchanged():+ """Backwards compatibility: nothing that does not pass a size sees a different number."""+ assert h3_diffusers_vram_base_gb() == pytest.approx(H3_DIFFUSERS_VRAM_BASE_GB, abs = 0.001)+ assert estimate_h3_diffusers_vram_gb(960, 544, 124) == pytest.approx(73.68, abs = 0.02)+ assert estimate_h3_diffusers_vram_gb(1344, 768, 345) == pytest.approx(96.98, abs = 0.02)+++def test_an_unpinned_floor_is_the_largest_component_not_the_sum():+ # Every component runs under CPU offload, so quantizing ONE of the two 66 GB components buys+ # nothing while both stay in the rotation.+ assert h3_diffusers_vram_base_gb(transformer_gb = 20.3) == pytest.approx(68.5, abs = 0.001)+ assert h3_diffusers_vram_base_gb(text_encoder_gb = 27.2) == pytest.approx(68.1, abs = 0.001)+++def test_a_pinned_denoiser_makes_the_floor_additive():+ """The pre-quantized denoiser is pinned out of the offload rotation, so it is resident+ alongside whatever else is running. Treating that as a max under-states the floor by the whole+ denoiser, which is the direction that lets a doomed generation start."""+ pinned = h3_diffusers_vram_base_gb(transformer_gb = 20.3, transformer_pinned = True)+ assert pinned == pytest.approx(20.3 + 66.7 + 2.6, abs = 0.001)+ assert pinned > h3_diffusers_vram_base_gb(transformer_gb = 20.3)+ # A tiny conditioner cannot drag the floor under the VAEs, which still rotate through.+ assert h3_diffusers_vram_base_gb(+ text_encoder_gb = 1.0, transformer_gb = 20.3, transformer_pinned = True+ ) == pytest.approx(20.3 + 11.1 + 2.6, abs = 0.001)+++def test_the_floor_matches_the_two_measured_runs():+ """Calibration, against torch.cuda.max_memory_allocated over a real 960x544x124 generation with+ the int8 denoiser pinned. Both must be covered, and neither by an absurd margin."""+ for text_encoder_gb, measured in ((H3_TEXT_ENCODER_BF16_GB, 94.62), (27.2, 55.20)):+ predicted = estimate_h3_diffusers_vram_gb(+ 960,+ 544,+ 124,+ text_encoder_gb = text_encoder_gb,+ transformer_gb = 20.3,+ transformer_pinned = True,+ )+ assert measured <= predicted <= measured + 1.0, (text_encoder_gb, predicted, measured)+++def test_quantizing_the_conditioner_is_what_finally_moves_the_floor():+ dense = estimate_h3_diffusers_vram_gb(+ 960, 544, 124, transformer_gb = 20.3, transformer_pinned = True+ )+ quantized = estimate_h3_diffusers_vram_gb(+ 960, 544, 124, text_encoder_gb = 27.2, transformer_gb = 20.3, transformer_pinned = True+ )+ # The saving is the conditioner delta and nothing else.+ assert dense - quantized == pytest.approx(H3_TEXT_ENCODER_BF16_GB - 27.2, abs = 0.001)+ assert quantized < H3_DIFFUSERS_VRAM_BASE_GB+++def test_resident_sizes_track_the_engaged_scheme_only():+ assert h3_te_resident_gb("int8", bf16_gb = H3_TEXT_ENCODER_BF16_GB) == 27.2+ # A scheme with no hosted artifact, and a declined request recorded as None, both keep the+ # dense budget. Under-stating the floor is the expensive direction.+ for mode in (None, "fp8", "nvfp4"):+ assert h3_te_resident_gb(mode, bf16_gb = H3_TEXT_ENCODER_BF16_GB) == H3_TEXT_ENCODER_BF16_GB+ assert h3_transformer_resident_gb("int8") == 20.3+ assert h3_transformer_resident_gb(None) == H3_TRANSFORMER_BF16_GB+++# ── the download plan ────────────────────────────────────────────────────────────+def test_only_a_modular_family_drops_its_dense_encoder():+ assert VideoBackend._h3_te_quant_scheme(_fam(), "int8", H3_BASE) == "int8"+ # A conventional family casts its own dense encoder in place and still needs those shards.+ assert VideoBackend._h3_te_quant_scheme(_fam(modular_workflow = None), "int8", H3_BASE) is None+ assert VideoBackend._h3_te_quant_scheme(_fam(), "fp8", H3_BASE) is None+ assert VideoBackend._h3_te_quant_scheme(_fam(), None, H3_BASE) is None+++def test_only_the_base_the_artifact_was_cut_from_gets_the_hosted_conditioner():+ """A derivative can keep the Qwen3-VL architecture and change the conditioner weights. The+ strict load cannot tell -- every name and shape still matches -- so gate on the base instead,+ exactly as the pre-quantized denoiser does through its baked base_model_id."""+ # A local snapshot of the same base still qualifies (same repo tail).+ assert VideoBackend._h3_te_quant_scheme(_fam(), "int8", "/models/MiniMax-H3") == "int8"+ # A derivative, however it was selected (detection or family_override), keeps its own encoder.+ for other in ("someone/MiniMax-H3-anime", "someone/MiniMax-H3-v2", "MiniMaxAI/MiniMax-H2"):+ assert VideoBackend._h3_te_quant_scheme(_fam(), "int8", other) is None+ # And an unknown base is not a licence to substitute one either.+ assert VideoBackend._h3_te_quant_scheme(_fam(), "int8", None) is None+ assert VideoBackend._h3_te_quant_scheme(_fam(base_repo = None), "int8", H3_BASE) is None+++def test_an_unsupported_request_never_breaks_the_plan():+ # The plan runs before validate_load_request has had the last word on some paths, and a raise+ # here would cost the whole download plan rather than one optimisation.+ assert VideoBackend._h3_te_quant_scheme(_fam(), "not-a-scheme", H3_BASE) is None+ assert VideoBackend._h3_te_quant_scheme(object(), "int8", H3_BASE) is None+++def test_the_real_family_resolves_the_hosted_conditioner():+ fam = detect_video_family(H3_BASE)+ assert fam is not None and fam.modular_workflow+ assert VideoBackend._h3_te_quant_scheme(fam, "int8", H3_BASE) == "int8"+++def test_an_unresolvable_artifact_keeps_the_dense_shards():+ """Only an artifact that really exists on the Hub earns the right to drop 62 GB of encoder."""++ class _Boom:+ def model_info(self, *_args, **_kwargs):+ raise RuntimeError("hub down")++ assert VideoBackend._h3_te_quant_hub_files("int8", _Boom()) == (None, [])+ assert VideoBackend._h3_te_quant_hub_files(None, _Boom()) == (None, [])++ class _Empty:+ def model_info(self, *_args, **_kwargs):+ return types.SimpleNamespace(siblings = [])++ assert VideoBackend._h3_te_quant_hub_files("int8", _Empty()) == (None, [])+++def test_a_resolvable_artifact_is_staged_in_place_of_the_dense_shards():+ wanted = h3_te_quant_filename("int8")++ class _Api:+ def model_info(self, repo_id, **_kwargs):+ assert repo_id == H3_TE_QUANT_REPO+ return types.SimpleNamespace(+ siblings = [+ types.SimpleNamespace(rfilename = wanted, size = 27_141_342_152),+ types.SimpleNamespace(rfilename = "vae/other.safetensors", size = 5),+ ]+ )++ repo, files = VideoBackend._h3_te_quant_hub_files("int8", _Api())+ assert repo == H3_TE_QUANT_REPO+ # Exactly the one artifact, at its real size: the disk preflight is sized off this.+ assert files == [(wanted, 27_141_342_152)]+++def test_the_conditioner_repo_is_protected_while_the_load_is_in_flight(monkeypatch):+ """The artifact comes from a THIRD repo. Without it in ``asset_repos`` the delete-cached guard+ would let it go while the fetch (or the base pull that no longer carries a dense encoder) is+ still running."""+ from core.inference import video as video_mod++ backend = VideoBackend()+ backend._load_token = 7+ backend._loading = video_mod._VideoLoadingState(repo_id = H3_BASE, base_repo = H3_BASE)++ seen: dict[str, tuple[str, ...]] = {}+ # The verified resolver reads the base's modular index; this test is about the delete guard,+ # not the index, and the suite blocks the network.+ monkeypatch.setattr(backend, "_h3_te_base_index_source", lambda *a, **k: H3_BASE)+ monkeypatch.setattr(backend, "_estimate_download_bytes", lambda *a, **k: 1)+ monkeypatch.setattr(backend, "_fetch_te_prequant", lambda *a, **k: ())+ monkeypatch.setattr(backend, "_predownload_base", lambda *a, **k: None)+ monkeypatch.setattr(backend, "load_pipeline", lambda **k: None)++ def _fetch(scheme, _token, **_kwargs):+ seen["scheme"] = scheme+ seen["ids"] = backend.loading_repo_ids()+ return ("text_encoder",)++ monkeypatch.setattr(backend, "_fetch_h3_te_quant", _fetch)+ backend._run_load(+ repo_id = H3_BASE,+ model_kind = "pipeline",+ text_encoder_quant = "int8",+ _load_token = 7,+ )+ assert seen["scheme"] == "int8"+ assert H3_TE_QUANT_REPO in seen["ids"]+++def test_the_conditioner_repo_is_not_claimed_by_a_load_that_does_not_want_it(monkeypatch):+ from core.inference import video as video_mod++ backend = VideoBackend()+ backend._load_token = 7+ backend._loading = video_mod._VideoLoadingState(repo_id = H3_BASE, base_repo = H3_BASE)+ monkeypatch.setattr(backend, "_estimate_download_bytes", lambda *a, **k: 1)+ monkeypatch.setattr(backend, "_fetch_te_prequant", lambda *a, **k: ())+ monkeypatch.setattr(backend, "_fetch_h3_te_quant", lambda *a, **k: ())+ monkeypatch.setattr(backend, "_predownload_base", lambda *a, **k: None)+ monkeypatch.setattr(backend, "load_pipeline", lambda **k: None)+ backend._run_load(repo_id = H3_BASE, model_kind = "pipeline", _load_token = 7)+ assert backend._loading is None or H3_TE_QUANT_REPO not in backend.loading_repo_ids()+++def test_the_encoder_config_is_read_from_the_pinned_cache_not_the_default_one(monkeypatch):+ """Studio runs on a configured cache root. An AutoConfig call that ignores it resolves against+ huggingface_hub's import-time default, which re-downloads into a root Studio does not read and+ simply fails on an offline host that has already staged the model."""+ import sys++ import core.inference.video_minimax_h3_te as te_mod++ captured: dict[str, object] = {}++ class _AutoConfig:+ @staticmethod+ def from_pretrained(name, **kwargs):+ captured["name"] = name+ captured["kwargs"] = kwargs+ # The load is best-effort by contract, so raising here returns None and exercises+ # exactly the one call this test is about.+ raise RuntimeError("only the call shape is under test")++ # Every import the loader makes before the config read is stubbed, so this asserts the call+ # shape on any host. Without accelerate / safetensors it would otherwise return None from the+ # import line and never reach AutoConfig, which is a pass for the wrong reason (and a KeyError+ # on the assertions below) on a CPU runner that has torch but not the rest.+ monkeypatch.setitem(sys.modules, "transformers", types.SimpleNamespace(AutoConfig = _AutoConfig))+ monkeypatch.setitem(+ sys.modules,+ "accelerate",+ types.SimpleNamespace(init_empty_weights = lambda **_k: None),+ )+ monkeypatch.setitem(+ sys.modules, "safetensors", types.SimpleNamespace(safe_open = lambda *a, **k: None)+ )+ monkeypatch.setitem(+ sys.modules,+ "utils.hf_xet_fallback",+ types.SimpleNamespace(hf_hub_download_with_xet_fallback = lambda *a, **k: "/nope"),+ )++ assert (+ te_mod.load_h3_quantized_text_encoder(+ H3_BASE, "int8", dtype = None, cache_dir = "/tmp/studio-hub"+ )+ is None+ )+ assert captured["name"] == H3_BASE+ assert captured["kwargs"]["cache_dir"] == "/tmp/studio-hub"+ assert captured["kwargs"]["subfolder"] == "text_encoder"++ # A staged snapshot is preferred over the hub id: its config.json is already on disk, so the+ # resolution cannot go to the network at all.+ captured.clear()+ te_mod.load_h3_quantized_text_encoder(+ H3_BASE, "int8", dtype = None, cache_dir = "/tmp/studio-hub", local_base = "/snap/h3"+ )+ assert captured["name"] == "/snap/h3"+++def test_the_dense_encoder_is_dropped_from_the_base_pull_but_its_config_is_kept():+ """The loader meta-inits from <base>/text_encoder/config.json, so dropping that would break+ the very load that made the skip safe."""+ from core.inference.diffusion_te_prequant import is_prequant_covered_weight++ covered = ("text_encoder",)+ assert is_prequant_covered_weight("text_encoder/model-00001-of-00014.safetensors", covered)+ assert not is_prequant_covered_weight("text_encoder/config.json", covered)+ assert not is_prequant_covered_weight("text_encoder/tokenizer.json", covered)+ # Other components are untouched.+ assert not is_prequant_covered_weight("vae/diffusion_pytorch_model.safetensors", covered)+ assert not is_prequant_covered_weight(+ "transformer/diffusion_pytorch_model.safetensors", covered+ )+++# ── the resolved record ──────────────────────────────────────────────────────────+def test_a_declined_request_reads_as_a_fallback_not_as_never_asked():+ """The record has to keep the REQUEST on the left. Erasing it to None makes a refused fp8+ request indistinguishable from a load nobody asked to quantize."""+ from core.inference.diffusion_auto_policy import build_resolved_record++ record = build_resolved_record(+ {+ "text_encoder_quant": (+ "fp8",+ "off",+ "no hosted quantized fp8 conditioner for minimax-h3; "+ "loaded the released bfloat16 encoder instead",+ )+ }+ )+ entry = record["text_encoder_quant"]+ assert entry["requested"] == "fp8"+ assert entry["value"] == "off"+ assert entry["status"] != "as_requested"+++# ── the identity gate the base NAME cannot make ──────────────────────────────────+def test_the_index_names_the_conditioner_a_pipeline_would_have_loaded():+ """A repo-id comparison cannot tell a derivative stored as .../MiniMax-H3 from the real one.+ The pipeline's own modular index can: it records where each component comes from, and a+ derivative that retrained the conditioner ships it under its own id."""++ def _pipe(source):+ spec = types.SimpleNamespace(pretrained_model_name_or_path = source)+ return types.SimpleNamespace(get_component_spec = lambda name: spec)++ assert VideoBackend._h3_te_index_source(_pipe(H3_BASE)) == H3_BASE+ assert VideoBackend._h3_te_index_source(_pipe("someone/MiniMax-H3")) == "someone/MiniMax-H3"+ # Unanswerable is None, and the caller reads None as a refusal.+ assert VideoBackend._h3_te_index_source(_pipe(None)) is None+ assert VideoBackend._h3_te_index_source(_pipe(["a", "b"])) is None+ assert VideoBackend._h3_te_index_source(_pipe("")) is None+ assert VideoBackend._h3_te_index_source(object()) is None++ # The deprecated spelling, for a spec built by hand rather than parsed from the index.+ legacy = types.SimpleNamespace(repo = H3_BASE, pretrained_model_name_or_path = None)+ assert (+ VideoBackend._h3_te_index_source(+ types.SimpleNamespace(get_component_spec = lambda name: legacy)+ )+ == H3_BASE+ )+++def test_the_real_index_records_where_the_conditioner_comes_from():+ """Pinned against the shape MiniMaxAI/MiniMax-H3 actually ships, so a schema change is caught+ here rather than by silently declining every quantized conditioner."""+ entry = [+ "transformers",+ "Qwen3VLForConditionalGeneration",+ {+ "type_hint": ["transformers", "Qwen3VLForConditionalGeneration"],+ "pretrained_model_name_or_path": H3_BASE,+ "subfolder": "text_encoder",+ "variant": None,+ "revision": None,+ },+ ]+ from core.inference.diffusion_te_prequant import te_base_equivalent++ source = entry[2]["pretrained_model_name_or_path"]+ assert te_base_equivalent("MiniMaxAI/MiniMax-H3", source)+ # A derivative that retrained its conditioner names itself here and is refused, even though+ # its own repo id would pass the tail-segment comparison.+ assert not te_base_equivalent("MiniMaxAI/MiniMax-H3", "someone/MiniMax-H3-anime")+++def test_the_index_compare_has_no_tail_name_tolerance():+ """The plan-side gate uses te_base_equivalent, which accepts a matching final path segment.+ That tolerance is the hole this gate closes, so it must not be reused here: someone/MiniMax-H3+ is a different repo with different weights."""+ from core.inference.diffusion_te_prequant import te_base_equivalent+ from core.inference.video import _h3_te_canonical++ # What the tolerant helper accepts and this one must not.+ for other in ("someone/MiniMax-H3", "/models/MiniMax-H3", "someone/minimax-h3"):+ assert te_base_equivalent(H3_BASE, other), "precondition: the tolerant helper accepts it"+ assert _h3_te_canonical(other) != _h3_te_canonical(H3_BASE)+ # The canonical id, in any casing or with stray whitespace, still matches.+ for same in (H3_BASE, H3_BASE.lower(), f" {H3_BASE} "):+ assert _h3_te_canonical(same) == _h3_te_canonical(H3_BASE)+ assert _h3_te_canonical(None) == ""+++def test_a_known_mirror_is_still_the_same_conditioner():+ """canonical_base folds a mirror onto the id it copies, so tightening the compare must not+ refuse one. Skipped when no mirror is registered rather than asserting a table entry."""+ from core.inference.diffusion_families import _MIRROR_UPSTREAM+ from core.inference.video import _h3_te_canonical++ for mirror, upstream in _MIRROR_UPSTREAM.items():+ assert _h3_te_canonical(mirror) == _h3_te_canonical(upstream)+++# ── the precision contract ───────────────────────────────────────────────────────+def test_a_hosted_conditioner_is_not_judged_by_the_generic_precision_gate(monkeypatch):+ """The gate rewrites int8 -> fp8 (H3 has no keep-bf16 schedule) and then asks for fp8 tensor+ cores. This loader uses neither: INT8 storage, a Hadamard rotation, an ordinary F.linear. Left+ to the generic path, a CPU H3 int8 load comes back as a 409 for hardware nothing needs."""+ from core.inference.video import assert_video_precision_available++ fam = detect_video_family(H3_BASE)+ monkeypatch.setattr(+ "core.inference.video.precision_fallback_allowed", lambda: False, raising = False+ )+ monkeypatch.setattr(+ "core.inference.video.te_quant_supported", lambda *_a, **_k: False, raising = False+ )+ # The hosted scheme is exempt.+ assert_video_precision_available(fam, model_kind = "pipeline", text_encoder_quant = "int8")+ # A scheme with no hosted artifact is still judged by the generic gate.+ with pytest.raises(RuntimeError):+ assert_video_precision_available(fam, model_kind = "pipeline", text_encoder_quant = "fp8")+++def test_an_explicit_encoder_request_that_engages_nothing_is_refused(monkeypatch):+ """The conventional path already raises here: a render that succeeds at an unrequested+ precision quietly invalidates whatever it was measuring. The modular path has to match, with+ the same documented escape hatch."""+ import core.inference.video as video_mod++ seen: dict = {}++ class _Pipe:+ def get_component_spec(self, _name):+ return types.SimpleNamespace(pretrained_model_name_or_path = "someone/MiniMax-H3")++ def update_components(self, **kwargs):+ seen["seeded"] = kwargs++ def load_components(self, **kwargs):+ seen["loaded"] = kwargs++ fam = detect_video_family(H3_BASE)+ backend = video_mod.VideoBackend()+ fake_diffusers = types.SimpleNamespace(+ ComponentsManager = lambda: object(),+ ModularPipeline = types.SimpleNamespace(from_pretrained = lambda *a, **k: _Pipe()),+ )+ monkeypatch.setattr(video_mod, "precision_fallback_allowed", lambda: False)++ with pytest.raises(RuntimeError) as exc:+ backend._load_h3_modular_pipeline(+ fam = fam,+ repo_id = H3_BASE,+ base = H3_BASE,+ kind = "pipeline",+ dtype = None,+ device = "cpu",+ hf_token = None,+ memory_mode = None,+ text_encoder_quant = "int8",+ diffusers = fake_diffusers,+ torch = None,+ )+ assert "text_encoder_quant" in str(exc.value)+ # Refused BEFORE anything is built, so the refusal costs nothing.+ assert "loaded" not in seen and "seeded" not in seen+++def test_the_staging_skip_reads_the_same_index_the_seed_will(tmp_path):+ """The plan compares repo NAMES, which is right for a plan and wrong for dropping a+ derivative's dense encoder: the seed would then decline and leave load_components to fetch+ 62 GB inline. The staging resolver reads the base's own index first."""+ import json++ backend = VideoBackend()+ fam = detect_video_family(H3_BASE)++ def _base_dir(source):+ root = tmp_path / source.replace("/", "_")+ root.mkdir(parents = True, exist_ok = True)+ entry = [+ "transformers",+ "Qwen3VLForConditionalGeneration",+ {"pretrained_model_name_or_path": source, "subfolder": "text_encoder"},+ ]+ with open(root / "modular_model_index.json", "w", encoding = "utf-8") as handle:+ json.dump({"text_encoder": entry}, handle)+ return str(root)++ canonical = _base_dir(H3_BASE)+ derivative = _base_dir("someone/MiniMax-H3")+ # Both pass the NAME comparison: the directories are called MiniMaxAI_MiniMax-H3 and+ # someone_MiniMax-H3, so this is the index doing the work, not the path.+ assert backend._h3_te_base_index_source(canonical, None) == H3_BASE+ assert backend._h3_te_base_index_source(derivative, None) == "someone/MiniMax-H3"+ assert backend._h3_te_quant_scheme_verified(fam, "int8", derivative, None) is None+ # An unreadable index keeps the dense shards rather than guessing.+ assert backend._h3_te_base_index_source(str(tmp_path / "nope"), None) is None+ assert backend._h3_te_quant_scheme_verified(fam, "int8", str(tmp_path / "nope"), None) is None+++def test_a_projection_left_dense_is_refused_not_budgeted():+ """strict=True proves the artifact and the skeleton name the same tensors, not that they are+ quantized. A projection re-uploaded as a plain dense weight drops out of the swap, loads+ cleanly, and would be recorded as engaged int8 while the resident encoder crept back toward+ 51 GB -- and the VRAM preflight sizes the floor from the ENGAGED scheme."""+ from torch import nn++ from core.inference.video_minimax_h3_te import _int8_convrot_linear_class++ quantized_cls = _int8_convrot_linear_class()++ class _Layer(nn.Module):+ def __init__(self, dense_projection):+ super().__init__()+ self.self_attn = nn.Module()+ self.self_attn.q_proj = (+ nn.Linear(8, 8) if dense_projection else quantized_cls(8, 8, False, 256)+ )++ def _dense_names(stack):+ return [n for n, m in stack.named_modules() if isinstance(m, nn.Linear)]++ # The check the loader makes, on a stack where every projection was swapped.+ assert _dense_names(nn.ModuleList([_Layer(False), _Layer(False)])) == []+ # And on one where a single projection came back dense.+ assert _dense_names(nn.ModuleList([_Layer(False), _Layer(True)])) == ["1.self_attn.q_proj"]+ # The stand-in is not an nn.Linear, so it cannot be mistaken for one.+ assert not isinstance(quantized_cls(8, 8, False, 256), nn.Linear)