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: load pre-quant checkpoints with weights_only and a constructor allowlist (#8409)
Daniel Han0d25628cd540
diff --git a/studio/backend/core/inference/diffusion_prequant.py b/studio/backend/core/inference/diffusion_prequant.pyindex a8edb0a3c21..d752485cd70 100644--- a/studio/backend/core/inference/diffusion_prequant.py+++ b/studio/backend/core/inference/diffusion_prequant.py@@ -15,12 +15,18 @@ Measured (B200, Z-Image fp8): GPU load peak 12.9 -> 6.3 GB, download 12 -> 6.28bit-identical (LPIPS 0.0). The checkpoint carries the same scheme + ``min_features`` as theruntime path, so the result matches quantising on the fly.+torchao's weight subclasses are not safetensors-serializable, so the artifact is a torch.save+pickle -- read under ``weights_only`` plus the constructor ALLOWLIST below, never as a free one.+It is a mutable remote file reached by loads that never asked for a scheme (auto resolves an unset+precision to a hosted checkpoint), so "first-party repo" cannot stand in for that restriction.+Best-effort and lazily imported: a missing / mismatched / unreadable checkpoint returns Noneand the caller falls back to dense-quantise (then GGUF). Inert with nothing configured."""from __future__ import annotations+import threading as _threadingfrom dataclasses import dataclassfrom typing import Any, Optional@@ -45,10 +51,239 @@ def prequant_format_for(metadata: Any) -> str:return PREQUANT_FORMAT_ROTATED if declares_rotation(metadata) else PREQUANT_FORMAT-# Loading ends in ``torch.load(weights_only=False)``, which executes pickle code. A hosted repo checkpoint is first-party;-# a ``kind == "path"`` can come from a request, so it is unpickled ONLY inside an operator-configured directory ALLOWLIST.+# A request-supplied ``kind == "path"`` is read ONLY inside an operator-configured directory+# ALLOWLIST: an arbitrary path is an arbitrary MODEL. Not a code-execution gate -- the load is+# weights_only either way.ALLOW_LOCAL_PREQUANT_PATH_ENV = "UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH"+# The constructors a pre-quant checkpoint's pickle may name, on top of what ``weights_only``+# already permits (storages, dtypes, ``_rebuild_*``, ``OrderedDict``, ``torch.device``,+# ``_get_layout``). Surveyed across every hosted checkpoint Studio resolves (image + video, fp8 ++# int8, rotated and not) this is the complete set, so the load runs ``weights_only = True`` and a+# checkpoint naming anything else is refused before one opcode of it executes, hosted or local.+#+# Registered under the name the PICKLE records, which for a re-exported class is not the class's+# own ``__module__`` (``torchao.quantization.Float8Tensor`` really lives in+# ``...quantize_.workflows.float8.float8_tensor``), so both spellings are listed. Names a given+# torchao lacks are skipped rather than raised: the set spans every release+# ``install_python_stack`` pins (0.14, 0.16, 0.17) and an absent class could not have produced a+# loadable checkpoint here anyway.+#+# Adding a scheme means adding its constructors here; forgetting warns and falls back to+# dense-quantise, never a silent unpickle.+_PREQUANT_SAFE_GLOBALS: tuple[tuple[str, str], ...] = (+ # int8: AffineQuantizedTensor + its plain layout, wrapped for dynamic activation quant.+ ("torchao.dtypes.affine_quantized_tensor", "AffineQuantizedTensor"),+ ("torchao.dtypes.uintx.plain_layout", "PlainAQTTensorImpl"),+ ("torchao.dtypes.utils", "PlainLayout"),+ ("torchao.quantization.linear_activation_quantized_tensor", "LinearActivationQuantizedTensor"),+ ("torchao.quantization.quant_api", "_int8_symm_per_token_reduced_range_quant"),+ ("torchao.quantization.quant_primitives", "ZeroPointDomain"),+ ("torchao.quantization.quant_primitives", "MappingType"),+ # fp8: the newer tensor subclass, its per-row granularity and its kernel/mm options.+ ("torchao.quantization", "Float8Tensor"),+ ("torchao.quantization.quantize_.workflows.float8.float8_tensor", "Float8Tensor"),+ (+ "torchao.quantization.quantize_.workflows.float8.float8_tensor",+ "QuantizeTensorToFloat8Kwargs",+ ),+ ("torchao.quantization.quantize_.common.kernel_preference", "KernelPreference"),+ ("torchao.quantization.granularity", "PerRow"),+ ("torchao.quantization.granularity", "PerTensor"),+ ("torchao.float8.inference", "Float8MMConfig"),+ # mxfp8 / nvfp4: no hosted checkpoint uses these, but they are TQ_SCHEMES that+ # scripts/build_prequant_checkpoint.py bakes, so a LOCAL override can be either. torchao only+ # registers them on import of the prototype package, which nothing on this path imports.+ ("torchao.prototype.mx_formats.mx_tensor", "MXTensor"),+ ("torchao.prototype.mx_formats.mx_tensor", "QuantizeTensorToMXKwargs"),+ ("torchao.prototype.mx_formats.config", "ScaleCalculationMode"),+ ("torchao.prototype.mx_formats.nvfp4_tensor", "NVFP4Tensor"),+ ("torchao.prototype.mx_formats.nvfp4_tensor", "QuantizeTensorToNVFP4Kwargs"),+ # The version string torch.save stamps into the subclass state: not in torch's default set,+ # and without it every torchao checkpoint refuses to load.+ ("torch.torch_version", "TorchVersion"),+)+++def _prequant_safe_globals() -> list:+ """``(object, pickled name)`` pairs to register; names this torchao lacks are skipped."""+ import importlib++ pairs = []+ for module, name in _PREQUANT_SAFE_GLOBALS:+ try:+ obj = getattr(importlib.import_module(module), name)+ except Exception: # noqa: BLE001 -- a name this release does not ship is not allowed+ continue+ pairs.append((obj, f"{module}.{name}"))+ return pairs+++_SAFE_GLOBALS_LOCK = _threading.Lock()+_SAFE_GLOBALS_REGISTERED: Optional[bool] = None+# Filled in by the registration: which of the names above this install actually resolved.+_RESOLVED_SAFE_GLOBALS: set = set()++# What a checkpoint of each scheme actually NAMES, read off the artifacts with pickletools rather+# than assumed: every hosted repo the family tables list, plus a local bake of each scheme for the+# two nothing hosts. Only these are required, so dropping an unused name does not fail a scheme.+_SCHEME_REQUIRED_GLOBALS: dict = {+ "int8": frozenset(+ {+ "torchao.dtypes.affine_quantized_tensor.AffineQuantizedTensor",+ "torchao.dtypes.uintx.plain_layout.PlainAQTTensorImpl",+ "torchao.dtypes.utils.PlainLayout",+ "torchao.quantization.linear_activation_quantized_tensor."+ "LinearActivationQuantizedTensor",+ "torchao.quantization.quant_api._int8_symm_per_token_reduced_range_quant",+ "torchao.quantization.quant_primitives.ZeroPointDomain",+ "torch.torch_version.TorchVersion",+ }+ ),+ "fp8": frozenset(+ {+ # The ALIAS spelling, which is what the fp8 pickles record.+ "torchao.quantization.Float8Tensor",+ "torchao.quantization.quantize_.workflows.float8.float8_tensor."+ "QuantizeTensorToFloat8Kwargs",+ "torchao.quantization.quantize_.common.kernel_preference.KernelPreference",+ "torchao.quantization.granularity.PerRow",+ "torchao.float8.inference.Float8MMConfig",+ "torch.torch_version.TorchVersion",+ }+ ),+ "mxfp8": frozenset(+ {+ "torchao.prototype.mx_formats.mx_tensor.MXTensor",+ "torchao.prototype.mx_formats.mx_tensor.QuantizeTensorToMXKwargs",+ "torchao.prototype.mx_formats.config.ScaleCalculationMode",+ "torchao.quantization.quantize_.common.kernel_preference.KernelPreference",+ }+ ),+ "nvfp4": frozenset(+ {+ "torchao.prototype.mx_formats.nvfp4_tensor.NVFP4Tensor",+ "torchao.prototype.mx_formats.nvfp4_tensor.QuantizeTensorToNVFP4Kwargs",+ }+ ),+}+++def _tuple_safe_globals_supported() -> bool:+ """Whether this torch's ``add_safe_globals`` understands ``(object, name)`` pairs (2.6+).++ Asked by VERSION rather than by trying it: 2.4/2.5 accept the pairs silently and only fail+ later, in ``_get_user_allowed_globals``, which reads ``f.__module__`` off every entry of a+ PROCESS-WIDE list -- so a tuple left there breaks every other weights_only load in Studio.+ Nothing is registered unless the answer here is yes."""+ try:+ import torch+ parts = str(torch.__version__).split("+")[0].split(".")+ return (int(parts[0]), int(parts[1])) >= (2, 6)+ except Exception: # noqa: BLE001 -- an unreadable version is not a supported one+ return False+++def _register_prequant_safe_globals() -> bool:+ """Register the allowlist ONCE, process-wide and permanently. True when the load can run.++ Not the ``safe_globals`` context manager, deliberately: it adds on entry and REMOVES on exit+ against a process-wide table, so two overlapping reads (a download-plan probe beside a load;+ both arrive on the route's thread pool) let whichever finishes first strip the allowlist out+ from under the other's ``torch.load``, failing a good checkpoint and dropping it to dense.+ Adding once and never removing has no such window.++ The widening this costs is small and bounded: other ``weights_only`` loads in the process+ also accept these torch/torchao tensor constructors, which build tensors and nothing else. A+ pickle naming ANY global is still refused.++ Registration takes ``(object, name)`` pairs so a re-exported class is registered under the+ name the pickle records, and that form is version-checked BEFORE anything is registered (see+ ``_tuple_safe_globals_supported``). Below 2.6 nothing is registered and+ ``restricted_prequant_load_supported`` tells planning to stop offering pre-quant sources at+ all. Answered once and memoised, including the failure."""+ global _SAFE_GLOBALS_REGISTERED++ if _SAFE_GLOBALS_REGISTERED is not None:+ return _SAFE_GLOBALS_REGISTERED+ with _SAFE_GLOBALS_LOCK:+ if _SAFE_GLOBALS_REGISTERED is not None:+ return _SAFE_GLOBALS_REGISTERED+ ok = False+ try:+ from core._torchao_stub import is_stubbed++ import torch++ add = getattr(torch.serialization, "add_safe_globals", None)+ # A STUBBED torchao (Windows ROCm) fabricates a class for every name asked of it, so+ # the allowlist would register fakes and answer yes for an install that cannot+ # rebuild a single quantized tensor.+ if add is not None and not is_stubbed("torchao") and _tuple_safe_globals_supported():+ pairs = _prequant_safe_globals()+ resolved = {name for _obj, name in pairs}+ # "Some entries resolved" is not "a checkpoint can be opened". The floor is what+ # EVERY artifact needs whatever its scheme: the version stamp plus at least one+ # real torchao tensor class. Per-SCHEME completeness is asked separately, by the+ # caller that knows which scheme it is about to plan for.+ if "torch.torch_version.TorchVersion" in resolved and any(+ name.startswith("torchao.") for name in resolved+ ):+ add(pairs)+ _RESOLVED_SAFE_GLOBALS.update(resolved)+ # The same derivation the unpickler runs, so a form this torch cannot express+ # fails here rather than under a load a plan was already sized on.+ try:+ torch._weights_only_unpickler._get_user_allowed_globals()+ except AttributeError: # noqa: BLE001 -- private; absence is not a failure+ pass+ ok = True+ except Exception: # noqa: BLE001 -- no allowlist means no restricted load, never a raise+ ok = False+ _SAFE_GLOBALS_REGISTERED = ok+ return ok+++def restricted_prequant_load_supported(scheme: Optional[str] = None) -> bool:+ """Whether this install can read a pre-quant checkpoint, for ``scheme`` when one is named.++ Without the allowlist there is no safe way to open a pre-quant pickle and the loader refuses.+ Planning has to ask the same question BEFORE it sizes the load: a plan that counts on a 6 GB+ artifact, drops the dense shards and evicts the resident pipeline has nothing left when the+ refusal arrives. ``usable_prequant_source`` therefore answers None here, hosted and local+ alike, which is the same answer the loader will give.++ PER SCHEME, because the schemes do not share constructors and torchao does not retire them+ together: ``AffineQuantizedTensor`` and its layout carry every int8 checkpoint and are+ already deprecated upstream (pytorch/ao#2752), so a release that drops them while keeping+ ``Float8Tensor`` leaves fp8 loadable and int8 not. An unknown or unnamed scheme gets the+ floor answer the registration itself already checked."""+ if not _register_prequant_safe_globals():+ return False+ required = _SCHEME_REQUIRED_GLOBALS.get((scheme or "").strip().lower())+ return True if required is None else required <= _RESOLVED_SAFE_GLOBALS+++def _torch_load_prequant(path: str, **kwargs: Any) -> Any:+ """``torch.load`` a pre-quant checkpoint under the allowlist above.++ ``weights_only = True`` is the whole point: a pickle that may name any global is remote code+ execution the moment the artifact is not the one that was published. Everything the format+ legitimately needs is allowlisted, so the restriction costs nothing and a mutated artifact+ raises ``UnpicklingError`` into the caller's dense fallback instead of running. A torch that+ cannot express the allowlist is refused outright, never reopened unrestricted."""+ import torch++ if not _register_prequant_safe_globals():+ raise RuntimeError(+ "this torch cannot register the pre-quant constructor allowlist (needs "+ "torch.serialization.add_safe_globals with (object, name) support, i.e. >= 2.6), so "+ "a pre-quant checkpoint cannot be deserialized without allowing arbitrary pickle "+ "globals"+ )+ return torch.load(path, weights_only = True, **kwargs)++_PREQUANT_TOGGLE_TOKENS = {"1", "true", "yes", "on", "0", "false", "no", "off"}@@ -210,9 +445,9 @@ def local_prequant_scheme(path: str) -> Optional[str]:Cheap despite the file size: ``mmap`` plus ``map_location = "meta"`` maps the storages insteadof reading them, so only the pickle structure is parsed (~1s on a 34 GB checkpoint). Cached on- (path, mtime, size) because the auto ladder asks once per candidate scheme. ``weights_only``- has to be False for the torchao subclasses, which is what the loader already does, and the- path is allowlisted before we get here, so this opens nothing new."""+ (path, mtime, size) because the auto ladder asks once per candidate scheme. Read under the+ same allowlisted ``weights_only`` load the loader uses, so probing a file that turns out not+ to be a checkpoint cannot execute anything either."""import ostry:@@ -228,8 +463,7 @@ def local_prequant_scheme(path: str) -> Optional[str]:return _LOCAL_PREQUANT_SCHEME[key]scheme: Optional[str] = Nonetry:- import torch- obj = torch.load(real, map_location = "meta", weights_only = False, mmap = True)+ obj = _torch_load_prequant(real, map_location = "meta", mmap = True)if isinstance(obj, dict) and obj.get("format") in PREQUANT_FORMATS:recorded = (obj.get("metadata") or {}).get("scheme")scheme = str(recorded) if recorded else None@@ -256,7 +490,13 @@ def usable_prequant_source(The scheme check matters most under ``auto``, which picks a scheme the user never named: anint8 override must not read as an available fp8 pre-quant just because the file exists. Acheckpoint whose scheme cannot be read is treated as not usable, matching every other unknown- here, since the loader would reject it too."""+ here, since the loader would reject it too.++ An install that cannot restrict the load has no usable source AT ALL, hosted included: the+ loader refuses every checkpoint there, and a plan that had already dropped the dense shards+ for one would find that out after the eviction."""+ if not restricted_prequant_load_supported(scheme):+ return Nonesrc = resolve_prequant_source(fam, scheme, path_override = path_override, base_repo = base_repo)if src is not None and src.kind == "path":if not local_prequant_path_ready(src.location):@@ -395,15 +635,16 @@ def load_prequantized_transformer(artifact."""try:- # weights_only=False executes pickle code, so a local path is unpickled ONLY when allowlisted; the hosted family repo is first-party.+ # A request-supplied local path names arbitrary WEIGHTS, a different question from the+ # deserialization one below: allowlisted or not, the file is read weights_only.if source.kind == "path" and not _local_prequant_path_allowed(source.location):_warn(logger,f"{scheme}:path",RuntimeError(- "request-supplied local pre-quant path refused (unpickling an arbitrary "- f"file is unsafe); set {ALLOW_LOCAL_PREQUANT_PATH_ENV} to an allowlisted "- "directory containing trusted checkpoints to permit it",+ "request-supplied local pre-quant path refused (loading arbitrary weights "+ f"into the served model); set {ALLOW_LOCAL_PREQUANT_PATH_ENV} to an "+ "allowlisted directory containing trusted checkpoints to permit it",),)return None@@ -412,10 +653,12 @@ def load_prequantized_transformer(if path is None:return None- import torch-- # torchao weight subclasses are not safetensors-serializable, so the checkpoint is a torch.save pickle and weights_only=False rebuilds them. Local paths gated above.- ckpt = torch.load(path, weights_only = False, map_location = "cpu")+ # A torch.save pickle, deserialized under the constructor ALLOWLIST above and never as a+ # free-running one. First-party hosting is no reason to execute whatever bytes arrive: the+ # artifact is mutable, fetched over the network, and reached by loads that never asked for+ # one (auto resolves an unset precision to a hosted checkpoint), so a mutated file must+ # fail to load rather than run.+ ckpt = _torch_load_prequant(path, map_location = "cpu")if not _validate_checkpoint(ckpt, scheme, base, logger, min_features = min_features, fast_accum = fast_accum):diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 5d76eeaa9a7..367d470a448 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -776,6 +776,13 @@ def _h3_auto_denoiser_scheme(# Asked per (scheme, PARTITION): a partition with no hosted checkpoint has no fallback, and# serving the other partition's would generate the wrong thing.return None+ from .diffusion_prequant import restricted_prequant_load_supported++ if not restricted_prequant_load_supported(H3_AUTO_FALLBACK_SCHEME):+ # An install that cannot restrict the deserialization cannot open a checkpoint at all, and+ # this runs BEFORE the download plan: choosing one would drop the dense denoiser shards+ # for an artifact the loader is going to refuse.+ return None# And the replacement has to fit BEFORE it is chosen. A torchao denoiser cannot ride the offload# rotation at all (it does not survive the mid-block move), so taking it means pinning it, which# turns the memory floor from a max into a sum: 20.3 GB resident PLUS whatever runs beside it.@@ -1861,6 +1868,18 @@ class VideoBackend:direction: unanswerable keeps the dense shards."""if not self._denoiser_prequant_covered(fam, transformer_quant, base, h3_task):return False+ from .diffusion_prequant import restricted_prequant_load_supported++ if not restricted_prequant_load_supported(transformer_quant):+ # An install that cannot open a checkpoint keeps the dense shards. This is the+ # decision that COMMITS (it drops 66 GB from the pull) and it runs for an EXPLICIT+ # request too, which the auto selector's gate never sees.+ logger.info(+ "video.denoiser_prequant: this install cannot deserialize a pre-quantized "+ "checkpoint, so the %s request keeps its dense denoiser shards",+ transformer_quant,+ )+ return Falsetry:from huggingface_hub import HfApirepo, _files = self._denoiser_prequant_hub_files(diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 59cc7a30110..2453ed25b41 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -2511,7 +2511,7 @@ class DiffusionLoadRequest(BaseModel):"scheme. Loads the already-quantized weights with the dense bf16 never on the ""GPU (~half the load VRAM and a smaller download). null uses the family's hosted ""checkpoint if configured, else quantises the dense transformer at load time. "- "Loading a local path unpickles the file (arbitrary code execution), so it is "+ "A local path installs arbitrary weights into the served model, so it is ""ignored unless the path resolves inside a directory the operator allowlisted ""via UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH (one or more directories, separated by ""the OS path separator). A bare on/off value such as '1' is deliberately not "diff --git a/studio/backend/tests/test_diffusion_auto_policy.py b/studio/backend/tests/test_diffusion_auto_policy.pyindex 5c23cd93734..864e1f0f141 100644--- a/studio/backend/tests/test_diffusion_auto_policy.py+++ b/studio/backend/tests/test_diffusion_auto_policy.py@@ -12,9 +12,23 @@ estimate fits resident."""from __future__ import annotations+import pytest+from types import SimpleNamespaceimport core.inference.diffusion_auto_policy as ap++[email protected](autouse = True)+def _assume_the_restricted_load_is_available(monkeypatch):+ """Policy/planning tests, not a check on whether this host's torchao imports.++ Without this, a machine with no (or a skewed) torchao turns every hosted-prequant decision+ below into "keep the dense weights". The capability is covered in test_diffusion_prequant.py."""+ import core.inference.diffusion_prequant as _pq+ monkeypatch.setattr(_pq, "restricted_prequant_load_supported", lambda scheme = None: True)++from core.inference.diffusion_auto_policy import (DenseQuantEstimate,build_resolved_record,diff --git a/studio/backend/tests/test_diffusion_prequant.py b/studio/backend/tests/test_diffusion_prequant.pyindex 35095b3e92f..457786e7aef 100644--- a/studio/backend/tests/test_diffusion_prequant.py+++ b/studio/backend/tests/test_diffusion_prequant.py@@ -152,7 +152,14 @@ def test_local_prequant_path_ready(tmp_path, monkeypatch):# ── usable_prequant_source ───────────────────────────────────────────────────────-def test_usable_source_missing_path_is_none(tmp_path, monkeypatch):+def restricted_load_available(monkeypatch):+ """Whether this install could open a checkpoint depends on the host's torchao. The resolution+ tests below are not about that, so pin it on."""+ monkeypatch.setattr(pq, "restricted_prequant_load_supported", lambda scheme = None: True)+++def test_usable_source_missing_path_is_none(tmp_path, monkeypatch, restricted_load_available):# An allowlisted but ABSENT path is not a prequant source: load_prequantized_transformer would find no file and fall back# to the dense bf16 build after evicting, so the planner must run the dense fit checks up front.import os@@ -163,7 +170,7 @@ def test_usable_source_missing_path_is_none(tmp_path, monkeypatch):assert pq.usable_prequant_source(fam, "fp8", path_override = missing) is None-def test_usable_source_disallowed_path_is_none(tmp_path, monkeypatch):+def test_usable_source_disallowed_path_is_none(tmp_path, monkeypatch, restricted_load_available):# A path OUTSIDE the UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH allowlist (including the empty default) is refused by the loader, so it resolves to None even when it exists.ckpt = tmp_path / "model.pt"ckpt.write_bytes(b"x")@@ -172,7 +179,7 @@ def test_usable_source_disallowed_path_is_none(tmp_path, monkeypatch):assert pq.usable_prequant_source(fam, "fp8", path_override = str(ckpt)) is None-def test_usable_source_allowed_present_path_wins(tmp_path, monkeypatch):+def test_usable_source_allowed_present_path_wins(tmp_path, monkeypatch, restricted_load_available):# Allowlisted, present AND baked for this scheme: the override is usable and beats the hosted repo, exactly like resolve_prequant_source.import os@@ -185,7 +192,9 @@ def test_usable_source_allowed_present_path_wins(tmp_path, monkeypatch):assert src == PrequantSource(kind = "path", location = str(ckpt), filename = None)-def test_usable_source_rejects_an_override_baked_for_another_scheme(tmp_path, monkeypatch):+def test_usable_source_rejects_an_override_baked_for_another_scheme(+ tmp_path, monkeypatch, restricted_load_available+):"""An int8 checkpoint must not read as an available fp8 pre-quant.resolve_prequant_source hands back a path source for ANY override without inspecting the file,@@ -206,7 +215,7 @@ def test_usable_source_rejects_an_override_baked_for_another_scheme(tmp_path, moassert src == PrequantSource(kind = "path", location = str(ckpt), filename = None)-def test_an_unreadable_override_is_not_usable(tmp_path, monkeypatch):+def test_an_unreadable_override_is_not_usable(tmp_path, monkeypatch, restricted_load_available):# A file we cannot parse as a pre-quant checkpoint is "unknown", and the loader would reject it# too, so planning must budget dense rather than assume a shortcut it will not get.import os@@ -253,7 +262,7 @@ def test_the_local_scheme_cache_survives_a_same_second_swap(tmp_path):assert pq.local_prequant_scheme(str(ckpt)) == "fp8"-def test_usable_source_repo_unaffected_by_allowlist(monkeypatch):+def test_usable_source_repo_unaffected_by_allowlist(monkeypatch, restricted_load_available):# Hosted-repo sources are first-party and keep resolving with no allowlist at all.monkeypatch.setattr(pq, "_allowed_prequant_roots", lambda: [])fam = _fam(prequant_repos = (("fp8", "org/hosted-fp8"),))@@ -320,22 +329,34 @@ def _stub_torch_accelerate(load_raises = False,):torch = types.ModuleType("torch")+ # Registration is version-gated (2.6+), so the stub needs a version or every load declines.+ torch.__version__ = "2.9.1+cu128"+ seen = {"weights_only": None, "safe_globals": None}def _load(path,weights_only = False,map_location = None,+ **kwargs,):+ seen["weights_only"] = weights_onlyif load_raises:raise RuntimeError("corrupt checkpoint")return ckpt+ def _add_safe_globals(entries):+ seen["safe_globals"] = list(entries)+torch.load = _load+ # A stub without this namespace would let a regression to an unrestricted load pass silently.+ torch.serialization = types.SimpleNamespace(add_safe_globals = _add_safe_globals)monkeypatch.setitem(sys.modules, "torch", torch)+ monkeypatch.setitem(sys.modules, "torch.serialization", torch.serialization)accelerate = types.ModuleType("accelerate")accelerate.init_empty_weights = lambda: contextlib.nullcontext()monkeypatch.setitem(sys.modules, "accelerate", accelerate)+ return seendef _good_ckpt(scheme = "fp8", base = "Tongyi-MAI/Z-Image-Turbo"):@@ -363,7 +384,7 @@ def _load():_FakeTransformer.calls = {}_stub_torch_accelerate(monkeypatch, ckpt, load_raises = load_raises)- # The local-path branch is opt-in via a directory ALLOWLIST (it unpickles an arbitrary file); allowlist tmp_path unless a test checks the gate.+ # The local-path branch is opt-in via a directory ALLOWLIST (it loads arbitrary weights); allowlist tmp_path unless a test checks the gate.if allow_local:monkeypatch.setenv(pq.ALLOW_LOCAL_PREQUANT_PATH_ENV, str(tmp_path))else:@@ -548,7 +569,351 @@ def test_resolve_checkpoint_path_expands_user(monkeypatch, tmp_path):assert pq._resolve_checkpoint_path(source, None) == str(real)-# ── local-path opt-in gate (RCE guard) ───────────────────────────────────────────+# ── deserialization gate (RCE guard) ─────────────────────────────────────────────+def test_the_checkpoint_is_deserialized_under_an_allowlist(monkeypatch):+ """A pre-quant checkpoint is a pickle, so the load has to be ``weights_only``.++ It is a mutable remote file reached WITHOUT anyone asking for it (auto resolves an unset+ precision to a hosted checkpoint), so "the repo is first-party" is not a reason to run+ whatever bytes arrive. Everything the format needs is allowlisted instead."""+ seen = _stub_torch_accelerate(monkeypatch, _good_ckpt())+ monkeypatch.setattr(pq, "_SAFE_GLOBALS_REGISTERED", None)+ monkeypatch.setattr(pq, "_resolve_checkpoint_path", lambda *a, **k: "/cache/x.pt")+ load_prequantized_transformer(+ _FakeTransformer,+ "Tongyi-MAI/Z-Image-Turbo",+ PrequantSource(kind = "repo", location = "org/hosted-fp8", filename = "x.pt"),+ device = "cpu",+ dtype = "bf16",+ hf_token = None,+ scheme = "fp8",+ )+ assert seen["weights_only"] is True+ assert seen["safe_globals"], "the allowlist has to be registered before the load"+++def test_the_allowlist_names_every_constructor_the_hosted_checkpoints_use(monkeypatch):+ """The exact set read out of the pickles Studio actually resolves.++ Surveyed with ``pickletools`` (no unpickling) over every hosted prequant repo the family+ tables name -- image and video, fp8 and int8, rotated and not -- so a checkpoint naming+ anything beyond this is not one of ours. Torch's defaults cover the storages, dtypes,+ ``_rebuild_*``, ``OrderedDict``, ``torch.device`` and ``_get_layout``; what is left is+ torchao's subclasses plus ``TorchVersion``."""+ listed = {f"{module}.{name}" for module, name in pq._PREQUANT_SAFE_GLOBALS}+ required = {+ # every TQ_SCHEME the builder can bake, not just the two the hosted repos ship+ "torchao.prototype.mx_formats.mx_tensor.MXTensor",+ "torchao.prototype.mx_formats.nvfp4_tensor.NVFP4Tensor",+ "torchao.dtypes.affine_quantized_tensor.AffineQuantizedTensor",+ "torchao.dtypes.uintx.plain_layout.PlainAQTTensorImpl",+ "torchao.dtypes.utils.PlainLayout",+ "torchao.quantization.linear_activation_quantized_tensor.LinearActivationQuantizedTensor",+ "torchao.quantization.quant_api._int8_symm_per_token_reduced_range_quant",+ "torchao.quantization.quant_primitives.ZeroPointDomain",+ "torchao.quantization.Float8Tensor",+ "torchao.quantization.quantize_.workflows.float8.float8_tensor"+ ".QuantizeTensorToFloat8Kwargs",+ "torchao.quantization.quantize_.common.kernel_preference.KernelPreference",+ "torchao.quantization.granularity.PerRow",+ "torchao.float8.inference.Float8MMConfig",+ "torch.torch_version.TorchVersion",+ }+ assert required <= listed, sorted(required - listed)+ # Nothing outside torch/torchao, so the allowlist cannot grow a general-purpose callable.+ assert all(+ module.split(".")[0] in ("torch", "torchao") for module, _ in pq._PREQUANT_SAFE_GLOBALS+ )+ # A name a given torchao release does not ship is skipped, not raised.+ monkeypatch.setattr(+ pq, "_PREQUANT_SAFE_GLOBALS", (("torchao.nowhere", "Nope"), ("collections", "OrderedDict"))+ )+ assert [name for _obj, name in pq._prequant_safe_globals()] == ["collections.OrderedDict"]+++def test_a_malicious_checkpoint_is_refused_before_it_executes():+ """The whole point, against real torch: a checkpoint carrying a ``__reduce__`` payload must+ fail to load rather than run. The unrestricted load this replaces executes it."""+ import os++ torch = pytest.importorskip("torch")+ if not hasattr(torch.serialization, "safe_globals"):+ pytest.skip("torch < 2.6 has no safe_globals")+ import tempfile++ with tempfile.TemporaryDirectory() as tmp:+ marker = os.path.join(tmp, "executed")++ class _Payload:+ # mkdir rather than a command: observable proof of execution, confined to the temp dir.+ def __reduce__(self):+ return (os.mkdir, (marker,))++ path = os.path.join(tmp, "ckpt.pt")+ torch.save(+ {"format": PREQUANT_FORMAT, "metadata": {"scheme": "int8"}, "state_dict": _Payload()},+ path,+ )+ with pytest.raises(Exception):+ pq._torch_load_prequant(path, map_location = "cpu")+ assert not os.path.exists(marker)+++def test_the_scheme_probe_does_not_execute_the_checkpoint_either(tmp_path, monkeypatch):+ """The probe is the WIDER reach of the two, so it gets its own test.++ ``local_prequant_scheme`` runs during download PLANNING, not only during a load, so it is+ reached for a request that never loads anything. An unreadable checkpoint is "unknown", which+ the caller already handles, and nothing in it runs."""+ import os++ torch = pytest.importorskip("torch")+ if not hasattr(torch.serialization, "safe_globals"):+ pytest.skip("torch < 2.6 has no safe_globals")+ marker = tmp_path / "executed"++ class _Payload:+ def __reduce__(self):+ return (os.mkdir, (str(marker),))++ ckpt = tmp_path / "malicious.pt"+ torch.save(+ {"format": PREQUANT_FORMAT, "metadata": {"scheme": "fp8"}, "payload": _Payload()}, ckpt+ )+ monkeypatch.setattr(pq, "_allowed_prequant_roots", lambda: [os.path.realpath(str(tmp_path))])++ assert pq.local_prequant_scheme(str(ckpt)) is None+ assert not marker.exists()+ # And the planning entry point declines the override, as for any unreadable scheme.+ fam = _fam(prequant_repos = (("fp8", "org/hosted-fp8"),))+ assert pq.usable_prequant_source(fam, "fp8", path_override = str(ckpt)) is None+ assert not marker.exists()+++class _UnknownConstructor:+ """A constructor no allowlist entry names. Module level so it pickles by reference."""+++def test_the_probe_and_the_loader_agree_on_what_is_readable(tmp_path, monkeypatch):+ """One mechanism on both sites, so the two cannot drift apart.++ ``usable_prequant_source`` treats an unreadable scheme as not usable "since the loader would+ reject it too", which only holds while both answer the same question: a probe reading MORE+ than the loader accepts would let planning skip the dense shards for a checkpoint the load+ then drops -- the GGUF silent downgrade the scheme check exists to prevent."""+ import os++ torch = pytest.importorskip("torch")+ if not hasattr(torch.serialization, "safe_globals"):+ pytest.skip("torch < 2.6 has no safe_globals")++ path = tmp_path / "off-allowlist.pt"+ torch.save(+ {+ "format": PREQUANT_FORMAT,+ "metadata": {"scheme": "int8", "base_model_id": "Tongyi-MAI/Z-Image-Turbo"},+ "state_dict": {"weight": _UnknownConstructor()},+ },+ path,+ )+ monkeypatch.setattr(pq, "_allowed_prequant_roots", lambda: [os.path.realpath(str(tmp_path))])++ # The probe: unknown, so planning budgets the dense build.+ assert pq.local_prequant_scheme(str(path)) is None+ fam = _fam(prequant_repos = (("int8", "org/hosted-int8"),))+ assert pq.usable_prequant_source(fam, "int8", path_override = str(path)) is None+ # And the loader agrees rather than installing it: same allowlist, same verdict.+ assert (+ load_prequantized_transformer(+ _FakeTransformer,+ "Tongyi-MAI/Z-Image-Turbo",+ PrequantSource(kind = "path", location = str(path), filename = None),+ device = "cpu",+ dtype = "bf16",+ hf_token = None,+ scheme = "int8",+ )+ is None+ )+++def test_a_torch_without_safe_globals_refuses_rather_than_reopening_the_pickle(monkeypatch):+ """No allowlist support means no load. Falling back to an unrestricted one would put the+ sink back on exactly the installs least able to defend it."""+ torch = types.ModuleType("torch")+ torch.load = lambda *a, **k: pytest.fail("torch.load must not run without add_safe_globals")+ torch.serialization = types.SimpleNamespace()+ monkeypatch.setitem(sys.modules, "torch", torch)+ monkeypatch.setattr(pq, "_SAFE_GLOBALS_REGISTERED", None)+ with pytest.raises(RuntimeError, match = "add_safe_globals"):+ pq._torch_load_prequant("/nonexistent.pt", map_location = "cpu")+++def test_an_old_torch_registers_nothing_at_all(monkeypatch):+ """2.4/2.5 take the (object, name) pairs without looking at them and only fail later, in+ ``_get_user_allowed_globals``, which reads ``f.__module__`` off every entry of a PROCESS-WIDE+ list -- so a tuple left there breaks every OTHER weights_only load in Studio too. Hence:+ decide by version first, register nothing below 2.6."""+ torch = types.ModuleType("torch")+ torch.serialization = types.SimpleNamespace(+ add_safe_globals = lambda entries: pytest.fail("nothing may be registered below 2.6")+ )+ torch.load = lambda *a, **k: pytest.fail("and no load may run")+ for version in ("2.4.0", "2.5.1+cu124", "2.5.0"):+ torch.__version__ = version+ monkeypatch.setitem(sys.modules, "torch", torch)+ monkeypatch.setattr(pq, "_SAFE_GLOBALS_REGISTERED", None)+ assert pq._tuple_safe_globals_supported() is False, version+ assert pq.restricted_prequant_load_supported() is False, version+ torch.__version__ = "2.6.0"+ assert pq._tuple_safe_globals_supported() is True+++def test_a_stubbed_torchao_cannot_open_a_checkpoint(monkeypatch):+ """Windows ROCm runs on the torchao IMPORT STUB, which fabricates a class for every name asked+ of it. The allowlist would register those fakes and answer yes for an install that cannot+ rebuild a single quantized tensor, and the H3 auto fallback treats ROCm as eligible, so the+ plan would drop the dense denoiser shards for a checkpoint nothing can open."""+ import core._torchao_stub as stub++ monkeypatch.setattr(pq, "_SAFE_GLOBALS_REGISTERED", None)+ monkeypatch.setattr(stub, "is_stubbed", lambda package: package == "torchao")+ torch = types.ModuleType("torch")+ torch.__version__ = "2.9.1"+ torch.serialization = types.SimpleNamespace(+ add_safe_globals = lambda entries: pytest.fail("a stub must never be registered")+ )+ monkeypatch.setitem(sys.modules, "torch", torch)+ assert pq.restricted_prequant_load_supported() is False+++def test_a_torchao_that_resolves_nothing_reports_no_support(monkeypatch):+ """Registering successfully is not the same as being able to open a checkpoint.++ A missing or skewed torchao leaves nothing to register but the torch entries, which+ ``add_safe_globals`` accepts happily -- while the load then refuses the first torchao global+ the file names, after planning already dropped the dense shards for it. So the answer requires+ the two entries every artifact needs whatever its scheme."""+ registered = []+ torch = types.ModuleType("torch")+ torch.__version__ = "2.9.1"+ torch.serialization = types.SimpleNamespace(add_safe_globals = registered.append)+ monkeypatch.setitem(sys.modules, "torch", torch)++ def only(names):+ return [(object(), n) for n in names]++ # torchao contributes nothing: the version string alone opens no checkpoint.+ monkeypatch.setattr(pq, "_SAFE_GLOBALS_REGISTERED", None)+ monkeypatch.setattr(+ pq, "_prequant_safe_globals", lambda: only(["torch.torch_version.TorchVersion"])+ )+ assert pq.restricted_prequant_load_supported() is False+ assert registered == [], "and nothing is registered on the way to saying no"++ # torchao is there but the version stamp is not: every torchao checkpoint carries one.+ monkeypatch.setattr(pq, "_SAFE_GLOBALS_REGISTERED", None)+ monkeypatch.setattr(+ pq, "_prequant_safe_globals", lambda: only(["torchao.quantization.Float8Tensor"])+ )+ assert pq.restricted_prequant_load_supported() is False++ # Both present: supported, and registered exactly once.+ monkeypatch.setattr(pq, "_SAFE_GLOBALS_REGISTERED", None)+ monkeypatch.setattr(+ pq,+ "_prequant_safe_globals",+ lambda: only(["torch.torch_version.TorchVersion", "torchao.quantization.Float8Tensor"]),+ )+ assert pq.restricted_prequant_load_supported() is True+ assert len(registered) == 1+++def test_support_is_answered_per_scheme(monkeypatch):+ """The schemes do not share constructors, and torchao does not retire them together.++ AffineQuantizedTensor and its layout carry every int8 checkpoint and are already deprecated+ upstream (pytorch/ao#2752), so a release that drops them while keeping Float8Tensor leaves fp8+ loadable and int8 not. One answer for both would drop the dense shards for an int8 pick this+ install cannot open."""+ torch = types.ModuleType("torch")+ torch.__version__ = "2.9.1"+ torch.serialization = types.SimpleNamespace(add_safe_globals = lambda entries: None)+ monkeypatch.setitem(sys.modules, "torch", torch)++ fp8_only = set(pq._SCHEME_REQUIRED_GLOBALS["fp8"])+ monkeypatch.setattr(pq, "_SAFE_GLOBALS_REGISTERED", None)+ monkeypatch.setattr(pq, "_RESOLVED_SAFE_GLOBALS", set())+ monkeypatch.setattr(pq, "_prequant_safe_globals", lambda: [(object(), n) for n in fp8_only])++ assert pq.restricted_prequant_load_supported("fp8") is True+ assert pq.restricted_prequant_load_supported("int8") is False+ assert pq.restricted_prequant_load_supported("nvfp4") is False+ # An unnamed or unknown scheme gets the floor answer the registration already checked.+ assert pq.restricted_prequant_load_supported() is True+ assert pq.restricted_prequant_load_supported("something-else") is True+ # And the source resolver carries the scheme through, so an int8 pick is not offered.+ fam = _fam(prequant_repos = (("int8", "org/hosted-int8"), ("fp8", "org/hosted-fp8")))+ assert pq.usable_prequant_source(fam, "int8") is None+ assert pq.usable_prequant_source(fam, "fp8") is not None+++def test_the_required_sets_are_a_subset_of_the_allowlist():+ """A required name the allowlist never registers would refuse its scheme forever."""+ listed = {f"{module}.{name}" for module, name in pq._PREQUANT_SAFE_GLOBALS}+ for scheme, required in pq._SCHEME_REQUIRED_GLOBALS.items():+ assert required <= listed, (scheme, sorted(required - listed))+++def test_an_install_that_cannot_restrict_the_load_offers_no_prequant_source(monkeypatch, tmp_path):+ """Planning has to ask the loader's question BEFORE it sizes the load.++ A plan that keeps a hosted pre-quant source, drops the dense shards and evicts the resident+ pipeline has nothing left when the loader then refuses every checkpoint: the dense build it+ now needs was never budgeted or staged."""+ import os++ fam = _fam(prequant_repos = (("int8", "org/hosted-int8"),))+ monkeypatch.setattr(pq, "restricted_prequant_load_supported", lambda scheme = None: True)+ assert pq.usable_prequant_source(fam, "int8") is not None+ monkeypatch.setattr(pq, "restricted_prequant_load_supported", lambda scheme = None: False)+ # Hosted and local alike: the loader refuses both, so neither is usable.+ assert pq.usable_prequant_source(fam, "int8") is None+ ckpt = tmp_path / "model.pt"+ ckpt.write_bytes(b"x")+ monkeypatch.setattr(pq, "_allowed_prequant_roots", lambda: [os.path.realpath(str(tmp_path))])+ assert pq.usable_prequant_source(fam, "int8", path_override = str(ckpt)) is None+++def test_the_allowlist_is_registered_once_and_never_withdrawn(monkeypatch):+ """The registration must OUTLIVE the load that installed it.++ ``safe_globals`` as a context manager adds on entry and removes on exit, against a+ process-wide table that is not refcounted. Two overlapping reads (a download-plan probe beside+ a load, both on the route's thread pool) then let whichever finishes first strip the allowlist+ out from under the other's ``torch.load``, dropping a good checkpoint to dense."""+ torch = pytest.importorskip("torch")+ if not hasattr(torch.serialization, "add_safe_globals"):+ pytest.skip("torch without add_safe_globals")+ calls = []+ monkeypatch.setattr(pq, "_SAFE_GLOBALS_REGISTERED", None)+ monkeypatch.setattr(+ torch.serialization, "add_safe_globals", lambda entries: calls.append(list(entries))+ )+ # No remove_safe_globals / safe_globals context: nothing gives the entries back.+ monkeypatch.setattr(+ torch.serialization,+ "safe_globals",+ lambda *a, **k: pytest.fail("the load must not scope the allowlist to itself"),+ )+ monkeypatch.setattr(torch, "load", lambda *a, **k: {"ok": True})+ assert pq._torch_load_prequant("/x.pt", map_location = "cpu") == {"ok": True}+ assert pq._torch_load_prequant("/x.pt", map_location = "cpu") == {"ok": True}+ assert len(calls) == 1, "registered once for the process, not per load"+ assert calls[0], "and with the allowlist, not an empty list"+++# ── local-path opt-in gate ───────────────────────────────────────────────────────def test_load_local_path_refused_by_default(monkeypatch, tmp_path):# Even a valid checkpoint is refused: torch.load must never run on a request-supplied path without the operator opt-in.called = {"load": False}diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.pyindex b20207cf11c..33b75bde02c 100644--- a/studio/backend/tests/test_video_backend.py+++ b/studio/backend/tests/test_video_backend.py@@ -28,6 +28,15 @@ from core.inference.video import (from core.inference.video_families import VIDEO_CANCELLED_MSG, VIDEO_NOT_LOADED_MSG[email protected](autouse = True)+def _assume_the_restricted_load_is_available(monkeypatch):+ """A checkpoint only deserializes where torchao is importable, which here it may not be. These+ tests are about the load/plan decisions; the capability is covered in+ test_diffusion_prequant.py."""+ import core.inference.diffusion_prequant as _pq+ monkeypatch.setattr(_pq, "restricted_prequant_load_supported", lambda scheme = None: True)++class _FakeDtype:def __init__(self, name: str) -> None:self._name = namediff --git a/studio/backend/tests/test_video_prequant.py b/studio/backend/tests/test_video_prequant.pyindex 5cdeb7df92f..a38dd1124ad 100644--- a/studio/backend/tests/test_video_prequant.py+++ b/studio/backend/tests/test_video_prequant.py@@ -18,6 +18,18 @@ from core.inference.diffusion_prequant import (resolve_prequant_source,)from core.inference.video import VideoBackend++[email protected](autouse = True)+def _assume_the_restricted_load_is_available(monkeypatch):+ """Policy/planning tests, not a check on whether this host's torchao imports.++ Without this, a machine with no (or a skewed) torchao turns every hosted-prequant decision+ below into "keep the dense weights". The capability is covered in test_diffusion_prequant.py."""+ import core.inference.diffusion_prequant as _pq+ monkeypatch.setattr(_pq, "restricted_prequant_load_supported", lambda scheme = None: True)++from core.inference.video_families import (VideoFamily,detect_video_family,@@ -86,7 +98,8 @@ def test_minimax_h3_declares_hosted_denoiser_checkpoints():assert set(video_family_prequant_schemes(fam)) == {"int8", "fp8"}for scheme in ("int8", "fp8"):repo = video_family_prequant_repo(fam, scheme)- # Curated hosted artifacts only: a third-party repo here would be unpickled by the loader.+ # Curated hosted artifacts only: a third-party repo here would be served as this family's+ # own weights, for a load that may never have asked for a scheme at all.assert repo and repo.startswith("unsloth/")