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 ComfyUI-format video quants on the int8 / fp8 runtimes (#12851)
Daniel Hane4911f5c2c08
diff --git a/studio/backend/core/inference/diffusion_comfy_quant.py b/studio/backend/core/inference/diffusion_comfy_quant.pyindex 990929afa1e..a03decda104 100644--- a/studio/backend/core/inference/diffusion_comfy_quant.py+++ b/studio/backend/core/inference/diffusion_comfy_quant.py@@ -259,12 +259,21 @@ def comfy_resident_mib(keep_int8: bool,keep_fp8: bool,compute_bytes: int = 2,+ keep_key: Any = None,+ exclude_tokens: Any = (),+ min_features: int = 0,+ fp8_divisible: int = 0,+ key_map: Any = None,) -> Optional[int]:"""What the loader leaves resident for a ComfyUI-quantized file, priced from its header: a quantizedweight a runtime keeps costs its stored bytes, one that is dequantized costs ``numel * compute_bytes``(2x an int8 / fp8 file), every other floating tensor is cast to the compute dtype. The file name saysnothing reliable here (an fp8 file Studio runs natively is not upcast; an int8 one with no runtime is).- None when the header cannot be read. Torch-free."""+ ``keep_key(key)`` limits the count to the keys the loader reads (a file bundling other components);+ an int8 layer whose name holds one of ``exclude_tokens`` is priced dequantized, as Studio's int8 filter+ leaves it, and so is a layer the runtime filter skips (in / out features under ``min_features``, or fp8 features+ not multiples of ``fp8_divisible``). ``key_map`` names layers as the loader's filter sees them (an original-layout+ file). None when the header cannot be read. Torch-free."""try:scan = scan if scan is not None else scan_comfy_quant(path)if scan is None:@@ -273,13 +282,37 @@ def comfy_resident_mib(except Exception: # noqa: BLE001 -- unknown size: the caller keeps its own estimatereturn Noneheader.pop("__metadata__", None)- kept = {- name + ".weight": (layer.format == INT8_TENSORWISE and keep_int8)- or (layer.format == FP8_E4M3 and keep_fp8)- for name, layer in scan.layers.items()- }++ def _fits(shape: Any, divisible: int) -> bool:+ if len(shape or ()) != 2:+ return False+ out_f, in_f = (int(d) for d in shape)+ if min(out_f, in_f) < min_features:+ return False+ return not divisible or not (out_f % divisible or in_f % divisible)++ def _excluded(key: str, shape: Any) -> bool:+ names = [key]+ if key_map is not None:+ try:+ names = [k for k, _rows in key_map(key, tuple(shape or ()))] or names+ except ValueError:+ pass+ return any(t in n for n in names for t in exclude_tokens)++ kept = {}+ for name, layer in scan.layers.items():+ shape = (header.get(name + ".weight") or {}).get("shape")+ kept[name + ".weight"] = (+ layer.format == INT8_TENSORWISE+ and keep_int8+ and not _excluded(name + ".weight", shape)+ and _fits(shape, 0)+ ) or (layer.format == FP8_E4M3 and keep_fp8 and _fits(shape, fp8_divisible))total = 0for key, entry in header.items():+ if keep_key is not None and not keep_key(key):+ continueshape = entry.get("shape") or ()numel = 1for d in shape:@@ -492,6 +525,56 @@ def _decode_rows(return segments+def original_layout(transformer_cls: Any, path: str) -> Optional[dict]:+ """The key map / prepare / dtype hooks for a class with no diffusers single-file converter, or None."""+ name = getattr(transformer_cls, "__name__", "")+ if name == "HunyuanVideo15Transformer3DModel":+ from .video_hv15_comfy import comfy_layout+ elif name == "MiniMaxH3Transformer3DModel":+ from .video_minimax_h3_comfy import comfy_layout+ else:+ return None+ return comfy_layout(path)+++def _apply_key_map(state: dict, kept: list, key_map: Any) -> dict:+ """``state`` (file keys) renamed and row-split by ``key_map``; kept layers become ``(codes, scale, group, format)``.++ Row selections are views where they are one contiguous run, so no layer is copied except a reordered one."""+ import torch++ sources = {+ layer.name + ".weight": (codes, scale, layer.group, layer.format)+ for layer, codes, scale in kept+ }++ def take(value: Any, rows: Any) -> Any:+ if rows is None:+ return value+ if isinstance(value, tuple):+ codes, scale, group, fmt = value+ scale = scale.reshape(-1, 1).expand(codes.shape[0], 1)+ return (take(codes, rows), take(scale, rows), group, fmt)+ if value.dtype not in (torch.int8, torch.uint8) and value.element_size() == 1:+ # float8: concatenation goes through uint8 (not implemented for float8 on every torch)+ return take(value.view(torch.uint8), rows).view(value.dtype)+ parts = [value[int(r) : int(r) + int(n)] for r, n in rows]+ return parts[0] if len(parts) == 1 else torch.cat(parts)++ converted: dict = {}+ for key in list(state):+ value = state.pop(key)+ if value is None:+ value = sources.pop(key)+ data = value[0] if isinstance(value, tuple) else value+ rows_total = data.shape[0] if data.dim() else 0+ for new_key, rows in key_map(key, tuple(data.shape)):+ if rows is not None and any(r < 0 or n <= 0 or r + n > rows_total for r, n in rows):+ raise ValueError(f"{key}: row selection {rows} outside its {rows_total} rows")+ converted[new_key] = take(value, rows)+ return converted++def comfy_torchao_quantized(model: Any) -> bool:"""Whether a ComfyUI load left torchao-quantized weights in ``model`` (eager is several times slower)."""info = getattr(model, "_unsloth_comfy_quant", None) or {}@@ -684,6 +767,11 @@ def load_comfy_quant_transformer(min_features: Optional[int] = None,finalize: bool = True,logger: Any = None,+ keep_key: Any = None,+ pre_convert: Any = None,+ key_map: Any = None,+ prepare_model: Any = None,+ keep_dtype: Any = None,) -> Any:"""Build ``transformer_cls`` from the ComfyUI-quantized ``path``.@@ -695,8 +783,15 @@ def load_comfy_quant_transformer((``comfy_fp8_backend``) the ``float8_e4m3fn`` layers Studio's own fp8 filter selects do the same,as per-row ``Float8Tensor`` weights or native fp8 twins. Everything else is dequantized to thecompute dtype. ``finalize`` applies the small-M padding here (the single-file path); the hosted- prequant loader passes False and pads after placement, as for its own checkpoints. Raises- ``ValueError`` for a checkpoint it must refuse."""+ prequant loader passes False and pads after placement, as for its own checkpoints.++ ``keep_key(key)`` limits the read to the DiT's keys of a file that bundles other components;+ ``pre_convert(state)`` renames keys (never values) before the family converter runs. A family with no+ diffusers single-file converter passes ``key_map(key, shape)`` (or registers it in ``original_layout``):+ ``[(diffusers key, rows)]`` per file key, ``rows`` None (the whole tensor) or ``[(first row, n rows), ...]``;+ ``prepare_model(model)`` reshapes the freshly built model before the weights load, and ``keep_dtype(key)``+ names a dtype a file tensor keeps instead of the compute dtype. Raises ``ValueError`` for a checkpoint it+ must refuse."""import torchfrom safetensors.torch import load_file@@ -713,12 +808,30 @@ def load_comfy_quant_transformer(problem = comfy_quant_error(scan, os.path.basename(path))if problem:raise ValueError(problem)+ if key_map is None:+ layout = original_layout(transformer_cls, path)+ if layout:+ key_map = layout.get("key_map")+ prepare_model = prepare_model or layout.get("prepare_model")+ keep_dtype = keep_dtype or layout.get("keep_dtype")kwargs = dict(sf_kwargs)dtype = kwargs.pop("torch_dtype", None) or kwargs.pop("dtype", None) or torch.bfloat16if dtype is not torch.bfloat16:# Studio's fp8 runtime asserts bf16 weights; an fp16 / fp32 pipeline dequantizes them instead.fp8_backend = None- state = load_file(str(path))+ if keep_key is None:+ state = load_file(str(path))+ else:+ from safetensors import safe_open++ with safe_open(str(path), framework = "pt", device = "cpu") as handle:+ state = {k: handle.get_tensor(k) for k in handle.keys() if keep_key(k)}+ stray = [n for n in scan.layers if n + ".weight" not in state]+ if stray:+ raise ValueError(+ f"{os.path.basename(path)}: ComfyUI-quantized layers outside the denoiser "+ f"({stray[0]}) are not supported"+ )state.pop(LEGACY_SCALED_FP8_KEY, None)for key in [k for k in state if k.endswith(COMFY_QUANT_SUFFIX)]:del state[key]@@ -755,12 +868,18 @@ def load_comfy_quant_transformer(dequantized += 1for key, value in list(state.items()):- if fp16_keep or value is None or not value.is_floating_point() or value.dtype == dtype:+ if value is None or not value.is_floating_point():+ continue+ wanted_dtype = keep_dtype(key) if keep_dtype is not None else None+ if wanted_dtype is not None:+ state[key] = value.to(wanted_dtype)+ continue+ if fp16_keep or value.dtype == dtype:continuestate[key] = value.to(dtype)from accelerate import init_empty_weights- mapping_fn, sfm = _mapping(transformer_cls)+ mapping_fn, sfm = _mapping(transformer_cls) if key_map is None else (None, None)config_repo = kwargs.pop("config", None)subfolder = kwargs.pop("subfolder", None)token = kwargs.pop("token", None)@@ -779,6 +898,8 @@ def load_comfy_quant_transformer(config.update({k: v for k, v in kwargs.items() if k in expected or k in optional})with init_empty_weights():model = transformer_cls.from_config(config)+ if prepare_model is not None:+ prepare_model(model)wanted = model.state_dict()def _convert_tagged(width: Optional[int]) -> dict:@@ -787,14 +908,15 @@ def load_comfy_quant_transformer(rows = torch.arange(codes.shape[0], dtype = torch.float64) + index * _TAGcols = codes.shape[1] if width is None else widthstate[layer.name + ".weight"] = rows.view(-1, 1).expand(codes.shape[0], cols)- if sfm._should_convert_state_dict_to_diffusers(wanted, state):+ checkpoint = pre_convert(dict(state)) if pre_convert is not None else state+ if sfm._should_convert_state_dict_to_diffusers(wanted, checkpoint):out = mapping_fn(config = config,- checkpoint = dict(state),+ checkpoint = dict(checkpoint),**sfm._get_mapping_function_kwargs(mapping_fn, **kwargs),)else:- out = dict(state)+ out = dict(checkpoint)for name in [k for k, v in out.items() if torch.is_tensor(v) and v.dtype == torch.float64]:segments = _decode_rows(name, out[name], sources, width = width)kinds = {(sources[i][0].format, sources[i][0].group) for i, _r, _n in segments}@@ -817,11 +939,21 @@ def load_comfy_quant_transformer(out[name] = (codes, scale, group, fmt)return out- try:- # Narrow tags first (full width costs tens of seconds on a large DiT); anything unproven reruns at full width.- converted = _convert_tagged(_NARROW_TAG_COLUMNS if sources else None)- except Exception: # noqa: BLE001 -- the full-width pass raises the real refusal- converted = _convert_tagged(None)+ if key_map is not None:+ # Rows move whole (no float64 tags: a 21 GB file would need ~5x that in tags)+ converted = _apply_key_map(state, sources, key_map)+ for name, value in converted.items():+ if isinstance(value, tuple) and name in wanted:+ if tuple(wanted[name].shape) != tuple(value[0].shape):+ raise ValueError(+ f"{name}: rebuilt as {tuple(value[0].shape)}, the model expects {tuple(wanted[name].shape)}"+ )+ else:+ try:+ # Narrow tags first (full width is slow on a large DiT); anything unproven reruns at full width.+ converted = _convert_tagged(_NARROW_TAG_COLUMNS if sources else None)+ except Exception: # noqa: BLE001 -- the full-width pass raises the real refusal+ converted = _convert_tagged(None)del stateif fp16_keep:for key, value in list(converted.items()):@@ -918,12 +1050,17 @@ def load_comfy_quant_transformer():# Same rebuild the hosted prequant loader does for buffers made in __init__.model = transformer_cls.from_config(config)+ if prepare_model is not None:+ prepare_model(model)_install_native(model)model.load_state_dict(converted, strict = False, assign = True)+ loaded = set(converted)del converted- # from_single_file ends with model.to(torch_dtype): buffers built in __init__ (Wan's float64 rope) follow it+ # __init__ buffers (Wan's float64 rope) follow the compute dtype; checkpoint buffers keep theirs (H3 curve table)for module_name, module in model.named_modules():for buffer_name, buffer in list(module._buffers.items()):+ if (f"{module_name}.{buffer_name}" if module_name else buffer_name) in loaded:+ continueif buffer is not None and buffer.is_floating_point():want = _dtype_for(f"{module_name}.{buffer_name}")if buffer.dtype != want:diff --git a/studio/backend/core/inference/diffusion_native_quant.py b/studio/backend/core/inference/diffusion_native_quant.pyindex bbedbc9f122..8bd1f7e172b 100644--- a/studio/backend/core/inference/diffusion_native_quant.py+++ b/studio/backend/core/inference/diffusion_native_quant.py@@ -41,6 +41,37 @@ def int8_rotation_group() -> int:return DEFAULT_CONVROT_GROUPSIZE+@lru_cache(maxsize = 1)+def _row_major_op() -> Any:+ """``unsloth_studio::native_row_major``: a row-major copy Inductor cannot re-layout, or None.++ cuBLASLt runs int8 GEMMs only with a row-major activation. Inductor lays the int8 activation out in the stride+ order of whatever produced it (a transposed view upstream, even one passed through ``.contiguous()``, which it+ drops), so ``torch._int_mm`` can get it column-major and fail with CUBLAS_STATUS_NOT_SUPPORTED."""+ import torch++ ns = getattr(torch.ops, "unsloth_studio", None)+ if ns is not None and hasattr(ns, "native_row_major"):+ return ns.native_row_major+ custom_op = getattr(getattr(torch, "library", None), "custom_op", None)+ if custom_op is None:+ return None+ try:++ @custom_op(+ "unsloth_studio::native_row_major", mutates_args = (), schema = "(Tensor x) -> Tensor"+ )+ def _native_row_major(x):+ return x.clone(memory_format = torch.contiguous_format)++ @_native_row_major.register_fake+ def _(x):+ return x.new_empty(x.shape)+ except Exception: # noqa: BLE001 - a registration failure keeps the plain copy+ return None+ return torch.ops.unsloth_studio.native_row_major++@lru_cache(maxsize = 1)def native_linear_class():"""``NativeWeightOnlyLinear``, defined on first use so this module imports torch-free."""@@ -124,6 +155,8 @@ def native_linear_class():"weight_scale", scale.squeeze(1).to(torch.float32).contiguous().view(torch.int32))self.bias = linear.bias+ # Registered here, in eager, so a compiled forward only reads the handle (see _row_major_op).+ self._row_major = _row_major_op() if self.act_int8 and not self.rot_group else Nonedef _stored_weight(self, dtype: Any) -> Any:wq = (@@ -170,6 +203,10 @@ def native_linear_class():)x_scale = x_scale.clamp_(min = 1e-12).div_(127.0)xq = torch.mul(x2, x_scale.reciprocal()).round_().clamp_(-127, 127).to(torch.int8)+ # A rotated input is a matmul output, row-major; an un-rotated one follows its producer's layout.+ if not self.rot_group and (torch.compiler.is_compiling() or not xq.is_contiguous()):+ op = getattr(self, "_row_major", None)+ xq = op(xq) if op is not None else xq.contiguous()acc = torch._int_mm(xq, self.weight_q.t())w_scale = self.weight_scale.view(torch.float32)out = torch.mul(acc, x_scale)diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex dc2f98b9286..e85bfc51b8a 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -56,7 +56,13 @@ from .diffusion_attention import (select_attention_backend,)from .diffusion_flow_shift import apply_comfy_flow_shift-from .diffusion_comfy_quant import load_comfy_quant_transformer, refuse_comfy_quant+from .diffusion_comfy_quant import (+ comfy_fp8_backend,+ comfy_int8_backend,+ comfy_resident_mib,+ load_comfy_quant_transformer,+ refuse_comfy_quant,+)from .diffusion_prequant import scoped_local_files_onlyfrom .diffusion_cache import (FBCACHE_MIN_STEPS,@@ -338,6 +344,99 @@ def assert_video_precision_available()+def _video_comfy_key_map(fam: Any) -> Any:+ """The original-layout key map for a family diffusers has no single-file converter for, else None."""+ if getattr(fam, "transformer_class", None) == "HunyuanVideo15Transformer3DModel":+ from .video_hv15_comfy import hv15_comfy_key_map+ return hv15_comfy_key_map+ return None+++def _h3_single_file_task(+ fam: Any, kind: str, gguf_filename: Optional[str], h3_task: Optional[str]+) -> Optional[str]:+ """The partition an H3 ComfyUI denoiser file serves (its name), unless the request set one."""+ if not (getattr(fam, "modular_workflow", None) and kind == "single_file"):+ return h3_task+ from .video_minimax_h3_comfy import h3_comfy_task++ return h3_task or h3_comfy_task(gguf_filename)+++def _video_comfy_resident(plan: Any, bf16_plan: Any = None) -> bool:+ """A single-file load never re-plans for a runtime quant, so the DiT is resident only if every plan keeps it."""+ return all(plan_keeps_transformer_resident(p) for p in (plan, bf16_plan) if p is not None)+++def _video_comfy_backends(+ fam: Any,+ base: str,+ target: Any,+ plan: Any,+ bf16_plan: Any = None,+ *,+ keep: bool = True,+) -> dict[str, Optional[str]]:+ """``load_comfy_quant_transformer`` backends for a ComfyUI-quantized video DiT: the ones Studio's own int8 / fp8+ quant would run on this card and plan (int8: torchao resident, the torchao-free twin under offload; fp8: torchao+ resident only). ``keep=False`` (the user asked for the bf16 DiT) dequantizes everything."""+ if not keep:+ return {"int8_backend": None, "fp8_backend": None}+ offload = not _video_comfy_resident(plan, bf16_plan)+ name = getattr(fam, "name", None)+ return {+ "int8_backend": comfy_int8_backend(target, name, base, offload = offload),+ "fp8_backend": comfy_fp8_backend(target, name, base, offload = offload),+ }+++def _video_comfy_resident_mib(+ fam: Any,+ base: str,+ target: Any,+ path: Any,+ scan: Any,+ *,+ keep: bool = True,+ keep_key: Any = None,+ offload: bool = False,+) -> Optional[int]:+ """Planning size of a ComfyUI-quantized DiT, before the plan exists: int8 layers are priced as int8 when either+ int8 runtime runs here, fp8 layers as fp8 when the resident fp8 path does, the rest at bf16 (a dequantized fp8+ file is twice its size on disk). ``offload`` prices what an offloaded load keeps instead."""+ name = getattr(fam, "name", None)+ keep_int8 = keep_fp8 = False+ exclude: tuple = ()+ filters: dict = {}+ if keep:+ try:+ from .diffusion_transformer_quant import (+ DEFAULT_MIN_LINEAR_FEATURES,+ divisible_for_scheme,+ exclude_tokens_for_scheme,+ )+ exclude = exclude_tokens_for_scheme(TQ_INT8, name)+ filters = {+ "min_features": DEFAULT_MIN_LINEAR_FEATURES,+ "fp8_divisible": divisible_for_scheme(TQ_FP8),+ }+ except Exception: # noqa: BLE001 -- the estimate then keeps every int8 layer+ exclude = ()+ # Only a resident runtime keeps codes in a resident plan; an offloaded plan is re-priced.+ keep_int8 = bool(comfy_int8_backend(target, name, base, offload = offload))+ keep_fp8 = comfy_fp8_backend(target, name, base, offload = offload) is not None+ return comfy_resident_mib(+ str(path),+ scan,+ keep_int8 = keep_int8,+ keep_fp8 = keep_fp8,+ keep_key = keep_key,+ exclude_tokens = exclude,+ key_map = _video_comfy_key_map(fam),+ **filters,+ )++def _ltx23_prequant_pick(fam: Any,model_kind: str,@@ -569,12 +668,12 @@ def _assert_video_precision_for_target(# 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+ # decided at the seed, which is not a host-level impossibility and so is not this gate's question. Diffusers-path+ # loads only (a pipeline, or an H3 ComfyUI denoiser file). 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"+ model_kind in ("pipeline", "single_file")and getattr(fam, "modular_workflow", None)and h3_te_quant_scheme(te_mode) is not None):@@ -2529,7 +2628,17 @@ class VideoBackend:# refusal placed after them would be unreachable on any install whose diffusers cannot even be imported -- and# these two are exactly the picks that cost the most to discover late.# ── modular-workflow refusals, before anything heavier.- if fam.modular_workflow and kind == "single_file":+ from .video_minimax_h3_comfy import is_h3_comfy_name++ if fam.modular_workflow and kind == "single_file" and is_h3_comfy_name(gguf_filename):+ from .video_minimax_h3_comfy import h3_comfy_task+ file_task = h3_comfy_task(gguf_filename)+ if h3_task and str(h3_task).strip().lower() != file_task:+ raise ValueError(+ f"'{Path(str(gguf_filename)).name}' is the {file_task} partition, but the load asked for "+ f"{h3_task}. Pick the matching checkpoint."+ )+ if fam.modular_workflow and kind == "single_file" and not is_h3_comfy_name(gguf_filename):# A modular workflow has no single-file assembly: its components each load through their own from_pretrained# from the modular index, and nothing consumes a lone .safetensors DiT. Today that only surfaces inside the# loader, i.e. after ~98.7 GB has downloaded AND after the resident pipeline was torn down to make room for@@ -2543,9 +2652,10 @@ class VideoBackend:f"'{fam.name}' cannot load from a single .safetensors checkpoint: it is assembled "f"by its Modular Diffusers workflow, which builds every component from a repo. "f"Load the diffusers pipeline repo '{fam.base_repo}' for the full bfloat16 "- f"model{gguf_hint}."+ f"model{gguf_hint}, or a ComfyUI-quantized MiniMax-H3 denoiser "+ f"(minimax_h3_*_int8_convrot / *_fp8_scaled .safetensors) as its denoiser.")- if fam.modular_workflow and kind == "pipeline":+ if fam.modular_workflow and kind in ("pipeline", "single_file"):# Metal cannot place a modular workflow at all. _load_h3_modular_pipeline hands every non-CPU device to# ComponentsManager.enable_auto_cpu_offload, which reads torch.<device>.mem_get_info and raises# NotImplementedError for a device module without one; torch.mps has never exposed it. Refuse here, before@@ -2563,6 +2673,7 @@ class VideoBackend:f"torch device exposing mem_get_info, and Metal (MPS) does not have it."f"{gguf_hint}")+ if fam.modular_workflow and kind == "pipeline":# Same normaliser the load uses, so a malformed value raises the identical message it would below and only a# real scheme reaches the availability check.requested_scheme = normalize_transformer_quant(transformer_quant)@@ -2902,6 +3013,10 @@ class VideoBackend:else resolve_video_base_repo(fam, kwargs.get("base_repo")))kwargs["base_repo"] = base+ # Before the plan: it stages the partition the file serves (transformer_ref/ for ref2va).+ kwargs["h3_task"] = _h3_single_file_task(+ fam, kind, kwargs.get("gguf_filename"), kwargs.get("h3_task")+ )# An fp8 encoder request loads a hosted pre-cast checkpoint, so neither the estimate nor the pull includes# those dense shards.te_sources = self._te_prequant_sources(@@ -2917,14 +3032,19 @@ class VideoBackend:# 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"),- gpu_ordinal = kwargs.get("gpu_ordinal"),+ # An H3 single file is its own denoiser: no hosted one is planned (or fetched) around it.+ 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"),+ gpu_ordinal = kwargs.get("gpu_ordinal"),+ )+ if kind != "single_file"+ else None)video_auto_denoiser = self._video_planned_auto_denoiser_scheme(fam,@@ -4628,11 +4748,12 @@ class VideoBackend:continueif (kind != "pipeline"- and name.startswith("transformer/")+ # An H3 single file (a ComfyUI denoiser) replaces the partition it serves, transformer_ref/ included.+ and name.startswith(("transformer/", h3_denoiser_prefix))# transformer/config.json is the exception: from_single_file(config = <repo id>, subfolder =# "transformer") reads it off the Hub, so a load that promised to download nothing needs it staged.# Without it the locality gate cleared the pick and the fetch happened after eviction.- and name != "transformer/config.json"+ and not name.endswith("/config.json")):continue# is_prequant_covered_weight is component-agnostic (it matches "<component>/" against a weight suffix), so@@ -4758,6 +4879,7 @@ 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)+ h3_task = _h3_single_file_task(fam, kind, gguf_filename, h3_task)# 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.@@ -4772,8 +4894,9 @@ class VideoBackend:# Sizes the file set from device capacity, so it has to read the selected card.gpu_ordinal = load_kwargs.get("gpu_ordinal"),)- or transformer_quant- )+ if kind != "single_file"+ else None+ ) or transformer_quantvideo_planned = self._video_planned_auto_denoiser_scheme(fam,base = base,@@ -5607,13 +5730,22 @@ class VideoBackend:_nvfp4_install_outcome = ensure_flashinfer_for_nvfp4(device, logger = logger, local_files_only = local_files_only)+ comfy_checkpoint = None+ if kind == "single_file":+ comfy_checkpoint = str(+ self._resolve_checkpoint_path(+ repo_id, gguf_filename, hf_token, local_files_only = local_files_only+ )+ )return self._load_h3_modular_pipeline(diffusers = diffusers,torch = torch,local_files_only = local_files_only,fam = fam,target = target,+ comfy_checkpoint = comfy_checkpoint,repo_id = repo_id,+ gguf_filename = gguf_filename,display_repo_id = display_repo_id,base = base,kind = kind,@@ -5669,13 +5801,42 @@ class VideoBackend:base = repo_id if kind == "pipeline" else base,)transformer_mib: Optional[int] = None+ comfy_scan = None+ # False: the user pinned the bf16 DiT, so quantized layers dequantize.+ comfy_keep = (+ transformer_quant is None or normalize_transformer_quant(transformer_quant) is not None+ )if kind != "pipeline":checkpoint_path = self._resolve_checkpoint_path(repo_id, gguf_filename, hf_token, local_files_only = local_files_only)size_mib = file_size_mib(str(checkpoint_path))+ if kind == "single_file":+ comfy_scan = refuse_comfy_quant(str(checkpoint_path))+ if comfy_scan is None and _video_comfy_key_map(fam) is not None:+ # No diffusers converter: an unquantized original-layout file goes through the key map too.+ from .diffusion_comfy_quant import ComfyQuantScan+ comfy_scan = ComfyQuantScan()if kind == "gguf":transformer_mib = estimate_gguf_resident_mib(size_mib)+ elif comfy_scan is not None:+ ltx_keys = None+ if fam.name == "ltx-2":+ # The file also bundles VAE / audio VAE / vocoder, priced as companions; connectors stay in.+ from .video_ltx2 import ltx23_is_dit_or_connector_key as ltx_keys+ transformer_mib = _video_comfy_resident_mib(+ fam,+ base,+ target,+ checkpoint_path,+ comfy_scan,+ keep = comfy_keep,+ keep_key = ltx_keys,+ )+ if transformer_mib is None:+ transformer_mib = estimate_safetensors_dense_mib(size_mib, fp8_upcast = True)+ if transformer_mib is not None:+ transformer_mib = int(transformer_mib * dtype_scale)else:transformer_mib = estimate_safetensors_dense_mib(size_mib)if fam.name == "ltx-2" and transformer_mib is not None:@@ -5687,7 +5848,9 @@ class VideoBackend:if transformer_mib is not None:transformer_mib = int(transformer_mib * dtype_scale)# Price the plan at the hosted fp8 DiT: the bf16 file size would plan an offload and skip the seed.- ltx23_prequant_pick = transformer_mib is not None and _ltx23_prequant_serves(+ ltx23_prequant_pick = (+ transformer_mib is not None and comfy_scan is None+ ) and _ltx23_prequant_serves(fam,kind,gguf_filename,@@ -5888,6 +6051,23 @@ class VideoBackend:denoiser_seed_scheme = Nonedenoiser_seed_gb = Noneplan, bf16_plan, quant_replanned = _plan_for_te_scale(te_scale, log = False)+ if comfy_scan is not None and not _video_comfy_resident(plan, bf16_plan):+ # Offloaded, fp8 layers dequantize on NVIDIA: price the DiT the load will actually build.+ offload_mib = _video_comfy_resident_mib(+ fam,+ base,+ target,+ checkpoint_path,+ comfy_scan,+ keep = comfy_keep,+ keep_key = ltx_keys,+ offload = True,+ )+ if offload_mib is not None and transformer_mib is not None:+ offload_mib = int(offload_mib * dtype_scale)+ if offload_mib > transformer_mib:+ transformer_mib = offload_mib+ plan, bf16_plan, quant_replanned = _plan_for_te_scale(te_scale, log = False)settled_te_scale = te_scale# On unified memory the plan's 'none' policy is a placement, not a fit: there is no offload tier left to fall@@ -6035,7 +6215,25 @@ class VideoBackend:ltx23_override = Noneltx23_scheme = normalize_transformer_quant(transformer_quant)seeded = None- if ltx23_prequant_pick and plan_keeps_transformer_resident(plan):+ if comfy_scan is not None:+ # The DiT goes in as the override; the assembly reads the rest from the same file (or extras).+ from .video_ltx2 import load_ltx23_comfy_transformer+ ltx23_override = load_ltx23_comfy_transformer(+ checkpoint_path,+ comfy_scan,+ base_repo = base,+ torch_dtype = dtype,+ hf_token = hf_token,+ cache_dir = hub_cache_dir(),+ local_files_only = local_files_only,+ **_video_comfy_backends(+ fam, base, target, plan, bf16_plan, keep = comfy_keep+ ),+ family = fam.name,+ target = target,+ logger = logger,+ )+ elif ltx23_prequant_pick and plan_keeps_transformer_resident(plan):from .video_ltx2 import load_ltx23_prequant_transformerseeded = load_ltx23_prequant_transformer(fam,@@ -6116,19 +6314,19 @@ class VideoBackend:text_encoder_device = ltx23_te_device,)else:- comfy_scan = (- refuse_comfy_quant(str(checkpoint_path)) if kind == "single_file" else None- )if comfy_scan is not None:- # Dequantized on load: a single-file video load never engages the int8 runtime.transformer = load_comfy_quant_transformer(transformer_cls,str(checkpoint_path),comfy_scan,sf_kwargs,- int8_backend = None,+ **_video_comfy_backends(+ fam, base, target, plan, bf16_plan, keep = comfy_keep+ ),family = fam.name,+ target = target,logger = logger,+ key_map = _video_comfy_key_map(fam),)else:transformer = transformer_cls.from_single_file(@@ -6174,6 +6372,14 @@ class VideoBackend:transformer_quant_source: Optional[str] = None# Text encoders streaming around a resident DiT do not move its weights, so torchao stays valid.video_offload = not plan_keeps_transformer_resident(plan)+ comfy_info = (+ getattr(getattr(pipe, "transformer", None), "_unsloth_comfy_quant", None)+ if comfy_scan is not None+ else None+ ) or {}+ comfy_scheme = (+ TQ_INT8 if comfy_info.get("int8") else TQ_FP8 if comfy_info.get("fp8") else None+ )native_scheme = (native_quant_scheme(target,@@ -6185,6 +6391,8 @@ class VideoBackend:)# A seeded denoiser is a torchao checkpoint; the torchao-free path must not claim it.if kind == "pipeline" and not denoiser_injected+ else TQ_INT8+ if comfy_scheme == TQ_INT8 and comfy_info.get("backend") == "native"else None)native_kwargs = (@@ -6212,7 +6420,12 @@ class VideoBackend:transformer_quant_decline = ("auto: the bf16 DiT fits resident, where int8 costs accuracy for little or no speed")- if transformer_quant_pinned is not None and kind != "pipeline" and not denoiser_injected:+ if (+ transformer_quant_pinned is not None+ and kind != "pipeline"+ and not denoiser_injected+ and transformer_quant_pinned != comfy_scheme+ ):transformer_quant_decline = (f"the dense DiT quant applies to full-pipeline loads only, and this is a "f"'{kind}' load, which runs the precision its checkpoint carries"@@ -6228,7 +6441,16 @@ class VideoBackend:# holding a working GPU learns nothing about why it declined.transformer_quant_decline = dense_transformer_unsupported_reason(target)transformer_quant_decline_status = RESOLVED_UNSUPPORTED- if denoiser_injected:+ if comfy_scheme is not None:+ transformer_quant_engaged = comfy_scheme+ transformer_quant_source = (+ f"ComfyUI-quantized checkpoint ({Path(str(checkpoint_path)).name}): "+ f"{comfy_info.get('int8', 0)} int8 / {comfy_info.get('fp8', 0)} fp8 layers kept "+ f"({comfy_info.get('backend') or comfy_info.get('fp8_backend')} runtime), "+ f"{comfy_info.get('dequantized', 0)} dequantized"+ )+ logger.info("video.transformer_quant: %s", transformer_quant_source)+ elif denoiser_injected:transformer_quant_engaged = denoiser_seed_schemetransformer_quant_source = (f"hosted pre-quantized {denoiser_seed_scheme} denoiser checkpoint "@@ -6947,9 +7169,14 @@ class VideoBackend:_nvfp4_install_outcome: Optional[tuple[bool, str]] = None,local_files_only: bool = False,transformer_cache: Optional[str] = None,+ comfy_checkpoint: Optional[str] = None,+ gguf_filename: Optional[str] = None,) -> dict[str, Any]:"""Load MiniMax-H3 through its official Modular Diffusers workflow.+ ``comfy_checkpoint``: a ComfyUI-quantized denoiser file (int8_convrot / fp8_scaled) seeded in place of the+ released or hosted one, its codes kept on Studio's int8 / fp8 runtime.+``transformer_quant`` and ``text_encoder_quant`` are RAW requests, read as the tri-state``_h3_precision_unset`` / ``_h3_precision_pinned_dense`` describe. Unset takes the hostedquantized CONDITIONER and the released bfloat16 DENOISER; ``"none"`` pins the released@@ -6958,8 +7185,23 @@ class VideoBackend:# 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.- if kind != "pipeline":+ if kind != "pipeline" and not (kind == "single_file" and comfy_checkpoint):raise ValueError("MiniMax-H3 Diffusers loading requires the pipeline artifact.")+ comfy_scan = None+ if comfy_checkpoint:+ from .video_minimax_h3_comfy import h3_comfy_task++ comfy_scan = refuse_comfy_quant(comfy_checkpoint)+ if comfy_scan is None:+ from .diffusion_comfy_quant import ComfyQuantScan+ comfy_scan = ComfyQuantScan()+ file_task = h3_comfy_task(comfy_checkpoint)+ if h3_task and h3_task != file_task:+ raise ValueError(+ f"'{Path(comfy_checkpoint).name}' is the {file_task} partition, but the load asked for "+ f"{h3_task}. Pick the matching checkpoint."+ )+ h3_task = file_taskumem_target = target if target is not None else self._device_target()# What the CALLER asked for, kept for the resolved record, before the tri-state below rewrites it. An unset# request must not read back as a pin.@@ -6981,7 +7223,9 @@ class VideoBackend:}if hf_token:load_kwargs["token"] = hf_token- pipe = diffusers.ModularPipeline.from_pretrained(_base_local_dir or repo_id, **load_kwargs)+ pipe = diffusers.ModularPipeline.from_pretrained(+ _base_local_dir or (base if comfy_checkpoint else repo_id), **load_kwargs+ )transformer_quant_engaged: Optional[str] = Nonetransformer_quant_reason = "released bfloat16 components"# "auto" asks the backend to choose. The auto LADDER is still not it -- that quantises a dense module on device,@@ -6994,7 +7238,17 @@ class VideoBackend:if scheme == TQ_AUTO: # defence in depth; _h3_precision_unset already caught "auto"scheme = Noneauto_fallback_scheme = None- if transformer_quant_is_auto:+ # A ComfyUI denoiser file IS the precision choice: no hosted checkpoint is picked around it.+ comfy_scheme = None+ if comfy_scan is not None:+ counts = comfy_scan.counts()+ comfy_scheme = (+ TQ_INT8 if any(k.startswith("int8") for k in counts) else TQ_FP8 if counts else None+ )+ if _h3_precision_pinned_dense(transformer_quant):+ comfy_scheme = None+ scheme = None+ if transformer_quant_is_auto and comfy_scan is None:# 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@@ -7054,8 +7308,73 @@ class VideoBackend:dtype = dtype,device = device,memory_mode = memory_mode,- scheme = scheme,+ scheme = comfy_scheme or scheme,)+ if comfy_scan is not None:+ from .video_minimax_h3_comfy import load_h3_comfy_transformer++ # torchao only: H3's pin / stream / residency path is built on torchao weights, like the hosted ones.+ dense_pin = _h3_precision_pinned_dense(transformer_quant_requested)+ h3_int8 = h3_fp8 = None+ if not dense_pin:+ h3_int8 = (+ "torchao"+ if comfy_int8_backend(umem_target, fam.name, base) == "torchao"+ else None+ )+ h3_fp8 = (+ "torchao"+ if comfy_fp8_backend(umem_target, fam.name, base) == "torchao"+ else None+ )+ if (+ comfy_scheme is not None+ and not dense_pin+ and (h3_int8 if comfy_scheme == TQ_INT8 else h3_fp8) is None+ ):+ raise RuntimeError(+ f"{Path(comfy_checkpoint).name} needs Studio's {comfy_scheme} runtime, which this "+ f"device does not run; dequantized, the denoiser would be the 40 GB bfloat16 model. "+ f"Load '{fam.base_repo}' instead."+ )+ transformer = load_h3_comfy_transformer(+ getattr(diffusers, fam.transformer_class),+ comfy_checkpoint,+ comfy_scan,+ config = _base_local_dir or base,+ subfolder = denoiser_component,+ dtype = dtype,+ hf_token = hf_token,+ cache_dir = hub_cache_dir(),+ local_files_only = local_files_only,+ int8_backend = h3_int8,+ fp8_backend = h3_fp8,+ target = umem_target,+ logger = logger,+ )+ comfy_info = getattr(transformer, "_unsloth_comfy_quant", None) or {}+ engaged = (+ TQ_INT8 if comfy_info.get("int8") else TQ_FP8 if comfy_info.get("fp8") else None+ )+ if engaged is None and comfy_scheme is not None and not dense_pin:+ del transformer+ raise RuntimeError(+ f"{Path(comfy_checkpoint).name} needs Studio's {comfy_scheme} runtime, which this "+ f"device does not run; dequantized, the denoiser would be the 40 GB bfloat16 model. "+ f"Load '{fam.base_repo}' instead."+ )+ transformer.requires_grad_(False)+ # Seeded before load_components, so the released denoiser is never fetched (as for a hosted one).+ pipe.update_components(**{denoiser_component: transformer})+ transformer_quant_engaged = engaged+ transformer_quant_reason = (+ f"ComfyUI-quantized denoiser ({Path(comfy_checkpoint).name}): "+ f"{comfy_info.get('int8', 0)} int8 / {comfy_info.get('fp8', 0)} fp8 layers kept, "+ f"{comfy_info.get('dequantized', 0)} dequantized"+ if engaged is not None+ else f"ComfyUI denoiser ({Path(comfy_checkpoint).name}) at bfloat16"+ )+ logger.info("video.transformer_quant: %s", transformer_quant_reason)if scheme is not None:from .diffusion_prequant import load_prequantized_transformer, resolve_prequant_sourcefrom .diffusion_transformer_quant import DEFAULT_MIN_LINEAR_FEATURES@@ -7887,6 +8206,7 @@ class VideoBackend:placed_ordinal = placed_cuda_ordinal(umem_target),dtype = str(dtype).replace("torch.", ""),kind = kind,+ gguf_filename = gguf_filename if comfy_checkpoint else None,engine = "diffusers",h3_task = workflow,offload_policy = offload_policy,diff --git a/studio/backend/core/inference/video_hv15_comfy.py b/studio/backend/core/inference/video_hv15_comfy.pynew file mode 100644index 00000000000..9bd82a546b3--- /dev/null+++ b/studio/backend/core/inference/video_hv15_comfy.py@@ -0,0 +1,133 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""HunyuanVideo-1.5 original (ComfyUI) layout -> diffusers names, for ``load_comfy_quant_transformer`` (diffusers has+no single-file converter for it). Row-only reshapes keep int8 / fp8 codes and per-row scales exact: fused qkv+projections split by thirds, ``final_layer.adaLN_modulation.1`` swaps ``[shift; scale]`` to ``[scale; shift]``.+Torch-free."""++from __future__ import annotations++import re+from typing import Any++_FIXED = {+ "time_in.mlp.0": "time_embed.timestep_embedder.linear_1",+ "time_in.mlp.2": "time_embed.timestep_embedder.linear_2",+ "time_r_in.mlp.0": "time_embed.timestep_embedder_r.linear_1",+ "time_r_in.mlp.2": "time_embed.timestep_embedder_r.linear_2",+ "txt_in.t_embedder.mlp.0": "context_embedder.time_text_embed.timestep_embedder.linear_1",+ "txt_in.t_embedder.mlp.2": "context_embedder.time_text_embed.timestep_embedder.linear_2",+ "txt_in.c_embedder.linear_1": "context_embedder.time_text_embed.text_embedder.linear_1",+ "txt_in.c_embedder.linear_2": "context_embedder.time_text_embed.text_embedder.linear_2",+ "txt_in.input_embedder": "context_embedder.proj_in",+ "byt5_in.layernorm": "context_embedder_2.norm",+ "byt5_in.fc1": "context_embedder_2.linear_1",+ "byt5_in.fc2": "context_embedder_2.linear_2",+ "byt5_in.fc3": "context_embedder_2.linear_3",+ "vision_in.proj.0": "image_embedder.norm_in",+ "vision_in.proj.1": "image_embedder.linear_1",+ "vision_in.proj.3": "image_embedder.linear_2",+ "vision_in.proj.4": "image_embedder.norm_out",+ "img_in.proj": "x_embedder.proj",+ "cond_type_embedding": "cond_type_embed",+ "final_layer.linear": "proj_out",+ "final_layer.adaLN_modulation.1": "norm_out.linear",+}+_REFINER = {+ "norm1": "norm1",+ "norm2": "norm2",+ "self_attn_proj": "attn.to_out.0",+ "mlp.fc1": "ff.net.0.proj",+ "mlp.fc2": "ff.net.2",+ "adaLN_modulation.1": "norm_out.linear",+}+_DOUBLE = {+ "img_mod.linear": "norm1.linear",+ "txt_mod.linear": "norm1_context.linear",+ "img_attn_q": "attn.to_q",+ "img_attn_k": "attn.to_k",+ "img_attn_v": "attn.to_v",+ "img_attn_q_norm": "attn.norm_q",+ "img_attn_k_norm": "attn.norm_k",+ "img_attn_proj": "attn.to_out.0",+ "txt_attn_q": "attn.add_q_proj",+ "txt_attn_k": "attn.add_k_proj",+ "txt_attn_v": "attn.add_v_proj",+ "txt_attn_q_norm": "attn.norm_added_q",+ "txt_attn_k_norm": "attn.norm_added_k",+ "txt_attn_proj": "attn.to_add_out",+ "img_mlp.fc1": "ff.net.0.proj",+ "img_mlp.fc2": "ff.net.2",+ "txt_mlp.fc1": "ff_context.net.0.proj",+ "txt_mlp.fc2": "ff_context.net.2",+}+# fused projection -> its three diffusers parts, in row order+_FUSED_DOUBLE = {+ "img_attn_qkv": ("attn.to_q", "attn.to_k", "attn.to_v"),+ "txt_attn_qkv": ("attn.add_q_proj", "attn.add_k_proj", "attn.add_v_proj"),+}+_DOUBLE_RE = re.compile(r"^double_blocks\.(\d+)\.(.+)\.(weight|bias)$")+_REFINER_RE = re.compile(r"^txt_in\.individual_token_refiner\.blocks\.(\d+)\.(.+)\.(weight|bias)$")+_PLAIN_RE = re.compile(r"^(.+)\.(weight|bias)$")+++def _thirds(prefix: str, parts: tuple, leaf: str, rows: int) -> list:+ if rows % 3:+ raise ValueError(f"{prefix}: fused projection with {rows} rows is not three equal parts")+ third = rows // 3+ return [(f"{prefix}{part}.{leaf}", [(i * third, third)]) for i, part in enumerate(parts)]+++_DIFFUSERS_PREFIXES = (+ "transformer_blocks.",+ "context_embedder.",+ "context_embedder_2.",+ "x_embedder.",+ "time_embed.",+ "image_embedder.",+ "cond_type_embed.",+ "norm_out.",+ "proj_out.",+)+++def hv15_comfy_key_map(key: str, shape: Any) -> list:+ """``[(diffusers key, rows)]`` for one original-layout HunyuanVideo-1.5 key (see the module docstring). A key+ already in the diffusers layout passes through unchanged."""+ if key.startswith(_DIFFUSERS_PREFIXES):+ return [(key, None)]+ rows = int(shape[0]) if shape else 0+ m = _DOUBLE_RE.match(key)+ if m:+ index, name, leaf = m.groups()+ prefix = f"transformer_blocks.{index}."+ if name in _FUSED_DOUBLE:+ return _thirds(prefix, _FUSED_DOUBLE[name], leaf, rows)+ if name in _DOUBLE:+ return [(f"{prefix}{_DOUBLE[name]}.{leaf}", None)]+ raise ValueError(f"{key}: not a HunyuanVideo-1.5 double-block tensor")+ m = _REFINER_RE.match(key)+ if m:+ index, name, leaf = m.groups()+ prefix = f"context_embedder.token_refiner.refiner_blocks.{index}."+ if name == "self_attn_qkv":+ return _thirds(prefix, ("attn.to_q", "attn.to_k", "attn.to_v"), leaf, rows)+ if name in _REFINER:+ return [(f"{prefix}{_REFINER[name]}.{leaf}", None)]+ raise ValueError(f"{key}: not a HunyuanVideo-1.5 token-refiner tensor")+ m = _PLAIN_RE.match(key)+ if m and m.group(1) in _FIXED:+ name, leaf = m.groups()+ if name == "final_layer.adaLN_modulation.1":+ if rows % 2:+ raise ValueError(f"{key}: odd row count {rows} for a shift / scale pair")+ half = rows // 2+ return [(f"{_FIXED[name]}.{leaf}", [(half, half), (0, half)])]+ return [(f"{_FIXED[name]}.{leaf}", None)]+ raise ValueError(f"{key}: not a HunyuanVideo-1.5 transformer tensor")+++def comfy_layout(_path: str) -> dict:+ """``diffusion_comfy_quant.original_layout`` hooks for HunyuanVideo-1.5."""+ return {"key_map": hv15_comfy_key_map}diff --git a/studio/backend/core/inference/video_ltx2.py b/studio/backend/core/inference/video_ltx2.pyindex 73968d52184..804afea2b31 100644--- a/studio/backend/core/inference/video_ltx2.py+++ b/studio/backend/core/inference/video_ltx2.py@@ -1075,6 +1075,75 @@ def _build_from_config(return model.to(torch_dtype)+def ltx23_is_dit_key(key: str) -> bool:+ """Whether a combined-checkpoint key belongs to the DiT (not the connectors, VAEs or vocoder)."""+ return _checkpoint_group(key)[0] == "dit"+++def ltx23_is_dit_or_connector_key(key: str) -> bool:+ """The keys a single-file DiT plan prices: the connectors stay in, as for a bf16 file."""+ return _checkpoint_group(key)[0] in ("dit", "connectors")+++def _ltx23_pre_convert(state: dict[str, Any]) -> dict[str, Any]:+ """Bare DiT keys with the 2.3-only prefixes renamed, as ``load_ltx23_transformer`` does before the converter."""+ out: dict[str, Any] = {}+ for key, value in state.items():+ bare = key[len(_DIT_PREFIX) :] if key.startswith(_DIT_PREFIX) else key+ for old, new in _TRANSFORMER_PRERENAME:+ if bare.startswith(old):+ bare = new + bare[len(old) :]+ break+ out[bare] = value+ return out+++def load_ltx23_comfy_transformer(+ checkpoint_path: Path | str,+ scan: Any,+ *,+ base_repo: str,+ torch_dtype: Any,+ hf_token: Optional[str],+ cache_dir: Optional[str] = None,+ local_files_only: bool = False,+ int8_backend: Optional[str] = None,+ fp8_backend: Optional[str] = None,+ family: Optional[str] = None,+ target: Any = None,+ logger: Any = None,+) -> Any:+ """The LTX-2.3 DiT of a ComfyUI-quantized single file, for ``load_ltx23_pipeline(transformer_override=...)``.++ Reads only the DiT keys (the assembly reads the connectors, VAEs and vocoder from the same file), applies the+ 2.3 pre-rename and the stock converter, and keeps int8 / fp8 codes where ``load_comfy_quant_transformer`` can."""+ from diffusers import LTX2VideoTransformer3DModel++ from .diffusion_comfy_quant import load_comfy_quant_transformer++ return load_comfy_quant_transformer(+ LTX2VideoTransformer3DModel,+ str(checkpoint_path),+ scan,+ {+ "torch_dtype": torch_dtype,+ "config": base_repo,+ "subfolder": "transformer",+ "token": hf_token,+ "cache_dir": cache_dir,+ "local_files_only": local_files_only,+ **LTX_2_3_TRANSFORMER_CONFIG_OVERRIDES,+ },+ int8_backend = int8_backend,+ fp8_backend = fp8_backend,+ family = family,+ target = target,+ logger = logger,+ keep_key = ltx23_is_dit_key,+ pre_convert = _ltx23_pre_convert,+ )++def load_ltx23_transformer(dit_state: dict[str, Any],*,diff --git a/studio/backend/core/inference/video_minimax_h3_comfy.py b/studio/backend/core/inference/video_minimax_h3_comfy.pynew file mode 100644index 00000000000..0b049a74824--- /dev/null+++ b/studio/backend/core/inference/video_minimax_h3_comfy.py@@ -0,0 +1,198 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""MiniMax-H3 denoisers in ComfyUI's layout for ``load_comfy_quant_transformer``: key map (fused qkv split by thirds,+``mlp.fc1`` ``[gate; value]`` -> SwiGLU ``[value; gate]``, rows move whole so codes and scales stay exact), the pruned+curve adaLN from ``adaln_t_table``'s shape, and the float32 tensors the pruned model keeps. The partition (fl2va /+ref2va) is not in the tensors, so it comes from the file name."""++from __future__ import annotations++import functools+import json+import os+import re+import struct+from typing import Any, Optional++H3_COMFY_TABLE_KEY = "adaln_t_table"+_DROPPED = ("rope.inv_freq",)+_RENAMES = (+ ("video_patch_proj.", "proj_in."),+ ("audio_patch_proj.", "audio_proj_in."),+ ("condition_proj.", "context_embedder."),+ ("final_layer.norm.", "norm_out.norm."),+ ("final_layer.adaln_proj.linear.", "norm_out.linear."),+ ("final_layer.video_out.", "proj_out."),+ ("final_layer.audio_out.", "audio_proj_out."),+ (".attn.q_norm.", ".attn.norm_q."),+ (".attn.k_norm.", ".attn.norm_k."),+ (".attn.out_proj.", ".attn.to_out.0."),+ (".mlp.fc2.", ".ff.net.2."),+ # dense (non-pruned) files only: the timestep MLP the curve table replaces+ ("time_embedder.proj_in.", "time_embedder.linear_1."),+ ("time_embedder.proj_out.", "time_embedder.linear_2."),+)+# Kept float32 like the hosted curve-form checkpoints (ComfyUI stores some of them as float16: widening is exact).+_FP32_PREFIXES = (+ H3_COMFY_TABLE_KEY,+ "time_embedder.",+ "video_patch_proj.",+ "audio_patch_proj.",+ "final_layer.video_out.",+ "final_layer.audio_out.",+)+# Only the pruned (curve-form) adaLN projections are float32; a dense file's are bf16 like the block stack.+_FP32_PRUNED_PREFIXES = ("final_layer.adaln_proj.",)+_FP32_BLOCK = re.compile(r"^blocks\.\d+\.adaln_proj\.linear\.")+++def is_h3_comfy_name(filename: Optional[str]) -> bool:+ """A ``.safetensors`` name that can only be an H3 denoiser (not the Qwen conditioner or a VAE)."""+ name = os.path.basename(str(filename or "")).lower()+ if not name.endswith(".safetensors") or not re.search(r"minimax[_-]h3", name):+ return False+ if any(token in name for token in ("qwen", "vae", "text_encoder", "controlnet", "lora")):+ return False+ # Packed w6a8 / nvfp4 / mxfp files have no Studio runtime.+ return any(t in name for t in ("int8", "fp8", "bf16", "fp16")) and not any(+ t in name for t in ("w6a8", "w4a", "nvfp4", "mxfp")+ )+++def h3_comfy_task(filename: Optional[str]) -> str:+ """The workflow partition a ComfyUI H3 denoiser file serves, from its name: ``ref2va`` or ``fl2va``."""+ return "ref2va" if "ref2va" in os.path.basename(str(filename or "")).lower() else "fl2va"+++def h3_comfy_key_map(key: str, shape: Any) -> list:+ """``[(diffusers key, rows)]`` for one ComfyUI H3 key (``rows``: None or ``[(first row, n rows), ...]``)."""+ if key in _DROPPED:+ return []+ if key == H3_COMFY_TABLE_KEY:+ return [("time_embedder.table", None)]+ name = key+ if name.startswith("token_refiner.blocks."):+ name = "token_refiner.refiner_blocks." + name[len("token_refiner.blocks.") :]+ elif name.startswith("blocks."):+ name = "transformer_blocks." + name[len("blocks.") :]+ for old, new in _RENAMES:+ name = name.replace(old, new)+ rows = int(shape[0]) if shape else 0+ if name.endswith(".attn.qkv_proj.weight"):+ if rows % 3:+ raise ValueError(f"{key}: fused qkv with {rows} rows is not three equal projections")+ third = rows // 3+ stem = name[: -len("qkv_proj.weight")]+ return [+ (f"{stem}{part}.weight", [(i * third, third)])+ for i, part in enumerate(("to_q", "to_k", "to_v"))+ ]+ if name.endswith(".mlp.fc1.weight"):+ if rows % 2:+ raise ValueError(f"{key}: gated fc1 with an odd row count {rows}")+ half = rows // 2+ return [+ (name.replace(".mlp.fc1.weight", ".ff.net.0.proj.weight"), [(half, half), (0, half)])+ ]+ return [(name, None)]+++def h3_comfy_keep_dtype(key: str, pruned: bool = True) -> Optional[Any]:+ """float32 for the tensors H3 keeps at full precision, else None (compute dtype)."""+ if key.startswith(_FP32_PREFIXES) or (+ pruned and (key.startswith(_FP32_PRUNED_PREFIXES) or _FP32_BLOCK.match(key))+ ):+ import torch+ return torch.float32+ return None+++def h3_comfy_curve_metadata(path: str) -> Optional[dict]:+ """``apply_h3_adaln_curve`` metadata for a pruned (curve-form) ComfyUI H3 file, from its header; None for a+ dense one (no ``adaln_t_table``)."""+ with open(path, "rb") as handle:+ size = struct.unpack("<Q", handle.read(8))[0]+ header = json.loads(handle.read(size))+ table = header.get(H3_COMFY_TABLE_KEY)+ if not isinstance(table, dict) or len(table.get("shape") or ()) != 2:+ return None+ grid, dim = (int(v) for v in table["shape"])+ from .video_minimax_h3_adaln import (+ ADALN_CURVE_FORM,+ ADALN_FORM_KEY,+ ADALN_OUT_DTYPE_KEY,+ CURVE_DIM_KEY,+ CURVE_GRID_KEY,+ )++ return {+ ADALN_FORM_KEY: ADALN_CURVE_FORM,+ CURVE_DIM_KEY: dim,+ CURVE_GRID_KEY: grid,+ # The pruned modulation feeds the bf16 block stack, as in the hosted checkpoints built from the same file.+ ADALN_OUT_DTYPE_KEY: "bfloat16",+ }+++def comfy_layout(path: str) -> dict:+ """``diffusion_comfy_quant.original_layout`` hooks for MiniMax-H3: key map, float32 tensors and, for a pruned+ file, the curve adaLN installed on the freshly built model."""+ from .video_minimax_h3_adaln import apply_h3_adaln_curve++ metadata = h3_comfy_curve_metadata(path)+ return {+ "key_map": h3_comfy_key_map,+ "keep_dtype": functools.partial(h3_comfy_keep_dtype, pruned = metadata is not None),+ "prepare_model": (lambda model: apply_h3_adaln_curve(model, metadata))+ if metadata is not None+ else None,+ }+++def load_h3_comfy_transformer(+ transformer_cls: Any,+ path: str,+ scan: Any,+ *,+ config: str,+ subfolder: str,+ dtype: Any,+ hf_token: Optional[str],+ cache_dir: Optional[str],+ local_files_only: bool,+ int8_backend: Optional[str],+ fp8_backend: Optional[str],+ target: Any = None,+ logger: Any = None,+) -> Any:+ """The H3 denoiser of a ComfyUI-quantized file, int8 / fp8 codes kept, curve adaLN installed."""+ from .diffusion_comfy_quant import load_comfy_quant_transformer+ from .video_minimax_h3_adaln import apply_h3_adaln_curve++ metadata = h3_comfy_curve_metadata(path)+ return load_comfy_quant_transformer(+ transformer_cls,+ path,+ scan,+ {+ "torch_dtype": dtype,+ "config": config,+ "subfolder": subfolder,+ "token": hf_token,+ "cache_dir": cache_dir,+ "local_files_only": local_files_only,+ },+ int8_backend = int8_backend,+ fp8_backend = fp8_backend,+ family = "minimax-h3",+ target = target,+ logger = logger,+ key_map = h3_comfy_key_map,+ prepare_model = (+ (lambda model: apply_h3_adaln_curve(model, metadata, logger = logger))+ if metadata is not None+ else None+ ),+ keep_dtype = functools.partial(h3_comfy_keep_dtype, pruned = metadata is not None),+ )diff --git a/studio/backend/tests/test_diffusion_native_quant.py b/studio/backend/tests/test_diffusion_native_quant.pyindex d7d01c9754c..2ff27ecdfdb 100644--- a/studio/backend/tests/test_diffusion_native_quant.py+++ b/studio/backend/tests/test_diffusion_native_quant.py@@ -318,6 +318,28 @@ def test_int_mm_matches_the_dense_layer():assert ((got.float() - ref).norm() / ref.norm()).item() < 0.03[email protected](not torch.cuda.is_available(), reason = "needs a CUDA torch._int_mm")[email protected]("compiled", [False, True])+def test_int_mm_takes_a_transposed_activation_without_rotation(compiled):+ # cuBLASLt runs int8 GEMMs only on a row-major activation. A patch-embed style [B, C, S] -> [B, S, C] view is+ # column-major, and Inductor keeps that layout for the int8 codes even through an explicit .contiguous().+ torch.manual_seed(0)+ lin = torch.nn.Linear(256, 128).to("cuda", torch.bfloat16)+ layer = nq.native_linear_class()(lin, "int8", act_int8 = True)++ def run(x):+ return layer(x.flatten(2).transpose(1, 2).contiguous())++ x = torch.randn(1, 256, 5, 7, 31, device = "cuda", dtype = torch.bfloat16) # 1085 tokens, odd+ ref = lin(x.flatten(2).transpose(1, 2)).float()+ if compiled:+ torch._dynamo.reset()+ run = torch.compile(run)+ got = run(x) if compiled else layer(x.flatten(2).transpose(1, 2))+ assert got.shape == ref.shape and got.dtype == torch.bfloat16+ assert ((got.float() - ref).norm() / ref.norm()).item() < 0.03++def test_rotation_only_applies_to_w8a8_and_divisible_inputs():cls = nq.native_linear_class()lin = torch.nn.Linear(512, 64).to(torch.bfloat16)diff --git a/studio/backend/tests/test_video_comfy_quant.py b/studio/backend/tests/test_video_comfy_quant.pynew file mode 100644index 00000000000..2abda5d8a0e--- /dev/null+++ b/studio/backend/tests/test_video_comfy_quant.py@@ -0,0 +1,744 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""ComfyUI-format quantized VIDEO denoisers: Wan / HunyuanVideo single files on Studio's int8 / fp8 runtimes,+LTX-2.3's bundled file, and MiniMax-H3's converter-less layout (rename + row-only splits + curve adaLN)."""++from __future__ import annotations++import json+import types++import pytest++torch = pytest.importorskip("torch")+safetensors_torch = pytest.importorskip("safetensors.torch")+from torch import nn # noqa: E402++import core.inference.diffusion_comfy_quant as cq # noqa: E402+from core.inference import video as vid # noqa: E402+from core.inference import video_minimax_h3_comfy as h3c # noqa: E402++DIM = 512+++def _conf(**conf) -> torch.Tensor:+ return torch.tensor(list(json.dumps(conf).encode("utf-8")), dtype = torch.uint8)+++def _int8(weight: torch.Tensor) -> tuple:+ w = weight.float()+ scale = w.abs().amax(dim = 1, keepdim = True).clamp_min(1e-8) / 127.0+ return torch.round(w / scale).clamp(-127, 127).to(torch.int8), scale+++def _save(+ path,+ tensors,+ metadata = None,+) -> str:+ safetensors_torch.save_file(+ {k: v.contiguous().clone() for k, v in tensors.items()}, str(path), metadata = metadata+ )+ return str(path)+++def _cos(a, b) -> float:+ return torch.nn.functional.cosine_similarity(+ a.flatten().float(), b.flatten().float(), dim = 0+ ).item()+++def test_h3_key_map_renames_and_splits_rows_only():+ m = h3c.h3_comfy_key_map+ assert m("rope.inv_freq", (16,)) == []+ assert m("adaln_t_table", (1025, 8)) == [("time_embedder.table", None)]+ assert m("blocks.3.attn.out_proj.weight", (5376, 7168)) == [+ ("transformer_blocks.3.attn.to_out.0.weight", None)+ ]+ assert m("token_refiner.blocks.1.attn.q_norm.weight", (128,)) == [+ ("token_refiner.refiner_blocks.1.attn.norm_q.weight", None)+ ]+ assert m("final_layer.adaln_proj.linear.bias", (10752,)) == [("norm_out.linear.bias", None)]+ assert m("condition_proj.weight", (5376, 5120)) == [("context_embedder.weight", None)]+ assert m("blocks.0.mlp.fc2.weight", (5376, 14336)) == [+ ("transformer_blocks.0.ff.net.2.weight", None)+ ]+ assert m("blocks.0.attn.qkv_proj.weight", (21504, 5376)) == [+ ("transformer_blocks.0.attn.to_q.weight", [(0, 7168)]),+ ("transformer_blocks.0.attn.to_k.weight", [(7168, 7168)]),+ ("transformer_blocks.0.attn.to_v.weight", [(14336, 7168)]),+ ]+ # [gate; value] -> SwiGLU's [value; gate]+ assert m("blocks.0.mlp.fc1.weight", (28672, 5376)) == [+ ("transformer_blocks.0.ff.net.0.proj.weight", [(14336, 14336), (0, 14336)])+ ]+ with pytest.raises(ValueError, match = "three equal"):+ m("blocks.0.attn.qkv_proj.weight", (10, 4))+++def test_h3_keeps_the_pruned_model_float32_tensors():+ assert h3c.h3_comfy_keep_dtype("blocks.7.adaln_proj.linear.weight") is torch.float32+ assert h3c.h3_comfy_keep_dtype("adaln_t_table") is torch.float32+ assert h3c.h3_comfy_keep_dtype("final_layer.video_out.bias") is torch.float32+ assert h3c.h3_comfy_keep_dtype("blocks.7.attn.qkv_proj.weight") is None+ assert h3c.h3_comfy_keep_dtype("condition_proj.weight") is None+++ "name, ok, task",+ [+ ("minimax_h3_fl2va_pruned_int8_convrot.safetensors", True, "fl2va"),+ ("minimax_h3_ref2va_pruned_fp8_scaled.safetensors", True, "ref2va"),+ ("MiniMax-H3-Ref2VA-INT8-ConvRot-comfy.safetensors", True, "ref2va"),+ ("MiniMax-H3-INT8-ConvRot-comfy.safetensors", True, "fl2va"),+ ("qwen3vl_32b_minimax_h3_int8_convrot.safetensors", False, None),+ ("minimax_h3_video_vae_int8_convrot.safetensors", False, None),+ ("minimax_h3_fl2va_pruned-Q4_K.gguf", False, None),+ ("wan2.2_ti2v_5B_fp16.safetensors", False, None),+ ("minimax_h3_fl2va_pruned_bf16.safetensors", True, "fl2va"),+ ("minimax_h3_fl2va_pruned_nvfp4.safetensors", False, None),+ ("minimax_h3_fl2va_pruned_w6a8.safetensors", False, None),+ ],+)+def test_h3_single_file_names(name, ok, task):+ assert h3c.is_h3_comfy_name(name) is ok+ if task:+ assert h3c.h3_comfy_task(name) == task+++def test_h3_curve_metadata_comes_from_the_table_shape(tmp_path):+ path = _save(tmp_path / "h3.safetensors", {"adaln_t_table": torch.zeros(1025, 8)})+ meta = h3c.h3_comfy_curve_metadata(path)+ assert meta["curve_grid"] == 1025 and meta["curve_dim"] == 8 and meta["adaln_form"] == "curve"+ dense = _save(tmp_path / "dense.safetensors", {"blocks.0.norm1.weight": torch.zeros(4)})+ assert h3c.h3_comfy_curve_metadata(dense) is None+++class _Attn(nn.Module):+ def __init__(self) -> None:+ super().__init__()+ self.to_q, self.to_k, self.to_v = (nn.Linear(DIM, DIM, bias = False) for _ in range(3))+++class _FF(nn.Module):+ def __init__(self) -> None:+ super().__init__()+ self.proj = nn.Linear(DIM, 2 * DIM, bias = False)+++class _H3Like(nn.Module):+ """Diffusers-side names; the file below stores ComfyUI's fused qkv and [gate; value] fc1."""++ _keep_in_fp32_modules = None+ _keys_to_ignore_on_load_unexpected = None++ def __init__(self, dim: int = DIM) -> None:+ super().__init__()+ self.attn = _Attn()+ self.ff = _FF()+ self.head = nn.Linear(dim, 16)++ @classmethod+ def load_config(cls, repo, **_kwargs):+ return {"dim": DIM}++ @staticmethod+ def _get_signature_keys(_cls):+ return {"dim"}, set()++ @classmethod+ def from_config(cls, config):+ return cls(**config)+++def _h3like_map(key, shape):+ rows = shape[0] if shape else 0+ if key == "attn.qkv.weight":+ t = rows // 3+ return [(f"attn.to_{p}.weight", [(i * t, t)]) for i, p in enumerate("qkv")]+ if key == "fc1.weight":+ h = rows // 2+ return [("ff.proj.weight", [(h, h), (0, h)])]+ return [(key, None)]+++def h3like_file(tmp_path):+ torch.manual_seed(3)+ dense = _H3Like()+ qkv = torch.cat(+ [dense.attn.to_q.weight, dense.attn.to_k.weight, dense.attn.to_v.weight]+ ).detach()+ value, gate = dense.ff.proj.weight.detach().chunk(2)+ fc1 = torch.cat([gate, value]) # ComfyUI's order+ tensors = {+ "head.weight": dense.head.weight.detach().half(),+ "head.bias": dense.head.bias.detach(),+ }+ for name, w in (("attn.qkv", qkv), ("fc1", fc1)):+ q, s = _int8(w)+ tensors[f"{name}.weight"], tensors[f"{name}.weight_scale"] = q, s+ tensors[f"{name}.comfy_quant"] = _conf(format = "int8_tensorwise")+ return _save(tmp_path / "h3like.safetensors", tensors), dense, tensors+++def _load_h3like(path, **kwargs):+ prepared = []+ model = cq.load_comfy_quant_transformer(+ _H3Like,+ path,+ cq.refuse_comfy_quant(path),+ {"torch_dtype": torch.bfloat16, "config": "base/repo"},+ family = "minimax-h3",+ key_map = _h3like_map,+ prepare_model = prepared.append,+ keep_dtype = lambda key: torch.float32 if key.startswith("head.") else None,+ **kwargs,+ )+ return model, prepared+++def test_key_map_dequant_path_rebuilds_the_dense_layers(h3like_file):+ path, dense, _ = h3like_file+ model, prepared = _load_h3like(path, int8_backend = None)+ assert len(prepared) == 1 # the hook ran on the freshly built model+ assert model._unsloth_comfy_quant["dequantized"] == 2+ for part in ("to_q", "to_k", "to_v"):+ assert _cos(getattr(model.attn, part).weight, getattr(dense.attn, part).weight) > 0.9999+ assert _cos(model.ff.proj.weight, dense.ff.proj.weight) > 0.9999 # halves swapped back+ # keep_dtype: the file's float16 head widens to float32 instead of narrowing to the compute dtype+ assert model.head.weight.dtype is torch.float32 and model.head.bias.dtype is torch.float32+++def test_key_map_native_backend_keeps_codes_row_exact(h3like_file):+ from core.inference.diffusion_native_quant import is_native_linear++ path, _dense, tensors = h3like_file+ model, _ = _load_h3like(path, int8_backend = "native")+ assert model._unsloth_comfy_quant["int8"] == 4+ q, s = tensors["attn.qkv.weight"], tensors["attn.qkv.weight_scale"]+ for i, part in enumerate(("to_q", "to_k", "to_v")):+ linear = getattr(model.attn, part)+ assert is_native_linear(linear)+ assert torch.equal(linear.weight_q, q[i * DIM : (i + 1) * DIM])+ assert torch.equal(linear.weight_scale.view(torch.float32), s[i * DIM : (i + 1) * DIM, 0])+ fq, fs = tensors["fc1.weight"], tensors["fc1.weight_scale"]+ proj = model.ff.proj+ assert torch.equal(proj.weight_q, torch.cat([fq[DIM:], fq[:DIM]]))+ assert torch.equal(proj.weight_scale.view(torch.float32), torch.cat([fs[DIM:], fs[:DIM]])[:, 0])+++def test_key_map_torchao_backend_keeps_codes(h3like_file):+ pytest.importorskip("torchao")+ path, _dense, tensors = h3like_file+ model, _ = _load_h3like(path, int8_backend = "torchao")+ if not model._unsloth_comfy_quant["int8"]:+ pytest.skip("this torchao has no Int8Tensor")+ q = tensors["attn.qkv.weight"]+ assert torch.equal(model.attn.to_v.weight.qdata, q[2 * DIM :])+++def test_a_key_map_row_selection_outside_the_tensor_is_refused(h3like_file):+ path, _dense, _ = h3like_file+ with pytest.raises(ValueError, match = "outside"):+ cq.load_comfy_quant_transformer(+ _H3Like,+ path,+ cq.refuse_comfy_quant(path),+ {"torch_dtype": torch.bfloat16, "config": "base/repo"},+ int8_backend = None,+ key_map = lambda key, shape: [(key, [(0, int(shape[0]) + 1)])]+ if shape+ else [(key, None)],+ )+++def test_keep_key_reads_only_the_denoiser_and_refuses_quantized_companions(tmp_path, monkeypatch):+ monkeypatch.setattr(+ cq,+ "_mapping",+ lambda cls: (+ lambda checkpoint = None, **_k: checkpoint,+ types.SimpleNamespace(+ _should_convert_state_dict_to_diffusers = lambda *_a: False,+ _get_mapping_function_kwargs = lambda fn, **kw: {},+ ),+ ),+ )+ torch.manual_seed(4)+ dense = _H3Like()+ tensors = {f"model.diffusion_model.{k}": v.detach() for k, v in dense.state_dict().items()}+ q, s = _int8(dense.attn.to_q.weight)+ tensors["model.diffusion_model.attn.to_q.weight"] = q+ tensors["model.diffusion_model.attn.to_q.weight_scale"] = s+ tensors["model.diffusion_model.attn.to_q.comfy_quant"] = _conf(format = "int8_tensorwise")+ tensors["vae.decoder.weight"] = torch.ones(3)+ path = _save(tmp_path / "bundle.safetensors", tensors)+ seen = []++ def pre(state):+ seen.extend(state)+ return {k.removeprefix("model.diffusion_model."): v for k, v in state.items()}++ model = cq.load_comfy_quant_transformer(+ _H3Like,+ path,+ cq.refuse_comfy_quant(path),+ {"torch_dtype": torch.float32, "config": "base/repo"},+ int8_backend = None,+ keep_key = lambda k: k.startswith("model.diffusion_model."),+ pre_convert = pre,+ )+ assert not any(k.startswith("vae.") for k in seen)+ assert _cos(model.attn.to_q.weight, dense.attn.to_q.weight) > 0.9999+ # a quantized layer the keep_key filters out would be silently dropped: refused instead+ tensors["vae.decoder.weight"] = q+ tensors["vae.decoder.weight_scale"] = s+ tensors["vae.decoder.comfy_quant"] = _conf(format = "int8_tensorwise")+ path = _save(tmp_path / "bundle_q.safetensors", tensors)+ with pytest.raises(ValueError, match = "outside the denoiser"):+ cq.load_comfy_quant_transformer(+ _H3Like,+ path,+ cq.refuse_comfy_quant(path),+ {"torch_dtype": torch.float32, "config": "base/repo"},+ int8_backend = None,+ keep_key = lambda k: k.startswith("model.diffusion_model."),+ pre_convert = pre,+ )+++def test_ltx23_pre_convert_strips_the_prefix_and_renames_23_keys():+ from core.inference.video_ltx2 import (+ _ltx23_pre_convert,+ ltx23_is_dit_key,+ ltx23_is_dit_or_connector_key,+ )++ out = _ltx23_pre_convert(+ {+ "model.diffusion_model.transformer_blocks.0.attn1.to_q.weight": 1,+ "model.diffusion_model.prompt_adaln_single.linear.weight": 2,+ "audio_prompt_adaln_single.linear.bias": 3,+ }+ )+ assert out == {+ "transformer_blocks.0.attn1.to_q.weight": 1,+ "prompt_adaln.linear.weight": 2,+ "audio_prompt_adaln.linear.bias": 3,+ }+ assert ltx23_is_dit_key("model.diffusion_model.transformer_blocks.0.ff.net.0.proj.weight")+ assert not ltx23_is_dit_key("vae.decoder.conv_in.weight")+ assert not ltx23_is_dit_key("model.diffusion_model.video_embeddings_connector.x.weight")+ assert ltx23_is_dit_or_connector_key(+ "model.diffusion_model.video_embeddings_connector.x.weight"+ )+ assert not ltx23_is_dit_or_connector_key("vocoder.conv.weight")+++def test_resident_mib_prices_kept_layers_as_stored_and_the_rest_at_bf16(tmp_path):+ rows, cols = 2048, 1024+ q = torch.zeros(rows, cols, dtype = torch.int8)+ tensors = {+ "a.weight": q,+ "a.weight_scale": torch.ones(rows, 1),+ "a.comfy_quant": _conf(format = "int8_tensorwise"),+ "audio.weight": q,+ "audio.weight_scale": torch.ones(rows, 1),+ "audio.comfy_quant": _conf(format = "int8_tensorwise"),+ "b.weight": torch.zeros(rows, cols, dtype = torch.float8_e4m3fn),+ "b.weight_scale": torch.ones(()),+ "b.comfy_quant": _conf(format = "float8_e4m3fn"),+ "n.weight": torch.zeros(rows, cols, dtype = torch.float32),+ "vae.w": torch.zeros(rows, cols, dtype = torch.bfloat16),+ }+ path = _save(tmp_path / "plan.safetensors", tensors)+ scan = cq.refuse_comfy_quant(path)+ n = rows * cols+ small = 8 * rows + 4 + sum(v.numel() for k, v in tensors.items() if k.endswith(".comfy_quant"))++ def mib(total):+ return -(-total // (1024 * 1024))++ # int8 kept (minus the excluded name), fp8 dequantized, fp32 narrowed, VAE out of the read+ got = cq.comfy_resident_mib(+ path,+ scan,+ keep_int8 = True,+ keep_fp8 = False,+ exclude_tokens = ("audio",),+ keep_key = lambda k: not k.startswith("vae."),+ )+ assert got == mib(n + 2 * n + 2 * n + 2 * n + small)+ everything = cq.comfy_resident_mib(path, scan, keep_int8 = True, keep_fp8 = True)+ assert everything == mib(3 * n + 2 * n + 2 * n + small)+ # nothing kept: every quantized layer at bf16, twice its stored size+ assert cq.comfy_resident_mib(path, scan, keep_int8 = False, keep_fp8 = False) == mib(+ 3 * 2 * n + 2 * n + 2 * n + small+ )+++def _plan(resident: bool):+ return types.SimpleNamespace(resident = resident)+++def test_video_backends_follow_studio_rules(monkeypatch):+ monkeypatch.setattr(vid, "plan_keeps_transformer_resident", lambda p: p.resident)+ calls = []++ def int8(+ target,+ family,+ base,+ *,+ offload = False,+ ):+ calls.append(("int8", offload))+ return "native" if offload else "torchao"++ def fp8(+ target,+ family,+ base,+ *,+ offload = False,+ ):+ calls.append(("fp8", offload))+ return None if offload else "torchao"++ monkeypatch.setattr(vid, "comfy_int8_backend", int8)+ monkeypatch.setattr(vid, "comfy_fp8_backend", fp8)+ fam = types.SimpleNamespace(name = "wan2.2-ti2v-5b")+ assert vid._video_comfy_backends(fam, "b", None, _plan(True), _plan(True)) == {+ "int8_backend": "torchao",+ "fp8_backend": "torchao",+ }+ # either plan offloading the DiT means the hooks move it: int8 takes the torchao-free twin, fp8 dequantizes+ assert vid._video_comfy_backends(fam, "b", None, _plan(True), _plan(False)) == {+ "int8_backend": "native",+ "fp8_backend": None,+ }+ assert vid._video_comfy_backends(fam, "b", None, _plan(True), keep = False) == {+ "int8_backend": None,+ "fp8_backend": None,+ }+++def test_video_plan_size_prices_only_what_runs_quantized(monkeypatch, tmp_path):+ rows, cols = 1024, 1024+ tensors = {+ "x.weight": torch.zeros(rows, cols, dtype = torch.float8_e4m3fn),+ "x.weight_scale": torch.ones(()),+ "x.comfy_quant": _conf(format = "float8_e4m3fn"),+ }+ path = _save(tmp_path / "f.safetensors", tensors)+ scan = cq.refuse_comfy_quant(path)+ fam = types.SimpleNamespace(name = "wan2.2-ti2v-5b")+ monkeypatch.setattr(vid, "comfy_int8_backend", lambda *a, **k: None)+ monkeypatch.setattr(vid, "comfy_fp8_backend", lambda *a, **k: "torchao")+ n = rows * cols+ assert (+ vid._video_comfy_resident_mib(fam, "b", None, path, scan) == 2+ ) # 1 MiB of codes + scale + config+ monkeypatch.setattr(vid, "comfy_fp8_backend", lambda *a, **k: None)+ assert vid._video_comfy_resident_mib(fam, "b", None, path, scan) == 3+ assert vid._video_comfy_resident_mib(fam, "b", None, path, scan, keep = False) == 3+ assert n == 2**20+++def test_h3_single_file_validation_accepts_a_comfy_denoiser_and_refuses_the_rest():+ from core.inference.video import VideoBackend++ backend = VideoBackend()+ for name in (+ "qwen3vl_32b_minimax_h3_bf16.safetensors",+ "minimax_h3_video_vae_fp16.safetensors",+ ):+ with pytest.raises(ValueError, match = "single .safetensors checkpoint"):+ backend.validate_load_request(+ "MiniMaxAI/MiniMax-H3", gguf_filename = name, model_kind = "single_file"+ )+ try:+ backend.validate_load_request(+ "MiniMaxAI/MiniMax-H3",+ gguf_filename = "minimax_h3_fl2va_pruned_int8_convrot.safetensors",+ model_kind = "single_file",+ )+ except (+ ValueError,+ ImportError,+ ) as exc: # later probes may refuse or need diffusers; never the modular refusal+ assert "single .safetensors checkpoint" not in str(exc)+++def test_hv15_key_map_renames_splits_and_swaps_rows_only():+ from core.inference.video_hv15_comfy import hv15_comfy_key_map as m++ assert m("double_blocks.3.img_attn_qkv.weight", (6144, 2048)) == [+ ("transformer_blocks.3.attn.to_q.weight", [(0, 2048)]),+ ("transformer_blocks.3.attn.to_k.weight", [(2048, 2048)]),+ ("transformer_blocks.3.attn.to_v.weight", [(4096, 2048)]),+ ]+ assert m("double_blocks.3.txt_attn_qkv.bias", (6144,)) == [+ ("transformer_blocks.3.attn.add_q_proj.bias", [(0, 2048)]),+ ("transformer_blocks.3.attn.add_k_proj.bias", [(2048, 2048)]),+ ("transformer_blocks.3.attn.add_v_proj.bias", [(4096, 2048)]),+ ]+ assert m("double_blocks.0.img_mod.linear.weight", (12288, 2048)) == [+ ("transformer_blocks.0.norm1.linear.weight", None)+ ]+ assert m("double_blocks.0.txt_mlp.fc2.weight", (2048, 8192)) == [+ ("transformer_blocks.0.ff_context.net.2.weight", None)+ ]+ assert m("txt_in.individual_token_refiner.blocks.1.self_attn_qkv.weight", (6144, 2048))[2] == (+ "context_embedder.token_refiner.refiner_blocks.1.attn.to_v.weight",+ [(4096, 2048)],+ )+ assert m("txt_in.individual_token_refiner.blocks.1.adaLN_modulation.1.bias", (4096,)) == [+ ("context_embedder.token_refiner.refiner_blocks.1.norm_out.linear.bias", None)+ ]+ # [shift; scale] -> diffusers' [scale; shift]+ assert m("final_layer.adaLN_modulation.1.weight", (4096, 2048)) == [+ ("norm_out.linear.weight", [(2048, 2048), (0, 2048)])+ ]+ assert m("vision_in.proj.3.weight", (2048, 1152)) == [("image_embedder.linear_2.weight", None)]+ assert m("img_in.proj.weight", (2048, 65, 1, 1, 1)) == [("x_embedder.proj.weight", None)]+ assert m("cond_type_embedding.weight", (3, 2048)) == [("cond_type_embed.weight", None)]+ assert m("transformer_blocks.0.attn.to_q.weight", (2048, 2048)) == [+ ("transformer_blocks.0.attn.to_q.weight", None)+ ]+ with pytest.raises(ValueError, match = "not a HunyuanVideo-1.5"):+ m("double_blocks.0.mystery.weight", (4, 4))+ with pytest.raises(ValueError, match = "not a HunyuanVideo-1.5"):+ m("something_else.weight", (4, 4))+++def test_hv15_is_the_family_with_a_key_map():+ assert (+ vid._video_comfy_key_map(+ types.SimpleNamespace(transformer_class = "HunyuanVideo15Transformer3DModel")+ )+ is not None+ )+ assert (+ vid._video_comfy_key_map(types.SimpleNamespace(transformer_class = "WanTransformer3DModel"))+ is None+ )+++def test_original_layouts_are_found_by_class_name(tmp_path):+ hv = type("HunyuanVideo15Transformer3DModel", (), {})+ from core.inference.video_hv15_comfy import hv15_comfy_key_map++ assert cq.original_layout(hv, "x.safetensors")["key_map"] is hv15_comfy_key_map+ path = _save(tmp_path / "h3.safetensors", {"adaln_t_table": torch.zeros(1025, 8)})+ h3 = cq.original_layout(type("MiniMaxH3Transformer3DModel", (), {}), path)+ assert h3["key_map"] is h3c.h3_comfy_key_map+ assert h3["keep_dtype"].func is h3c.h3_comfy_keep_dtype+ assert h3["keep_dtype"].keywords == {"pruned": True}+ assert callable(h3["prepare_model"])+ assert cq.original_layout(type("WanTransformer3DModel", (), {}), path) is None+++def test_a_class_without_a_converter_uses_its_registered_layout(h3like_file, monkeypatch):+ """Any caller (a hosted ComfyUI-format twin included) gets the layout without passing a key map."""+ path, dense, _ = h3like_file+ monkeypatch.setattr(+ cq,+ "original_layout",+ lambda cls, p: {"key_map": _h3like_map, "keep_dtype": None, "prepare_model": None}+ if cls is _H3Like+ else None,+ )+ model = cq.load_comfy_quant_transformer(+ _H3Like,+ path,+ cq.refuse_comfy_quant(path),+ {"torch_dtype": torch.float32, "config": "base/repo"},+ int8_backend = None,+ )+ assert _cos(model.ff.proj.weight, dense.ff.proj.weight) > 0.9999+++def test_h3_single_file_task_comes_from_the_file_name_unless_requested():+ from core.inference.video import _h3_single_file_task+ from core.inference.video_families import detect_video_family++ h3 = detect_video_family("MiniMaxAI/MiniMax-H3")+ ref = "minimax_h3_ref2va_pruned_int8_convrot.safetensors"+ assert _h3_single_file_task(h3, "single_file", ref, None) == "ref2va"+ assert _h3_single_file_task(h3, "single_file", ref, "fl2va") == "fl2va"+ assert _h3_single_file_task(h3, "pipeline", None, None) is None+ wan = detect_video_family("Wan-AI/Wan2.2-TI2V-5B-Diffusers")+ assert _h3_single_file_task(wan, "single_file", ref, None) is None+++def test_h3_single_file_is_refused_on_metal(monkeypatch):+ from core.inference.diffusion_device import DiffusionDeviceTarget+ from core.inference.video import VideoBackend++ monkeypatch.setattr(+ "core.inference.video.resolve_diffusion_device_target",+ lambda: DiffusionDeviceTarget(+ device = "mps",+ dtype = None,+ backend = "mps",+ vendor = None,+ supports_model_cpu_offload = False,+ supports_default_torch_compile = False,+ supports_pinned_transfer = False,+ supports_float64 = False,+ ),+ )+ with pytest.raises(ValueError, match = "cannot run on Apple Silicon"):+ VideoBackend().validate_load_request(+ "MiniMaxAI/MiniMax-H3",+ gguf_filename = "minimax_h3_fl2va_pruned_int8_convrot.safetensors",+ model_kind = "single_file",+ )+++def test_h3_single_file_conditioner_skips_the_generic_precision_gate(monkeypatch):+ from core.inference.video import assert_video_precision_available+ from core.inference.video_families import detect_video_family++ fam = detect_video_family("MiniMaxAI/MiniMax-H3")+ 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+ )+ assert_video_precision_available(+ fam,+ model_kind = "single_file",+ text_encoder_quant = "int8",+ checkpoint_filename = "minimax_h3_fl2va_pruned_int8_convrot.safetensors",+ )+++def test_resident_mib_prices_layers_the_runtime_filter_skips_at_bf16(tmp_path):+ big, small, ragged = (2048, 1024), (2048, 64), (2048, 1000)+ tensors = {}+ for name, shape, fmt, dtype in (+ ("i_big", big, "int8_tensorwise", torch.int8),+ ("i_small", small, "int8_tensorwise", torch.int8),+ ("f_ragged", ragged, "float8_e4m3fn", torch.float8_e4m3fn),+ ):+ tensors[f"{name}.weight"] = torch.zeros(shape, dtype = dtype)+ tensors[f"{name}.weight_scale"] = torch.ones(shape[0], 1)+ tensors[f"{name}.comfy_quant"] = _conf(format = fmt)+ path = _save(tmp_path / "filter.safetensors", tensors)+ scan = cq.refuse_comfy_quant(path)+ kw = dict(keep_int8 = True, keep_fp8 = True)+ loose = cq.comfy_resident_mib(path, scan, **kw)+ strict = cq.comfy_resident_mib(path, scan, **kw, min_features = 128, fp8_divisible = 16)+ extra = 2048 * 64 + 2048 * 1000 # i_small and f_ragged: stored 1 B, priced 2 B+ assert strict * 1024 * 1024 - loose * 1024 * 1024 >= extra - 1024 * 1024+ assert strict > loose+++def test_a_checkpoint_buffer_keeps_its_keep_dtype(h3like_file, tmp_path):+ path, _dense, tensors = h3like_file+ table = torch.randn(9, 4, dtype = torch.float64)+ path = _save(tmp_path / "h3like_table.safetensors", {**tensors, "table": table.half()})++ def add_table(model):+ model.register_buffer("table", torch.empty(9, 4, dtype = torch.float32))++ model = cq.load_comfy_quant_transformer(+ _H3Like,+ path,+ cq.refuse_comfy_quant(path),+ {"torch_dtype": torch.bfloat16, "config": "base/repo"},+ family = "minimax-h3",+ key_map = _h3like_map,+ prepare_model = add_table,+ keep_dtype = lambda key: torch.float32+ if key in ("table",) or key.startswith("head.")+ else None,+ int8_backend = None,+ )+ assert model.table.dtype is torch.float32+ assert torch.equal(model.table, table.half().float())+++def test_offloaded_plan_size_prices_fp8_that_only_runs_resident(monkeypatch, tmp_path):+ rows = cols = 1024+ tensors = {+ "x.weight": torch.zeros(rows, cols, dtype = torch.float8_e4m3fn),+ "x.weight_scale": torch.ones(()),+ "x.comfy_quant": _conf(format = "float8_e4m3fn"),+ }+ path = _save(tmp_path / "f.safetensors", tensors)+ scan = cq.refuse_comfy_quant(path)+ fam = types.SimpleNamespace(name = "wan2.2-ti2v-5b")+ monkeypatch.setattr(vid, "comfy_int8_backend", lambda *a, **k: None)+ monkeypatch.setattr(+ vid, "comfy_fp8_backend", lambda *a, offload = False, **k: None if offload else "torchao"+ )+ assert vid._video_comfy_resident_mib(fam, "b", None, path, scan) == 2+ assert vid._video_comfy_resident_mib(fam, "b", None, path, scan, offload = True) == 3+++def test_dense_h3_maps_its_timestep_mlp_and_keeps_adaln_at_compute_dtype():+ m = h3c.h3_comfy_key_map+ assert m("time_embedder.proj_in.weight", (5376, 256)) == [+ ("time_embedder.linear_1.weight", None)+ ]+ assert m("time_embedder.proj_out.bias", (2688,)) == [("time_embedder.linear_2.bias", None)]+ keep = h3c.h3_comfy_keep_dtype+ assert keep("time_embedder.proj_in.weight", pruned = False) is torch.float32+ assert keep("blocks.3.adaln_proj.linear.weight", pruned = False) is None+ assert keep("final_layer.adaln_proj.linear.bias", pruned = False) is None+ assert keep("blocks.3.adaln_proj.linear.weight") is torch.float32+ assert keep("final_layer.video_out.weight", pruned = False) is torch.float32+++def test_h3_single_file_refuses_a_conflicting_partition_before_staging():+ from core.inference.video import VideoBackend+ with pytest.raises(ValueError, match = "ref2va partition"):+ VideoBackend().validate_load_request(+ "MiniMaxAI/MiniMax-H3",+ gguf_filename = "minimax_h3_ref2va_pruned_int8_convrot.safetensors",+ model_kind = "single_file",+ h3_task = "fl2va",+ )+++def test_resident_mib_excludes_by_the_converted_name(tmp_path):+ from core.inference.video_hv15_comfy import hv15_comfy_key_map++ shape = (2048, 1024)+ tensors = {+ "time_in.mlp.0.weight": torch.zeros(shape, dtype = torch.int8),+ "time_in.mlp.0.weight_scale": torch.ones(shape[0], 1),+ "time_in.mlp.0.comfy_quant": _conf(format = "int8_tensorwise"),+ }+ path = _save(tmp_path / "hv.safetensors", tensors)+ scan = cq.refuse_comfy_quant(path)+ kw = dict(keep_int8 = True, keep_fp8 = False, exclude_tokens = ("timestep_embed",))+ plain = cq.comfy_resident_mib(path, scan, **kw)+ mapped = cq.comfy_resident_mib(path, scan, **kw, key_map = hv15_comfy_key_map)+ assert (+ mapped > plain+ ) # time_embed.timestep_embedder.linear_1 is excluded, so it is priced at bf16+++def test_offload_only_int8_is_priced_dense_for_a_resident_plan(monkeypatch, tmp_path):+ rows = cols = 1024+ tensors = {+ "x.weight": torch.zeros(rows, cols, dtype = torch.int8),+ "x.weight_scale": torch.ones(rows, 1),+ "x.comfy_quant": _conf(format = "int8_tensorwise"),+ }+ path = _save(tmp_path / "i.safetensors", tensors)+ scan = cq.refuse_comfy_quant(path)+ fam = types.SimpleNamespace(name = "wan2.2-ti2v-5b")+ monkeypatch.setattr(+ vid, "comfy_int8_backend", lambda *a, offload = False, **k: "native" if offload else None+ )+ monkeypatch.setattr(vid, "comfy_fp8_backend", lambda *a, **k: None)+ assert vid._video_comfy_resident_mib(fam, "b", None, path, scan) == 3+ assert vid._video_comfy_resident_mib(fam, "b", None, path, scan, offload = True) == 2diff --git a/studio/backend/tests/test_video_prequant.py b/studio/backend/tests/test_video_prequant.pyindex cab0a0d4c2d..0cc289bc83f 100644--- a/studio/backend/tests/test_video_prequant.py+++ b/studio/backend/tests/test_video_prequant.py@@ -376,7 +376,8 @@ def test_a_modular_family_refuses_a_single_file_load_before_anything_downloads()with pytest.raises(ValueError) as excinfo:backend.validate_load_request("MiniMaxAI/MiniMax-H3",- gguf_filename = "minimax_h3_fl2va_pruned_int8_rowwise.safetensors",+ # A ComfyUI-quantized denoiser file is the one H3 single file Studio loads; anything else is refused.+ gguf_filename = "qwen3vl_32b_minimax_h3_bf16.safetensors",model_kind = "single_file",)message = str(excinfo.value)diff --git a/studio/backend/tests/test_video_routes.py b/studio/backend/tests/test_video_routes.pyindex e056979c180..7526cf9429c 100644--- a/studio/backend/tests/test_video_routes.py+++ b/studio/backend/tests/test_video_routes.py@@ -1648,7 +1648,8 @@ def test_video_download_plan_refuses_an_unsupported_combination_before_staging(c"/api/inference/video/download-plan",json = {"model_path": "MiniMaxAI/MiniMax-H3",- "gguf_filename": "minimax_h3_fl2va_pruned_int8_rowwise.safetensors",+ # Only a ComfyUI-quantized denoiser loads as an H3 single file; the conditioner never does.+ "gguf_filename": "qwen3vl_32b_minimax_h3_bf16.safetensors","model_kind": "single_file",},)