Repository navigation
Studio: SAM 3.1 for Mask from text, with pre-quantized INT8 / FP8 files - #14310
Conversation
The segmenter checkpoint is now a small table of variants (repo, pinned revision, size, gated flag, license URL). SAM 3.1 is the default: its detector converted with transformers' SAM 3 converter into a BF16 Sam3Model repository (ungated, half the download of facebook/sam3). facebook/sam3 stays selectable with UNSLOTH_SAM3_VARIANT=sam3 and is kept when it is already downloaded and SAM 3.1 is not. UNSLOTH_SAM3_PATH still overrides both. The status and download routes report the active variant (id, label, repo, revision, size, gated); the download notice names it and shows the license-acceptance hint only for a gated variant. The shared pinned downloader honours a spec's commit pin; the SAM 3.1 pin is "main" until the repository is uploaded.
|
@codex review |
1 similar comment
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 340a99f788
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| candidates = [pinned_revision(variant), _read_revision_record(variant.repo)] | ||
| candidates += _fallback_revisions(variant.repo, hub_cache = root) | ||
| revisions = list(dict.fromkeys(rev for rev in candidates if rev)) |
There was a problem hiding this comment.
Restrict cache lookup to the pinned revision
When the pinned snapshot is absent but the same repository has a complete snapshot at another commit—for example, a user previously cached main—these fallback candidates cause status() to report the variant as downloaded and model_dir() to load that unpinned checkpoint. This silently defeats the new revision pin and can run different weights/configuration than the advertised revision; only consult recorded/fallback revisions for an unpinned variant, or explicitly validate a legacy snapshot against the configured pin.
Useful? React with 👍 / 👎.
…vRot) SAM 3.1 gains three pre-quantized detector files next to its bf16 model.safetensors: sam3.1-FP8, sam3.1-INT8 and sam3.1-INT8-ConvRot (0.99 to 1.05 GB instead of 1.68 GB, about 0.6 GB less GPU memory). They are built with the diffusion prequant machinery rather than a copy of it: the same torchao configs and Linear filter, the ConvRot rotation and its recorded-fqn contract, the safetensors container with unsloth_format / unsloth_metadata and the canonical fingerprint (diffusion_segment_quant, scripts/build_segmenter_prequant_checkpoint.py). The first ViT blocks stay bf16 (8 for FP8 and INT8-ConvRot, 4 for INT8): a per-group sensitivity scan put the error there for every scheme, and the 256-wide DETR / mask / scoring Linears stay bf16 by the size rule. Each file records its exclusions and the loader refuses one built under another rule. UNSLOTH_SAM3_PRECISION picks auto / bf16 / fp8 / int8. auto loads only a file that passed the accuracy gate (53 prompts through the segment path, every metric within 2x of what bf16 gives up against the fp32 weights): INT8-ConvRot on CUDA sm_80+ (UNSLOTH_SAM3_INT8_CONVROT=0 for the plain INT8 file). FP8 missed the gate on one prompt's score and stays an explicit choice. The CPU and MPS keep bf16 weights; when only a quantized file is on disk there it is dequantized. A file that fails to load falls back to bf16. The download fetches the configs, the tokenizer and that one weights file, and downloads bf16 instead when the file is not on the Hub at its revision. SAM31_PREQUANT_REVISION is None until the files are uploaded, so nothing changes for users until it is pinned. Status, the download route and each segment result report the precision; the download notice names it with the size.
unsloth/sam3.1 now holds sam3.1-FP8, sam3.1-INT8 and sam3.1-INT8-ConvRot at 771260d9, so SAM31_PREQUANT_REVISION points there. The variant and lifecycle tests pin UNSLOTH_SAM3_PRECISION=bf16 so they count the bf16 file on any test host; the precision choice is covered by the quant tests. [skip ci]
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ebe120bc67
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if _has_dense_weights(path) or not local: | ||
| return WeightsPlan(PRECISION_BF16, path, reason = why) | ||
| artifact, folder = local[0] |
There was a problem hiding this comment.
Do not dequantize an artifact rejected by auto
When the cache contains only an artifact that _loadable() rejects—for example, FP8 was explicitly downloaded earlier and the user later returns to auto, where FP8 failed the accuracy gate—resolve_precision() correctly selects BF16, but this fallback dequantizes local[0] anyway. Dequantization does not undo the checkpoint's quantization error, so the rejected FP8 weights run while status reports BF16/downloaded and the UI cannot offer the approved INT8 or dense download; restrict this fallback to an artifact eligible for the current selection, or treat the requested weights as not downloaded.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in b786366. A pre-quantized file now counts only when the current precision setting may load it (auto: a file that passed the gate; fp8 / int8: that precision's file; bf16: none), both for the dequantize fallback in plan_weights and for whether the variant reads as downloaded (_variant_snapshot). An FP8 file left from an explicit fp8 run is ignored under auto, so status reports not downloaded and the auto file is offered. Test: test_a_file_the_selection_rejected_is_never_dequantized, plus the cached-snapshot test now covers auto / fp8 / bf16.
| 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" |
There was a problem hiding this comment.
Reject ROCm before selecting NVIDIA quantized kernels
On a Linux ROCm build, PyTorch exposes AMD GPUs through torch.cuda, so this check accepts the device and the subsequent capability comparison can classify its gfx version as an eligible NVIDIA SM; torchao_unavailable_reason() also succeeds when normal torchao is installed. The repository's generic quant gate explicitly rejects this case in diffusion_transformer_quant.py:924-926 because these dynamic INT8/FP8 paths are NVIDIA-only. With the default auto setting, an AMD installation can therefore download and load the INT8 artifact and then fail during the first quantized matmul, where the loader's BF16 fallback no longer applies; return an unsupported reason when torch_is_rocm() is true.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in b786366. unsupported_reason now returns a reason on ROCm (torch_is_rocm()) and when torchao is the stub, the same rule as dense_transformer_supported, so auto stays BF16 and the download plan fetches the BF16 file on AMD. Test: test_rocm_never_runs_the_quantized_files.
| 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) |
There was a problem hiding this comment.
Avoid creating a CUDA context from status probes
On a CUDA install with no model loaded, merely polling /images/segment/status reaches download_plan(), which calls both _host_device() (torch.cuda.current_device()) and this capability probe (torch.cuda.get_device_capability()); these APIs perform PyTorch's lazy CUDA initialization rather than being property-only reads. Opening the Mask from text panel can therefore create a context and reserve GPU memory before any inference or training requested the card, contrary to both helpers' stated no-context contract; obtain the ordinal/capability through the existing context-free device helpers or defer this probe until the actual load.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Checked on a B200 with the Studio torch build: after torch.cuda.current_device(), torch.cuda.get_device_capability(0) and get_device_properties(0), the process has no entry in nvidia-smi's compute apps (no context, 0 MiB); the first torch.zeros(1, device="cuda") then shows 712 MiB. Lazy init reads properties through the runtime but does not create the primary context, which is why diffusion_probe_cache.fingerprint uses the same calls under the same no-context contract. Leaving these as they are.
A pre-quantized file on disk counts only when the current precision setting may load it (auto: a gate-passed file; fp8 / int8: that file; bf16: none). An FP8 file left from an explicit fp8 run is no longer dequantized under auto or bf16, and the variant reads as not downloaded so the selection's own file is offered. ROCm and a stubbed torchao never pick the quantized files: ROCm reports gfx versions through the CUDA capability API and these paths are NVIDIA-only, the same rule dense_transformer_supported applies. [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b7863665b2
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # or only a pre-quantized detector file (dequantized where it cannot run quantized) | ||
| or has(*(a.filename for v in SEGMENTER_VARIANTS.values() for a in v.prequant)) |
There was a problem hiding this comment.
Reject unusable prequant-only override directories
When UNSLOTH_SAM3_PATH contains the configs/tokenizer and only a prequant file that the current precision setting rejects—for example, the FP8 artifact under auto, or any quantized artifact under bf16—this unconditional check marks the override as downloaded. plan_weights() then selects BF16 without a weights file, so Sam3Model.from_pretrained() receives a directory with no model.safetensors and segmentation fails rather than reporting that usable weights are missing; validate the override's artifact with the same _loadable() rules or require dense weights in this case.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in f1b5baf: _override_dir now accepts a quantized-only folder only when the precision setting may load that file (the same _loadable rule), so FP8 alone under auto or any quantized file under bf16 reads as not downloaded. Test: test_an_override_folder_with_only_a_rejected_file_is_not_downloaded.
…ay load UNSLOTH_SAM3_PATH holding only the FP8 file under auto (or any quantized file under bf16) no longer reads as downloaded, so it reports missing weights instead of failing in from_pretrained. [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f1b5baf184
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| or any( | ||
| _loadable(v, a) and has(a.filename) for v in SEGMENTER_VARIANTS.values() for a in v.prequant |
There was a problem hiding this comment.
Validate override artifacts against the selected variant
When UNSLOTH_SAM3_VARIANT=sam3 and UNSLOTH_SAM3_PATH contains only a loadable SAM 3.1 prequant file, this loop accepts that file from the unrelated variant and reports the override as downloaded. Loading then plans weights for the selected sam3 variant, which has no prequant artifacts, and falls through to Sam3Model.from_pretrained() even though the directory has no model.safetensors, causing every segmentation request to fail; limit this check to the active variant or derive the variant from the accepted artifact.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in d1634fe: _override_dir now checks only the prequant files of the variant the override is reported and loaded as (UNSLOTH_SAM3_VARIANT, else the default), so sam3 with only a SAM 3.1 file reads as not downloaded. Test: test_an_override_folder_holds_the_reported_variants_file.
| for artifact in variant.prequant: | ||
| if not _loadable(variant, artifact): | ||
| continue | ||
| path = _cached_snapshot(prequant_spec_id(variant, artifact)) | ||
| if path is not None: | ||
| return path |
There was a problem hiding this comment.
Reject prequant-only caches when the reader is unavailable
On an installation that cannot deserialize these artifacts—most concretely Windows ROCm, where torchao is intentionally stubbed—a previously populated or shared cache containing only the auto-approved INT8 snapshot passes _loadable() and is reported as downloaded. Precision resolution then falls back to dense and plans to dequantize that same file, but load_prequant_safetensors() rejects the stub before dequantization, so every mask request returns 500 and the UI offers no BF16 download; only accept a prequant-only snapshot when safetensors_prequant_supported() is true, otherwise treat the variant as not downloaded.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in d1634fe: _loadable now requires safetensors_prequant_supported() (which already returns False for the Windows ROCm torchao stub), so with no reader no quantized file counts for the snapshot, the override or the dequantize fallback, and the BF16 download is offered. Test: test_no_prequant_reader_means_no_quantized_file_counts.
| if declared != rotated: | ||
| return "rotation expected" if rotated else "unexpected rotation" | ||
| if sorted(meta.get("exclude_name_tokens") or ()) != sorted(exclude_tokens(scheme, rotated)): |
There was a problem hiding this comment.
Enforce the gated ConvRot group size
For a rotated artifact, this validation checks only that some rotation was expected; the delegated structural check accepts every power-of-four group. The provided builder allows arbitrary --convrot-groupsize values, so a file built with (for example) group 16 and placed under the expected sam3.1-INT8-ConvRot.safetensors name passes validation and is eligible for auto, even though GATE_PASSED and the sensitivity exclusions describe the measured group-256 artifact (SEGMENTER_CONVROT_GROUP). Reject rotated headers whose recorded group differs from that constant so an unmeasured build cannot inherit the production accuracy verdict.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in d1634fe: checkpoint_problem now refuses a rotated header whose activation_rotation_group differs from SEGMENTER_CONVROT_GROUP (256); load_prequantized_segmenter takes convrot_group so the tiny CUDA test can still build at 16. The uploaded sam3.1-INT8-ConvRot.safetensors records 256 and passes. Test: test_a_rotated_file_at_another_group_is_refused.
|
The key sets do match; it is the second half that fails. With the transformers version CI resolves, the SAM 3.1 rotary buffers are named |
- An override folder counts only a quantized file of the variant it is reported and loaded as (UNSLOTH_SAM3_VARIANT=sam3 with a SAM 3.1 file reads as not downloaded). - With no prequant reader (no torchao, or the Windows ROCm stub) no quantized file counts, so a cached INT8-only snapshot is not a download and bf16 is offered instead of failing to dequantize. - A rotated file must use the gated ConvRot group (256); another group is refused instead of inheriting the measured accuracy verdict. [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d1634fedf2
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| plan.weights, | ||
| plan.artifact, | ||
| f"{why}; dequantized", | ||
| dequantize = True, |
There was a problem hiding this comment.
Stop retrying an invalid artifact as the BF16 fallback
When a snapshot contains only a currently eligible prequant file and its first load fails validation, fingerprint checking, or deserialization, this fallback points straight back to the same file with dequantize=True; the second call repeats those checks and fails again before dequantization. The remaining fresh case is therefore a corrupted or incompatible eligible artifact—not the previously fixed precision-rejected case—and it leaves status reporting the model as downloaded while every segmentation request fails and the UI cannot offer the missing dense weights. Only retry dequantized for failures known to be specific to quantized execution, or mark this snapshot unusable so BF16 can be downloaded.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 15a6b49: when the dequantized load of that same file fails too, the file is recorded as unusable for this process (_BROKEN_PREQUANT) and the request raises a clear error pointing at the BF16 download. From then on _variant_snapshot, _override_dir and plan_weights skip it, so status reads not downloaded, and download_plan offers the BF16 file instead of the same cached copy. Test: test_a_broken_file_with_no_bf16_beside_it_stops_counting.
With no bf16 file beside it, a pre-quantized file that fails even the dequantized load (corrupt, truncated, another build rule) now fails the request with a clear message and is remembered: it no longer makes the variant read as downloaded, plan_weights skips it, and the download route offers the bf16 file instead of the same cached copy. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
The repo is public now and its history was squashed into one commit holding the bf16 model and the FP8 / INT8 / INT8-ConvRot files, so both pins move to 6cfffd09 (same files, byte for byte). [skip ci]
|
@codex review |
|
The account paying for this security review has reached its Codex usage limits. The payer can check the Codex usage dashboard. For personal accounts, using credits requires enabling “Use credits for security reviews” in Code review settings. If you do not manage the paying account, contact this repository's admins. |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
… tables by any spelling (#14318) ## Problem `(Python 3.13, a-k)` fails on every PR since #14310 merged (for example #14316 and #14317, both on base fb372c1): ``` studio/backend/tests/test_diffusion_segment_quant.py: in test_skeleton_buffers_match_from_pretrained assert dense.keys() == built.keys() and any("rope" in name for name in dense) ``` #14310 showed the same failure on its own run before merging. Reproduced locally with transformers 5.18 (CI resolves 5.17.0); the 4.57 floor has no `Sam3Model`, so the test skips there. There are two layers: 1. With transformers 5.x the RoPE buffers are named `rotary_emb.inv_freq`, `rotary_emb.original_inv_freq` and `position_ids`; none contains `rope`. 2. Behind that check, the dtype comparison fails as well: `from_pretrained(dtype = bfloat16)` casts the ViT's `position_ids` to bf16 on 5.18, while `_build_skeleton` builds them in float32 on purpose. They are not just a different dtype: layer 1 (global attention) has different values in bf16, and swapping the skeleton's buffers into the dense model changes the vision encoder output. That is exactly the 0.04 shift the test's docstring describes, so the skeleton is right and a bf16 load is not a valid reference. ## Fix Test only: - The reference is `from_pretrained(dtype = float32)`, the exact tables the skeleton is meant to reproduce on every transformers version. - The RoPE presence check matches `rope`, `rotary` or `position_ids`. ## Testing - `test_diffusion_segment_quant.py` with transformers 5.18: 37 passed, 3 skipped. On main the skeleton test fails as in CI. - Building the skeleton without `_default_dtype(torch.float32)` (the regression the test exists for) makes it fail on `position_ids`. - `test_diffusion_segment.py` with `test_diffusion_segment_quant.py`: 109 passed, 3 skipped. ## Not covered here The dense bf16 path (`Sam3Model.from_pretrained(..., dtype = dtype)` in `diffusion_segment.py`) gets the rounded `position_ids` on 5.18, so on that release its masks differ from the pre-quantized path's. That is a product question for the segmenter, separate from this CI fix.
…of memory (unslothai#14736) ## Problem Since unslothai#14310, `UNSLOTH_SAM3_PRECISION=auto` (the default) picks the INT8-ConvRot detector on every sm_80+ NVIDIA card, and the download fetches only that file. The PR's own B200 numbers (median of 5 calls, 5 concepts) show that this trades speed for memory: | | Peak | Per Find | |---|---|---| | BF16 | 1.82 GB | 0.35 s | | INT8-ConvRot (auto) | 1.29 GB | 0.77 s | Re-measured through `MaskSegmenter.segment` on one shared B200 (same image, 5 concepts, rounds interleaved as bf16 / INT8-ConvRot / bf16, each round the median of 5 calls, 3 rounds): | | Weights | Peak | Per Find, round medians | |---|---|---|---| | BF16 (A) | 1666 MiB | 1964 MiB | 0.32 / 0.25 / 0.41 s | | INT8-ConvRot | 999 MiB | 1297 MiB | 0.92 / 1.64 / 1.38 s | | BF16 (A again) | | | 0.41 / 0.67 / 0.46 s | The card was shared, so the absolute numbers are noisy (bf16 A/A spread up to 0.25 s), but INT8-ConvRot was 2.2x to 3.0x slower than the slower bf16 arm of the same round in every round. So the default became more than 2x slower per Find to save about 0.65 GB, even on cards with plenty of free memory. The device gate needs 4 GiB free for either precision, so INT8 does not let the segmenter run on the GPU in any case where bf16 could not. ## Change - `auto` runs bf16 while the card has room for it. It picks a gated pre-quantized file (INT8-ConvRot, or plain INT8 with `UNSLOTH_SAM3_INT8_CONVROT=0`) only when the card's free memory, minus what a resident bf16 segmenter takes off free memory (2.5 GiB), would fall under the existing tight-VRAM floor (6 GiB or 20% of the card). - The memory reading is only taken once this process has initialised CUDA, so the status and download routes never create a CUDA context just to plan. Off CUDA, or when free memory cannot be read, auto stays bf16. - The download follows the same rule: a fresh install on a card with room fetches the bf16 `model.safetensors`. - A loaded segmenter reuses the reading taken when it was placed, so the free memory read with the model already on the card does not flip the choice and reload it on the next call. - If the only file on disk is an INT8 one (downloaded under the old default) and the card has room, it is dequantized to bf16 on load, which is the existing CPU / MPS path. - Explicit picks are unchanged: `UNSLOTH_SAM3_PRECISION=int8` / `fp8` load those files whatever the memory, and `bf16` stays bf16. ## Tests `studio/backend/tests/test_diffusion_segment_quant.py`: - New `test_auto_runs_bf16_while_the_card_has_room`: auto on a CUDA card with room resolves to bf16, explicit int8 / fp8 are honoured with or without memory pressure. Fails on main (auto returns int8). - New `test_auto_memory_tight_reads_the_card_only_once_cuda_is_up`: the threshold on an 80 GB and a 12 GB card, no memory read before CUDA is initialised, unknown memory reads as roomy. - New `test_a_loaded_segmenter_keeps_its_memory_reading`: the reading is reused while loaded and cleared on unload. - Updated `test_download_plan_fetches_one_weights_file`, `test_start_download_uses_the_plan`, `test_plan_weights`, `test_only_a_quantized_file_on_a_cpu_is_dequantized`, `test_status_reports_the_precision_and_its_size`, `test_auto_skips_a_file_that_failed_the_gate` and the gated-order test for the new default (bf16 with room, the gated file when tight). These fail on main on their first bf16 assertion. - `test_diffusion_segment_quant.py` and `test_diffusion_segment.py` pass with CUDA hidden. ## L4 and A100 re-measurement Colab L4 (sm_89) and A100-SXM4-40GB (sm_80), torch 2.11, transformers 5.5.0, torchao 0.17.0, unsloth/sam3.1 at the pinned revision, `MaskSegmenter.segment` on one COCO image with 5 concepts. Each arm runs in a fresh process; 3 rounds, order reversed every round; each value is the median of 5 calls after 2 warmup calls. | Arm | Precision | L4 per Find | A100 per Find | Peak (allocated) | Free drop after a Find (L4 / A100) | Mask IoU vs bf16 | |---|---|---|---|---|---|---| | main, auto | INT8-ConvRot | 1.42 / 1.44 / 1.45 s | 1.13 / 1.13 / 1.14 s | 1383 MiB | 1672 / 1718 MiB | 0.9994 / 0.9993 | | this PR, auto (room) | bf16 | 0.46 / 0.46 / 0.46 s | 0.33 / 0.32 / 0.33 s | 1982 MiB | 2188 / 2234 MiB | 1.0 | | this PR, int8 | INT8-ConvRot | 1.43 / 1.43 / 1.45 s | 1.15 / 1.14 / 1.11 s | 1383 MiB | | 0.9994 / 0.9993 | | this PR, int8 + `UNSLOTH_SAM3_INT8_CONVROT=0` | INT8 | 1.41 / 1.42 / 1.42 s | 1.10 / 1.11 / 1.10 s | 1329 MiB | | 0.9991 / 0.9992 | | this PR, auto, only the INT8 file on disk | bf16 (dequantized) | 0.51 / 0.51 / 0.52 s | 0.38 / 0.37 / 0.37 s | 2006 MiB | 2236 / 2282 MiB | 0.9996 | | main and this PR, auto, tight card | INT8-ConvRot | same on both | same on both | 1396 MiB | | 0.9994 / 0.9993 | So with room, auto is 3.1x (L4) to 3.5x (A100) faster per Find for about 0.6 GB more peak memory, and a tight card behaves exactly as on main. The first version held back 2048 MiB for bf16, but `mem_get_info` drops by 2188 to 2282 MiB once bf16 has run a Find (allocator reserve and cuBLAS workspace on top of the 1982 MiB allocated peak). On a card with free memory just above the floor plus 2048 MiB, auto loaded bf16, `_after_call` read the card as tight and unloaded it, and the next call reloaded the INT8 file (reproduced on both cards: one wasted bf16 load). The allowance is now 2560 MiB; with it the same card picks INT8 directly, and a card with room still picks bf16 (both measured). `test_a_bf16_pick_is_not_unloaded_as_tight_after_its_first_find` fails at 2048 and passes at 2560. ## Not covered - Not measured on sm_86 / sm_90 / sm_120 cards, and the timings above are on single Colab cards (not interleaved on one host). --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Mask from text now defaults to SAM 3.1. Meta publishes SAM 3.1 only as the original multiplex checkpoint (
sam3.1_multiplex.pt) and transformers has no SAM 3.1 class, so the detector is converted with transformers' own SAM 3 converter into a BF16Sam3Modelrepository,unsloth/sam3.1(ungated, SAM License included). The same converter reproducesfacebook/sam3's published safetensors exactly fromsam3.pt.Changes
sam3.1(default, ungated, 1.69 GB, pinned to6cfffd09) andsam3(facebook/sam3, gated, 3.44 GB, pinned).UNSLOTH_SAM3_VARIANT=sam3selectsfacebook/sam3. With no choice, an install that already downloadedfacebook/sam3keeps using it instead of downloading again.UNSLOTH_SAM3_PATHstill overrides both, and the cache is not read then./images/segment/statusand/images/segment/downloadreport the active variant (variant,label,repo,revision,gated,license_url,size_bytes).mainkeeps the resolve-and-record behaviour, so the dictation models are unaffected).sam3.1-INT8-ConvRot.safetensors(1.05 GB),sam3.1-INT8.safetensors(0.99 GB) andsam3.1-FP8.safetensors(1.05 GB). They are built with the diffusion prequant machinery (diffusion_segment_quant.py,scripts/build_segmenter_prequant_checkpoint.py): the same torchao configs and Linear filter, the ConvRot rotation, theunsloth_format/unsloth_metadatacontainer and the fingerprint. The first ViT blocks stay BF16 (8 for FP8 and INT8-ConvRot, 4 for INT8, from a per-group sensitivity scan) and every 256-wide DETR, mask and scoring Linear stays BF16. Each file records its exclusions and the loader refuses one built under another rule.UNSLOTH_SAM3_PRECISION=auto(default),bf16,fp8,int8.autoonly picks a file that passed the accuracy gate: INT8-ConvRot on CUDA sm_80+ (UNSLOTH_SAM3_INT8_CONVROT=0for plain INT8). FP8 missed the gate on one prompt's score and is explicit only. CPU, MPS, ROCm and fp16-only cards keep BF16; if only a quantized file the setting may load is on disk there, it is dequantized (a file the setting rejects, such as FP8 under auto, is ignored and the selection's own file is offered for download). A file that fails to load falls back to BF16; with no BF16 file beside it, a file that does not load even dequantized stops counting as downloaded and the BF16 download is offered. A file missing on the Hub at the pin downloads BF16 instead, and installs that cannot read the files (no torchao, the Windows ROCm stub) only use BF16.precisionandweights_file; the notice names the precision with the size.Accuracy
BF16 conversion, 15 prompts on 2 images, threshold 0.5:
facebook/sam3BF16Pre-quantized files, 53 prompts on 6 images (9 absent concepts, 12 with a
:Ncount) through Studio's own segment path, each against BF16. Two BF16 runs are bit-identical, so the yardstick is what BF16 already moves against the fp32 conversion, and a file passes when every number is within twice that with no change in which objects are found:Memory and speed on one shared B200 (median of 5 calls, 5 concepts per call):
The 8-bit files save about 0.6 GB of VRAM next to the image model and 0.6 GB of download, and cost about 0.4 s per Find: at this model size quantizing every activation costs more than the 8-bit matmuls save.
UNSLOTH_SAM3_PRECISION=bf16keeps the faster BF16 path.Testing
facebook/sam3download, gated vs ungated status, override, cache lookup at the pin, per-variant download file list and revision, route payloads; precision resolution per device and capability, gate and exclusion contract, file metadata checks, BF16 fallback on a bad or missing file, CPU dequantize, download plan and status fields (test_diffusion_segment.py,test_diffusion_segment_quant.py; 296 passed with the STT downloader and GPU arbiter suites; the two segment files also pass with CUDA hidden).image-mask-from-text.test.ts);tscclean.Sam3Modelwith safetensors, torchao 0.18 andstrict=True(1468 of 1468 tensors).sofa,red lampandpillow:2match thefacebook/sam3masks at IoU 0.998 to 0.999 in BF16; see the screenshots for the INT8-ConvRot run.6cfffd09: on an NVIDIA GPU (auto) it fetches the configs, the tokenizer and onlysam3.1-INT8-ConvRot.safetensors; withUNSLOTH_SAM3_PRECISION=bf16onlymodel.safetensors. Both load and findsofa,red lampandpillow:2with the same instances (scores within 0.0006), union masks at IoU 0.9995.Not covered: SAM 3.1 on the CPU and MPS fallbacks, and the 8-bit speed on consumer cards.
How it is wired into Studio and Desktop
Desktop (
studio/src-tauri) bundles the same frontend and starts the same backend, so both get it with no platform code./images/segment/status. With no weights it shows the download notice for the active variant: name, the precision this machine will fetch, and its size (SAM 3.1 (INT8, 1.1 GB)on an NVIDIA GPU,SAM 3.1 (BF16, 1.7 GB)on a CPU or Mac), and the Hugging Face license step only for a gated variant. Find posts the image and the text to/images/segment, and the mask lands in the painter's own layer.diffusion_segment.pyresolves the variant (UNSLOTH_SAM3_VARIANT, else SAM 3.1, else an existingfacebook/sam3download) and the precision (UNSLOTH_SAM3_PRECISION, elseauto), downloads the configs, the tokenizer and that one weights file at the pinned revision through the shared pinned downloader, and loadsSam3Modelon the image model's card (CPU in BF16 when another model owns the card or training runs, Metal on Apple Silicon). INT8-ConvRot applies the input rotation to its rotated Linears at load. The GPU arbiter releases it on loads, evictions, renders and training starts.Screenshots
Both Studios started with an empty Hugging Face cache and a local tiny FLUX.1 pipeline loaded for Inpaint, on an NVIDIA GPU. BEFORE offers the gated 3.4 GB
facebook/sam3with the license step; AFTER offers SAM 3.1 as the INT8 file (sam3.1-INT8-ConvRot.safetensors, 1.1 GB), no token or license needed:With the weights cached and Z-Image-Turbo loaded, "sofa" then "pillow:2" with "Add to current mask". BEFORE runs
facebook/sam3in BF16, AFTERunsloth/sam3.1with the INT8-ConvRot weights on the GPU (status after the run:precision: int8,precision_reason: auto,weights_file: sam3.1-INT8-ConvRot.safetensors). The masks match: coverage 25.413% vs 25.414% for the sofa, then 29.749% vs 29.750% with the pillows:The AFTER flow end to end with INT8-ConvRot: source, "sofa", Find, "pillow:2" added, then an inpaint from the sofa mask:
The BF16 run of the same flow (before the pre-quantized files) matched too, 25.41% vs 25.42%: