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: SAM 3.1 for Mask from text, with pre-quantized INT8 / FP8 files (#14310)

Daniel Hanfb372c13c0f3
diff --git a/scripts/build_segmenter_prequant_checkpoint.py b/scripts/build_segmenter_prequant_checkpoint.py
new file mode 100644
index 00000000000..931bcfe3177
--- /dev/null
+++ b/scripts/build_segmenter_prequant_checkpoint.py
@@ -0,0 +1,91 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Build a pre-quantized SAM 3 / SAM 3.1 detector (Mask from text) for Unsloth Studio.
+
+The segmenter counterpart of scripts/build_prequant_checkpoint.py: the same torchao config, filter, ConvRot rotation,
+safetensors container (torchao flatten layout + ``unsloth_format`` / ``unsloth_metadata``) and canonical fingerprint,
+reached through ``core.inference.diffusion_segment_quant`` so the artifact matches what Studio's loader checks
+(scheme, min_features, exclusions, rotation contract). Deterministic for a given source, scheme and torchao.
+
+ python scripts/build_segmenter_prequant_checkpoint.py --src <Sam3Model dir> --base-model-id unsloth/sam3.1 \\
+ --source-revision <sha> --scheme int8 --convrot-groupsize 256 --out sam3.1-INT8-ConvRot.safetensors
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+
+BACKEND = Path(__file__).resolve().parent.parent / "studio" / "backend"
+
+
+def main(argv = None) -> int:
+ p = argparse.ArgumentParser()
+ p.add_argument("--src", required = True, help = "transformers-format Sam3Model directory (bf16)")
+ p.add_argument(
+ "--base-model-id", required = True, help = "the repo the artifact belongs to (recorded)"
+ )
+ p.add_argument(
+ "--source-revision", default = None, help = "the repo commit the source was taken from"
+ )
+ p.add_argument("--scheme", required = True, choices = ("fp8", "int8"))
+ p.add_argument("--convrot-groupsize", type = int, default = 0)
+ p.add_argument("--out", required = True, help = "output .safetensors path")
+ p.add_argument("--device", default = "cuda")
+ args = p.parse_args(argv)
+ if not args.out.endswith(".safetensors"):
+ print("error: --out must end in .safetensors", flush = True)
+ return 2
+
+ sys.path.insert(0, str(BACKEND))
+ import torch
+ from transformers import Sam3Model
+
+ from core.inference.diffusion_segment_quant import quantize_segmenter_, write_prequant_file
+
+ started = time.time()
+ model = Sam3Model.from_pretrained(args.src, dtype = torch.bfloat16, device_map = args.device).eval()
+ quant = quantize_segmenter_(model, args.scheme, convrot_group = args.convrot_groupsize)
+ out = Path(args.out)
+ out.parent.mkdir(parents = True, exist_ok = True)
+ tmp = out.with_name(out.name + ".tmp")
+ metadata = write_prequant_file(
+ str(tmp),
+ model,
+ quant,
+ base_model_id = args.base_model_id,
+ source_revision = args.source_revision,
+ )
+ tmp.replace(out)
+ fmt = metadata["format"]
+ digest = hashlib.sha256()
+ with open(out, "rb") as fh:
+ for chunk in iter(lambda: fh.read(1 << 24), b""):
+ digest.update(chunk)
+ print(
+ json.dumps(
+ {
+ "out": str(out),
+ "bytes": out.stat().st_size,
+ "sha256": digest.hexdigest(),
+ "format": fmt,
+ "scheme": args.scheme,
+ "quantized_linears": quant["quantized_linears"],
+ "rotated_linears": len(quant.get("activation_rotation_fqns") or ()),
+ "exclude_name_tokens": quant["exclude_name_tokens"],
+ "fingerprinted": metadata["fingerprint"]["count"],
+ "seconds": round(time.time() - started, 1),
+ }
+ ),
+ flush = True,
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/studio/backend/core/inference/diffusion_segment.py b/studio/backend/core/inference/diffusion_segment.py
index 60ce9429888..9a3ba86db47 100644
--- a/studio/backend/core/inference/diffusion_segment.py
+++ b/studio/backend/core/inference/diffusion_segment.py
@@ -13,9 +13,18 @@ SAM 3 and transformers' post-processing (ComfyUI drops the presence term, and th
picture, "elephant" in a living room, masks the sofa at 0.72; with it every absent concept scores below 0.02 and no
present one changes), and ComfyUI's optional crop-and-refine pass through the tracker's SAM decoder is not run.
-Weights are the official transformers-format ``facebook/sam3`` checkpoint (gated: the license is accepted on Hugging
-Face). SAM 3.1 ships only an original-format multiplex checkpoint with no transformers integration, so it is not
-loaded here; ``UNSLOTH_SAM3_PATH`` points at any local transformers-format SAM 3 directory instead.
+Weights come from a small table of variants (SEGMENTER_VARIANTS). The default is SAM 3.1: Meta ships it only as an
+original-format multiplex checkpoint, so it is the SAM 3.1 detector converted with transformers' own SAM 3 converter
+into a BF16 ``Sam3Model`` repository (ungated, SAM License). The official transformers-format ``facebook/sam3``
+(gated: the license is accepted on Hugging Face) stays selectable with ``UNSLOTH_SAM3_VARIANT=sam3``, and is used
+when it is already downloaded and SAM 3.1 is not. ``UNSLOTH_SAM3_PATH`` points at any local transformers-format SAM 3
+directory instead.
+
+SAM 3.1 also ships pre-quantized detector files (FP8, INT8, INT8-ConvRot; diffusion_segment_quant). On a CUDA card
+``UNSLOTH_SAM3_PRECISION`` (auto / bf16 / fp8 / int8) picks one; auto loads only a file that passed the accuracy gate
+(INT8, the ConvRot build unless ``UNSLOTH_SAM3_INT8_CONVROT=0``). The download fetches that one weights file with the
+configs and tokenizer, and bf16 when the file is not published; the CPU and Apple's MPS run bf16 weights (a quantized
+file that is the only one on disk is dequantized there).
The model is auxiliary to the image model, like the FLUX.3 prompt upsampler: loaded on the first request, kept for
a short keep-alive, unloaded right after a call when the accelerator is tight, and dropped whenever the GPU arbiter
@@ -44,12 +53,9 @@ from loggers import get_logger
logger = get_logger(__name__)
# ── weights ─────────────────────────────────────────────────────────────────────────────────────────────────────────
-SEGMENTER_ID = "sam3"
-SEGMENTER_REPO = "facebook/sam3"
-SEGMENTER_LICENSE_URL = "https://huggingface.co/facebook/sam3"
SEGMENTER_WEIGHTS_FILE = "model.safetensors"
-# Only what Sam3Model and its tokenizer read: the repo also holds sam3.pt, the same weights in the original format.
-SEGMENTER_FILES = (
+# Only what Sam3Model and its tokenizer read: facebook/sam3 also holds sam3.pt, the same weights in the original format.
+SEGMENTER_CONFIG_FILES = (
"config.json",
"processor_config.json",
"tokenizer.json",
@@ -57,10 +63,93 @@ SEGMENTER_FILES = (
"special_tokens_map.json",
"vocab.json",
"merges.txt",
- SEGMENTER_WEIGHTS_FILE,
)
+SEGMENTER_FILES = SEGMENTER_CONFIG_FILES + (SEGMENTER_WEIGHTS_FILE,)
+
+
+@dataclass(frozen = True)
+class SegmenterPrequant:
+ """One pre-quantized detector file of a variant (scripts/build_segmenter_prequant_checkpoint.py): it replaces
+ model.safetensors, next to the same configs and tokenizer. ``tag`` names its download spec."""
+
+ precision: str
+ filename: str
+ size_bytes: int
+ rotated: bool = False
+
+ @property
+ def tag(self) -> str:
+ return self.precision + ("-convrot" if self.rotated else "")
+
+
+@dataclass(frozen = True)
+class SegmenterVariant:
+ """One downloadable transformers-format SAM 3 checkpoint. ``revision`` is a full commit sha, or "main" for a repo
+ whose pin is not set yet (the download then records the commit it resolved)."""
+
+ id: str
+ label: str
+ repo: str
+ revision: str
+ size_bytes: int
+ gated: bool
+ license_url: str
+ files: tuple = SEGMENTER_FILES
+ # Pre-quantized detector files and the commit that holds them (with the configs and tokenizer); "main" until
+ # that commit is pinned. A file not on the Hub there yet reads as absent, and bf16 is used.
+ prequant: tuple = ()
+ prequant_revision: Optional[str] = None
+
+
+# SAM 3.1's detector in transformers' Sam3Model format, BF16 (converted from facebook/sam3.1's sam3.1_multiplex.pt).
+SAM31_REPO = "unsloth/sam3.1"
+# The unsloth/sam3.1 commit the files below were verified at.
+SAM31_REVISION = "6cfffd097f83c94fdedf56e8d09d4f89174b733e"
+# 1_680_935_372 bytes of bf16 safetensors plus the configs and tokenizer.
+SAM31_CONFIG_BYTES = 5_037_537
+SAM31_SIZE_BYTES = 1_680_935_372 + SAM31_CONFIG_BYTES
+# The commit of unsloth/sam3.1 that holds the pre-quantized files (with the configs and tokenizer). None offers no
+# pre-quantized download and every load uses bf16 unless a file is already on disk; a file missing at this commit
+# downloads bf16 instead.
+SAM31_PREQUANT_REVISION: Optional[str] = "6cfffd097f83c94fdedf56e8d09d4f89174b733e"
+# Built by scripts/build_segmenter_prequant_checkpoint.py from the bf16 model.safetensors above; accuracy gate,
+# exclusions and the auto rule in diffusion_segment_quant. int8 is the ConvRot build unless UNSLOTH_SAM3_INT8_CONVROT=0.
+SAM31_PREQUANT = (
+ SegmenterPrequant("int8", "sam3.1-INT8-ConvRot.safetensors", 1_047_746_476, rotated = True),
+ SegmenterPrequant("int8", "sam3.1-INT8.safetensors", 992_371_564),
+ SegmenterPrequant("fp8", "sam3.1-FP8.safetensors", 1_047_320_804),
+)
+
+SAM3_REPO = "facebook/sam3"
+SAM3_REVISION = "3c879f39826c281e95690f02c7821c4de09afae7"
# fp32 safetensors as published (half of it once loaded in bf16 / fp16), plus the tokenizer and configs.
-SEGMENTER_SIZE_BYTES = 3_439_938_512 + 5_060_000
+SAM3_SIZE_BYTES = 3_439_938_512 + 5_060_000
+
+SEGMENTER_VARIANTS: dict[str, SegmenterVariant] = {
+ "sam3.1": SegmenterVariant(
+ id = "sam3.1",
+ label = "SAM 3.1",
+ repo = SAM31_REPO,
+ revision = SAM31_REVISION,
+ size_bytes = SAM31_SIZE_BYTES,
+ gated = False,
+ license_url = f"https://huggingface.co/{SAM31_REPO}/blob/main/LICENSE",
+ prequant = SAM31_PREQUANT,
+ prequant_revision = SAM31_PREQUANT_REVISION,
+ ),
+ "sam3": SegmenterVariant(
+ id = "sam3",
+ label = "SAM 3",
+ repo = SAM3_REPO,
+ revision = SAM3_REVISION,
+ size_bytes = SAM3_SIZE_BYTES,
+ gated = True,
+ license_url = f"https://huggingface.co/{SAM3_REPO}",
+ ),
+}
+DEFAULT_VARIANT = "sam3.1"
+ENV_VARIANT = "UNSLOTH_SAM3_VARIANT"
+
ENV_PATH_OVERRIDE = "UNSLOTH_SAM3_PATH"
ENV_KEEP_ALIVE = "UNSLOTH_SAM3_KEEP_ALIVE"
@@ -155,12 +244,20 @@ def _override_dir() -> Optional[str]:
if not value:
return None
path = Path(value).expanduser()
+ # Only the variant the override is reported (and loaded) as: another variant's file would plan no weights.
+ variant = SEGMENTER_VARIANTS[requested_variant_id() or DEFAULT_VARIANT]
has = lambda *names: any((path / name).is_file() for name in names) # noqa: E731
complete = (
has("config.json")
and (
has(SEGMENTER_WEIGHTS_FILE)
or _shards_complete(path / (SEGMENTER_WEIGHTS_FILE + ".index.json"))
+ # or only a pre-quantized detector file the precision setting may load (dequantized where it cannot
+ # run quantized); one the setting rejects (fp8 under auto, any under bf16) is not a loadable model
+ or any(
+ _loadable(variant, a) and has(a.filename) and not _broken(str(path), a)
+ for a in variant.prequant
+ )
)
# AutoTokenizer (CLIPTokenizer for sam3) loads tokenizer.json, else needs vocab.json and merges.txt together.
and (has("tokenizer.json") or (has("vocab.json") and has("merges.txt")))
@@ -180,13 +277,76 @@ def _shards_complete(index: Path) -> bool:
return all(isinstance(name, str) and (index.parent / name).is_file() for name in shards)
+_COMMIT_SHA = re.compile(r"[0-9a-f]{40}")
+
+
+def _commit(revision: Optional[str]) -> Optional[str]:
+ return revision if _COMMIT_SHA.fullmatch(revision or "") else None
+
+
+def pinned_revision(variant: SegmenterVariant) -> Optional[str]:
+ """The variant's commit pin, or None while it is a branch ("main"): the download then pins what it resolves."""
+ return _commit(variant.revision)
+
+
+# A pre-quantized file's download spec id: "<variant>@<tag>", e.g. "sam3.1@int8-convrot".
+_SPEC_SEP = "@"
+
+
+def prequant_spec_id(variant: SegmenterVariant, artifact: SegmenterPrequant) -> str:
+ return f"{variant.id}{_SPEC_SEP}{artifact.tag}"
+
+
+def split_spec_id(model_id: str) -> tuple[SegmenterVariant, Optional[SegmenterPrequant]]:
+ """(variant, pre-quantized file or None) for a variant id or a pre-quantized spec id; KeyError when unknown."""
+ variant_id, _, tag = str(model_id).partition(_SPEC_SEP)
+ variant = SEGMENTER_VARIANTS[variant_id]
+ if not tag:
+ return variant, None
+ for artifact in variant.prequant:
+ if artifact.tag == tag:
+ return variant, artifact
+ raise KeyError(model_id)
+
+
+def variant_artifact(variant: SegmenterVariant, precision: str) -> Optional[SegmenterPrequant]:
+ """The file ``precision`` loads for ``variant``, or None: int8 is the ConvRot build unless
+ UNSLOTH_SAM3_INT8_CONVROT=0 picks the plain one (never the other as a stand-in)."""
+ from core.inference.diffusion_segment_quant import PRECISION_INT8, int8_convrot_enabled
+
+ rotated = int8_convrot_enabled() if precision == PRECISION_INT8 else False
+ for artifact in variant.prequant:
+ if artifact.precision == precision and artifact.rotated == rotated:
+ return artifact
+ return None
+
+
+def requested_variant_id() -> Optional[str]:
+ """The variant UNSLOTH_SAM3_VARIANT names (its id or repo, any case), else None. An unknown name is logged and
+ ignored, so a typo falls back to the default instead of breaking the status route."""
+ value = (os.environ.get(ENV_VARIANT) or "").strip().lower()
+ if not value:
+ return None
+ for variant in SEGMENTER_VARIANTS.values():
+ if value in (variant.id, variant.repo.lower()):
+ return variant.id
+ logger.warning(
+ "images.segment: unknown %s=%r (choices: %s), using the default",
+ ENV_VARIANT,
+ value,
+ ", ".join(SEGMENTER_VARIANTS),
+ )
+ return None
+
+
def _cached_snapshot(
- model_id: str = SEGMENTER_ID,
+ model_id: str = DEFAULT_VARIANT,
*,
hub_cache: Optional[Path] = None,
revision: Optional[str] = None,
) -> Optional[str]:
- """The snapshot directory holding every SEGMENTER_FILES at one revision (the recorded one first), else None."""
+ """The snapshot directory holding every file of ``model_id`` (a variant's bf16 files, or a pre-quantized spec's
+ configs and file) at one revision (the pin first, then the recorded one, then any cached commit), else None."""
try:
from huggingface_hub import hf_hub_download
@@ -196,23 +356,21 @@ def _cached_snapshot(
_read_revision_record,
)
+ spec = SEGMENTER_SPECS[model_id]
root = hub_cache if hub_cache is not None else _active_hf_hub_cache()
if revision is not None:
revisions = [revision]
else:
- recorded = _read_revision_record(SEGMENTER_REPO)
- revisions = ([recorded] if recorded else []) + [
- rev
- for rev in _fallback_revisions(SEGMENTER_REPO, hub_cache = root)
- if rev != recorded
- ]
+ candidates = [_commit(spec.revision), _read_revision_record(spec.repo)]
+ candidates += _fallback_revisions(spec.repo, hub_cache = root)
+ revisions = list(dict.fromkeys(rev for rev in candidates if rev))
for rev in revisions:
paths = []
- for filename in SEGMENTER_FILES:
+ for filename in spec.files:
try:
paths.append(
hf_hub_download(
- repo_id = SEGMENTER_REPO,
+ repo_id = spec.repo,
filename = filename,
revision = rev,
local_files_only = True,
@@ -229,11 +387,65 @@ def _cached_snapshot(
return None
+# Pre-quantized files that failed to load even dequantized (corrupt, truncated, built for another rule) in this
+# process. They stop counting as downloaded, so status and the download route offer the bf16 file instead.
+_BROKEN_PREQUANT: set[str] = set()
+
+
+def _prequant_key(folder: str, artifact: SegmenterPrequant) -> str:
+ return os.path.realpath(os.path.join(folder, artifact.filename))
+
+
+def _broken(folder: Optional[str], artifact: SegmenterPrequant) -> bool:
+ return folder is not None and _prequant_key(folder, artifact) in _BROKEN_PREQUANT
+
+
+def _variant_snapshot(variant_id: str) -> Optional[str]:
+ """A cached snapshot of variant ``variant_id`` that Sam3Model can load: its bf16 files, else a pre-quantized file
+ with the configs and tokenizer."""
+ path = _cached_snapshot(variant_id)
+ if path is not None:
+ return path
+ variant = SEGMENTER_VARIANTS[variant_id]
+ for artifact in variant.prequant:
+ if not _loadable(variant, artifact):
+ continue
+ path = _cached_snapshot(prequant_spec_id(variant, artifact))
+ if path is not None and not _broken(path, artifact):
+ return path
+ return None
+
+
+def _resolve_active() -> tuple[SegmenterVariant, Optional[str]]:
+ """(the active variant, its cached snapshot or None). UNSLOTH_SAM3_VARIANT decides when set; else the default,
+ unless only another variant is already downloaded (an install that fetched facebook/sam3 keeps using it). With
+ UNSLOTH_SAM3_PATH set the cache is never read: the chosen (or default) variant is reported, with no snapshot."""
+ chosen = requested_variant_id()
+ if (os.environ.get(ENV_PATH_OVERRIDE) or "").strip():
+ return SEGMENTER_VARIANTS[chosen or DEFAULT_VARIANT], None
+ if chosen is not None:
+ return SEGMENTER_VARIANTS[chosen], _variant_snapshot(chosen)
+ default = SEGMENTER_VARIANTS[DEFAULT_VARIANT]
+ path = _variant_snapshot(default.id)
+ if path is None:
+ for variant in SEGMENTER_VARIANTS.values():
+ if variant.id != default.id:
+ other = _variant_snapshot(variant.id)
+ if other is not None:
+ return variant, other
+ return default, path
+
+
+def active_variant() -> SegmenterVariant:
+ return _resolve_active()[0]
+
+
def model_dir() -> Optional[str]:
- """The env override when set (a typo'd override is not silently replaced by the cache), else the cached repo."""
+ """The env override when set (a typo'd override is not silently replaced by the cache), else the active
+ variant's cached snapshot."""
if (os.environ.get(ENV_PATH_OVERRIDE) or "").strip():
return _override_dir()
- return _cached_snapshot()
+ return _resolve_active()[1]
@dataclass(frozen = True)
@@ -241,21 +453,57 @@ class _SegmenterSpec:
repo: str
files: tuple
label: str
+ # A commit sha pins the download; "main" resolves (and records) the newest commit.
+ revision: Optional[str] = None
model_file: str = SEGMENTER_WEIGHTS_FILE
mmproj_file: str = "config.json"
+ # Downloaded instead when a file of this spec is not on the Hub at its revision (a pre-quantized file not
+ # published yet): the variant's bf16 spec.
+ fallback: Optional[str] = None
+
+
+def _build_specs() -> dict:
+ specs = {}
+ for variant in SEGMENTER_VARIANTS.values():
+ specs[variant.id] = _SegmenterSpec(
+ repo = variant.repo,
+ files = variant.files,
+ label = f"{variant.label} segmenter",
+ revision = variant.revision,
+ )
+ for artifact in variant.prequant:
+ specs[prequant_spec_id(variant, artifact)] = _SegmenterSpec(
+ repo = variant.repo,
+ files = SEGMENTER_CONFIG_FILES + (artifact.filename,),
+ label = f"{variant.label} {artifact.precision.upper()} segmenter",
+ revision = variant.prequant_revision,
+ model_file = artifact.filename,
+ fallback = variant.id,
+ )
+ return specs
-SEGMENTER_SPEC = _SegmenterSpec(repo = SEGMENTER_REPO, files = SEGMENTER_FILES, label = "SAM 3 segmenter")
+SEGMENTER_SPECS = _build_specs()
def _resolve_segmenter_id(model_id: Optional[str]) -> str:
- if (model_id or SEGMENTER_ID) != SEGMENTER_ID:
+ """A variant id (the active one when None) or a pre-quantized spec id."""
+ if model_id is None:
+ return active_variant().id
+ if model_id not in SEGMENTER_SPECS:
raise ValueError(f"Unknown segmenter '{model_id}'.")
- return SEGMENTER_ID
+ return model_id
-def describe_download_error(_model_id: str, error: object) -> Optional[str]:
- """A gated-repo refusal names the license to accept; anything else keeps the generic message."""
+def describe_download_error(model_id: str, error: object) -> Optional[str]:
+ """A gated variant's refusal names the license to accept; anything else (and any ungated variant, which needs no
+ token) keeps the generic message."""
+ try:
+ variant = split_spec_id(model_id)[0]
+ except KeyError:
+ return None
+ if not variant.gated:
+ return None
name = type(error).__name__
text = str(error)
if (
@@ -266,7 +514,7 @@ def describe_download_error(_model_id: str, error: object) -> Optional[str]:
or "awaiting a review" in text
):
return (
- f"{SEGMENTER_REPO} is gated on Hugging Face. Accept the SAM 3 license at {SEGMENTER_LICENSE_URL} "
+ f"{variant.repo} is gated on Hugging Face. Accept the {variant.label} license at {variant.license_url} "
"with your account, add a Hugging Face token in Settings, then download again."
)
return None
@@ -292,17 +540,22 @@ def _get_download_state():
if _download_state is None:
from core.inference.stt_mtmd_sidecar import _MtmdDownloadState
_download_state = _MtmdDownloadState(
- specs = {SEGMENTER_ID: SEGMENTER_SPEC},
+ specs = SEGMENTER_SPECS,
cached_paths = _cached_download_paths,
resolve = _resolve_segmenter_id,
- label = "SAM 3 segmenter",
+ label = "Mask segmenter",
describe_error = describe_download_error,
)
return _download_state
-def start_download(hf_token: Optional[str] = None) -> str:
- return _get_download_state().start(SEGMENTER_ID, hf_token)
+def start_download(hf_token: Optional[str] = None, variant: Optional[str] = None) -> str:
+ """Download ``variant`` (the active one when None) in the background: the configs, the tokenizer and the one
+ weights file this host would run (download_plan), else the bf16 files."""
+ model_id = _resolve_segmenter_id(variant)
+ if _SPEC_SEP not in model_id:
+ model_id = download_plan(SEGMENTER_VARIANTS[model_id])["spec"]
+ return _get_download_state().start(model_id, hf_token)
def download_status() -> dict:
@@ -310,14 +563,184 @@ def download_status() -> dict:
def cancel_download(download_id: Optional[str] = None) -> bool:
- return _get_download_state().cancel(SEGMENTER_ID, download_id)
+ return _get_download_state().cancel(None, download_id)
+
+
+# ── precision ──────────────────────────────────────────────────────────────────────────────────────────────────────
+@dataclass(frozen = True)
+class WeightsPlan:
+ """Which weights a load uses. ``weights`` is a pre-quantized file (None: the bf16 model.safetensors in
+ ``model_dir``); ``dequantize`` loads that file as dense weights (no bf16 file on disk, and the device cannot run
+ it quantized, or its quantized load failed)."""
+
+ precision: str
+ model_dir: Optional[str]
+ weights: Optional[str] = None
+ artifact: Optional[SegmenterPrequant] = None
+ reason: str = ""
+ dequantize: bool = False
+
+
+def _loadable(variant: SegmenterVariant, artifact: SegmenterPrequant) -> bool:
+ """``artifact`` is a file the current UNSLOTH_SAM3_PRECISION may load: the file its precision loads here, and
+ under auto one that passed the accuracy gate, under fp8 / int8 that precision's, under bf16 none. Anything else
+ on disk is ignored (not used, not even dequantized), so the selection's own file is offered for download."""
+ from core.inference.diffusion_segment_quant import (
+ PRECISION_AUTO,
+ PRECISION_BF16,
+ auto_may_load,
+ requested_precision,
+ )
+
+ from core.inference.prequant_safetensors import safetensors_prequant_supported
+
+ if artifact != variant_artifact(variant, artifact.precision):
+ return False
+ # An install that cannot read the files (no torchao, or the Windows ROCm stub) cannot even dequantize them.
+ if not safetensors_prequant_supported():
+ return False
+ requested = requested_precision()
+ if requested == PRECISION_AUTO:
+ return auto_may_load(artifact.tag)
+ return requested != PRECISION_BF16 and artifact.precision == requested
+
+
+def _has_dense_weights(path: Optional[str]) -> bool:
+ if not path:
+ return False
+ folder = Path(path)
+ return (folder / SEGMENTER_WEIGHTS_FILE).is_file() or _shards_complete(
+ folder / (SEGMENTER_WEIGHTS_FILE + ".index.json")
+ )
+
+
+def _local_artifacts(
+ variant: SegmenterVariant, path: Optional[str], *, use_cache: bool
+) -> list[tuple[SegmenterPrequant, str]]:
+ """(file, its folder) for every pre-quantized file of ``variant`` beside ``path`` or, with ``use_cache``, in its
+ own cached snapshot (which may be another commit than the bf16 one)."""
+ found = []
+ for artifact in variant.prequant:
+ if path and (Path(path) / artifact.filename).is_file():
+ if not _broken(path, artifact):
+ found.append((artifact, path))
+ elif use_cache:
+ snapshot = _cached_snapshot(prequant_spec_id(variant, artifact))
+ if snapshot is not None and not _broken(snapshot, artifact):
+ found.append((artifact, snapshot))
+ return found
+
+
+def plan_weights(
+ path: Optional[str],
+ device: str,
+ dtype: Any = None,
+ *,
+ variant: Optional[SegmenterVariant] = None,
+ use_cache: bool = True,
+) -> WeightsPlan:
+ """The weights a load on ``device`` uses: the precision UNSLOTH_SAM3_PRECISION asks for (auto: the gated order
+ in diffusion_segment_quant) when its file is on disk and the device runs it, else bf16. bf16 with no bf16 file
+ on disk dequantizes a pre-quantized one the selection may load (never one it rejected)."""
+ from core.inference.diffusion_segment_quant import PRECISION_BF16, resolve_precision
+
+ variant = variant or active_variant()
+ local = _local_artifacts(variant, path, use_cache = use_cache)
+ usable: dict = {}
+ for artifact, folder in local:
+ if _loadable(variant, artifact):
+ usable.setdefault(artifact.precision, (artifact, folder))
+ precision, why = resolve_precision(device, dtype, available = tuple(usable))
+ if precision != PRECISION_BF16:
+ artifact, folder = usable[precision]
+ return WeightsPlan(precision, folder, str(Path(folder) / artifact.filename), artifact, why)
+ if _has_dense_weights(path) or not usable:
+ return WeightsPlan(PRECISION_BF16, path, reason = why)
+ artifact, folder = next(iter(usable.values()))
+ return WeightsPlan(
+ PRECISION_BF16,
+ folder,
+ str(Path(folder) / artifact.filename),
+ artifact,
+ f"{why}; no bf16 file on disk, {artifact.filename} is dequantized",
+ dequantize = True,
+ )
+
+
+def _host_device() -> str:
+ """The device a call would most likely use, for planning without a call: the current CUDA card, else Metal,
+ else the CPU. Reads properties only (no CUDA context)."""
+ try:
+ import torch
+ if torch.cuda.is_available():
+ return f"cuda:{torch.cuda.current_device()}"
+ if getattr(torch.backends, "mps", None) is not None and torch.backends.mps.is_available():
+ return "mps"
+ except Exception: # noqa: BLE001
+ pass
+ return "cpu"
+
+
+def download_plan(variant: SegmenterVariant, device: Optional[str] = None) -> dict:
+ """What a download of ``variant`` fetches on this host: the spec id, the precision it runs, why, and the bytes.
+ A pre-quantized file only when the variant publishes them (a pinned or "main" prequant revision) and the host
+ would run it; its spec falls back to bf16 when the file is not on the Hub yet."""
+ from core.inference.diffusion_segment_quant import PRECISION_BF16, resolve_precision
+
+ offered = {}
+ if variant.prequant_revision:
+ for artifact in variant.prequant:
+ # A cached copy that already failed to load would only be "downloaded" again: offer bf16 instead.
+ if _loadable(variant, artifact) and not _broken(
+ _cached_snapshot(prequant_spec_id(variant, artifact)), artifact
+ ):
+ offered.setdefault(artifact.precision, artifact)
+ precision, why = resolve_precision(device or _host_device(), available = tuple(offered))
+ if precision == PRECISION_BF16:
+ return {
+ "spec": variant.id,
+ "precision": precision,
+ "reason": why,
+ "file": SEGMENTER_WEIGHTS_FILE,
+ "size_bytes": variant.size_bytes,
+ }
+ artifact = offered[precision]
+ config_bytes = SAM31_CONFIG_BYTES if variant.id == "sam3.1" else 0
+ return {
+ "spec": prequant_spec_id(variant, artifact),
+ "precision": precision,
+ "reason": why,
+ "file": artifact.filename,
+ "size_bytes": artifact.size_bytes + config_bytes,
+ }
+
+
+def variant_summary(variant: SegmenterVariant) -> dict:
+ """What the status and download routes report about a variant."""
+ return {
+ "variant": variant.id,
+ "label": variant.label,
+ "repo": variant.repo,
+ "revision": variant.revision,
+ "gated": variant.gated,
+ "license_url": variant.license_url,
+ "size_bytes": variant.size_bytes,
+ }
def status() -> dict:
- """The status route body: can it run, is it downloaded, is it loaded (and where), and the download progress."""
+ """The status route body: can it run, which variant, is it downloaded, is it loaded (and where), and the download
+ progress."""
supported = transformers_supports_sam3()
- path = model_dir() if supported else None
+ override = bool((os.environ.get(ENV_PATH_OVERRIDE) or "").strip())
+ if supported:
+ variant, path = _resolve_active()
+ if override:
+ path = _override_dir()
+ else:
+ variant, path = SEGMENTER_VARIANTS[requested_variant_id() or DEFAULT_VARIANT], None
segmenter = _segmenter
+ precision = _precision_summary(variant, path, segmenter, supported = supported, override = override)
return {
"supported": supported,
"reason": None
@@ -326,15 +749,58 @@ def status() -> dict:
"downloaded": path is not None,
"loaded": bool(segmenter is not None and segmenter.loaded),
"device": segmenter.device if segmenter is not None and segmenter.loaded else None,
- "repo": SEGMENTER_REPO,
- "gated": True,
- "license_url": SEGMENTER_LICENSE_URL,
- "size_bytes": SEGMENTER_SIZE_BYTES,
- "override": bool((os.environ.get(ENV_PATH_OVERRIDE) or "").strip()),
+ **variant_summary(variant),
+ **precision,
+ "override": override,
"download": download_status(),
}
+def _precision_summary(
+ variant: SegmenterVariant,
+ path: Optional[str],
+ segmenter: Optional["MaskSegmenter"],
+ *,
+ supported: bool,
+ override: bool,
+) -> dict:
+ """The status route's precision fields: what runs (the loaded model), else what a load on this host would use
+ (on disk), else what a download would fetch. ``size_bytes`` is that download's size until it is on disk."""
+ from core.inference.diffusion_segment_quant import requested_precision
+
+ body = {"precision_requested": requested_precision()}
+ try:
+ if segmenter is not None and segmenter.loaded and segmenter.precision:
+ body.update(
+ precision = segmenter.precision,
+ precision_reason = segmenter.precision_reason,
+ weights_file = segmenter.weights_file,
+ )
+ elif not supported:
+ body.update(precision = None, precision_reason = None, weights_file = None)
+ elif path is not None:
+ plan = plan_weights(path, _host_device(), variant = variant, use_cache = not override)
+ body.update(
+ precision = plan.precision,
+ precision_reason = plan.reason,
+ weights_file = os.path.basename(plan.weights)
+ if plan.weights
+ else SEGMENTER_WEIGHTS_FILE,
+ )
+ else:
+ plan = download_plan(variant)
+ body.update(
+ precision = plan["precision"],
+ precision_reason = plan["reason"],
+ weights_file = plan["file"],
+ size_bytes = plan["size_bytes"],
+ )
+ except Exception as exc: # noqa: BLE001 -- the status route must answer
+ logger.debug("images.segment: precision summary failed: %s", exc)
+ body.update(precision = None, precision_reason = None, weights_file = None)
+ return body
+
+
# ── device choice ───────────────────────────────────────────────────────────────────────────────────────────────────
def _resident_cuda_ordinal() -> Optional[int]:
"""The CUDA card the resident image model sits on, else None."""
@@ -436,6 +902,7 @@ class SegmentResult:
concepts: list[dict] = field(default_factory = list)
device: str = "cpu"
elapsed_ms: float = 0.0
+ precision: Optional[str] = None
def to_json(self) -> dict:
return {
@@ -452,6 +919,7 @@ class SegmentResult:
],
"prompts": self.concepts,
"device": self.device,
+ "precision": self.precision,
"elapsed_ms": round(self.elapsed_ms, 1),
}
@@ -562,8 +1030,17 @@ class MaskSegmenter:
self._model = None
self._tokenizer = None
self._path: Optional[str] = None
+ self._weights_key: Optional[tuple] = None
self.device: Optional[str] = None
self._dtype = None
+ # What the loaded model runs: "bf16" / "fp8" / "int8", why, and the weights file it came from.
+ self.precision: Optional[str] = None
+ self.precision_reason: Optional[str] = None
+ self.weights_file: Optional[str] = None
+ # Why the last pre-quantized load fell back to bf16, if one did.
+ self.last_prequant_failure: Optional[str] = None
+ # Planning reads the Hub cache only for the active variant's own snapshot, not an explicit folder.
+ self._use_cache = True
self._timer: Optional[threading.Timer] = None
self._release_pending = False
self._release_epoch = 0
@@ -584,29 +1061,26 @@ class MaskSegmenter:
# -- lifecycle -------------------------------------------------------------------------------------------------
def _load(self, path: str, device: str, dtype: Any) -> None:
+ plan = plan_weights(path, device, dtype, use_cache = self._use_cache)
+ key = (plan.model_dir, plan.weights, plan.dequantize)
if (
self._model is not None
and self._path == path
+ and self._weights_key == key
and self.device == device
and self._dtype == dtype
):
return
if self._model is not None:
self._unload_locked("reload")
- from transformers import AutoTokenizer, Sam3Model
+ from transformers import AutoTokenizer
started = time.perf_counter()
# The tokenizer first: a broken one fails before any weights are placed on the device.
- tokenizer = AutoTokenizer.from_pretrained(path)
+ tokenizer = AutoTokenizer.from_pretrained(plan.model_dir or path)
model = None
try:
- if device.startswith("cuda"):
- # Straight onto the card: about a third faster than loading on the CPU and moving it.
- model = Sam3Model.from_pretrained(path, dtype = dtype, device_map = device)
- else:
- model = Sam3Model.from_pretrained(path, dtype = dtype)
- model.to(device)
- model.eval()
+ model, plan = self._load_weights(plan, path, device, dtype)
except BaseException:
# Weights placed before the failure are referenced nowhere else: drop them and their cached blocks.
model = None
@@ -614,14 +1088,103 @@ class MaskSegmenter:
raise
self._model, self._tokenizer = model, tokenizer
self._path, self.device, self._dtype = path, device, dtype
+ self._weights_key = key
+ self.precision, self.precision_reason = plan.precision, plan.reason
+ self.weights_file = (
+ os.path.basename(plan.weights) if plan.weights else SEGMENTER_WEIGHTS_FILE
+ )
logger.info(
- "images.segment: loaded %s on %s (%s) in %.1fs",
- path,
+ "images.segment: loaded %s on %s (%s, precision %s from %s: %s) in %.1fs",
+ plan.model_dir or path,
device,
str(dtype).replace("torch.", ""),
+ plan.precision,
+ self.weights_file,
+ plan.reason,
time.perf_counter() - started,
)
+ def _load_weights(
+ self, plan: WeightsPlan, path: str, device: str, dtype: Any
+ ) -> tuple[Any, WeightsPlan]:
+ """(model, the plan that loaded). A pre-quantized file that fails to load falls back to the bf16 file, else
+ to the same file dequantized; nothing is left half-placed on the device."""
+ from transformers import Sam3Model
+
+ from core.inference.diffusion_segment_quant import (
+ PRECISION_BF16,
+ load_prequantized_segmenter,
+ )
+
+ variant = active_variant()
+ base = variant.repo
+ if plan.weights is not None and not plan.dequantize:
+ try:
+ model, _info = load_prequantized_segmenter(
+ plan.model_dir,
+ plan.weights,
+ scheme = plan.artifact.precision,
+ rotated = plan.artifact.rotated,
+ device = device,
+ dtype = dtype,
+ base_model_id = base,
+ )
+ self.last_prequant_failure = None
+ return model, plan
+ except Exception as exc: # noqa: BLE001 -- bf16 is slower and bigger, never wrong
+ self.last_prequant_failure = f"{type(exc).__name__}: {str(exc)[:200]}"
+ logger.warning(
+ "images.segment: pre-quantized %s file %s did not load (%s); using bf16",
+ plan.precision,
+ os.path.basename(plan.weights),
+ self.last_prequant_failure,
+ )
+ _free_device_cache(device)
+ why = f"{plan.artifact.filename} did not load"
+ if _has_dense_weights(path):
+ plan = WeightsPlan(PRECISION_BF16, path, reason = why)
+ else:
+ plan = WeightsPlan(
+ PRECISION_BF16,
+ plan.model_dir,
+ plan.weights,
+ plan.artifact,
+ f"{why}; dequantized",
+ dequantize = True,
+ )
+ if plan.weights is not None:
+ try:
+ model, _info = load_prequantized_segmenter(
+ plan.model_dir,
+ plan.weights,
+ scheme = plan.artifact.precision,
+ rotated = plan.artifact.rotated,
+ device = device,
+ dtype = dtype,
+ base_model_id = base,
+ dequantize = True,
+ )
+ except Exception as exc:
+ # Not a quantized-kernel problem: the file itself does not load. Stop counting it as downloaded so
+ # the next status offers the bf16 download rather than failing every request on the same file.
+ _BROKEN_PREQUANT.add(_prequant_key(plan.model_dir, plan.artifact))
+ _free_device_cache(device)
+ raise RuntimeError(
+ f"{plan.artifact.filename} could not be loaded ({type(exc).__name__}: {str(exc)[:200]}); "
+ f"download the {variant.label} BF16 weights from the Mask from text panel"
+ ) from exc
+ return model, plan
+ if device.startswith("cuda"):
+ # Straight onto the card: about a third faster than loading on the CPU and moving it.
+ model = Sam3Model.from_pretrained(
+ plan.model_dir or path, dtype = dtype, device_map = device
+ )
+ else:
+ model = Sam3Model.from_pretrained(plan.model_dir or path, dtype = dtype)
+ model.to(device)
+ model.eval()
+ return model, plan
+
def _unload_locked(self, reason: str) -> bool:
with self._state_lock:
if self._timer is not None:
@@ -633,8 +1196,10 @@ class MaskSegmenter:
self._model = None
self._tokenizer = None
self._path = None
+ self._weights_key = None
self.device = None
self._dtype = None
+ self.precision = self.precision_reason = self.weights_file = None
_free_device_cache(device)
logger.info("images.segment: unloaded from %s (%s)", device, reason)
return True
@@ -746,10 +1311,12 @@ class MaskSegmenter:
raise SegmenterUnavailableError(
"This install's transformers has no SAM 3. It needs transformers 5 (Python 3.10 or newer)."
)
+ self._use_cache = path is None and not (os.environ.get(ENV_PATH_OVERRIDE) or "").strip()
path = path or model_dir()
if path is None:
+ variant = active_variant()
raise SegmenterNotDownloadedError(
- f"The SAM 3 segmenter is not downloaded. Download {SEGMENTER_REPO} first."
+ f"The {variant.label} segmenter is not downloaded. Download {variant.repo} first."
)
queued_at = self._handover_epoch
with self._run_lock:
@@ -889,6 +1456,7 @@ class MaskSegmenter:
instances = instances,
concepts = summary,
device = device,
+ precision = self.precision,
)
@@ -1016,12 +1584,15 @@ def segment_image(
__all__ = [
"Concept",
"DEFAULT_THRESHOLD",
+ "DEFAULT_VARIANT",
"MaskSegmenter",
- "SEGMENTER_REPO",
+ "SEGMENTER_VARIANTS",
+ "SegmenterVariant",
"SegmenterBusyError",
"SegmenterNotDownloadedError",
"SegmenterReleaseTimeoutError",
"SegmenterUnavailableError",
+ "active_variant",
"get_segmenter",
"parse_prompt",
"release_segmenter",
diff --git a/studio/backend/core/inference/diffusion_segment_quant.py b/studio/backend/core/inference/diffusion_segment_quant.py
new file mode 100644
index 00000000000..78f1c8cb55a
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_segment_quant.py
@@ -0,0 +1,521 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Pre-quantized SAM 3 / SAM 3.1 detector weights for Mask from text: FP8, INT8 and INT8-ConvRot.
+
+The segmenter is not a diffusion transformer, but its quantization is the diffusion one, imported rather than copied
+so the two cannot drift: the torchao config (``_make_quant_config``: fp8 per-row weight scale with dynamic per-token
+activations, int8 W8A8 dynamic), the Linear filter (``make_filter_fn``: min features, bf16 and alignment rules), the
+ConvRot block-Hadamard rotation and its recorded-fqn contract (``diffusion_convrot``), the safetensors container
+(``prequant_safetensors``, torchao's flatten layout + ``unsloth_format`` / ``unsloth_metadata``) and the
+version-neutral weight fingerprint. What is SAM specific lives here: which Linears are left in bf16, which arms
+``auto`` may pick, the artifact names, and the loader that builds a ``Sam3Model`` around the quantized state dict.
+
+Exclusions come from a per-group sensitivity scan (numbers on the unsloth/sam3.1 model card): one group at a time,
+mask IoU / score / kept-count measured against bf16 over a 53-prompt set. They are baked into every artifact and
+compared at load, like the diffusion families' exclude tokens, so an artifact built under a different rule is refused
+rather than loaded.
+
+Quantized kernels are CUDA only here: on the CPU or Apple's MPS the segmenter runs bf16 / fp32 weights, and a
+quantized file that is the only one downloaded is dequantized for that device (the rotation, when present, stays
+installed, which is exact in floating point).
+"""
+
+from __future__ import annotations
+
+import os
+import time
+from contextlib import contextmanager
+from typing import Any, Iterator, Optional
+
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+# ── precision choice ───────────────────────────────────────────────────────────────────────────────────────────────
+PRECISION_AUTO = "auto"
+PRECISION_BF16 = "bf16"
+PRECISION_FP8 = "fp8"
+PRECISION_INT8 = "int8"
+PRECISIONS = (PRECISION_AUTO, PRECISION_BF16, PRECISION_FP8, PRECISION_INT8)
+QUANT_PRECISIONS = (PRECISION_FP8, PRECISION_INT8)
+ENV_PRECISION = "UNSLOTH_SAM3_PRECISION"
+# int8 loads the ConvRot artifact unless this is 0 (then the plain INT8 one).
+ENV_INT8_CONVROT = "UNSLOTH_SAM3_INT8_CONVROT"
+
+# What ``auto`` may pick on a CUDA card, best first; it also needs that file's GATE_PASSED. Empty: auto stays bf16.
+AUTO_ORDER: tuple[str, ...] = (PRECISION_INT8,)
+
+# Minimum compute capability per scheme: fp8 scaled_mm needs Ada / Hopper (sm_89+), int8 _int_mm Ampere (sm_80+).
+_MIN_CAPABILITY = {PRECISION_FP8: (8, 9), PRECISION_INT8: (8, 0)}
+
+# ── what is quantized ──────────────────────────────────────────────────────────────────────────────────────────────
+SEGMENTER_QUANT_FAMILY = "sam3"
+# The diffusion runtime's DEFAULT_MIN_LINEAR_FEATURES. Every DETR encoder / decoder, geometry, mask-decoder and
+# scoring Linear in SAM 3 is 256 wide, so this leaves all of them bf16; the ViT (1024 / 4736) and the CLIP text
+# encoder (1024 / 4096) are what gets quantized.
+SEGMENTER_MIN_FEATURES = 512
+SEGMENTER_CONVROT_GROUP = 256
+
+
+def _first_vision_blocks(count: int) -> tuple[str, ...]:
+ return tuple(f"backbone.layers.{index}." for index in range(count))
+
+
+def artifact_tag(scheme: str, rotated: bool = False) -> str:
+ """ "fp8", "int8" or "int8-convrot": one per published file."""
+ return scheme + ("-convrot" if rotated else "")
+
+
+# Name tokens left in bf16 on top of the size rule, per file. The sensitivity scan (one group quantized at a time,
+# 53 prompts) put the error in the first ViT blocks for every scheme (the text encoder, its projection and the late
+# ViT blocks cost a fraction of it; the 256-wide DETR / mask / scoring Linears, already bf16 by the size rule, cost as
+# much as a whole ViT half for 4% of the bytes). Each file keeps the smallest set of early blocks that brought it
+# inside the gate tolerance (or, for fp8, closest to it).
+SEGMENTER_EXCLUDE_TOKENS: dict[str, tuple[str, ...]] = {
+ "fp8": _first_vision_blocks(8),
+ "int8": _first_vision_blocks(4),
+ "int8-convrot": _first_vision_blocks(8),
+}
+# Each file's verdict on the accuracy gate (unsloth/sam3.1 model card, Checks: the built file through the segment
+# path, 53 prompts, every metric within 2x of what bf16 itself gives up against the fp32 weights, no kept-count,
+# false-positive or absent-concept change). ``auto`` loads only a file that passed; an explicit precision loads any.
+GATE_PASSED: dict[str, bool] = {"fp8": False, "int8": True, "int8-convrot": True}
+
+
+def exclude_tokens(scheme: str, rotated: bool = False) -> tuple[str, ...]:
+ return SEGMENTER_EXCLUDE_TOKENS.get(artifact_tag(scheme, rotated), ())
+
+
+def auto_may_load(tag: str) -> bool:
+ return bool(GATE_PASSED.get(tag))
+
+
+def segmenter_filter_fn(
+ scheme: str,
+ *,
+ exclude: Optional[tuple[str, ...]] = None,
+ select: Any = None,
+ min_features: int = SEGMENTER_MIN_FEATURES,
+) -> Any:
+ """The torchao ``quantize_`` filter for ``scheme``: the diffusion runtime's filter with SAM's exclusions.
+ ``select(fqn)`` narrows it further (the sensitivity scan quantizes one group at a time)."""
+ from .diffusion_transformer_quant import (
+ _REQUIRE_BF16_SCHEMES,
+ divisible_for_scheme,
+ make_filter_fn,
+ )
+
+ base = make_filter_fn(
+ min_features,
+ exclude_name_tokens = exclude_tokens(scheme)
+ if exclude is None
+ else tuple(exclude), # plain-file set
+ require_bf16 = scheme in _REQUIRE_BF16_SCHEMES,
+ require_divisible = divisible_for_scheme(scheme),
+ )
+ if select is None:
+ return base
+ return lambda module, fqn = "": bool(select(fqn)) and base(module, fqn)
+
+
+def quantize_segmenter_(
+ model: Any,
+ scheme: str,
+ *,
+ convrot_group: int = 0,
+ exclude: Optional[tuple[str, ...]] = None,
+ select: Any = None,
+ min_features: int = SEGMENTER_MIN_FEATURES,
+) -> dict:
+ """Quantize ``model`` (a dense bf16 Sam3Model) in place with the Studio runtime config; with ``convrot_group``,
+ rotate every selected Linear whose input width the group divides first. Returns the metadata fragment to record
+ (exclusions, filter facts, and the rotation contract when rotated). ``select`` / ``min_features`` exist for the
+ sensitivity scan; artifacts use the defaults, which the loader checks."""
+ from torchao.quantization import quantize_
+
+ from .diffusion_transformer_quant import _REQUIRE_BF16_SCHEMES, _make_quant_config
+ from .diffusion_transformer_quant import divisible_for_scheme
+
+ if scheme not in QUANT_PRECISIONS:
+ raise ValueError(f"unknown segmenter quant scheme {scheme!r}")
+ if convrot_group and scheme != PRECISION_INT8:
+ raise ValueError("ConvRot is an int8 rotation")
+ if exclude is None:
+ exclude = exclude_tokens(scheme, bool(convrot_group))
+ filter_fn = segmenter_filter_fn(
+ scheme, exclude = exclude, select = select, min_features = min_features
+ )
+ meta: dict = {
+ "scheme": scheme,
+ "min_features": int(min_features),
+ "exclude_name_tokens": list(exclude),
+ "require_bf16": scheme in _REQUIRE_BF16_SCHEMES,
+ "require_divisible": divisible_for_scheme(scheme),
+ }
+ if convrot_group:
+ from .diffusion_convrot import rotatable_fqns, rotate_linears_, rotation_metadata
+
+ rotatable, plain = rotatable_fqns(model, filter_fn, int(convrot_group))
+ if not rotatable:
+ raise ValueError(f"ConvRot group {convrot_group} divides no quantized Linear")
+ rotate_linears_(model, rotatable, int(convrot_group))
+ meta.update(rotation_metadata(int(convrot_group), rotatable))
+ meta["convrot_plain_linears"] = len(plain)
+ quantize_(model, _make_quant_config(scheme), filter_fn = filter_fn)
+ meta["quantized_linears"] = sum(
+ 1 for _n, m in model.named_modules() if _is_quantized_weight(getattr(m, "weight", None))
+ )
+ return meta
+
+
+def _is_quantized_weight(weight: Any) -> bool:
+ if weight is None:
+ return False
+ data = getattr(weight, "data", weight)
+ import torch
+
+ return type(data) not in (torch.Tensor, torch.nn.Parameter)
+
+
+# ── artifacts ──────────────────────────────────────────────────────────────────────────────────────────────────────
+def write_prequant_file(
+ path: str,
+ model: Any,
+ quant_meta: dict,
+ *,
+ base_model_id: str,
+ source_revision: Optional[str] = None,
+) -> dict:
+ """Save a quantized Sam3Model (``quantize_segmenter_``'s output and fragment) as a segmenter prequant artifact:
+ the diffusion prequant safetensors container, v2 when a rotation is baked, with the canonical fingerprint.
+ Returns the metadata written."""
+ import safetensors
+ import torch
+ import torchao
+ import transformers
+
+ from .diffusion_prequant import canonical_weight_fingerprint, prequant_format_for
+ from .diffusion_transformer_quant import FP8_GRANULARITY, _resolve_fast_accum
+ from .prequant_safetensors import save_prequant_safetensors
+
+ state_dict = {
+ k: (v.detach().to("cpu") if hasattr(v, "detach") else v)
+ for k, v in model.state_dict().items()
+ }
+ scheme = quant_meta["scheme"]
+ metadata = {
+ "base_model_id": base_model_id,
+ "source_revision": source_revision,
+ "family": SEGMENTER_QUANT_FAMILY,
+ "model_class": type(model).__name__,
+ "component": "detector",
+ "torch_dtype": "bfloat16",
+ "quant_backend": "torchao",
+ "fast_accum": _resolve_fast_accum(None) if scheme == PRECISION_FP8 else None,
+ "torch_version": torch.__version__,
+ "torchao_version": getattr(torchao, "__version__", "?"),
+ "transformers_version": transformers.__version__,
+ "safetensors_version": safetensors.__version__,
+ **quant_meta,
+ }
+ if scheme == PRECISION_FP8:
+ metadata["fp8_granularity"] = FP8_GRANULARITY
+ metadata["fingerprint"] = canonical_weight_fingerprint(state_dict)
+ fmt = prequant_format_for(metadata)
+ save_prequant_safetensors(str(path), fmt = fmt, state_dict = state_dict, metadata = metadata)
+ return {"format": fmt, **metadata}
+
+
+def artifact_filename(
+ prefix: str,
+ scheme: str,
+ *,
+ rotated: bool = False,
+) -> str:
+ """``<prefix>-FP8.safetensors`` / ``-INT8.safetensors`` / ``-INT8-ConvRot.safetensors`` (the diffusion prequant
+ naming)."""
+ tag = scheme.upper() + ("-ConvRot" if rotated else "")
+ return f"{prefix}-{tag}.safetensors"
+
+
+def int8_convrot_enabled() -> bool:
+ return (os.environ.get(ENV_INT8_CONVROT) or "").strip().lower() not in (
+ "0",
+ "off",
+ "false",
+ "no",
+ )
+
+
+def checkpoint_problem(
+ fmt: Any,
+ meta: Any,
+ *,
+ scheme: str,
+ rotated: bool,
+ base_model_id: Optional[str] = None,
+ convrot_group: int = SEGMENTER_CONVROT_GROUP,
+) -> Optional[str]:
+ """Why a segmenter prequant header must not be loaded, or None. Torch free, header only. A rotated file must use
+ ``convrot_group``: the accuracy gate and the exclusions were measured at that group, not at any power of four."""
+ from .diffusion_convrot import ROTATION_GROUP_KEY, declares_rotation, rotation_metadata_error
+ from .diffusion_prequant import PREQUANT_FORMAT, PREQUANT_FORMAT_ROTATED
+
+ if not isinstance(meta, dict):
+ return "no metadata"
+ if meta.get("family") != SEGMENTER_QUANT_FAMILY:
+ return f"family {meta.get('family')!r} is not {SEGMENTER_QUANT_FAMILY!r}"
+ if meta.get("scheme") != scheme:
+ return f"scheme {meta.get('scheme')!r}, expected {scheme!r}"
+ if base_model_id and str(meta.get("base_model_id") or "").lower() != base_model_id.lower():
+ return f"built from {meta.get('base_model_id')!r}, not {base_model_id!r}"
+ if meta.get("min_features") != SEGMENTER_MIN_FEATURES:
+ return f"min_features {meta.get('min_features')!r} != {SEGMENTER_MIN_FEATURES}"
+ declared = declares_rotation(meta)
+ if declared != (fmt == PREQUANT_FORMAT_ROTATED):
+ return f"format {fmt!r} and the declared rotation ({declared}) disagree"
+ if fmt not in (PREQUANT_FORMAT, PREQUANT_FORMAT_ROTATED):
+ return f"unknown format {fmt!r}"
+ if declared != rotated:
+ return "rotation expected" if rotated else "unexpected rotation"
+ if rotated and meta.get(ROTATION_GROUP_KEY) != convrot_group:
+ return f"ConvRot group {meta.get(ROTATION_GROUP_KEY)!r}, expected {convrot_group}"
+ if sorted(meta.get("exclude_name_tokens") or ()) != sorted(exclude_tokens(scheme, rotated)):
+ return (
+ f"excludes {meta.get('exclude_name_tokens')!r} differ from this build's "
+ f"{list(exclude_tokens(scheme, rotated))!r}"
+ )
+ return rotation_metadata_error(meta)
+
+
+@contextmanager
+def _default_dtype(dtype: Any) -> Iterator[None]:
+ import torch
+
+ previous = torch.get_default_dtype()
+ torch.set_default_dtype(dtype)
+ try:
+ yield
+ finally:
+ torch.set_default_dtype(previous)
+
+
+def _build_skeleton(model_dir: str) -> Any:
+ """Sam3Model with meta parameters (the file supplies every one) and real buffers. The buffers are built in
+ float32, which is what ``from_pretrained(dtype = bfloat16)`` leaves them in: built under a bf16 default the
+ global-attention RoPE tables of the ViT come out up to 0.04 off and every mask moves."""
+ import torch
+ from accelerate import init_empty_weights
+ from transformers import Sam3Config, Sam3Model
+
+ config = Sam3Config.from_pretrained(model_dir)
+ with _default_dtype(torch.float32), init_empty_weights(include_buffers = False):
+ return Sam3Model(config)
+
+
+def _dequantize_state_dict(state_dict: dict, dtype: Any) -> dict:
+ """Every quantized weight as a dense ``dtype`` tensor (rotated weights stay rotated)."""
+ out = {}
+ for key, value in state_dict.items():
+ if _is_quantized_weight(value):
+ value = value.dequantize().to(dtype)
+ elif getattr(value, "is_floating_point", lambda: False)():
+ value = value.to(dtype)
+ out[key] = value
+ return out
+
+
+def load_prequantized_segmenter(
+ model_dir: str,
+ weights_path: str,
+ *,
+ scheme: str,
+ rotated: bool,
+ device: str,
+ dtype: Any,
+ base_model_id: Optional[str] = None,
+ dequantize: bool = False,
+ convrot_group: int = SEGMENTER_CONVROT_GROUP,
+) -> tuple[Any, dict]:
+ """``(Sam3Model, info)`` from a segmenter prequant artifact. On CUDA the weights stay quantized unless
+ ``dequantize``; elsewhere they are dequantized to ``dtype``. Raises on anything wrong with the file (the caller
+ falls back to bf16)."""
+ from .diffusion_convrot import apply_activation_rotation
+ from .diffusion_prequant import _pin_kernel_preference, _verify_packed_fingerprint
+ from .prequant_safetensors import load_prequant_safetensors
+
+ started = time.perf_counter()
+ quantized = device.startswith("cuda") and not dequantize
+ ckpt = load_prequant_safetensors(weights_path, device = device if quantized else "cpu")
+ fmt, meta, state_dict = ckpt["format"], ckpt["metadata"], ckpt["state_dict"]
+ problem = checkpoint_problem(
+ fmt,
+ meta,
+ scheme = scheme,
+ rotated = rotated,
+ base_model_id = base_model_id,
+ convrot_group = convrot_group,
+ )
+ if problem:
+ raise ValueError(f"segmenter prequant refused: {problem}")
+ if not _verify_packed_fingerprint(state_dict, meta, logger = logger, path = weights_path):
+ raise ValueError("segmenter prequant fingerprint mismatch")
+ if quantized:
+ _pin_kernel_preference(state_dict)
+ else:
+ state_dict = _dequantize_state_dict(state_dict, dtype)
+ model = _build_skeleton(model_dir)
+ model.load_state_dict(state_dict, strict = True, assign = True)
+ rotated_fqns = apply_activation_rotation(model, meta, logger = logger)
+ model.to(device)
+ model.eval()
+ stray = [n for n, p in model.named_parameters() if p.device.type == "meta"]
+ stray += [n for n, b in model.named_buffers() if b.device.type == "meta"]
+ if stray:
+ raise ValueError(f"segmenter prequant left {len(stray)} tensors unset (e.g. {stray[0]})")
+ info = {
+ "precision": scheme if quantized else "bf16",
+ "scheme": scheme,
+ "rotated": bool(rotated_fqns),
+ "rotated_linears": len(rotated_fqns),
+ "quantized_linears": sum(
+ 1 for _n, m in model.named_modules() if _is_quantized_weight(getattr(m, "weight", None))
+ ),
+ "kernels": "quantized" if quantized else "dequantized",
+ "file": os.path.basename(weights_path),
+ "load_s": round(time.perf_counter() - started, 2),
+ }
+ logger.info(
+ "images.segment: pre-quantized %s file engaged (%s weights, %d quantized linears, %d rotated, on %s): %s",
+ scheme,
+ info["kernels"],
+ info["quantized_linears"],
+ info["rotated_linears"],
+ device,
+ info["file"],
+ )
+ return model, info
+
+
+# ── which precision runs ───────────────────────────────────────────────────────────────────────────────────────────
+def requested_precision() -> str:
+ """UNSLOTH_SAM3_PRECISION (auto / bf16 / fp8 / int8; "bfloat16" reads as bf16). Unknown values warn, read auto."""
+ raw = (os.environ.get(ENV_PRECISION) or "").strip().lower()
+ if raw in ("", PRECISION_AUTO):
+ return PRECISION_AUTO
+ if raw in ("bfloat16", "bf16", "dense", "none", "off"):
+ return PRECISION_BF16
+ if raw in QUANT_PRECISIONS:
+ return raw
+ logger.warning(
+ "images.segment: unknown %s=%r (choices: %s), using auto",
+ ENV_PRECISION,
+ raw,
+ ", ".join(PRECISIONS),
+ )
+ return PRECISION_AUTO
+
+
+def _cuda_capability(device: str) -> Optional[tuple[int, int]]:
+ """The card's compute capability; reads properties only, so no CUDA context is created."""
+ try:
+ import torch
+
+ if not torch.cuda.is_available():
+ return None
+ ordinal = int(device.split(":", 1)[1]) if ":" in device else None
+ major, minor = torch.cuda.get_device_capability(ordinal)
+ return int(major), int(minor)
+ except Exception: # noqa: BLE001
+ return None
+
+
+def unsupported_reason(
+ precision: str,
+ device: str,
+ dtype: Any = None,
+) -> Optional[str]:
+ """Why ``precision`` cannot run quantized on ``device``, or None."""
+ if not device.startswith("cuda"):
+ return "quantized kernels run on CUDA only"
+ from core._torchao_stub import is_stubbed, torch_is_rocm
+
+ # ROCm reports gfx versions through the CUDA capability API and these dynamic INT8 / FP8 paths are NVIDIA-only
+ # (diffusion_transformer_quant.dense_transformer_supported refuses ROCm for the same reason).
+ if torch_is_rocm():
+ return "quantized kernels run on NVIDIA CUDA only (ROCm build)"
+ if is_stubbed("torchao"):
+ return "torchao is a stub on this install"
+ if dtype is not None:
+ import torch
+ if dtype != torch.bfloat16:
+ return "the card has no bf16"
+ capability = _cuda_capability(device)
+ need = _MIN_CAPABILITY[precision]
+ if capability is None or capability < need:
+ return f"{precision} needs compute capability {need[0]}.{need[1]}+"
+ from .diffusion_transformer_quant import torchao_unavailable_reason
+ from .prequant_safetensors import safetensors_prequant_supported
+
+ why = torchao_unavailable_reason()
+ if why:
+ return why
+ if not safetensors_prequant_supported():
+ return "this torchao cannot read safetensors pre-quant files"
+ return None
+
+
+def resolve_precision(
+ device: str,
+ dtype: Any = None,
+ *,
+ available: tuple[str, ...] = QUANT_PRECISIONS,
+) -> tuple[str, str]:
+ """``(precision, why)`` for a run on ``device``. ``available`` is the quantized arms the variant ships (and, at
+ load, has on disk). bf16 when asked for, when nothing quantized can run here, or when auto has no gated arm."""
+ requested = requested_precision()
+ if requested == PRECISION_BF16:
+ return PRECISION_BF16, f"{ENV_PRECISION}=bf16"
+ candidates = AUTO_ORDER if requested == PRECISION_AUTO else (requested,)
+ reasons = []
+ for precision in candidates:
+ if precision not in available:
+ reasons.append(f"{precision}: not available")
+ continue
+ why = unsupported_reason(precision, device, dtype)
+ if why is None:
+ return (
+ precision,
+ "auto" if requested == PRECISION_AUTO else f"{ENV_PRECISION}={precision}",
+ )
+ reasons.append(f"{precision}: {why}")
+ if requested == PRECISION_AUTO and not AUTO_ORDER:
+ return PRECISION_BF16, "auto: no quantized arm passed the accuracy gate"
+ return PRECISION_BF16, "; ".join(reasons) or "bf16"
+
+
+__all__ = [
+ "AUTO_ORDER",
+ "ENV_INT8_CONVROT",
+ "ENV_PRECISION",
+ "PRECISIONS",
+ "PRECISION_AUTO",
+ "PRECISION_BF16",
+ "PRECISION_FP8",
+ "PRECISION_INT8",
+ "SEGMENTER_CONVROT_GROUP",
+ "SEGMENTER_EXCLUDE_TOKENS",
+ "SEGMENTER_MIN_FEATURES",
+ "GATE_PASSED",
+ "artifact_filename",
+ "artifact_tag",
+ "auto_may_load",
+ "write_prequant_file",
+ "checkpoint_problem",
+ "load_prequantized_segmenter",
+ "quantize_segmenter_",
+ "requested_precision",
+ "resolve_precision",
+ "segmenter_filter_fn",
+]
diff --git a/studio/backend/core/inference/stt_mtmd_sidecar.py b/studio/backend/core/inference/stt_mtmd_sidecar.py
index 6b10ef4dfdf..36428772a30 100644
--- a/studio/backend/core/inference/stt_mtmd_sidecar.py
+++ b/studio/backend/core/inference/stt_mtmd_sidecar.py
@@ -313,6 +313,12 @@ def is_model_downloaded(model_id: str) -> bool:
return downloaded
+def _hub_entry_missing(exc: BaseException) -> bool:
+ """The Hub answered that this file (or revision) does not exist, as opposed to a network, auth or gate error."""
+ names = {cls.__name__ for cls in type(exc).__mro__}
+ return bool(names & {"EntryNotFoundError", "RemoteEntryNotFoundError", "RevisionNotFoundError"})
+
+
class _MtmdDownloadState:
"""Tracks the two-file download of one mtmd dictation model.
@@ -507,12 +513,38 @@ class _MtmdDownloadState:
from huggingface_hub import get_hf_file_metadata, hf_hub_url
selected: list[_SelectedHubFile] = []
- revision: Optional[str] = None
+ # A spec may pin a commit (the segmenter's variants); none, or a branch such as "main", resolves the newest.
+ pinned = getattr(spec, "revision", None)
+ revision: Optional[str] = (
+ pinned if isinstance(pinned, str) and _HF_COMMIT_SHA.fullmatch(pinned) else None
+ )
for filename in getattr(spec, "files", None) or (spec.model_file, spec.mmproj_file):
- meta = get_hf_file_metadata(
- hf_hub_url(spec.repo, filename, revision = revision),
- token = normalize_token(hf_token),
- )
+ try:
+ meta = get_hf_file_metadata(
+ hf_hub_url(spec.repo, filename, revision = revision),
+ token = normalize_token(hf_token),
+ )
+ except Exception as exc:
+ fallback = getattr(spec, "fallback", None)
+ if not fallback or not _hub_entry_missing(exc):
+ raise
+ # A spec whose file is not published (yet) at its revision downloads its fallback instead:
+ # the segmenter's pre-quantized file falls back to the bf16 one.
+ logger.info(
+ "%s: %s is not on %s at %s (%s); downloading %s instead",
+ self._label,
+ filename,
+ spec.repo,
+ revision or "main",
+ type(exc).__name__,
+ fallback,
+ )
+ with self._lock:
+ if self._cancelled:
+ return
+ self._model_id = fallback
+ self._run(fallback, hf_token, hub_cache)
+ return
if revision is None:
revision = meta.commit_hash
if not isinstance(revision, str) or not _HF_COMMIT_SHA.fullmatch(revision):
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 547e72a8ca7..65e84bd7dea 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -5312,7 +5312,8 @@ class MaskSegmenterDownloadRequest(BaseModel):
"""Body of POST /images/segment/download (optional)."""
hf_token: Optional[str] = Field(
- None, description = "Hugging Face token for the gated facebook/sam3 download"
+ None,
+ description = "Hugging Face token, needed only for a gated segmenter variant (facebook/sam3)",
)
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 37090ebc359..0bd6416dcee 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -53147,13 +53147,13 @@ async def prompt_upsampler_preview(
return PromptUpsamplerPreviewResponse(enhanced_prompt = caption)
-# ── Text-to-mask segmenter (SAM 3) ───────────────────────────────────────────────────────────────────────────────────
+# ── Text-to-mask segmenter (SAM 3.1 / SAM 3) ─────────────────────────────────────────────────────────────────────
@studio_router.get("/images/segment/status")
async def mask_segmenter_status(current_subject: str = Depends(get_current_subject)):
- """Whether SAM 3 can run here, is downloaded (gated facebook/sam3), is loaded and where, and the download
- progress (the dictation download's shape)."""
+ """Whether SAM 3 can run here, which variant is active (repo, size, gated or not), whether it is downloaded and
+ loaded (and where), and the download progress (the dictation download's shape)."""
from core.inference import diffusion_segment
return JSONResponse(content = await asyncio.to_thread(diffusion_segment.status))
@@ -53164,26 +53164,42 @@ async def mask_segmenter_download(
current_subject: str = Depends(get_current_subject),
hf_token: HfTokenArg = Depends(get_request_hf_token),
):
- """Start the background download of facebook/sam3's transformers weights; progress on /status."""
+ """Start the background download of the active segmenter variant's transformers weights; progress on /status."""
from core.inference import diffusion_segment
from core.inference.stt_sidecar import SttDownloadCacheError, SttModelIdError
account_access.require_installation_owner()
if not diffusion_segment.transformers_supports_sam3():
raise HTTPException(status_code = 501, detail = diffusion_segment.status()["reason"])
- if diffusion_segment.status().get("override"):
+ variant = await asyncio.to_thread(diffusion_segment.active_variant)
+ if (os.environ.get(diffusion_segment.ENV_PATH_OVERRIDE) or "").strip():
raise HTTPException(
status_code = 409,
- detail = "The segmenter weights come from UNSLOTH_SAM3_PATH; unset it to download facebook/sam3.",
+ detail = (
+ f"The segmenter weights come from {diffusion_segment.ENV_PATH_OVERRIDE}; "
+ f"unset it to download {variant.repo}."
+ ),
)
+ # An ungated variant needs no token; one the user set is still sent.
token = account_access.account_hf_token(
(payload.hf_token if payload is not None and payload.hf_token else None) or hf_token
)
try:
- download_id = await asyncio.to_thread(diffusion_segment.start_download, token)
+ download_id = await asyncio.to_thread(diffusion_segment.start_download, token, variant.id)
except (SttModelIdError, SttDownloadCacheError) as exc:
raise HTTPException(status_code = 409, detail = str(exc))
- return JSONResponse(content = {**diffusion_segment.download_status(), "download_id": download_id})
+ plan = diffusion_segment.download_plan(variant)
+ return JSONResponse(
+ content = {
+ **diffusion_segment.download_status(),
+ **diffusion_segment.variant_summary(variant),
+ # The one weights file this host fetches (a pre-quantized one, or bf16) and its download size.
+ "precision": plan["precision"],
+ "weights_file": plan["file"],
+ "size_bytes": plan["size_bytes"],
+ "download_id": download_id,
+ }
+ )
@studio_router.post("/images/segment/cancel")
diff --git a/studio/backend/tests/test_diffusion_segment.py b/studio/backend/tests/test_diffusion_segment.py
index 006f78c6951..6da2f56252f 100644
--- a/studio/backend/tests/test_diffusion_segment.py
+++ b/studio/backend/tests/test_diffusion_segment.py
@@ -9,6 +9,7 @@ from __future__ import annotations
import base64
import io
+import re
import threading
import time
import types
@@ -18,6 +19,14 @@ import pytest
from core.inference import diffusion_segment as seg
[email protected](autouse = True)
+def _bf16_weights(monkeypatch):
+ """Load and download the bf16 model.safetensors whatever card the test host has: the variant and lifecycle tests
+ here count its bytes and files. The pre-quantized choice is covered in test_diffusion_segment_quant.py."""
+ monkeypatch.setenv("UNSLOTH_SAM3_PRECISION", "bf16")
+ monkeypatch.delenv("UNSLOTH_SAM3_INT8_CONVROT", raising = False)
+
+
@pytest.fixture(autouse = True)
def _no_other_gpu_owner(monkeypatch):
"""Start every test with no GPU arbiter resident.
@@ -304,7 +313,17 @@ def test_tiny_model_segments_at_source_size(tiny_sam3):
assert mask.mode == "L" and mask.size == (64, 40)
body = result.to_json()
assert body["mask"].startswith("data:image/png;base64,")
- assert set(body) == {"mask", "width", "height", "instances", "prompts", "device", "elapsed_ms"}
+ assert set(body) == {
+ "mask",
+ "width",
+ "height",
+ "instances",
+ "prompts",
+ "device",
+ "precision",
+ "elapsed_ms",
+ }
+ assert body["precision"] == "bf16"
# No keep-alive: the weights left with the call.
assert not segmenter.loaded
# An unreachable threshold keeps nothing: an all-black mask, still at the source size.
@@ -790,55 +809,234 @@ def test_sharded_override_needs_every_shard(tmp_path, monkeypatch):
def test_status_shape(monkeypatch):
monkeypatch.delenv(seg.ENV_PATH_OVERRIDE, raising = False)
+ monkeypatch.delenv(seg.ENV_VARIANT, raising = False)
monkeypatch.setattr(seg, "_cached_snapshot", lambda *a, **k: None)
body = seg.status()
- assert body["repo"] == "facebook/sam3" and body["gated"] is True
+ assert body["variant"] == seg.DEFAULT_VARIANT == "sam3.1" and body["label"] == "SAM 3.1"
+ assert body["repo"] == seg.SAM31_REPO and body["gated"] is False
assert body["downloaded"] is False and body["loaded"] is False
- assert body["license_url"].startswith("https://huggingface.co/facebook/sam3")
- assert body["size_bytes"] > 3_000_000_000
+ assert body["license_url"].startswith(f"https://huggingface.co/{seg.SAM31_REPO}")
+ assert 1_600_000_000 < body["size_bytes"] < 1_800_000_000
assert {"downloading", "error", "bytes_total", "bytes_done"} <= set(body["download"])
-def test_the_download_names_only_what_sam3model_reads():
- assert seg.SEGMENTER_SPEC.files == seg.SEGMENTER_FILES
- assert "model.safetensors" in seg.SEGMENTER_FILES and "sam3.pt" not in seg.SEGMENTER_FILES
+# ── variants ────────────────────────────────────────────────────────────────────────────────────────────────────────
+_SHA = re.compile(r"[0-9a-f]{40}")
+
+
+def test_variant_table():
+ assert list(seg.SEGMENTER_VARIANTS) == ["sam3.1", "sam3"] and seg.DEFAULT_VARIANT == "sam3.1"
+ sam31, sam3 = seg.SEGMENTER_VARIANTS["sam3.1"], seg.SEGMENTER_VARIANTS["sam3"]
+ assert sam31.repo == seg.SAM31_REPO and re.fullmatch(r"[\w.-]+/[\w.-]+", sam31.repo)
+ assert sam31.gated is False and sam3.gated is True
+ assert (
+ sam3.repo == "facebook/sam3" and sam3.license_url == "https://huggingface.co/facebook/sam3"
+ )
+ # bf16 SAM 3.1 is half of the fp32 facebook/sam3 download.
+ assert 1_600_000_000 < sam31.size_bytes < 1_800_000_000 < 3_400_000_000 < sam3.size_bytes
+ for variant in seg.SEGMENTER_VARIANTS.values():
+ assert variant.id in seg.SEGMENTER_SPECS
+ spec = seg.SEGMENTER_SPECS[variant.id]
+ assert (spec.repo, spec.files, spec.revision) == (
+ variant.repo,
+ variant.files,
+ variant.revision,
+ )
+ assert "model.safetensors" in variant.files and "sam3.pt" not in variant.files
+ assert not any(name.endswith(".pt") for name in variant.files)
+ assert variant.license_url.startswith(f"https://huggingface.co/{variant.repo}")
+
+
+def test_pinned_revision_constants():
+ """facebook/sam3 and unsloth/sam3.1 (bf16 and pre-quantized files) are pinned to full commit shas, never a
+ short or partial one."""
+ assert _SHA.fullmatch(seg.SAM3_REVISION)
+ assert _SHA.fullmatch(seg.SAM31_REVISION)
+ assert _SHA.fullmatch(seg.SAM31_PREQUANT_REVISION)
+ for variant in seg.SEGMENTER_VARIANTS.values():
+ assert variant.revision == "main" or _SHA.fullmatch(variant.revision)
+ assert seg.pinned_revision(variant) == (
+ None if variant.revision == "main" else variant.revision
+ )
+ assert seg.pinned_revision(seg.SEGMENTER_VARIANTS["sam3"]) == seg.SAM3_REVISION
+
+
+def test_variant_env_choice(monkeypatch):
+ for value, expected in (
+ ("sam3", "sam3"),
+ (" SAM3.1 ", "sam3.1"),
+ ("facebook/sam3", "sam3"),
+ (seg.SAM31_REPO.upper(), "sam3.1"),
+ ("sam2", None),
+ ("", None),
+ ):
+ monkeypatch.setenv(seg.ENV_VARIANT, value)
+ assert seg.requested_variant_id() == expected, value
+
+
+def _cached(*ids):
+ return (
+ lambda model_id = seg.DEFAULT_VARIANT, **_k: f"/cache/{model_id}" if model_id in ids else None
+ )
+
+
+def test_active_variant_prefers_the_default_and_keeps_an_existing_sam3(monkeypatch):
+ monkeypatch.delenv(seg.ENV_PATH_OVERRIDE, raising = False)
+ monkeypatch.delenv(seg.ENV_VARIANT, raising = False)
+ monkeypatch.setattr(seg, "_cached_snapshot", _cached())
+ assert seg.active_variant().id == "sam3.1" and seg.model_dir() is None
+ # An install that already fetched facebook/sam3 keeps using it rather than downloading again.
+ monkeypatch.setattr(seg, "_cached_snapshot", _cached("sam3"))
+ assert seg.active_variant().id == "sam3" and seg.model_dir() == "/cache/sam3"
+ monkeypatch.setattr(seg, "_cached_snapshot", _cached("sam3", "sam3.1"))
+ assert seg.active_variant().id == "sam3.1" and seg.model_dir() == "/cache/sam3.1"
+ # The env choice wins even when only the other variant is on disk.
+ monkeypatch.setenv(seg.ENV_VARIANT, "sam3")
+ monkeypatch.setattr(seg, "_cached_snapshot", _cached("sam3.1"))
+ assert seg.active_variant().id == "sam3" and seg.model_dir() is None
+
+
+def test_status_reports_gated_and_ungated_variants(monkeypatch):
+ monkeypatch.delenv(seg.ENV_PATH_OVERRIDE, raising = False)
+ monkeypatch.setattr(seg, "transformers_supports_sam3", lambda: True)
+ monkeypatch.setattr(seg, "_cached_snapshot", _cached())
+ monkeypatch.setenv(seg.ENV_VARIANT, "sam3")
+ body = seg.status()
+ assert (body["variant"], body["label"], body["repo"], body["gated"]) == (
+ "sam3",
+ "SAM 3",
+ "facebook/sam3",
+ True,
+ )
+ assert body["revision"] == seg.SAM3_REVISION and body["size_bytes"] == seg.SAM3_SIZE_BYTES
+ assert body["downloaded"] is False
+ monkeypatch.setenv(seg.ENV_VARIANT, "sam3.1")
+ body = seg.status()
+ assert (body["variant"], body["label"], body["repo"], body["gated"]) == (
+ "sam3.1",
+ "SAM 3.1",
+ seg.SAM31_REPO,
+ False,
+ )
+ assert body["size_bytes"] == seg.SAM31_SIZE_BYTES
+ monkeypatch.setattr(seg, "_cached_snapshot", _cached("sam3.1"))
+ assert seg.status()["downloaded"] is True
+ # Unsupported installs still name the variant they would use, without touching the cache.
+ monkeypatch.setattr(seg, "transformers_supports_sam3", lambda: False)
+ monkeypatch.setattr(seg, "_cached_snapshot", lambda *a, **k: pytest.fail("cache read"))
+ body = seg.status()
+ assert body["variant"] == "sam3.1" and body["downloaded"] is False
+
+
+def test_override_still_wins_over_the_variant(tmp_path, monkeypatch):
+ monkeypatch.setenv(seg.ENV_PATH_OVERRIDE, str(tmp_path))
+ monkeypatch.setenv(seg.ENV_VARIANT, "sam3")
+ monkeypatch.setattr(seg, "_cached_snapshot", _cached("sam3", "sam3.1"))
+ for name in ("config.json", "model.safetensors", "tokenizer.json"):
+ (tmp_path / name).write_bytes(b"{}")
+ assert seg.model_dir() == str(tmp_path)
+ monkeypatch.setattr(seg, "transformers_supports_sam3", lambda: True)
+ body = seg.status()
+ assert body["override"] is True and body["downloaded"] is True and body["variant"] == "sam3"
+ # With the override the cache is not consulted: a cached facebook/sam3 never relabels the override as SAM 3.
+ monkeypatch.delenv(seg.ENV_VARIANT)
+ monkeypatch.setattr(seg, "_cached_snapshot", lambda *a, **k: pytest.fail("cache read"))
+ body = seg.status()
+ assert (
+ body["variant"] == seg.DEFAULT_VARIANT
+ and body["gated"] is False
+ and body["downloaded"] is True
+ )
+ assert seg.active_variant().id == seg.DEFAULT_VARIANT
+
+
+def test_cached_snapshot_reads_the_variant_repo_at_its_pin(tmp_path, monkeypatch):
+ from core.inference import stt_sidecar
+
+ monkeypatch.setattr(stt_sidecar, "_read_revision_record", lambda repo: None)
+ variant = seg.SEGMENTER_VARIANTS["sam3"]
+ snapshot = tmp_path / "models--facebook--sam3" / "snapshots" / variant.revision
+ snapshot.mkdir(parents = True)
+ for name in variant.files[:-1]:
+ (snapshot / name).write_text("{}")
+ assert seg._cached_snapshot("sam3", hub_cache = tmp_path) is None # no weights yet
+ (snapshot / seg.SEGMENTER_WEIGHTS_FILE).write_bytes(b"")
+ assert seg._cached_snapshot("sam3", hub_cache = tmp_path) == str(snapshot)
+ # facebook/sam3's files are not unsloth/sam3.1's.
+ assert seg._cached_snapshot("sam3.1", hub_cache = tmp_path) is None
def test_gated_download_error_names_the_license():
class GatedRepoError(Exception):
pass
+ sam3 = seg.SEGMENTER_VARIANTS["sam3"]
message = seg.describe_download_error("sam3", GatedRepoError("403 Client Error"))
- assert "license" in message and seg.SEGMENTER_LICENSE_URL in message
+ assert "license" in message and sam3.license_url in message and sam3.repo in message
assert seg.describe_download_error("sam3", RuntimeError("disk full")) is None
+ # An ungated variant needs no token or license: a refusal there keeps the generic message.
+ assert seg.describe_download_error("sam3.1", GatedRepoError("401 Client Error")) is None
+
[email protected]("variant_id", ["sam3.1", "sam3"])
+def test_download_fetches_the_variant_files_at_its_revision(monkeypatch, tmp_path, variant_id):
+ """The pinned downloader asks for exactly the variant's files, at its pinned commit (or main, recorded)."""
+ from huggingface_hub import hf_hub_url
-def test_shared_download_state_uses_the_spec_file_list(monkeypatch, tmp_path):
- """The pinned downloader fetches a spec's ``files`` when it has them (the dictation specs keep their pair)."""
from core.inference import stt_mtmd_sidecar as mtmd
+ variant = seg.SEGMENTER_VARIANTS[variant_id]
+ resolved = seg.pinned_revision(variant) or "b" * 40
seen = []
class _Meta:
- commit_hash = "a" * 40
+ commit_hash = resolved
size = 10
etag = "e"
def _meta(url, token = None):
seen.append(url)
- raise RuntimeError("stop after the first lookup")
+ return _Meta()
+
+ def _stop(repo):
+ seen.append(("claim", repo))
+ raise RuntimeError("stop before the transfer")
monkeypatch.setattr("huggingface_hub.get_hf_file_metadata", _meta)
+ monkeypatch.setattr(mtmd, "_claim_stt_repository", _stop)
state = mtmd._MtmdDownloadState(
- specs = {seg.SEGMENTER_ID: seg.SEGMENTER_SPEC},
+ specs = seg.SEGMENTER_SPECS,
cached_paths = lambda *a, **k: None,
resolve = seg._resolve_segmenter_id,
- label = "SAM 3 segmenter",
- describe_error = lambda model_id, error: "described",
+ label = "Mask segmenter",
+ describe_error = lambda model_id, error: f"described {model_id}",
)
- state._run(seg.SEGMENTER_ID, None, hub_cache = tmp_path)
- assert seen and seen[0].endswith(seg.SEGMENTER_FILES[0])
- assert state.status()["error"] == "described"
+ state._run(variant_id, None, hub_cache = tmp_path)
+ # The first lookup resolves the revision (the pin, else main), the rest are asked at that commit.
+ expected = [hf_hub_url(variant.repo, variant.files[0], revision = seg.pinned_revision(variant))]
+ expected += [hf_hub_url(variant.repo, name, revision = resolved) for name in variant.files[1:]]
+ if variant.revision == "main":
+ assert "/resolve/main/" in expected[0]
+ else:
+ assert all(f"/resolve/{variant.revision}/" in url for url in expected)
+ assert seen[:-1] == expected and seen[-1] == ("claim", variant.repo)
+ assert state.status()["error"] == f"described {variant_id}"
+
+
+def test_start_download_uses_the_active_variant(monkeypatch):
+ started = []
+
+ class _State:
+ def start(self, model_id, token):
+ started.append((model_id, token))
+ return "dl"
+
+ monkeypatch.setattr(seg, "_get_download_state", lambda: _State())
+ monkeypatch.setattr(seg, "active_variant", lambda: seg.SEGMENTER_VARIANTS["sam3"])
+ assert seg.start_download("hf_x") == "dl" and started[-1] == ("sam3", "hf_x")
+ assert seg.start_download(None, "sam3.1") == "dl" and started[-1] == ("sam3.1", None)
+ with pytest.raises(ValueError):
+ seg.start_download(None, "sam2")
# ── GPU arbiter hooks ───────────────────────────────────────────────────────────────────────────────────────────────
@@ -1370,13 +1568,25 @@ def test_status_download_cancel_release_routes(client, monkeypatch):
)
assert http.get("/api/inference/images/segment/status").json()["downloaded"] is False
monkeypatch.setattr(seg, "transformers_supports_sam3", lambda: True)
+ monkeypatch.delenv(seg.ENV_PATH_OVERRIDE, raising = False)
+ monkeypatch.setattr(seg, "active_variant", lambda: seg.SEGMENTER_VARIANTS["sam3.1"])
started = {}
monkeypatch.setattr(
- seg, "start_download", lambda token: started.setdefault("token", token) and "dl-1"
+ seg,
+ "start_download",
+ lambda token, variant: started.update(token = token, variant = variant) or "dl-1",
)
monkeypatch.setattr(seg, "download_status", lambda: {"downloading": True})
r = http.post("/api/inference/images/segment/download", json = {"hf_token": "hf_x"})
- assert r.status_code == 200 and r.json()["download_id"] == "dl-1" and started["token"] == "hf_x"
+ assert r.status_code == 200 and r.json()["download_id"] == "dl-1"
+ assert started == {"token": "hf_x", "variant": "sam3.1"}
+ body = r.json()
+ assert (body["variant"], body["repo"], body["gated"]) == ("sam3.1", seg.SAM31_REPO, False)
+ assert body["size_bytes"] == seg.SAM31_SIZE_BYTES and body["downloading"] is True
+ monkeypatch.setenv(seg.ENV_PATH_OVERRIDE, "/somewhere")
+ r = http.post("/api/inference/images/segment/download")
+ assert r.status_code == 409 and seg.SAM31_REPO in r.json()["detail"]
+ monkeypatch.delenv(seg.ENV_PATH_OVERRIDE)
monkeypatch.setattr(seg, "cancel_download", lambda: True)
r = http.post("/api/inference/images/segment/cancel")
assert r.status_code == 200 and r.json()["cancelled"] is True
diff --git a/studio/backend/tests/test_diffusion_segment_quant.py b/studio/backend/tests/test_diffusion_segment_quant.py
new file mode 100644
index 00000000000..da4f70054f3
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_segment_quant.py
@@ -0,0 +1,799 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Pre-quantized SAM 3.1 detector files for Mask from text: the precision choice (UNSLOTH_SAM3_PRECISION, auto, CUDA
+only), the per-precision download specs and their bf16 fallback when a file is not published, which weights a load
+uses, the header checks, and a real build -> save -> load round trip on a tiny random Sam3Model (dequantized on the
+CPU; quantized kernels on CUDA when a card is present)."""
+
+from __future__ import annotations
+
+import dataclasses
+import json
+import re
+from pathlib import Path
+
+import pytest
+
+from core.inference import diffusion_segment as seg
+from core.inference import diffusion_segment_quant as sq
+
+
[email protected](autouse = True)
+def _clean_env(monkeypatch):
+ for name in (sq.ENV_PRECISION, sq.ENV_INT8_CONVROT, seg.ENV_PATH_OVERRIDE, seg.ENV_VARIANT):
+ monkeypatch.delenv(name, raising = False)
+ monkeypatch.setattr(seg, "_BROKEN_PREQUANT", set())
+
+
+def _cuda(monkeypatch, capability):
+ """Pretend ``cuda:N`` cards have ``capability`` (None: no CUDA) and torchao can read the files."""
+ monkeypatch.setattr(sq, "_cuda_capability", lambda device: capability)
+ from core.inference import diffusion_transformer_quant as tq
+ from core.inference import prequant_safetensors as pst
+
+ monkeypatch.setattr(tq, "torchao_unavailable_reason", lambda: None)
+ monkeypatch.setattr(pst, "safetensors_prequant_supported", lambda: True)
+
+
+# ── precision choice ───────────────────────────────────────────────────────────────────────────────────────────────
+ "value, expected",
+ [
+ ("", "auto"),
+ ("auto", "auto"),
+ (" BF16 ", "bf16"),
+ ("bfloat16", "bf16"),
+ ("fp8", "fp8"),
+ ("INT8", "int8"),
+ ("nf4", "auto"),
+ ],
+)
+def test_requested_precision(monkeypatch, value, expected):
+ monkeypatch.setenv(sq.ENV_PRECISION, value)
+ assert sq.requested_precision() == expected
+
+
+def test_auto_follows_the_gated_order_on_cuda(monkeypatch):
+ import torch
+
+ _cuda(monkeypatch, (9, 0))
+ assert sq.AUTO_ORDER, "the gate passed at least one quantized arm"
+ assert sq.resolve_precision("cuda:0", torch.bfloat16)[0] == sq.AUTO_ORDER[0]
+ # Only what is on disk (or published) counts.
+ assert sq.resolve_precision("cuda:0", available = ())[0] == "bf16"
+ assert sq.resolve_precision("cuda:0", available = (sq.AUTO_ORDER[-1],))[0] == sq.AUTO_ORDER[-1]
+ monkeypatch.setattr(sq, "AUTO_ORDER", ())
+ precision, why = sq.resolve_precision("cuda:0")
+ assert precision == "bf16" and "gate" in why
+
+
+def test_quantized_kernels_are_cuda_only(monkeypatch):
+ import torch
+
+ _cuda(monkeypatch, (10, 0))
+ for value in ("auto", "fp8", "int8"):
+ monkeypatch.setenv(sq.ENV_PRECISION, value)
+ for device in ("cpu", "mps"):
+ precision, why = sq.resolve_precision(device, torch.float32)
+ assert precision == "bf16" and (value == "auto" or "CUDA only" in why), (value, device)
+ # A card without bf16 runs the segmenter in fp16: dense.
+ monkeypatch.setenv(sq.ENV_PRECISION, "int8")
+ assert sq.resolve_precision("cuda:0", torch.float16)[0] == "bf16"
+
+
+def test_capability_floors(monkeypatch):
+ _cuda(monkeypatch, (8, 0)) # Ampere: int8 yes, fp8 no
+ monkeypatch.setenv(sq.ENV_PRECISION, "fp8")
+ precision, why = sq.resolve_precision("cuda:0")
+ assert precision == "bf16" and "8.9" in why
+ monkeypatch.setenv(sq.ENV_PRECISION, "int8")
+ assert sq.resolve_precision("cuda:0")[0] == "int8"
+ _cuda(monkeypatch, (8, 9))
+ monkeypatch.setenv(sq.ENV_PRECISION, "fp8")
+ assert sq.resolve_precision("cuda:0")[0] == "fp8"
+ _cuda(monkeypatch, (7, 5)) # Turing
+ monkeypatch.setenv(sq.ENV_PRECISION, "int8")
+ assert sq.resolve_precision("cuda:0")[0] == "bf16"
+ monkeypatch.setenv(sq.ENV_PRECISION, "bf16")
+ _cuda(monkeypatch, (10, 0))
+ assert sq.resolve_precision("cuda:0") == ("bf16", f"{sq.ENV_PRECISION}=bf16")
+
+
+def test_a_missing_torchao_keeps_bf16(monkeypatch):
+ _cuda(monkeypatch, (10, 0))
+ from core.inference import diffusion_transformer_quant as tq
+
+ monkeypatch.setattr(tq, "torchao_unavailable_reason", lambda: "no torchao")
+ monkeypatch.setenv(sq.ENV_PRECISION, "int8")
+ assert sq.resolve_precision("cuda:0") == ("bf16", "int8: no torchao")
+
+
+# ── the variant table ──────────────────────────────────────────────────────────────────────────────────────────────
+def test_sam31_lists_one_file_per_scheme_and_sam3_none():
+ sam31, sam3 = seg.SEGMENTER_VARIANTS["sam3.1"], seg.SEGMENTER_VARIANTS["sam3"]
+ names = {(a.precision, a.rotated): a.filename for a in sam31.prequant}
+ assert names == {
+ ("int8", True): "sam3.1-INT8-ConvRot.safetensors",
+ ("int8", False): "sam3.1-INT8.safetensors",
+ ("fp8", False): "sam3.1-FP8.safetensors",
+ }
+ for artifact in sam31.prequant:
+ assert artifact.filename == sq.artifact_filename(
+ "sam3.1", artifact.precision, rotated = artifact.rotated
+ )
+ # Every pre-quantized file is smaller than the bf16 one it replaces.
+ assert 0 < artifact.size_bytes < seg.SAM31_SIZE_BYTES - seg.SAM31_CONFIG_BYTES
+ assert sam3.prequant == () and sam3.prequant_revision is None
+ rev = sam31.prequant_revision
+ assert rev is None or rev == "main" or re.fullmatch(r"[0-9a-f]{40}", rev)
+
+
+def test_each_file_has_a_download_spec_that_falls_back_to_bf16():
+ sam31 = seg.SEGMENTER_VARIANTS["sam3.1"]
+ for artifact in sam31.prequant:
+ spec_id = seg.prequant_spec_id(sam31, artifact)
+ spec = seg.SEGMENTER_SPECS[spec_id]
+ assert spec.files == seg.SEGMENTER_CONFIG_FILES + (artifact.filename,)
+ assert seg.SEGMENTER_WEIGHTS_FILE not in spec.files # only the chosen weights file
+ assert (spec.repo, spec.revision, spec.fallback) == (
+ sam31.repo,
+ sam31.prequant_revision,
+ "sam3.1",
+ )
+ assert seg.split_spec_id(spec_id) == (sam31, artifact)
+ assert seg._resolve_segmenter_id(spec_id) == spec_id
+ assert seg.SEGMENTER_SPECS["sam3.1"].fallback is None
+ with pytest.raises(ValueError):
+ seg._resolve_segmenter_id("sam3.1@nf4")
+
+
+def test_int8_is_the_convrot_file_unless_turned_off(monkeypatch):
+ sam31 = seg.SEGMENTER_VARIANTS["sam3.1"]
+ assert seg.variant_artifact(sam31, "int8").filename == "sam3.1-INT8-ConvRot.safetensors"
+ monkeypatch.setenv(sq.ENV_INT8_CONVROT, "0")
+ assert seg.variant_artifact(sam31, "int8").filename == "sam3.1-INT8.safetensors"
+ assert seg.variant_artifact(sam31, "fp8").filename == "sam3.1-FP8.safetensors"
+ assert seg.variant_artifact(seg.SEGMENTER_VARIANTS["sam3"], "int8") is None
+
+
+def _published(monkeypatch, revision = "main"):
+ """sam3.1 with its pre-quantized files published at ``revision``."""
+ variant = dataclasses.replace(seg.SEGMENTER_VARIANTS["sam3.1"], prequant_revision = revision)
+ monkeypatch.setitem(seg.SEGMENTER_VARIANTS, "sam3.1", variant)
+ return variant
+
+
+def test_download_plan_fetches_one_weights_file(monkeypatch):
+ _cuda(monkeypatch, (9, 0))
+ unpublished = dataclasses.replace(seg.SEGMENTER_VARIANTS["sam3.1"], prequant_revision = None)
+ # Not published: the bf16 files, whatever the host.
+ plan = seg.download_plan(unpublished, "cuda:0")
+ assert (plan["spec"], plan["precision"], plan["size_bytes"]) == (
+ "sam3.1",
+ "bf16",
+ seg.SAM31_SIZE_BYTES,
+ )
+ variant = _published(monkeypatch)
+ plan = seg.download_plan(variant, "cuda:0")
+ artifact = seg.variant_artifact(variant, sq.AUTO_ORDER[0])
+ assert (
+ plan["spec"] == seg.prequant_spec_id(variant, artifact)
+ and plan["precision"] == sq.AUTO_ORDER[0]
+ )
+ assert plan["file"] == artifact.filename
+ assert plan["size_bytes"] == artifact.size_bytes + seg.SAM31_CONFIG_BYTES < seg.SAM31_SIZE_BYTES
+ # CPU / Mac hosts fetch bf16.
+ assert seg.download_plan(variant, "cpu")["spec"] == "sam3.1"
+ assert seg.download_plan(variant, "mps")["spec"] == "sam3.1"
+ monkeypatch.setenv(sq.ENV_PRECISION, "bf16")
+ assert seg.download_plan(variant, "cuda:0")["spec"] == "sam3.1"
+
+
+def test_start_download_uses_the_plan(monkeypatch):
+ _cuda(monkeypatch, (9, 0))
+ variant = _published(monkeypatch)
+ monkeypatch.setattr(seg, "SEGMENTER_SPECS", seg._build_specs())
+ monkeypatch.setattr(seg, "_host_device", lambda: "cuda:0")
+ started = []
+
+ class _State:
+ def start(self, model_id, token):
+ started.append(model_id)
+ return "id"
+
+ monkeypatch.setattr(seg, "_get_download_state", lambda: _State())
+ seg.start_download(None, "sam3.1")
+ assert started == [
+ seg.prequant_spec_id(variant, seg.variant_artifact(variant, sq.AUTO_ORDER[0]))
+ ]
+ # A spec id passes through untouched.
+ seg.start_download(None, "sam3.1@fp8")
+ assert started[-1] == "sam3.1@fp8"
+
+
+class _Meta:
+ def __init__(self, commit):
+ self.commit_hash, self.size, self.etag = commit, 10, "e"
+
+
+def _download_state(monkeypatch, missing_exc):
+ """A download state whose Hub has every file except the pre-quantized ones (they raise ``missing_exc``)."""
+ from core.inference import stt_mtmd_sidecar as mtmd
+
+ seen, commit = [], "c" * 40
+
+ def _meta(url, token = None):
+ seen.append(url.rsplit("/", 1)[-1])
+ if "INT8" in url or "FP8" in url:
+ raise missing_exc
+ asked = url.split("/resolve/", 1)[1].split("/", 1)[0]
+ return _Meta(asked if re.fullmatch(r"[0-9a-f]{40}", asked) else commit)
+
+ def _stop(repo):
+ seen.append(("claim", repo))
+ raise RuntimeError("stop before the transfer")
+
+ monkeypatch.setattr("huggingface_hub.get_hf_file_metadata", _meta)
+ monkeypatch.setattr(mtmd, "_claim_stt_repository", _stop)
+ specs = seg._build_specs()
+ state = mtmd._MtmdDownloadState(
+ specs = specs,
+ cached_paths = lambda *a, **k: None,
+ resolve = seg._resolve_segmenter_id,
+ label = "Mask segmenter",
+ describe_error = lambda model_id, error: None,
+ )
+ return state, seen
+
+
+def test_an_unpublished_file_downloads_bf16_instead(monkeypatch, tmp_path):
+ from huggingface_hub.errors import EntryNotFoundError
+
+ _published(monkeypatch)
+ state, seen = _download_state(
+ monkeypatch, EntryNotFoundError("404 Client Error: Entry Not Found")
+ )
+ state._model_id = "sam3.1@int8-convrot"
+ state._run("sam3.1@int8-convrot", None, hub_cache = tmp_path)
+ # The quantized file was asked for first, then every bf16 file, and the bf16 run went on to claim the repo.
+ assert seen[0] == "config.json" and "sam3.1-INT8-ConvRot.safetensors" in seen
+ assert seg.SEGMENTER_WEIGHTS_FILE in seen and ("claim", seg.SAM31_REPO) in seen
+ assert state._model_id == "sam3.1"
+
+
+def test_other_hub_errors_do_not_fall_back(monkeypatch, tmp_path):
+ _published(monkeypatch)
+ state, seen = _download_state(monkeypatch, ConnectionError("network down"))
+ state._model_id = "sam3.1@fp8"
+ state._run("sam3.1@fp8", None, hub_cache = tmp_path)
+ assert seg.SEGMENTER_WEIGHTS_FILE not in seen and state._model_id == "sam3.1@fp8"
+ assert state.status()["error"]
+
+
+def test_cached_snapshot_finds_a_prequant_spec(tmp_path, monkeypatch):
+ from core.inference import stt_sidecar
+
+ monkeypatch.setattr(stt_sidecar, "_read_revision_record", lambda repo: None)
+ variant = _published(monkeypatch, "d" * 40)
+ monkeypatch.setattr(seg, "SEGMENTER_SPECS", seg._build_specs())
+ snapshot = tmp_path / "models--unsloth--sam3.1" / "snapshots" / ("d" * 40)
+ snapshot.mkdir(parents = True)
+ for name in seg.SEGMENTER_CONFIG_FILES:
+ (snapshot / name).write_text("{}")
+ spec_id = "sam3.1@fp8"
+ assert seg._cached_snapshot(spec_id, hub_cache = tmp_path) is None
+ (snapshot / "sam3.1-FP8.safetensors").write_bytes(b"")
+ assert seg._cached_snapshot(spec_id, hub_cache = tmp_path) == str(snapshot)
+ # The bf16 spec still needs model.safetensors.
+ assert seg._cached_snapshot("sam3.1", hub_cache = tmp_path) is None
+ # A variant with only a pre-quantized file cached is downloaded, when the precision setting may load that file:
+ # fp8 failed the gate, so under auto it is ignored and the auto file is offered for download instead.
+ monkeypatch.setattr(
+ seg, "_cached_snapshot", lambda model_id, **k: "/snap" if model_id == spec_id else None
+ )
+ assert seg._variant_snapshot("sam3.1") is None
+ monkeypatch.setenv(sq.ENV_PRECISION, "fp8")
+ assert seg._variant_snapshot("sam3.1") == "/snap"
+ monkeypatch.setenv(sq.ENV_PRECISION, "bf16")
+ assert seg._variant_snapshot("sam3.1") is None
+ monkeypatch.delenv(sq.ENV_PRECISION)
+ convrot_id = "sam3.1@int8-convrot"
+ monkeypatch.setattr(
+ seg, "_cached_snapshot", lambda model_id, **k: "/snap" if model_id == convrot_id else None
+ )
+ assert seg._variant_snapshot("sam3.1") == "/snap"
+ assert variant.id == "sam3.1"
+
+
+# ── which weights a load uses ──────────────────────────────────────────────────────────────────────────────────────
+def _folder(tmp_path, *names):
+ tmp_path.mkdir(parents = True, exist_ok = True)
+ for name in ("config.json", "tokenizer.json", *names):
+ (tmp_path / name).write_bytes(b"{}")
+ return str(tmp_path)
+
+
+def test_plan_weights(monkeypatch, tmp_path):
+ import torch
+
+ _cuda(monkeypatch, (9, 0))
+ sam31 = seg.SEGMENTER_VARIANTS["sam3.1"]
+ every = [a.filename for a in sam31.prequant]
+ full = _folder(tmp_path / "full", "model.safetensors", *every)
+ plan = seg.plan_weights(full, "cuda:0", torch.bfloat16, variant = sam31, use_cache = False)
+ first = seg.variant_artifact(sam31, sq.AUTO_ORDER[0])
+ assert (plan.precision, plan.weights, plan.dequantize) == (
+ sq.AUTO_ORDER[0],
+ str(Path(full) / first.filename),
+ False,
+ )
+ # The CPU (OOM retry, a busy card) and Metal keep the bf16 file.
+ for device in ("cpu", "mps"):
+ plan = seg.plan_weights(full, device, torch.float32, variant = sam31, use_cache = False)
+ assert (plan.precision, plan.weights) == ("bf16", None)
+ # bf16 asked for.
+ monkeypatch.setenv(sq.ENV_PRECISION, "bf16")
+ assert seg.plan_weights(full, "cuda:0", variant = sam31, use_cache = False).weights is None
+ monkeypatch.setenv(sq.ENV_PRECISION, "fp8")
+ assert seg.plan_weights(full, "cuda:0", variant = sam31, use_cache = False).weights.endswith(
+ "FP8.safetensors"
+ )
+ # Not yet uploaded: only model.safetensors on disk -> bf16, no error.
+ monkeypatch.setenv(sq.ENV_PRECISION, "int8")
+ dense = _folder(tmp_path / "dense", "model.safetensors")
+ plan = seg.plan_weights(dense, "cuda:0", variant = sam31, use_cache = False)
+ assert (plan.precision, plan.weights) == ("bf16", None) and "not available" in plan.reason
+ # Only the plain INT8 file while ConvRot is preferred: never used as a stand-in.
+ plain = _folder(tmp_path / "plain", "model.safetensors", "sam3.1-INT8.safetensors")
+ assert seg.plan_weights(plain, "cuda:0", variant = sam31, use_cache = False).precision == "bf16"
+ monkeypatch.setenv(sq.ENV_INT8_CONVROT, "0")
+ assert seg.plan_weights(plain, "cuda:0", variant = sam31, use_cache = False).precision == "int8"
+
+
+def test_only_a_quantized_file_on_a_cpu_is_dequantized(monkeypatch, tmp_path):
+ _cuda(monkeypatch, (9, 0))
+ sam31 = seg.SEGMENTER_VARIANTS["sam3.1"]
+ only = _folder(tmp_path, "sam3.1-INT8-ConvRot.safetensors")
+ plan = seg.plan_weights(only, "cpu", variant = sam31, use_cache = False)
+ assert (
+ plan.precision == "bf16"
+ and plan.dequantize
+ and plan.weights.endswith("INT8-ConvRot.safetensors")
+ )
+ plan = seg.plan_weights(only, "cuda:0", variant = sam31, use_cache = False)
+ assert plan.precision == "int8" and not plan.dequantize
+
+
+def test_a_file_the_selection_rejected_is_never_dequantized(monkeypatch, tmp_path):
+ """FP8 downloaded earlier, then back on auto (FP8 failed the gate): not run, not dequantized, not downloaded."""
+ _cuda(monkeypatch, (9, 0))
+ sam31 = seg.SEGMENTER_VARIANTS["sam3.1"]
+ only = _folder(tmp_path, "sam3.1-FP8.safetensors")
+ for device in ("cuda:0", "cpu"):
+ plan = seg.plan_weights(only, device, variant = sam31, use_cache = False)
+ assert (plan.precision, plan.weights, plan.dequantize) == ("bf16", None, False)
+ # bf16 asked for: an int8 file on disk is not a bf16 model either.
+ monkeypatch.setenv(sq.ENV_PRECISION, "bf16")
+ convrot = _folder(tmp_path / "convrot", "sam3.1-INT8-ConvRot.safetensors")
+ assert seg.plan_weights(convrot, "cpu", variant = sam31, use_cache = False).weights is None
+ # Asked for explicitly, the fp8 file is what runs (and on the CPU it is dequantized).
+ monkeypatch.setenv(sq.ENV_PRECISION, "fp8")
+ plan = seg.plan_weights(only, "cpu", variant = sam31, use_cache = False)
+ assert plan.dequantize and plan.weights.endswith("FP8.safetensors")
+
+
+def test_rocm_never_runs_the_quantized_files(monkeypatch):
+ from core import _torchao_stub
+
+ _cuda(monkeypatch, (9, 4))
+ assert sq.unsupported_reason("int8", "cuda:0") is None
+ monkeypatch.setattr(_torchao_stub, "torch_is_rocm", lambda: True)
+ assert "ROCm" in sq.unsupported_reason("int8", "cuda:0")
+ assert sq.resolve_precision("cuda:0", available = ("int8", "fp8"))[0] == "bf16"
+ sam31 = seg.SEGMENTER_VARIANTS["sam3.1"]
+ assert seg.download_plan(sam31, "cuda:0")["precision"] == "bf16"
+
+
+def test_an_override_folder_holds_the_reported_variants_file(tmp_path, monkeypatch):
+ """UNSLOTH_SAM3_VARIANT=sam3 with only a SAM 3.1 file in the override folder: nothing sam3 can load."""
+ _folder(tmp_path, "sam3.1-INT8-ConvRot.safetensors")
+ monkeypatch.setenv(seg.ENV_PATH_OVERRIDE, str(tmp_path))
+ assert seg.model_dir() == str(tmp_path)
+ monkeypatch.setenv(seg.ENV_VARIANT, "sam3")
+ assert seg.model_dir() is None
+
+
+def test_no_prequant_reader_means_no_quantized_file_counts(tmp_path, monkeypatch):
+ """No torchao (or the Windows ROCm stub): a cached INT8 file cannot even be dequantized, so it is not a
+ download and bf16 is offered."""
+ from core.inference import prequant_safetensors as pst
+
+ _cuda(monkeypatch, (9, 0))
+ sam31 = seg.SEGMENTER_VARIANTS["sam3.1"]
+ only = _folder(tmp_path, "sam3.1-INT8-ConvRot.safetensors")
+ assert seg.plan_weights(only, "cpu", variant = sam31, use_cache = False).dequantize
+ monkeypatch.setattr(pst, "safetensors_prequant_supported", lambda: False)
+ plan = seg.plan_weights(only, "cpu", variant = sam31, use_cache = False)
+ assert (plan.weights, plan.dequantize) == (None, False)
+ monkeypatch.setenv(seg.ENV_PATH_OVERRIDE, str(tmp_path))
+ assert seg.model_dir() is None
+
+
+def test_a_rotated_file_at_another_group_is_refused():
+ from core.inference.diffusion_convrot import rotation_metadata
+ from core.inference.diffusion_prequant import PREQUANT_FORMAT_ROTATED
+
+ def meta(group):
+ return {
+ "family": sq.SEGMENTER_QUANT_FAMILY,
+ "scheme": "int8",
+ "min_features": sq.SEGMENTER_MIN_FEATURES,
+ "exclude_name_tokens": list(sq.exclude_tokens("int8", True)),
+ **rotation_metadata(group, ["vision_encoder.backbone.layers.9.mlp.fc1"]),
+ }
+
+ check = lambda m, **k: sq.checkpoint_problem(
+ PREQUANT_FORMAT_ROTATED, m, scheme = "int8", rotated = True, **k
+ ) # noqa: E731
+ assert check(meta(sq.SEGMENTER_CONVROT_GROUP)) is None
+ assert "ConvRot group 16" in check(meta(16))
+ assert check(meta(16), convrot_group = 16) is None
+
+
+def test_an_override_folder_with_only_a_rejected_file_is_not_downloaded(tmp_path, monkeypatch):
+ _folder(tmp_path, "sam3.1-FP8.safetensors")
+ monkeypatch.setenv(seg.ENV_PATH_OVERRIDE, str(tmp_path))
+ assert seg.model_dir() is None and seg.status()["downloaded"] is False
+ monkeypatch.setenv(sq.ENV_PRECISION, "fp8")
+ assert seg.model_dir() == str(tmp_path)
+ monkeypatch.setenv(sq.ENV_PRECISION, "bf16")
+ assert seg.model_dir() is None
+
+
+def test_an_override_folder_with_only_a_quantized_file_is_downloaded(tmp_path, monkeypatch):
+ _folder(tmp_path, "sam3.1-INT8-ConvRot.safetensors")
+ monkeypatch.setenv(seg.ENV_PATH_OVERRIDE, str(tmp_path))
+ assert seg.model_dir() == str(tmp_path)
+ (tmp_path / "sam3.1-INT8-ConvRot.safetensors").unlink()
+ assert seg.model_dir() is None
+
+
+def test_status_reports_the_precision_and_its_size(monkeypatch):
+ _cuda(monkeypatch, (9, 0))
+ monkeypatch.setattr(seg, "transformers_supports_sam3", lambda: True)
+ monkeypatch.setattr(seg, "_cached_snapshot", lambda *a, **k: None)
+ monkeypatch.setattr(seg, "_host_device", lambda: "cuda:0")
+ unpublished = dataclasses.replace(seg.SEGMENTER_VARIANTS["sam3.1"], prequant_revision = None)
+ monkeypatch.setitem(seg.SEGMENTER_VARIANTS, "sam3.1", unpublished)
+ body = seg.status()
+ assert (body["precision"], body["weights_file"], body["size_bytes"]) == (
+ "bf16",
+ "model.safetensors",
+ seg.SAM31_SIZE_BYTES,
+ )
+ assert body["precision_requested"] == "auto"
+ variant = _published(monkeypatch)
+ body = seg.status()
+ artifact = seg.variant_artifact(variant, sq.AUTO_ORDER[0])
+ assert (body["precision"], body["weights_file"]) == (sq.AUTO_ORDER[0], artifact.filename)
+ assert body["size_bytes"] == artifact.size_bytes + seg.SAM31_CONFIG_BYTES
+ monkeypatch.setattr(seg, "_host_device", lambda: "cpu")
+ assert seg.status()["precision"] == "bf16"
+
+
+# ── header checks ──────────────────────────────────────────────────────────────────────────────────────────────────
+def _meta(
+ scheme = "int8",
+ rotated = False,
+ **extra,
+):
+ meta = {
+ "family": sq.SEGMENTER_QUANT_FAMILY,
+ "scheme": scheme,
+ "base_model_id": "unsloth/sam3.1",
+ "min_features": sq.SEGMENTER_MIN_FEATURES,
+ "exclude_name_tokens": list(sq.exclude_tokens(scheme, rotated)),
+ }
+ meta.update(extra)
+ return meta
+
+
+def test_checkpoint_problem():
+ from core.inference.diffusion_convrot import rotation_metadata
+ from core.inference.diffusion_prequant import PREQUANT_FORMAT, PREQUANT_FORMAT_ROTATED
+
+ ok = dict(scheme = "int8", rotated = False, base_model_id = "unsloth/sam3.1")
+ assert sq.checkpoint_problem(PREQUANT_FORMAT, _meta(), **ok) is None
+ assert "family" in sq.checkpoint_problem(PREQUANT_FORMAT, _meta(family = "flux.1"), **ok)
+ assert "scheme" in sq.checkpoint_problem(PREQUANT_FORMAT, _meta("fp8"), **ok)
+ assert "built from" in sq.checkpoint_problem(PREQUANT_FORMAT, _meta(base_model_id = "x/y"), **ok)
+ assert "min_features" in sq.checkpoint_problem(PREQUANT_FORMAT, _meta(min_features = 256), **ok)
+ assert "excludes" in sq.checkpoint_problem(
+ PREQUANT_FORMAT, _meta(exclude_name_tokens = ["something_else"]), **ok
+ )
+ rotated = _meta(
+ rotated = True, **rotation_metadata(256, ["vision_encoder.backbone.layers.9.mlp.fc1"])
+ )
+ rok = dict(ok, rotated = True)
+ assert sq.checkpoint_problem(PREQUANT_FORMAT_ROTATED, rotated, **rok) is None
+ # A rotation needs the v2 tag both ways, and the file must be the kind the plan asked for.
+ assert "disagree" in sq.checkpoint_problem(PREQUANT_FORMAT, rotated, **rok)
+ assert "disagree" in sq.checkpoint_problem(PREQUANT_FORMAT_ROTATED, _meta(), **ok)
+ assert "unexpected rotation" in sq.checkpoint_problem(PREQUANT_FORMAT_ROTATED, rotated, **ok)
+ assert sq.checkpoint_problem(PREQUANT_FORMAT, "x", **ok) == "no metadata"
+ # Each file carries its own measured exclusions: a plain INT8 header does not pass as the ConvRot one.
+ assert sq.exclude_tokens("int8") != sq.exclude_tokens("int8", rotated = True)
+ plain_as_rotated = _meta(**rotation_metadata(256, ["vision_encoder.backbone.layers.9.mlp.fc1"]))
+ assert "excludes" in sq.checkpoint_problem(PREQUANT_FORMAT_ROTATED, plain_as_rotated, **rok)
+
+
+def test_measured_exclusions_and_gate_verdicts():
+ """The early ViT blocks stay bf16 (the scan's most sensitive group); auto loads only the files that passed."""
+ assert sq.exclude_tokens("int8", rotated = True) == tuple(
+ f"backbone.layers.{i}." for i in range(8)
+ )
+ assert sq.exclude_tokens("int8") == tuple(f"backbone.layers.{i}." for i in range(4))
+ assert sq.exclude_tokens("fp8") == tuple(f"backbone.layers.{i}." for i in range(8))
+ assert sq.GATE_PASSED == {"fp8": False, "int8": True, "int8-convrot": True}
+ assert sq.AUTO_ORDER == ("int8",)
+ # A token names one ViT block, never a later one sharing its digits, nor a text-encoder layer.
+ from core.inference.diffusion_transformer_quant import make_filter_fn
+ import torch
+
+ keep = make_filter_fn(512, exclude_name_tokens = sq.exclude_tokens("fp8"))
+ lin = torch.nn.Linear(1024, 1024)
+ assert not keep(lin, "vision_encoder.backbone.layers.1.attention.q_proj")
+ assert keep(lin, "vision_encoder.backbone.layers.10.attention.q_proj")
+ assert keep(lin, "text_encoder.text_model.encoder.layers.1.self_attn.q_proj")
+
+
+def test_auto_skips_a_file_that_failed_the_gate(monkeypatch, tmp_path):
+ _cuda(monkeypatch, (9, 0))
+ sam31 = seg.SEGMENTER_VARIANTS["sam3.1"]
+ fp8_only = _folder(tmp_path, "model.safetensors", "sam3.1-FP8.safetensors")
+ monkeypatch.setattr(sq, "AUTO_ORDER", ("fp8",))
+ assert seg.plan_weights(fp8_only, "cuda:0", variant = sam31, use_cache = False).precision == "bf16"
+ monkeypatch.setenv(sq.ENV_PRECISION, "fp8")
+ assert seg.plan_weights(fp8_only, "cuda:0", variant = sam31, use_cache = False).precision == "fp8"
+
+
+def _segment_test_helpers():
+ """test_diffusion_segment's tiny config and fake tokenizer, loaded by path (it is not an importable module)."""
+ import importlib.util
+
+ spec = importlib.util.spec_from_file_location(
+ "_segment_tests", Path(__file__).with_name("test_diffusion_segment.py")
+ )
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module._FakeTokenizer, module._tiny_config
+
+
+# ── a real round trip on a tiny Sam3Model ─────────────────────────────────────────────────────────────────────────
+def _tiny_dir(
+ tmp_path,
+ monkeypatch,
+ scheme,
+ *,
+ convrot = 0,
+ keep_dense = True,
+):
+ """A folder with a tiny random Sam3Model's config, its pre-quantized ``scheme`` file (built with the real
+ quantize + write path at min_features 32) and, with ``keep_dense``, its bf16 model.safetensors."""
+ transformers = pytest.importorskip("transformers")
+ if not hasattr(transformers, "Sam3Model"):
+ pytest.skip("transformers without SAM 3")
+ pytest.importorskip("torchao")
+ import torch
+
+ from core.inference.prequant_safetensors import (
+ safetensors_prequant_supported,
+ scheme_is_flattenable,
+ )
+ from core.inference.diffusion_transformer_quant import _make_quant_config
+
+ if (
+ not safetensors_prequant_supported()
+ or scheme_is_flattenable(_make_quant_config(scheme)) is False
+ ):
+ pytest.skip(f"this torchao cannot write {scheme} safetensors")
+ _FakeTokenizer, _tiny_config = _segment_test_helpers()
+
+ monkeypatch.setattr(
+ transformers.AutoTokenizer, "from_pretrained", lambda *a, **k: _FakeTokenizer()
+ )
+ monkeypatch.setattr(sq, "SEGMENTER_MIN_FEATURES", 32)
+ if scheme == "fp8" and not torch.cuda.is_available():
+ # Building is plain tensor math; torchao only asserts a card that could RUN fp8, which the CPU tests do not.
+ import torchao.quantization.quant_api as quant_api
+ monkeypatch.setattr(
+ quant_api, "_check_hardware_support", lambda *a, **k: None, raising = False
+ )
+ torch.manual_seed(0)
+ model = transformers.Sam3Model(_tiny_config()).to(torch.bfloat16)
+ if keep_dense:
+ model.save_pretrained(tmp_path)
+ else:
+ model.config.save_pretrained(tmp_path)
+ quant = sq.quantize_segmenter_(model, scheme, convrot_group = convrot, min_features = 32)
+ assert quant["quantized_linears"] > 0
+ artifact = seg.variant_artifact(seg.SEGMENTER_VARIANTS["sam3.1"], scheme)
+ name = sq.artifact_filename("sam3.1", scheme, rotated = bool(convrot))
+ written = sq.write_prequant_file(
+ str(tmp_path / name), model, quant, base_model_id = seg.SAM31_REPO
+ )
+ assert (
+ written["family"] == "sam3"
+ and written["fingerprint"]["count"] == quant["quantized_linears"]
+ )
+ header = json.loads(json.dumps(written, default = str))
+ assert header["scheme"] == scheme and (artifact is None or artifact.precision == scheme)
+ return str(tmp_path), quant
+
+
+def test_tiny_fp8_file_dequantizes_and_segments_on_the_cpu(tmp_path, monkeypatch):
+ """No bf16 file on disk and no CUDA: the fp8 file is dequantized and Mask from text still runs."""
+ from PIL import Image
+
+ path, quant = _tiny_dir(tmp_path, monkeypatch, "fp8", keep_dense = False)
+ monkeypatch.setenv(sq.ENV_PRECISION, "fp8")
+ segmenter = seg.MaskSegmenter(keep_alive_seconds = 0)
+ result = segmenter.segment(
+ Image.new("RGB", (64, 40), (120, 80, 40)),
+ "sofa, pillow:2",
+ threshold = 0.0,
+ allow_gpu = False,
+ path = path,
+ )
+ assert result.device == "cpu" and result.precision == "bf16"
+ assert [c["found"] for c in result.concepts] == [1, 2]
+ assert result.to_json()["precision"] == "bf16"
+
+
+def test_tiny_dequantized_weights_match_the_quantized_values(tmp_path, monkeypatch):
+ import torch
+
+ path, quant = _tiny_dir(tmp_path, monkeypatch, "fp8", keep_dense = False)
+ model, info = sq.load_prequantized_segmenter(
+ path,
+ str(Path(path) / "sam3.1-FP8.safetensors"),
+ scheme = "fp8",
+ rotated = False,
+ device = "cpu",
+ dtype = torch.float32,
+ base_model_id = seg.SAM31_REPO,
+ )
+ assert (
+ info["kernels"] == "dequantized"
+ and info["precision"] == "bf16"
+ and info["quantized_linears"] == 0
+ )
+ from core.inference.prequant_safetensors import load_prequant_safetensors
+
+ stored = load_prequant_safetensors(str(Path(path) / "sam3.1-FP8.safetensors"))["state_dict"]
+ name = next(k for k, v in stored.items() if sq._is_quantized_weight(v))
+ assert torch.equal(model.state_dict()[name], stored[name].dequantize().float())
+ # Refused for another repo's base.
+ with pytest.raises(ValueError, match = "built from"):
+ sq.load_prequantized_segmenter(
+ path,
+ str(Path(path) / "sam3.1-FP8.safetensors"),
+ scheme = "fp8",
+ rotated = False,
+ device = "cpu",
+ dtype = torch.float32,
+ base_model_id = "facebook/sam3",
+ )
+
+
+def test_skeleton_buffers_match_from_pretrained(tmp_path):
+ """The quantized load builds the model around the file; its buffers must be from_pretrained's. At SAM 3's real
+ 1008 px input the ViT's global-attention RoPE tables are exact only when built in float32 (a bf16 default moved
+ them by up to 0.04 and every mask with them), so the skeleton is built in float32 whatever the caller's default."""
+ transformers = pytest.importorskip("transformers")
+ if not hasattr(transformers, "Sam3Model"):
+ pytest.skip("transformers without SAM 3")
+ import torch
+
+ _FakeTokenizer, _tiny_config = _segment_test_helpers()
+ config = _tiny_config()
+ config.vision_config.backbone_config.image_size = 1008
+ transformers.Sam3Model(config).to(torch.bfloat16).save_pretrained(tmp_path)
+ dense = dict(
+ transformers.Sam3Model.from_pretrained(tmp_path, dtype = torch.bfloat16).named_buffers()
+ )
+ previous = torch.get_default_dtype()
+ torch.set_default_dtype(torch.bfloat16)
+ try:
+ built = dict(sq._build_skeleton(str(tmp_path)).named_buffers())
+ finally:
+ torch.set_default_dtype(previous)
+ assert dense.keys() == built.keys() and any("rope" in name for name in dense)
+ for name, value in dense.items():
+ assert built[name].dtype == value.dtype and torch.equal(built[name], value), name
+
+
+def test_a_broken_file_falls_back_to_bf16(tmp_path, monkeypatch):
+ """A pre-quantized file that does not load leaves the bf16 one in charge, never a crash."""
+ import torch
+ from PIL import Image
+
+ path, _quant = _tiny_dir(tmp_path, monkeypatch, "fp8")
+ monkeypatch.setenv(sq.ENV_PRECISION, "fp8")
+ _cuda(monkeypatch, (9, 0))
+ plan = seg.plan_weights(path, "cuda:0", torch.bfloat16, use_cache = False)
+ assert plan.precision == "fp8"
+ (Path(path) / "sam3.1-FP8.safetensors").write_bytes(b"not a safetensors file")
+ segmenter = seg.MaskSegmenter(keep_alive_seconds = 0)
+ # Force the planned device's choice onto the CPU loader path: the quantized load runs (and fails) first.
+ monkeypatch.setattr(seg, "choose_device", lambda allow_gpu: ("cpu", torch.float32))
+ monkeypatch.setattr(
+ seg,
+ "plan_weights",
+ lambda *a, **k: plan,
+ )
+ result = segmenter.segment(
+ Image.new("RGB", (32, 32)), "sofa", threshold = 0.0, allow_gpu = True, path = path
+ )
+ assert result.precision == "bf16" and segmenter.last_prequant_failure
+
+
+def test_a_broken_file_with_no_bf16_beside_it_stops_counting(tmp_path, monkeypatch):
+ """Only a pre-quantized file on disk and it does not load, even dequantized: the request fails with a clear
+ error once, then the file no longer counts as downloaded and the bf16 download is offered."""
+ import torch
+ from PIL import Image
+
+ path, _quant = _tiny_dir(tmp_path, monkeypatch, "fp8", keep_dense = False)
+ monkeypatch.setenv(sq.ENV_PRECISION, "fp8")
+ _cuda(monkeypatch, (9, 0))
+ sam31 = _published(monkeypatch, "d" * 40)
+ artifact = seg.variant_artifact(sam31, "fp8")
+ (Path(path) / artifact.filename).write_bytes(b"not a safetensors file")
+ monkeypatch.setattr(seg, "choose_device", lambda allow_gpu: ("cpu", torch.float32))
+ segmenter = seg.MaskSegmenter(keep_alive_seconds = 0)
+ with pytest.raises(Exception, match = "BF16 weights"):
+ segmenter.segment(Image.new("RGB", (32, 32)), "sofa", threshold = 0.0, path = path)
+ plan = seg.plan_weights(path, "cpu", variant = sam31, use_cache = False)
+ assert (plan.weights, plan.dequantize) == (None, False)
+ monkeypatch.setenv(seg.ENV_PATH_OVERRIDE, path)
+ assert seg.model_dir() is None
+ monkeypatch.delenv(seg.ENV_PATH_OVERRIDE)
+ # The same file as the cached copy: the download route offers bf16, not that file again.
+ monkeypatch.setattr(
+ seg, "_cached_snapshot", lambda model_id, **k: path if "@" in model_id else None
+ )
+ assert seg._variant_snapshot("sam3.1") is None
+ assert seg.download_plan(sam31, "cuda:0")["precision"] == "bf16"
+
+
+ not __import__("torch").cuda.is_available(), reason = "quantized kernels need a CUDA card"
+)
[email protected]("scheme, convrot", [("fp8", 0), ("int8", 0), ("int8", 16)])
+def test_tiny_quantized_file_runs_quantized_on_cuda(tmp_path, monkeypatch, scheme, convrot):
+ import torch
+
+ capability = torch.cuda.get_device_capability()
+ if capability < sq._MIN_CAPABILITY[scheme]:
+ pytest.skip(f"{scheme} needs a newer card")
+ path, quant = _tiny_dir(tmp_path, monkeypatch, scheme, convrot = convrot)
+ model, info = sq.load_prequantized_segmenter(
+ path,
+ str(Path(path) / sq.artifact_filename("sam3.1", scheme, rotated = bool(convrot))),
+ scheme = scheme,
+ rotated = bool(convrot),
+ device = "cuda:0",
+ dtype = torch.bfloat16,
+ base_model_id = seg.SAM31_REPO,
+ convrot_group = convrot or sq.SEGMENTER_CONVROT_GROUP,
+ )
+ assert (
+ info["kernels"] == "quantized" and info["quantized_linears"] == quant["quantized_linears"]
+ )
+ assert info["rotated_linears"] == len(quant.get("activation_rotation_fqns") or ())
+ pixels = torch.zeros(1, 3, 112, 112, device = "cuda:0", dtype = torch.bfloat16)
+ with torch.inference_mode():
+ vision = model.get_vision_features(pixel_values = pixels)
+ assert vision is not None
diff --git a/studio/frontend/src/features/images/lib/mask-from-text.ts b/studio/frontend/src/features/images/lib/mask-from-text.ts
index 3217d688cd6..95a2ce4aaee 100644
--- a/studio/frontend/src/features/images/lib/mask-from-text.ts
+++ b/studio/frontend/src/features/images/lib/mask-from-text.ts
@@ -1,9 +1,9 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-// "Mask from text": SAM 3 finds the objects a short text names and returns their union as a mask the inpaint and
-// localized-edit painters load, so it stays editable with the brush. Pure logic only (no "@/" imports) so node:test
-// can load it directly.
+// "Mask from text": SAM 3.1 (or SAM 3) finds the objects a short text names and returns their union as a mask the
+// inpaint and localized-edit painters load, so it stays editable with the brush. Pure logic only (no "@/" imports)
+// so node:test can load it directly.
/** Every segmenter route, in one place. */
export const MASK_SEGMENT_ROUTES = {
@@ -34,10 +34,17 @@ export interface SegmenterStatus {
downloaded: boolean;
loaded: boolean;
device: string | null;
+ /** The active checkpoint variant ("sam3.1", "sam3") and its display name. */
+ variant: string;
+ label: string;
repo: string;
+ revision: string;
gated: boolean;
license_url: string;
size_bytes: number | null;
+ /** The weights precision that runs ("bf16", "fp8", "int8"): the loaded model's, else what this host would load or
+ * download. ``size_bytes`` is that download's size until it is on disk. */
+ precision: string | null;
download: SegmenterDownload;
}
@@ -78,6 +85,9 @@ export interface AppliedMask {
empty?: boolean;
}
+/** Shown when an older backend reports no variant name. */
+export const DEFAULT_SEGMENTER_LABEL = "SAM 3";
+
const IDLE_DOWNLOAD: SegmenterDownload = {
downloading: false,
download_id: null,
@@ -103,10 +113,14 @@ export function parseSegmenterStatus(raw: unknown): SegmenterStatus {
downloaded: body.downloaded === true,
loaded: body.loaded === true,
device: str(body.device),
+ variant: str(body.variant) ?? "",
+ label: str(body.label) || DEFAULT_SEGMENTER_LABEL,
repo: str(body.repo) ?? "",
+ revision: str(body.revision) ?? "",
gated: body.gated === true,
license_url: str(body.license_url) ?? "",
size_bytes: num(body.size_bytes),
+ precision: str(body.precision),
download: {
...IDLE_DOWNLOAD,
downloading: d.downloading === true,
@@ -162,6 +176,28 @@ export function parseSegmentResult(raw: unknown): SegmentResult {
};
}
+/** "BF16" / "FP8" / "INT8" for a known precision, else null (an older backend reports none). */
+export function segmenterPrecisionLabel(precision: string | null | undefined): string | null {
+ return precision === "bf16" || precision === "fp8" || precision === "int8"
+ ? precision.toUpperCase()
+ : null;
+}
+
+/** What the download notice says before a download: the variant's name, the precision and size it would fetch, and
+ * whether its license must be accepted on Hugging Face first (a gated variant only; an ungated one needs no token).
+ * ``size`` is pre-formatted. */
+export function segmenterDownloadNotice(
+ status: Pick<SegmenterStatus, "label" | "gated"> & { precision?: string | null },
+ size: string | null,
+): { text: string; needsLicense: boolean } {
+ const label = status.label || DEFAULT_SEGMENTER_LABEL;
+ const detail = [segmenterPrecisionLabel(status.precision), size].filter(Boolean).join(", ");
+ return {
+ text: `Mask from text uses ${label}${detail ? ` (${detail})` : ""}, which is not downloaded yet.`,
+ needsLicense: status.gated === true,
+ };
+}
+
/** The Download control is offered: supported, and the weights are not on disk yet. */
export function segmenterNeedsDownload(status: SegmenterStatus | null): boolean {
return status?.supported === true && !status.downloaded;
diff --git a/studio/frontend/src/features/images/mask-from-text-panel.tsx b/studio/frontend/src/features/images/mask-from-text-panel.tsx
index a9f026830d4..81c383af39a 100644
--- a/studio/frontend/src/features/images/mask-from-text-panel.tsx
+++ b/studio/frontend/src/features/images/mask-from-text-panel.tsx
@@ -22,6 +22,7 @@ import {
MASK_FROM_TEXT_PLACEHOLDER,
parseMaskPrompt,
segmenterDownloadFraction,
+ segmenterDownloadNotice,
segmenterNeedsDownload,
segmenterReady,
segmentSummary,
@@ -81,12 +82,14 @@ function SegmenterDownloadNotice({
const { download } = status;
const fraction = segmenterDownloadFraction(download);
const size = status.size_bytes ? formatBytes(status.size_bytes) : null;
+ const label = status.label;
+ const notice = segmenterDownloadNotice(status, size);
const start = async () => {
setBusy(true);
try {
await startSegmenterDownload(hfApiToken(getHfToken()));
} catch (err) {
- toast.error("Could not download SAM 3", {
+ toast.error(`Could not download ${label}`, {
description: err instanceof Error ? err.message : undefined,
});
} finally {
@@ -113,8 +116,8 @@ function SegmenterDownloadNotice({
<div className="flex items-center justify-between gap-2">
<span className="text-muted-foreground">
{download.bytes_total
- ? `Downloading SAM 3: ${formatBytes(download.bytes_done ?? 0)} of ${formatBytes(download.bytes_total)}`
- : "Downloading SAM 3..."}
+ ? `Downloading ${label}: ${formatBytes(download.bytes_done ?? 0)} of ${formatBytes(download.bytes_total)}`
+ : `Downloading ${label}...`}
</span>
<Button
type="button"
@@ -136,8 +139,8 @@ function SegmenterDownloadNotice({
) : (
<>
<span className="text-muted-foreground">
- {`Mask from text uses SAM 3${size ? ` (${size})` : ""}, which is not downloaded yet.`}
- {status.gated ? (
+ {notice.text}
+ {notice.needsLicense ? (
<>
{" Its license must be accepted on Hugging Face first"}
{status.license_url ? (
diff --git a/studio/frontend/src/features/images/mask-segment-api.ts b/studio/frontend/src/features/images/mask-segment-api.ts
index df17fcb484e..e546211ddac 100644
--- a/studio/frontend/src/features/images/mask-segment-api.ts
+++ b/studio/frontend/src/features/images/mask-segment-api.ts
@@ -29,7 +29,7 @@ export async function getSegmenterStatus(signal?: AbortSignal): Promise<Segmente
);
}
-/** Start the background download of the SAM 3 weights. Progress is read back from the status route. */
+/** Start the background download of the active segmenter variant. Progress is read back from the status route. */
export async function startSegmenterDownload(hfToken?: string): Promise<void> {
await parseJson<unknown>(
await authFetch(MASK_SEGMENT_ROUTES.download, {
diff --git a/studio/frontend/tests/image-mask-from-text.test.ts b/studio/frontend/tests/image-mask-from-text.test.ts
index ba301c7fff3..00880d9b427 100644
--- a/studio/frontend/tests/image-mask-from-text.test.ts
+++ b/studio/frontend/tests/image-mask-from-text.test.ts
@@ -12,7 +12,9 @@ import {
parseSegmenterStatus,
parseSegmentResult,
segmenterDownloadFraction,
+ segmenterDownloadNotice,
segmenterNeedsDownload,
+ segmenterPrecisionLabel,
segmenterReady,
segmentSummary,
tintMaskPixels,
@@ -265,3 +267,67 @@ test("a Replace that found nothing leaves both painters holding no mask", () =>
assert.match(page, /onMaskChange\(applyMask\.empty \? null : url\)/);
assert.match(localized, /dirty\.current = !applyMask\.empty;\s*onLayerChange\(applyMask\.empty \? null : url\)/);
});
+
+test("the status parse reads the active variant, and an older backend reads as SAM 3", () => {
+ const sam31 = parseSegmenterStatus({
+ supported: true,
+ downloaded: false,
+ variant: "sam3.1",
+ label: "SAM 3.1",
+ repo: "unsloth/sam3.1",
+ revision: "main",
+ gated: false,
+ license_url: "https://huggingface.co/unsloth/sam3.1/blob/main/LICENSE",
+ size_bytes: 1_685_972_909,
+ download: {},
+ });
+ assert.equal(sam31.variant, "sam3.1");
+ assert.equal(sam31.label, "SAM 3.1");
+ assert.equal(sam31.revision, "main");
+ assert.equal(sam31.gated, false);
+ const old = parseSegmenterStatus({ supported: true, repo: "facebook/sam3", gated: true });
+ assert.equal(old.variant, "");
+ assert.equal(old.label, "SAM 3");
+ assert.equal(old.revision, "");
+});
+
+test("the download notice names the variant and asks for a license only when it is gated", () => {
+ const ungated = segmenterDownloadNotice({ label: "SAM 3.1", gated: false }, "1.7 GB");
+ assert.equal(ungated.text, "Mask from text uses SAM 3.1 (1.7 GB), which is not downloaded yet.");
+ assert.equal(ungated.needsLicense, false);
+ const gated = segmenterDownloadNotice({ label: "SAM 3", gated: true }, "3.4 GB");
+ assert.equal(gated.text, "Mask from text uses SAM 3 (3.4 GB), which is not downloaded yet.");
+ assert.equal(gated.needsLicense, true);
+ assert.equal(
+ segmenterDownloadNotice({ label: "", gated: false }, null).text,
+ "Mask from text uses SAM 3, which is not downloaded yet.",
+ );
+});
+
+test("the download notice names the precision it would fetch", () => {
+ assert.equal(
+ segmenterDownloadNotice({ label: "SAM 3.1", gated: false, precision: "int8" }, "0.9 GB").text,
+ "Mask from text uses SAM 3.1 (INT8, 0.9 GB), which is not downloaded yet.",
+ );
+ assert.equal(
+ segmenterDownloadNotice({ label: "SAM 3.1", gated: false, precision: "bf16" }, null).text,
+ "Mask from text uses SAM 3.1 (BF16), which is not downloaded yet.",
+ );
+ // An unknown or missing precision (an older backend) keeps the plain notice.
+ assert.equal(
+ segmenterDownloadNotice({ label: "SAM 3.1", gated: false, precision: "nf4" }, "1.7 GB").text,
+ "Mask from text uses SAM 3.1 (1.7 GB), which is not downloaded yet.",
+ );
+ assert.equal(segmenterPrecisionLabel("fp8"), "FP8");
+ assert.equal(segmenterPrecisionLabel(null), null);
+ assert.equal(parseSegmenterStatus({ precision: "int8" }).precision, "int8");
+ assert.equal(parseSegmenterStatus({}).precision, null);
+});
+
+test("the panel takes the notice text and the license hint from the active variant", () => {
+ const src = readSrc("features/images/mask-from-text-panel.tsx");
+ assert.match(src, /segmenterDownloadNotice\(status, size\)/);
+ assert.match(src, /notice\.needsLicense \?/);
+ assert.doesNotMatch(src, /status\.gated \?/);
+ assert.doesNotMatch(src, /"Could not download SAM 3"|Downloading SAM 3/);
+});