Skip to content

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.

Studio video: cache the offloaded native int8 DiT per expert (Wan2.2-A14B warm load 210 s to 21 s) (#15152)

Daniel Hanf9c7416de172
diff --git a/studio/backend/core/inference/diffusion_native_cache.py b/studio/backend/core/inference/diffusion_native_cache.py
new file mode 100644
index 00000000000..454f3871f5f
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_native_cache.py
@@ -0,0 +1,456 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Local cache of native (torchao-free) runtime-quantized denoisers, one entry per component.
+
+Shares ``diffusion_prequant_cache``'s root, locks, manifest and eviction; the key adds the native build spec so an
+entry is only served to the identical native build.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import shutil
+import tempfile
+import time
+from typing import Any, Optional
+
+from . import diffusion_prequant_cache as _cache
+
+NATIVE_LAYOUT_VERSION = 1
+NATIVE_META_KEY = "unsloth_native_layers"
+
+
+def native_spec(
+ scheme: str,
+ family: Optional[str],
+ *,
+ act_int8: bool,
+ scale_dtype: Any = None,
+) -> dict:
+ """Everything beside the dense weights that ``quantize_transformer``'s native path bakes into the bytes."""
+ from .diffusion_native_quant import NATIVE_INT8, int8_rotation_group
+ from .diffusion_transformer_quant import DEFAULT_MIN_LINEAR_FEATURES, exclude_tokens_for_scheme
+
+ act = bool(act_int8) and scheme == NATIVE_INT8
+ return {
+ "layout": NATIVE_LAYOUT_VERSION,
+ "scheme": scheme,
+ "act_int8": act,
+ "rot_group": int(int8_rotation_group()) if act else 0,
+ "scale_dtype": str(scale_dtype) if scale_dtype is not None and not act else None,
+ "min_features": DEFAULT_MIN_LINEAR_FEATURES,
+ "exclude_name_tokens": sorted(set(exclude_tokens_for_scheme(scheme, family)) | {"lora_"}),
+ "require_bf16": True,
+ }
+
+
+def _key_for(
+ fam: Any,
+ spec: dict,
+ base: Optional[str],
+ component: str,
+ *,
+ base_id: Optional[str] = None,
+ shards: Optional[list] = None,
+) -> Optional[tuple[str, dict]]:
+ if spec.get("scheme") not in _cache.CACHEABLE_SCHEMES:
+ return None
+ if shards is None:
+ shards = _cache.source_shards(base, component)
+ if not shards:
+ return None
+ fp = _cache.source_fingerprint(shards)
+ if fp is None:
+ return None
+ try:
+ import torch
+ torch_minor = _cache._minor(torch.__version__)
+ except Exception: # noqa: BLE001
+ torch_minor = None
+ parts = {
+ "policy": _cache.POLICY_VERSION,
+ "family": str(getattr(fam, "name", fam if isinstance(fam, str) else None) or ""),
+ "transformer_class": str(getattr(fam, "transformer_class", None) or ""),
+ "scheme": spec["scheme"],
+ "component": component,
+ "source": fp,
+ "base": _cache.base_identity(base_id if base_id is not None else base),
+ "torch": torch_minor,
+ "native": dict(spec),
+ }
+ return _cache.cache_key(parts), parts
+
+
+def _header_metadata(path: Any) -> Optional[dict]:
+ raw = _cache.read_header_bytes(path)
+ if raw is None:
+ return None
+ try:
+ meta = json.loads(raw[8:].decode("utf-8")).get("__metadata__") or {}
+ return json.loads(meta[NATIVE_META_KEY])
+ except Exception: # noqa: BLE001 - not a native entry
+ return None
+
+
+def lookup(
+ fam: Any,
+ spec: dict,
+ *,
+ base_repo: Optional[str],
+ source_base: Optional[str] = None,
+ component: str = "transformer",
+ logger: Any = None,
+) -> Optional[str]:
+ """``source_base`` is where the dense shards are found (default ``base_repo``), as for ``save``.
+
+ Path of a cached native build of ``component`` for this exact dense source and ``spec``, or None. Local reads
+ (plus the Hub staleness probe a torchao hit also makes); never raises."""
+ if not _cache.enabled():
+ return None
+ try:
+ recorded_base = str(base_repo or getattr(fam, "base_repo", "") or "")
+ source = source_base or base_repo or getattr(fam, "base_repo", None)
+ key = shards = None
+ seen: set = set()
+ for candidate in (
+ _cache.source_shards(source, component),
+ *_cache._shard_sets(source, component),
+ ):
+ if not candidate or tuple(candidate) in seen:
+ continue
+ seen.add(tuple(candidate))
+ keyed = _key_for(fam, spec, source, component, base_id = recorded_base, shards = candidate)
+ if (
+ keyed is not None
+ and (_cache.cache_root() / keyed[0] / _cache.MANIFEST_NAME).is_file()
+ ):
+ key, shards = keyed[0], candidate
+ break
+ if key is None:
+ return None
+ if _cache._hub_source_stale(shards, logger):
+ return None
+ with _cache._cache_lock():
+ artifact = _cache._entry(key)
+ if artifact is None:
+ return None
+ with _cache._lock:
+ rejected = os.path.realpath(str(artifact)) in _cache._REJECTED
+ if rejected:
+ return None
+ _cache._touch(artifact.parent)
+ meta = _header_metadata(artifact)
+ if not isinstance(meta, dict) or meta.get("key") != key or meta.get("spec") != spec:
+ _cache.note_rejected(artifact, logger)
+ return None
+ return str(artifact)
+ except Exception as exc: # noqa: BLE001
+ _cache._log(logger, "warning", f"native lookup failed: {type(exc).__name__}: {exc}")
+ return None
+
+
+def _layer_facts(transformer: Any, spec: dict) -> Optional[dict]:
+ """``{fqn: facts}`` of every native Linear, or None when one disagrees with ``spec`` (a build the key does not
+ describe)."""
+ from .diffusion_native_quant import is_native_linear
+
+ layers: dict = {}
+ for name, mod in transformer.named_modules():
+ if not is_native_linear(mod):
+ continue
+ if mod.scheme != spec["scheme"] or bool(mod.act_int8) != bool(spec["act_int8"]):
+ return None
+ rot = int(getattr(mod, "rot_group", 0) or 0)
+ if rot not in (0, int(spec["rot_group"])):
+ return None
+ layers[name] = {
+ "scheme": mod.scheme,
+ "act_int8": bool(mod.act_int8),
+ "rot_group": rot,
+ "in_features": int(mod.in_features),
+ "out_features": int(mod.out_features),
+ "compute_dtype": str(mod.compute_dtype).replace("torch.", ""),
+ "fp8_format": str(getattr(mod, "fp8_format", "float8_e4m3fn")),
+ "bias": getattr(mod, "bias", None) is not None,
+ }
+ return layers or None
+
+
+def save(
+ transformer: Any,
+ fam: Any,
+ spec: dict,
+ *,
+ base_repo: Optional[str],
+ source_base: Optional[str] = None,
+ component: str = "transformer",
+ logger: Any = None,
+ cancel_check: Optional[Any] = None,
+) -> Optional[str]:
+ """Persist a just-built native denoiser; returns the artifact path or None (logged). Never raises."""
+ if not _cache.enabled():
+ return None
+ t0 = time.perf_counter()
+ root = _cache.cache_root()
+ try:
+ import torch
+
+ info = dict(getattr(transformer, "_unsloth_runtime_quant_info", None) or {})
+ if not info.get("native") or info.get("scheme") != spec.get("scheme"):
+ _cache._log(
+ logger,
+ "info",
+ f"native {component}: skipped (not a native {spec.get('scheme')} build)",
+ )
+ return None
+ if info.get("cache_path"):
+ return None
+ recorded_base = str(base_repo or getattr(fam, "base_repo", "") or "")
+ keyed = _key_for(fam, spec, source_base or base_repo, component, base_id = recorded_base)
+ if keyed is None:
+ _cache._log(
+ logger,
+ "info",
+ f"native {component}: skipped (dense source shards not found locally)",
+ )
+ return None
+ key, parts = keyed
+ layers = _layer_facts(transformer, spec)
+ if layers is None:
+ _cache._log(logger, "info", f"native {component}: skipped (layers differ from the key)")
+ return None
+ with _cache._writer_lock(root, key) as locked:
+ if not locked:
+ _cache._log(logger, "info", f"native {component}: skipped (no cross-process lock)")
+ return None
+ existing = _cache._entry(key)
+ replacing = None
+ if existing is not None:
+ real = os.path.realpath(str(existing))
+ with _cache._lock:
+ replacing = real if real in _cache._REJECTED else None
+ if replacing is None:
+ _cache._log(
+ logger, "info", f"native {component}: skipped (already cached as {key})"
+ )
+ return None
+ # an entry load() rejected (same size, bad bytes) would otherwise block every rebuild for good
+ _cache._log(
+ logger, "info", f"native {component}: replacing {key} (it failed to load)"
+ )
+ state = transformer.state_dict()
+ if any(".lora_" in k or k.startswith("lora_") for k in state):
+ _cache._log(logger, "info", f"native {component}: skipped (baked LoRA adapters)")
+ return None
+ for name, tensor in state.items():
+ if (
+ type(tensor) not in (torch.Tensor, torch.nn.Parameter)
+ or tensor.device.type == "meta"
+ ):
+ _cache._log(
+ logger,
+ "info",
+ f"native {component}: skipped ({name} is not a plain tensor)",
+ )
+ return None
+ nbytes = sum(_cache._tensor_bytes(t) for t in state.values())
+ budget = _cache.max_cache_bytes()
+ if budget is not None and nbytes > budget:
+ _cache._log(
+ logger, "info", f"native {component}: skipped (larger than the cache budget)"
+ )
+ return None
+ root.mkdir(parents = True, exist_ok = True)
+ need = nbytes + max(_cache._DISK_MARGIN_BYTES, nbytes // 20)
+ free = shutil.disk_usage(str(root)).free
+ if free < need:
+ _cache.evict(root = root, extra_free_bytes = need - free, keep = key, logger = logger)
+ free = shutil.disk_usage(str(root)).free
+ if free < need:
+ _cache._log(
+ logger,
+ "info",
+ f"native {component}: skipped (disk short: {free / 2**30:.1f} GiB free, "
+ f"need {need / 2**30:.1f} GiB)",
+ )
+ return None
+ meta = {
+ "key": key,
+ "spec": spec,
+ "family": parts["family"],
+ "component": component,
+ "base_model_id": recorded_base,
+ "transformer_class": parts["transformer_class"] or type(transformer).__name__,
+ "torch_version": str(torch.__version__),
+ "layers": layers,
+ }
+ header = {NATIVE_META_KEY: json.dumps(meta, sort_keys = True)}
+ kdir = root / key
+ if replacing is not None:
+ _cache._reclaim(kdir)
+ with _cache._lock:
+ _cache._REJECTED.discard(replacing)
+ kdir.mkdir(parents = True, exist_ok = True)
+ fd, tmp = tempfile.mkstemp(
+ dir = str(kdir), prefix = f".{_cache.FILE_NAME}.", suffix = _cache._TEMP_SUFFIX
+ )
+ os.close(fd)
+ try:
+ hasher = hashlib.sha256()
+ size = _cache.write_streaming_safetensors(
+ tmp, state, header, cancel_check = cancel_check, hasher = hasher
+ )
+ del state
+ os.replace(tmp, kdir / _cache.FILE_NAME)
+ tmp = None
+ finally:
+ if tmp is not None:
+ try:
+ os.unlink(tmp)
+ except OSError:
+ pass
+ sha = hasher.hexdigest()
+ _cache._record_verified(kdir, sha)
+ manifest = {
+ "key": key,
+ "bytes": size,
+ "sha256": sha,
+ "created": time.time(),
+ "parts": parts,
+ }
+ _cache._atomic_bytes(
+ kdir / _cache.MANIFEST_NAME,
+ json.dumps(manifest, indent = 1, default = str).encode("utf-8"),
+ )
+ _cache._touch(kdir)
+ _cache._log(
+ logger,
+ "info",
+ f"native {component}: saved ({key}, {size / 2**30:.2f} GiB in {time.perf_counter() - t0:.1f} s)",
+ )
+ _cache.evict(logger = logger, keep = key)
+ return str(kdir / _cache.FILE_NAME)
+ except Exception as exc: # noqa: BLE001 - a cache write never fails a load (the caller re-checks a cancel)
+ _cache._log(
+ logger,
+ "warning",
+ f"native {component}: save failed: {type(exc).__name__}: {str(exc)[:200]}",
+ )
+ return None
+
+
+def load(
+ path: str,
+ transformer_cls: Any,
+ config_source: str,
+ *,
+ component: str = "transformer",
+ spec: dict,
+ config_kwargs: Optional[dict] = None,
+ logger: Any = None,
+ cancel_check: Optional[Any] = None,
+) -> Any:
+ """Rebuild the cached native ``component`` (config from ``config_source``), or None. Never raises; a cancel
+ from ``cancel_check`` is a miss that leaves the entry usable (the caller re-checks it)."""
+ cancelled = [False]
+
+ def _check() -> None:
+ if cancel_check is None:
+ return
+ try:
+ cancel_check()
+ except BaseException:
+ cancelled[0] = True
+ raise
+
+ try:
+ import torch
+ from safetensors.torch import load_file
+
+ from .diffusion_native_quant import native_linear_class
+
+ if not _cache.verify_entry(path, logger, cancel_check = _check):
+ if not cancelled[0]:
+ _cache.note_rejected(path, logger)
+ return None
+ meta = _header_metadata(path)
+ if (
+ not isinstance(meta, dict)
+ or meta.get("spec") != spec
+ or meta.get("component") != component
+ ):
+ _cache.note_rejected(path, logger)
+ return None
+ layers = meta.get("layers") or {}
+ config = transformer_cls.load_config(
+ config_source, subfolder = component, **(config_kwargs or {})
+ )
+ try:
+ from accelerate import init_empty_weights
+ except Exception: # noqa: BLE001
+ return None
+ # Buffers stay real: non-persistent ones (rope tables) are built by __init__ as a dense load builds them.
+ with init_empty_weights(include_buffers = False):
+ model = transformer_cls.from_config(config)
+ state = load_file(str(path))
+ cls = native_linear_class()
+ for fqn, facts in layers.items():
+ parent_name, _, leaf = fqn.rpartition(".")
+ parent = model.get_submodule(parent_name) if parent_name else model
+ stand_in = torch.nn.Linear(
+ int(facts["in_features"]),
+ int(facts["out_features"]),
+ bias = bool(facts["bias"]),
+ device = "meta",
+ dtype = getattr(torch, str(facts["compute_dtype"])),
+ )
+ codes = state[f"{fqn}.weight_q"]
+ if facts["scheme"] != "int8":
+ codes = codes.view(getattr(torch, str(facts.get("fp8_format") or "float8_e4m3fn")))
+ scale = state[f"{fqn}.weight_scale"].view(torch.float32)
+ setattr(
+ parent,
+ leaf,
+ cls(
+ stand_in,
+ facts["scheme"],
+ act_int8 = bool(facts["act_int8"]),
+ rot_group = int(facts["rot_group"] or 0),
+ codes = codes,
+ scale = scale,
+ ),
+ )
+ model.load_state_dict(state, strict = True, assign = True)
+ del state
+ if any(t.device.type == "meta" for t in (*model.parameters(), *model.buffers())):
+ _cache._log(logger, "warning", f"native {component}: entry left meta tensors; not used")
+ _cache.note_rejected(path, logger)
+ return None
+ model.eval()
+ try:
+ model._unsloth_runtime_quant = spec["scheme"]
+ model._unsloth_runtime_quant_info = {
+ "scheme": spec["scheme"],
+ "native": True,
+ "cache_path": str(path),
+ }
+ except Exception: # noqa: BLE001
+ pass
+ _cache.note_hit(path, logger)
+ return model
+ except Exception as exc: # noqa: BLE001 - an unusable entry is a miss
+ if cancelled[0]:
+ return None
+ _cache._log(
+ logger,
+ "warning",
+ f"native {component}: read failed: {type(exc).__name__}: {str(exc)[:200]}",
+ )
+ try:
+ _cache.note_rejected(path, logger)
+ except Exception: # noqa: BLE001
+ pass
+ return None
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 8df6bc98286..2766c438cd2 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -3142,6 +3142,155 @@ def _save_runtime_quant_to_cache(
logger.warning("diffusion.prequant_cache: skipped (%s)", exc)
+def _video_native_cache_spec(
+ fam: Any,
+ *,
+ target: Any,
+ transformer_quant: Optional[str],
+ plan: Any,
+ kind: str,
+ source_dir: Optional[str],
+) -> Optional[dict]:
+ """Cache spec of the native build an OFFLOADED CUDA load's runtime quant makes, else None. Never raises.
+
+ Must use the same inputs as the quant step (``native_scheme`` / ``native_kwargs``) so a hit replays that build."""
+ try:
+ if kind != "pipeline" or getattr(fam, "modular_workflow", None):
+ return None
+ if getattr(target, "device", None) != "cuda" or plan is None:
+ return None
+ if plan_keeps_transformer_resident(plan):
+ return None
+ requested = normalize_transformer_quant(transformer_quant)
+ if requested is None:
+ return None
+ pinned = None if requested == TQ_AUTO else requested
+ scheme = native_quant_scheme(
+ target,
+ _auto_offload_scheme(transformer_quant) if pinned is None else pinned,
+ family = fam.name,
+ offload = True,
+ )
+ if scheme is None:
+ return None
+ if stored_denoiser_precision(source_dir) is not None:
+ return None # the quant step declines a widened checkpoint
+ from .diffusion_native_cache import native_spec
+
+ return native_spec(
+ scheme,
+ fam.name,
+ act_int8 = scheme == TQ_INT8 and native_int8_act(target),
+ )
+ except Exception: # noqa: BLE001 -- unanswerable: no cache, the dense build runs
+ return None
+
+
+def _native_spec_for(scheme: Optional[str], fam: Any, act_int8: Any) -> Optional[dict]:
+ try:
+ from .diffusion_native_cache import native_spec
+ return native_spec(scheme, getattr(fam, "name", None), act_int8 = bool(act_int8))
+ except Exception: # noqa: BLE001
+ return None
+
+
+def _save_native_quant_to_cache(
+ fam: Any,
+ views: Any,
+ spec: dict,
+ *,
+ base: Optional[str],
+ source: Optional[str],
+ cancel_check: Any = None,
+) -> None:
+ """Cache every expert of a native runtime build, one entry per component. Never raises."""
+ try:
+ from .diffusion_native_cache import save
+ from .video_denoiser_prequant import denoiser_components
+
+ components = denoiser_components(fam)
+ views = list(views or ())
+ if len(components) != len(views):
+ logger.info("diffusion.prequant_cache: native skipped (denoiser views != components)")
+ return
+ for component, view in zip(components, views):
+ save(
+ getattr(view, "transformer", None),
+ fam,
+ spec,
+ base_repo = base,
+ source_base = source,
+ component = component,
+ logger = logger,
+ cancel_check = cancel_check,
+ )
+ except Exception as exc: # noqa: BLE001 - a cache write never fails a load
+ logger.warning("diffusion.prequant_cache: native skipped (%s)", exc)
+
+
+def _read_native_quant_from_cache(
+ fam: Any,
+ spec: Optional[dict],
+ *,
+ base: Optional[str],
+ source: Optional[str],
+ config_kwargs: dict,
+ cancel_check: Any = None,
+) -> dict[str, Any]:
+ """``{component: module}`` for EVERY denoiser from the native cache, or ``{}`` (all or nothing). Never raises."""
+ if spec is None:
+ return {}
+ try:
+ from utils.torch_warmup import close_dynamo_import_window
+ close_dynamo_import_window(logger) # a no-op once the load closed it above
+ except Exception as exc: # noqa: BLE001 - optimisation only
+ logger.debug("dynamo pre-import skipped: %r", exc)
+ try:
+ import diffusers
+
+ from .diffusion_native_cache import load, lookup
+ from .video_denoiser_prequant import denoiser_components
+
+ transformer_cls = getattr(diffusers, str(getattr(fam, "transformer_class", "")), None)
+ if transformer_cls is None:
+ return {}
+ components = denoiser_components(fam)
+ paths = {}
+ for component in components:
+ path = lookup(
+ fam, spec, base_repo = base, source_base = source, component = component, logger = logger
+ )
+ if path is None:
+ return {}
+ paths[component] = path
+ out: dict[str, Any] = {}
+ for component, path in paths.items():
+ module = load(
+ path,
+ transformer_cls,
+ str(source or base),
+ component = component,
+ spec = spec,
+ config_kwargs = config_kwargs,
+ logger = logger,
+ cancel_check = cancel_check,
+ )
+ if module is None:
+ return {}
+ out[component] = module
+ logger.info(
+ "video.transformer_quant: read %d native %s denoiser(s) for %s from the local prequant "
+ "cache; the dense denoiser shards are not loaded",
+ len(out),
+ spec.get("scheme"),
+ getattr(fam, "name", None),
+ )
+ return out
+ except Exception as exc: # noqa: BLE001 - a cache problem is a miss
+ logger.warning("diffusion.prequant_cache: native read skipped (%s)", exc)
+ return {}
+
+
# The planner DECIDED against the seed (not "never ran"); a load must not re-take it after teardown.
DENOISER_SEED_DECLINED = "__declined__"
@@ -8924,6 +9073,36 @@ class VideoBackend:
raise_on_unified_memory_shortfall(
plan, family = getattr(fam, "name", None), logger = logger
)
+ # Offloaded: no hosted checkpoint matches the native build; replay this machine's own (all experts or none).
+ native_cache_spec = (
+ _video_native_cache_spec(
+ fam,
+ target = target,
+ transformer_quant = transformer_quant,
+ plan = plan,
+ kind = kind,
+ source_dir = _base_local_dir or repo_id,
+ )
+ if kind == "pipeline" and not denoiser_injected
+ else None
+ )
+ native_cache_hits = _read_native_quant_from_cache(
+ fam,
+ native_cache_spec,
+ base = base,
+ source = _base_local_dir or fetch_base,
+ config_kwargs = {}
+ if _base_local_dir
+ else {
+ "cache_dir": hub_cache_dir(),
+ "local_files_only": local_files_only,
+ **({"token": hf_token} if hf_token else {}),
+ **_pinned_base_kwargs(),
+ },
+ cancel_check = lambda: self._raise_if_video_load_superseded(_load_token),
+ )
+ self._raise_if_video_load_superseded(_load_token)
+ pipe_kwargs.update(native_cache_hits)
# Injection is best-effort (a missing checkpoint falls back to the dense encoder), but the scoped pre-download
# already dropped those shards and from_pretrained cannot re-fetch from a local snapshot dir, so top them up
# here. ltx23 never reaches this: it gets the hub id.
@@ -9310,6 +9489,45 @@ class VideoBackend:
if native_scheme is not None
else {}
)
+ native_cached = (
+ bool(native_cache_hits)
+ and native_cache_spec is not None
+ and video_offload
+ and native_scheme == native_cache_spec.get("scheme")
+ and bool(native_kwargs.get("act_int8")) == bool(native_cache_spec.get("act_int8"))
+ and _video_native_cache_spec(
+ fam,
+ target = target,
+ transformer_quant = transformer_quant,
+ plan = plan,
+ kind = kind,
+ source_dir = _base_local_dir or repo_id,
+ )
+ == native_cache_spec
+ )
+ if native_cache_hits and not native_cached:
+ # Not the build this load makes after all: put the dense experts back and let the quant below run.
+ logger.warning(
+ "video.transformer_quant: the cached native denoiser(s) do not match this load's "
+ "build; loading the dense denoiser shards instead"
+ )
+ dense_cls = getattr(diffusers, fam.transformer_class)
+ for component in native_cache_hits:
+ pipe.register_modules(
+ **{
+ component: dense_cls.from_pretrained(
+ _base_local_dir or fetch_base,
+ subfolder = component,
+ torch_dtype = dtype,
+ cache_dir = hub_cache_dir(),
+ local_files_only = local_files_only,
+ **({"token": hf_token} if hf_token else {}),
+ **_pinned_base_kwargs(),
+ )
+ }
+ )
+ native_cache_hits = {}
+ views = _views_for(pipe, fam)
# Auto quantises a video DiT only to keep it resident: with bf16 resident, int8 fails the default LPIPS bar.
if (
kind == "pipeline"
@@ -9366,6 +9584,18 @@ class VideoBackend:
denoiser_seed_scheme,
fam.name,
)
+ elif native_cached:
+ transformer_quant_engaged = native_scheme
+ transformer_quant_source = (
+ native_quant_reason(getattr(pipe, "transformer", None), native_scheme)
+ + "; read back from this machine's prequant cache of the same build"
+ )
+ logger.info(
+ "video.transformer_quant: %s native denoiser(s) read from the local prequant cache "
+ "for %s; skipping the runtime quantise",
+ native_scheme,
+ fam.name,
+ )
elif (
kind == "pipeline"
and normalize_transformer_quant(transformer_quant) is not None
@@ -9453,8 +9683,24 @@ class VideoBackend:
)
if engaged:
transformer_quant_engaged = engaged[0]
+ if (
+ native_cache_spec is not None
+ and native_scheme == engaged[0]
+ and native_cache_spec
+ == _native_spec_for(native_scheme, fam, native_kwargs.get("act_int8"))
+ ):
+ # The native build is read back under auto too: the cache replays the pick, never makes it.
+ _save_native_quant_to_cache(
+ fam,
+ views,
+ native_cache_spec,
+ base = base,
+ source = _base_local_dir or fetch_base,
+ cancel_check = lambda: self._raise_if_video_load_superseded(_load_token),
+ )
+ self._raise_if_video_load_superseded(_load_token)
# Only explicit schemes read the cache back, so an auto save would be a write nothing opens.
- if transformer_quant_pinned is not None:
+ elif transformer_quant_pinned is not None:
_save_runtime_quant_to_cache(
fam,
views,
diff --git a/studio/backend/tests/test_video_native_prequant_cache.py b/studio/backend/tests/test_video_native_prequant_cache.py
new file mode 100644
index 00000000000..e6ac8af8631
--- /dev/null
+++ b/studio/backend/tests/test_video_native_prequant_cache.py
@@ -0,0 +1,359 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Native prequant cache for offloaded two-expert video DiTs: round trip, keys, all-or-nothing reads, routing."""
+
+from __future__ import annotations
+
+import os
+
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+torch = pytest.importorskip("torch")
+diffusers = pytest.importorskip("diffusers")
+pytest.importorskip("safetensors")
+pytest.importorskip("accelerate")
+
+BACKEND = Path(__file__).resolve().parents[1]
+if str(BACKEND) not in sys.path:
+ sys.path.insert(0, str(BACKEND))
+
+from core.inference import diffusion_native_cache as NC # noqa: E402
+from core.inference import diffusion_prequant_cache as C # noqa: E402
+from core.inference import diffusion_transformer_quant as tq # noqa: E402
+from core.inference.video_families import detect_video_family # noqa: E402
+
+FAMILY = "wan2.2-t2v-a14b"
+COMPONENTS = ("transformer", "transformer_2")
+
+
+def _family():
+ return detect_video_family("Wan-AI/Wan2.2-T2V-A14B-Diffusers", override = FAMILY)
+
+
+def _tiny_config() -> dict:
+ # 2 x 256 = 512 wide: every attention / FFN Linear passes the 512 filter and the g256 ConvRot divides it.
+ return dict(
+ patch_size = (1, 2, 2),
+ num_attention_heads = 2,
+ attention_head_dim = 256,
+ in_channels = 4,
+ out_channels = 4,
+ text_dim = 64,
+ freq_dim = 32,
+ ffn_dim = 1024,
+ num_layers = 2,
+ cross_attn_norm = True,
+ qk_norm = "rms_norm_across_heads",
+ eps = 1e-6,
+ rope_max_seq_len = 64,
+ )
+
+
+def base_dir(tmp_path):
+ root = tmp_path / "Wan2.2-T2V-A14B-Diffusers"
+ for seed, component in enumerate(COMPONENTS):
+ torch.manual_seed(seed)
+ model = diffusers.WanTransformer3DModel(**_tiny_config())
+ model.save_pretrained(str(root / component), safe_serialization = True)
+ return str(root)
+
+
[email protected](autouse = True)
+def cache_root(tmp_path, monkeypatch):
+ root = tmp_path / "cache"
+ monkeypatch.setenv(C.ENV_DIR, str(root))
+ monkeypatch.delenv(C.ENV_MODE, raising = False)
+ monkeypatch.setattr(C, "_hub_source_stale", lambda shards, logger = None: False)
+ return root
+
+
+def _spec(act_int8 = True):
+ return NC.native_spec("int8", FAMILY, act_int8 = act_int8)
+
+
+def _fresh_build(
+ base_dir: str,
+ component: str,
+ act_int8 = True,
+):
+ """What the offloaded load's runtime quant builds: dense bf16 from_pretrained, then the native pass."""
+ model = diffusers.WanTransformer3DModel.from_pretrained(
+ base_dir, subfolder = component, torch_dtype = torch.bfloat16
+ )
+ view = types.SimpleNamespace(transformer = model)
+ assert (
+ tq._quantize_native(
+ view,
+ "int8",
+ family = FAMILY,
+ min_features = tq.DEFAULT_MIN_LINEAR_FEATURES,
+ act_int8 = act_int8,
+ logger = None,
+ )
+ == "int8"
+ )
+ return model
+
+
+def _inputs():
+ g = torch.Generator().manual_seed(7)
+ hidden = torch.randn(1, 4, 3, 8, 8, generator = g).to(torch.bfloat16)
+ text = torch.randn(1, 6, 64, generator = g).to(torch.bfloat16)
+ t = torch.tensor([500])
+ return hidden, t, text
+
+
+def _assert_same_module(a, b):
+ sa, sb = a.state_dict(), b.state_dict()
+ assert sa.keys() == sb.keys()
+ for k in sa:
+ assert sa[k].dtype == sb[k].dtype, k
+ assert torch.equal(sa[k], sb[k]), k
+ ba, bb = (
+ dict(a.named_buffers()),
+ dict(b.named_buffers()),
+ ) # non-persistent too (rope tables, rot_h)
+ assert ba.keys() == bb.keys()
+ for k in ba:
+ assert ba[k].dtype == bb[k].dtype and torch.equal(ba[k], bb[k]), k
+ for (na, ma), (nb, mb) in zip(a.named_modules(), b.named_modules()):
+ assert na == nb and type(ma).__name__ == type(mb).__name__, na
+ assert ma.extra_repr() == mb.extra_repr(), na
+ pa, pb = dict(a.named_parameters()), dict(b.named_parameters())
+ assert pa.keys() == pb.keys()
+ for k in pa:
+ assert pa[k].requires_grad == pb[k].requires_grad, k
+
+
+def test_round_trip_is_bit_identical_per_expert(base_dir):
+ fam = _family()
+ spec = _spec()
+ cls = diffusers.WanTransformer3DModel
+ for component in COMPONENTS:
+ fresh = _fresh_build(base_dir, component)
+ assert NC.save(fresh, fam, spec, base_repo = base_dir, component = component) is not None
+ path = NC.lookup(fam, spec, base_repo = base_dir, component = component)
+ assert path is not None
+ cached = NC.load(path, cls, base_dir, component = component, spec = spec)
+ assert cached is not None
+ assert cached._unsloth_runtime_quant_info["native"] is True
+ _assert_same_module(fresh, cached)
+ with torch.no_grad():
+ out_a = fresh(*_inputs(), return_dict = False)[0]
+ out_b = cached(*_inputs(), return_dict = False)[0]
+ assert torch.equal(out_a, out_b)
+
+
+def test_experts_have_distinct_keys_and_never_cross(base_dir):
+ fam = _family()
+ spec = _spec()
+ fresh = _fresh_build(base_dir, "transformer")
+ NC.save(fresh, fam, spec, base_repo = base_dir, component = "transformer")
+ assert NC.lookup(fam, spec, base_repo = base_dir, component = "transformer") is not None
+ # Expert 2 never resolves expert 1's entry: it would load fine and render with the wrong weights.
+ assert NC.lookup(fam, spec, base_repo = base_dir, component = "transformer_2") is None
+ k1 = NC._key_for(fam, spec, base_dir, "transformer")[0]
+ k2 = NC._key_for(fam, spec, base_dir, "transformer_2")[0]
+ assert k1 != k2
+
+
+def test_key_tracks_build_and_source(base_dir):
+ fam = _family()
+ spec = _spec()
+ NC.save(
+ _fresh_build(base_dir, "transformer"),
+ fam,
+ spec,
+ base_repo = base_dir,
+ component = "transformer",
+ )
+ assert (
+ NC.lookup(fam, _spec(act_int8 = False), base_repo = base_dir, component = "transformer") is None
+ )
+ assert _spec(act_int8 = False)["rot_group"] == 0 and _spec()["rot_group"] == 256
+ assert (
+ NC.lookup(
+ fam, spec, base_repo = base_dir + "-other", source_base = base_dir, component = "transformer"
+ )
+ is None
+ )
+ torch.manual_seed(99)
+ diffusers.WanTransformer3DModel(**_tiny_config()).save_pretrained(
+ str(Path(base_dir) / "transformer"), safe_serialization = True
+ )
+ assert NC.lookup(fam, spec, base_repo = base_dir, component = "transformer") is None
+
+
+def test_torchao_lookup_never_serves_a_native_entry(base_dir):
+ fam = _family()
+ NC.save(
+ _fresh_build(base_dir, "transformer"),
+ fam,
+ _spec(),
+ base_repo = base_dir,
+ component = "transformer",
+ )
+ assert C.lookup(fam, "int8", base_repo = base_dir, component = "transformer") is None
+
+
+def test_save_refuses_a_build_the_spec_does_not_describe(base_dir):
+ fam = _family()
+ weight_only = _fresh_build(base_dir, "transformer", act_int8 = False)
+ assert (
+ NC.save(weight_only, fam, _spec(act_int8 = True), base_repo = base_dir, component = "transformer")
+ is None
+ )
+ dense = diffusers.WanTransformer3DModel.from_pretrained(
+ base_dir, subfolder = "transformer", torch_dtype = torch.bfloat16
+ )
+ assert NC.save(dense, fam, _spec(), base_repo = base_dir, component = "transformer") is None
+
+
+def test_corrupt_entry_is_a_miss(base_dir):
+ fam = _family()
+ spec = _spec()
+ path = NC.save(
+ _fresh_build(base_dir, "transformer"),
+ fam,
+ spec,
+ base_repo = base_dir,
+ component = "transformer",
+ )
+ (Path(path).parent / C.VERIFIED_NAME).unlink()
+ with open(path, "r+b") as fh:
+ fh.seek(-16, 2)
+ fh.write(b"\x01" * 16)
+ assert (
+ NC.load(path, diffusers.WanTransformer3DModel, base_dir, component = "transformer", spec = spec)
+ is None
+ )
+
+
+def test_a_rejected_entry_is_replaced_by_the_next_build(base_dir):
+ fam = _family()
+ spec = _spec()
+ kw = dict(base_repo = base_dir, component = "transformer")
+ path = NC.save(_fresh_build(base_dir, "transformer"), fam, spec, **kw)
+ (Path(path).parent / C.VERIFIED_NAME).unlink()
+ with open(path, "r+b") as fh:
+ fh.seek(-16, 2)
+ fh.write(b"\x01" * 16)
+ load = lambda p: NC.load(
+ p, diffusers.WanTransformer3DModel, base_dir, component = "transformer", spec = spec
+ )
+ assert load(path) is None
+ # same key and size: without the rejection check this save was skipped and every later load missed
+ replaced = NC.save(_fresh_build(base_dir, "transformer"), fam, spec, **kw)
+ assert replaced is not None and load(replaced) is not None
+ assert os.path.realpath(replaced) not in C._REJECTED
+
+
+def test_video_read_is_all_or_nothing(base_dir):
+ from core.inference import video as V
+
+ fam = _family()
+ spec = _spec()
+ NC.save(
+ _fresh_build(base_dir, "transformer"),
+ fam,
+ spec,
+ base_repo = base_dir,
+ component = "transformer",
+ )
+ kw = dict(base = base_dir, source = base_dir, config_kwargs = {})
+ assert V._read_native_quant_from_cache(fam, spec, **kw) == {}
+ NC.save(
+ _fresh_build(base_dir, "transformer_2"),
+ fam,
+ spec,
+ base_repo = base_dir,
+ component = "transformer_2",
+ )
+ hits = V._read_native_quant_from_cache(fam, spec, **kw)
+ assert set(hits) == set(COMPONENTS)
+ assert V._read_native_quant_from_cache(fam, None, **kw) == {}
+
+
+def test_video_save_writes_one_entry_per_expert(base_dir):
+ from core.inference import video as V
+
+ fam = _family()
+ spec = _spec()
+ pipe = types.SimpleNamespace(
+ transformer = _fresh_build(base_dir, "transformer"),
+ transformer_2 = _fresh_build(base_dir, "transformer_2"),
+ )
+ views = (pipe, types.SimpleNamespace(transformer = pipe.transformer_2))
+ V._save_native_quant_to_cache(fam, views, spec, base = base_dir, source = base_dir)
+ for component in COMPONENTS:
+ assert NC.lookup(fam, spec, base_repo = base_dir, component = component) is not None
+ hits = V._read_native_quant_from_cache(
+ fam, spec, base = base_dir, source = base_dir, config_kwargs = {}
+ )
+ assert all(
+ NC.save(m, fam, spec, base_repo = base_dir, component = c) is None for c, m in hits.items()
+ )
+
+
+def nvidia(monkeypatch):
+ monkeypatch.setattr(tq, "torch_is_rocm", lambda: False)
+ monkeypatch.setattr(tq, "is_stubbed", lambda name: False)
+
+
+OFFLOAD = types.SimpleNamespace(offload_policy = "group", stream_transformer = True)
+RESIDENT = types.SimpleNamespace(offload_policy = "none")
+
+
+ "quant, plan, kind, device, expect",
+ [
+ ("int8", OFFLOAD, "pipeline", "cuda", True),
+ ("auto", OFFLOAD, "pipeline", "cuda", True),
+ (None, OFFLOAD, "pipeline", "cuda", False),
+ ("off", OFFLOAD, "pipeline", "cuda", False),
+ (
+ "int8",
+ RESIDENT,
+ "pipeline",
+ "cuda",
+ False,
+ ), # resident: torchao / hosted path, not native
+ (
+ "fp8",
+ OFFLOAD,
+ "pipeline",
+ "cuda",
+ False,
+ ), # fp8 has no torchao-free offload build on NVIDIA
+ ("int8", OFFLOAD, "gguf", "cuda", False),
+ ("int8", OFFLOAD, "pipeline", "mps", False),
+ ],
+)
+def test_offload_routing_gate(nvidia, quant, plan, kind, device, expect):
+ from core.inference import video as V
+
+ target = types.SimpleNamespace(device = device, dtype = torch.bfloat16)
+ spec = V._video_native_cache_spec(
+ _family(), target = target, transformer_quant = quant, plan = plan, kind = kind, source_dir = None
+ )
+ if not expect:
+ assert spec is None
+ return
+ assert spec == NC.native_spec("int8", FAMILY, act_int8 = tq.native_int8_act(target))
+ assert spec["act_int8"] is True and spec["rot_group"] == 256
+ assert spec == V._native_spec_for("int8", _family(), True)
+
+
+def test_hosted_int8_is_not_the_offload_build():
+ """The hosted A14B INT8 is a torchao v1 W8A8 checkpoint without ConvRot; the offload build rotates (g256)."""
+ from core.inference.diffusion_transformer_quant import int8_convrot_enabled
+
+ assert not int8_convrot_enabled(FAMILY)
+ assert _spec()["rot_group"] == 256