Skip to content

Studio: make inpaint and localized-edit masks from text with SAM 3 - #14235

Merged
danielhanchen merged 10 commits into
mainfrom
studio-images-sam3-mask
Oct 19, 2026
Merged

danielhanchen merged 10 commits into
mainfrom
studio-images-sam3-mask

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Closes #7832.

Adds "Mask from text" to the Images page. Type concepts such as sofa, red lamp, pillow:2 under the inpaint mask painter (or the localized edit mask and paint modes) and Find fills the mask. The mask stays editable with the brush, and "Add to current mask" unions instead of replacing.

How it works

  • core/inference/diffusion_segment.py runs the official facebook/sam3 checkpoint through transformers Sam3Model: bf16 on the image model's card, CPU while training runs or the card has no room, CPU retry on OOM.
  • Settings follow ComfyUI's SAM3 Detect node and its Image Segmentation blueprint: comma-separated concepts, :N keeps up to N of a concept (default 1), 1008x1008 bilinear input, threshold 0.5, union of the kept masks at the source size. No dilation or feather, as in the blueprint.
  • The score multiplies in SAM 3's presence head, as Meta's and transformers' post-processing do. Without it a concept missing from the picture masked something else (an "elephant" in a living room masked the sofa at 0.72; 8 of 18 absent concepts produced a mask). With it all 8 are empty and no kept detection of a present object changes.
  • The segmenter is auxiliary, like the FLUX.3 prompt upsampler: a 120 s keep-alive, unloaded at once when the card is tight, and released by the GPU arbiter on any load or eviction and when training starts. Mask requests are refused (409) while an image renders or loads.
  • Routes: POST /api/inference/images/segment, plus segment/status, segment/download (gated repo, pinned revision, license hint on 401/403; owner only), segment/cancel and segment/release.

Why SAM 3 and not SAM 3.1

SAM 3.1 is published only as an original-format multiplex .pt checkpoint with no transformers weights. Converted with transformers' own converter (which reproduces SAM 3's published model.safetensors exactly from its .pt), the 3.1 detector gives the same image masks as SAM 3: IoU of at least 0.993 on 15 prompts, scores within 0.008, identical kept counts. Its gains are in video tracking. The detector tensors differ only slightly (max abs 3.3e-3).

Testing

  • Backend: 43 new tests with a tiny random SAM 3 running the real forward on CPU (prompt parsing, keep rule, mask size, keep-alive and release, arbiter hooks, render slot, CPU retry on OOM, route contract). With the arbiter and upsampler suites: 242 passed.
  • Frontend: 9 new tests; the image suites pass (421/421) and tsc is clean.
  • End to end on a real Studio server with facebook/sam3 and Z-Image-Turbo on one B200:
    • "sofa, red lamp, pillow:2" found 4 objects at 0.97 to 0.98; "elephant" returned an empty mask.
    • First mask 17 to 27 s (load plus warm-up), then 70 to 180 ms per mask; 2.0 GB peak allocated; the release route freed 2.3 GB.
    • Loading Z-Image-Turbo released the segmenter; a mask requested mid-render got 409.
    • The sofa mask fed a real inpaint: mean pixel change 42.6 inside the mask, 3.0 outside.

Source, mask and inpaint result

Not covered: ComfyUI's optional tracker refine pass (it would load the tracker and roughly double memory), Apple Silicon / ROCm / Windows runs, and a browser run of the panel.

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.

  • Frontend: MaskFromTextPanel sits under the Inpaint mask painter and under the localized edit painter in its mask and paint modes (not annotate). Find posts the source image and the text to /api/inference/images/segment; the returned mask is drawn into the painter's own mask layer (mask-apply.ts), replacing it or, with "Add to current mask", adding to it. The brush and Clear keep working on it, and Generate sends it as a painted mask.
  • Backend: diffusion_segment.py loads SAM 3 on the first Find, on the image model's card in bf16 (CPU while training runs or the card is short, MPS fp32 on Apple Silicon). The GPU arbiter releases it on any model load, eviction or training start, and a handover is refused while a GPU call it could not stop is still running. Closing the painter calls /segment/release.
  • First use: the panel shows a download notice for facebook/sam3 (gated: the user's Hugging Face token must have accepted Meta's license; the error names the license page). UNSLOTH_SAM3_PATH points at a local copy instead.
  • Installs that cannot run it (Python below 3.10 with transformers 4.57, or --no-torch) show the panel disabled with the reason.

Screenshots

Inpaint with Z-Image-Turbo loaded, the same photo on both sides. BEFORE has no way to build the mask from text. AFTER: "sofa" then "pillow:2" with "Add to current mask" (mask coverage 25.4% then 29.7% of the image, segmenter status facebook/sam3 supported and downloaded):

Inpaint painter before and after

The flow end to end on the AFTER build: source, "sofa", Find, "pillow:2" added, then a real inpaint from the sofa mask (strength 0.6) that repaints only the sofa:

Mask from text flow

Type concepts such as "sofa, red lamp, pillow:2" under the inpaint mask
painter (and the localized edit mask and paint modes) and Find fills the
mask, which stays editable with the brush. Replace or add to the current
mask.

Backend: core/inference/diffusion_segment.py runs facebook/sam3 through
transformers Sam3Model, lazily loaded in bf16 on the image model's card
(fp16 without bf16, CPU while training runs or the card has no room, CPU
retry on OOM). Prompt syntax and settings follow ComfyUI's SAM3 Detect:
comma-separated concepts, :N keeps up to N (default 1), 1008 bilinear
input, threshold 0.5, union of the kept masks at the source size. The
score multiplies in SAM 3's presence head, as Meta's and transformers'
post-processing do, so a concept that is not in the picture masks nothing.

The segmenter is auxiliary like the FLUX.3 prompt upsampler: a 120 s
keep-alive, unloaded at once when the card is tight, and released by the
GPU arbiter on any load or eviction and when training starts. Calls are
refused (409) while the image model renders or loads.

Routes: POST /images/segment plus segment/status, /download (gated repo,
pinned revision, license hint on 401/403), /cancel and /release.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-19T14:05:17.326787Z 80bcc24 Manual request
🔒 Security Review ⚠️ Failed 2026-10-19T10:32:22.391707Z 63cb858 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 19, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ 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 module is None:
return
try:
module.release_segmenter(reason, wait = True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Do not hand over the GPU after a timed-out release

When a GPU-backed mask request takes longer than MaskSegmenter.release()'s 30-second default timeout—particularly during the first model load—this call returns False with only a deferred-release flag, but _release_mask_segmenter ignores that result and acquire_for continues loading the next GPU owner. The new model can then allocate on the card while SAM 3 is still running, violating the arbiter's ownership guarantee and potentially causing either operation to OOM; keep waiting, abort the handover, or otherwise prevent registration until the segmenter has actually released the GPU.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in cbc293a. A handover no longer proceeds over a release that did not finish. The segmenter records the device of the call in flight; release(handover=True) raises SegmenterReleaseTimeoutError when the wait runs out on a call that is on the GPU (or MPS, or has not chosen a device yet), and the arbiter turns that into the same "did not stop; GPU ownership cannot be transferred" refusal the chat eviction uses, in both acquire_for and _evict_diffusion. A call running on the CPU only defers the release. Tests: test_handover_refuses_while_a_gpu_call_outlives_the_wait, test_acquire_does_not_register_while_the_segmenter_holds_the_card.

additive: boolean;
overlay: "mask" | "paint";
}): Promise<string | null> {
const img = await loadMaskImage(dataUrl);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Guard canvas mutations after the asynchronous mask load

If the user clears the painter, changes the source image, or starts another mask application while loadMaskImage() is pending, the callers' effect cleanup only suppresses their .then() callbacks; this function still retains the reused canvas objects and mutates them after the await. Consequently, an older mask can be drawn into a newly reset/source-sized layer or overwrite a newer result, and the next brush stroke will export that stale mask. Add a cancellation/generation check before mutating the canvases, or build the result offscreen and commit it only if the request is still current.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in cbc293a. applyMaskToLayer takes an isCurrent() check and runs it right after the image decodes, before either canvas is touched; both painters pass their effect's live flag, so Clear, a new source or a newer mask drops the stale one. Test: a text mask that went stale while it decoded never touches the reused canvases.

Comment on lines +346 to +347
bf16 = bool(torch.cuda.is_bf16_supported())
return f"cuda:{ordinal}", torch.bfloat16 if bf16 else torch.float16

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Query BF16 support on the selected GPU

On a heterogeneous multi-GPU host, ordinal can be the image model's card while PyTorch's is_bf16_supported() checks the current card. If the current card supports BF16 but the selected card does not, this returns a BF16 dtype for cuda:{ordinal} and SAM 3 can fail during load or inference instead of using FP16. Probe inside torch.cuda.device(ordinal) (or inspect that ordinal's capability); PyTorch documents this API as checking the current CUDA device.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in cbc293a. The bf16 probe now runs inside torch.cuda.device(ordinal) for the card the segmenter will use. Test: test_choose_device_reads_bf16_on_the_chosen_card.

Comment on lines +636 to +637
device, dtype = "cpu", torch.float32
result = self._segment_on(image, concepts, threshold, path, device, dtype)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clean up when the CPU retry also fails

When the initial accelerator attempt raises an OOM, the CPU retry executes outside the exception-cleanup branch. If that retry loads the multi-gigabyte CPU model and then raises during preprocessing or inference, _after_call() is never invoked, so the model remains resident with no keep-alive timer and any release requested during the call remains pending. Ensure the retry is covered by a finally cleanup path so a failed request cannot retain the SAM 3 weights indefinitely.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in cbc293a. The CPU retry has its own cleanup: a failure there still runs the after-call bookkeeping (a release requested mid-call is honoured, otherwise the keep-alive is armed) before re-raising. Test: test_failed_cpu_retry_still_cleans_up.

Comment on lines +149 to +150
path = Path(value).expanduser()
return str(path) if (path / "config.json").is_file() else None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate the complete override before reporting it downloaded

When UNSLOTH_SAM3_PATH points to a partial or unrelated Transformers directory containing only config.json, this check accepts it and status() reports downloaded: true, enabling Find and suppressing the download notice. The later Sam3Model.from_pretrained and AutoTokenizer.from_pretrained calls then fail with a 500 because weights or tokenizer assets are absent, while the download endpoint also refuses recovery because an override is configured. Validate that the directory contains a loadable SAM 3 checkpoint and tokenizer, or report the invalid override explicitly instead of treating a config file alone as downloaded weights.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in cbc293a. UNSLOTH_SAM3_PATH counts as downloaded only with config.json, the weights (model.safetensors or a sharded index) and a tokenizer; an incomplete folder reports downloaded false with override true. Test: test_partial_override_does_not_read_as_downloaded.

A GPU handover that waits out a SAM 3 call still on the card now aborts the
transfer instead of letting the next owner load beside it. A failed CPU retry
after an OOM settles the CPU copy and any pending release, bf16 support is read
on the card the segmenter runs on, an UNSLOTH_SAM3_PATH override must hold the
weights and a tokenizer to count as downloaded, and a text mask that went stale
while it decoded no longer draws into the painter's reused canvases.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 19, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cbc293a40b

ℹ️ 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".

Comment on lines +656 to +657
with self._run_lock:
self._call_device = ""

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Fence queued segment calls across GPU handovers

When a mask request is waiting to enter _run_lock, a concurrent acquire_for can run release(handover=True), acquire and release this lock successfully, and then proceed toward its slow register callback; this request can immediately acquire the now-free lock and start loading SAM on the GPU while that new owner is still registering. Although release() increments _release_epoch, the call path never checks it, so the timeout fix protects only calls already holding the lock. Coordinate call admission with the whole handover or reject a queued call invalidated by that handover.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3ef225c. release(handover=True) now bumps a handover epoch that segment() reads before waiting on _run_lock and checks again once inside it. A call that may use the GPU and was queued across a handover is refused with the existing busy error (409, try again) instead of loading SAM 3 onto the card the new owner is taking; a CPU-only call still runs, and ordinary releases (keep-alive, the panel's release) do not fence. Test: test_a_call_queued_across_a_handover_stays_off_the_card.

Comment on lines +120 to +122
try:
count = max(1, round(float(match.group(2))))
except ValueError:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Handle overflowing detection counts as invalid suffixes

A prompt with a sufficiently long numeric suffix, such as object: followed by several hundred digits, passes _MAX_SUFFIX but converts to positive infinity; round(float(...)) then raises OverflowError, which this handler does not catch. The request model permits prompts long enough to trigger this, and the route maps the uncaught exception to a 500 instead of treating the suffix like the other malformed counts or returning a client error.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3ef225c. The count parse catches OverflowError with ValueError, so an overflowing suffix reads as a literal label with count 1, like any other malformed suffix. Test: test_parse_prompt_overflowing_count_is_a_malformed_suffix.

Comment on lines +726 to +735
cache: dict[str, Any] = {}
for concept in concepts:
if concept.text not in cache:
index = texts.index(concept.text)
cache[concept.text] = model(
vision_embeds = vision,
input_ids = tokens["input_ids"][index : index + 1],
attention_mask = tokens["attention_mask"][index : index + 1],
)
out = cache[concept.text]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Do not retain every concept's full mask logits

For a prompt containing many distinct concepts, this cache keeps each concept's complete Sam3ImageSegmentationOutput on the device until the whole request ends, even though unique concepts are never reused. Each output contains all 200 mask-logit planes, so the allowed 16-concept request can retain hundreds of MiB on CUDA (and roughly twice that in CPU float32), pushing otherwise viable requests into the OOM fallback or exhausting host memory. Cache only concepts that actually repeat, or retain the reduced detections rather than every raw output.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3ef225c. Each distinct concept runs one forward pass, keeps only its reduced detections at the largest cap it is asked for, and drops the raw output right away; a repeat with a smaller cap takes the first N of those, which matches its own run. Test: test_raw_outputs_do_not_outlive_their_concept (weakrefs show each output is freed before the next forward).

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 19, 2026
A mask from text that queued behind a call in flight and is admitted after a
GPU handover's release now refuses as busy instead of loading SAM 3 onto the
card the new owner is taking (a CPU-only call still runs). A detection count of
hundreds of digits reads as a malformed suffix instead of a 500, and each
concept keeps only its kept detections rather than the full SAM 3 output for
the whole request.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3ef225c2f3

ℹ️ 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".

Comment on lines +159 to +160
and has(SEGMENTER_WEIGHTS_FILE, SEGMENTER_WEIGHTS_FILE + ".index.json")
and has("tokenizer.json", "vocab.json")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Verify every shard before accepting an override

Although the config-only case is now rejected, fresh code evidence shows that a partial sharded override is still accepted: any model.safetensors.index.json satisfies this check without verifying that the shard files named by its weight_map exist. An interrupted copy containing the index, config, and tokenizer therefore reports downloaded: true, enables Find, and then fails in from_pretrained; parse the index and require every referenced shard before returning the directory.

Useful? React with 👍 / 👎.

@danielhanchen danielhanchen Oct 19, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1c46537. A sharded override needs every shard named in model.safetensors.index.json's weight_map to exist; an unreadable index or an empty map is rejected. Test: test_sharded_override_needs_every_shard.

Comment on lines +843 to +845
if owner == DIFFUSION:
# Training releases DIFFUSION before it starts, resident or not: the segmenter goes too.
_release_mask_segmenter("image GPU released")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Fence off-torch training starts against the segmenter

When the active image backend has runs_off_torch_device=True, both LLM and diffusion training cleanup skip diffusion.unload() and gpu_arbiter.release(DIFFUSION) in routes/training.py, so this newly added release hook is never reached. A concurrent mask request can nevertheless be using the torch-visible CUDA card, and an owner-initiated LLM training start is not excluded by the diffusion trainer admission held by the mask route; the trainer can therefore start allocating on the same card while SAM is still running. Coordinate training with the segmenter independently of whether the image engine itself uses a torch device.

Useful? React with 👍 / 👎.

@danielhanchen danielhanchen Oct 19, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1c46537. Both off-torch branches in routes/training.py (start_training and the diffusion-training GPU free) now call gpu_arbiter.release_mask_segmenter() first, which waits for a call in flight. Test: test_training_beside_an_off_torch_image_model_releases_the_segmenter.

Comment on lines +631 to +634
if self.keep_alive_seconds <= 0:
self._unload_locked("no keep-alive")
return
self._arm_keep_alive()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Release SAM before generating with an already-loaded model

After Find completes with at least the fixed free-memory floor, this keeps SAM's roughly 1.7 GB CUDA weights resident for 120 seconds. Clicking Generate then uses the already-loaded image backend directly and does not call gpu_arbiter.acquire_for, so none of the new handover hooks unloads SAM before denoising; an otherwise viable high-resolution or batched generation can consequently be refused by the activation-memory check or OOM solely because the mask model is still resident. Release the segmenter when entering image generation rather than relying only on model-load handovers and a fixed post-mask threshold.

Useful? React with 👍 / 👎.

@danielhanchen danielhanchen Oct 19, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1c46537. The generate core releases the segmenter (waiting for a call in flight) right after the prompt upsampler step and before the denoise loop, as the upsampler sidecar leaves before a render; it never fails the render. Test: test_a_render_releases_the_segmenter_first.

Comment on lines +688 to +695
logger.warning("images.segment: out of memory on %s, retrying on the CPU", device)
self._unload_locked("out of memory")
import torch

device, dtype = "cpu", torch.float32
self._call_device = device
try:
result = self._segment_on(image, concepts, threshold, path, device, dtype)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Drop the OOM traceback before declaring the retry CPU-only

Fresh evidence beyond the handover timeout fix is that an OOM caught as exc retains _segment_on's traceback and its local CUDA model/tensors throughout the nested CPU retry. _unload_locked() therefore cannot actually free those allocations, yet _call_device is changed to "cpu"; if the CPU retry exceeds the handover timeout, release(handover=True) permits a new GPU owner while the failed call's CUDA allocations are still live, and the earlier empty_cache() also ran too soon to release their eventual cache blocks. Exit the exception scope or clear the traceback before retrying, then empty the CUDA cache before marking the call CPU-only.

Useful? React with 👍 / 👎.

@danielhanchen danielhanchen Oct 19, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1c46537. The except branch only records the OOM; the unload and a device cache free (gc, then empty_cache, also when no model was kept yet) run after the handler has exited and the traceback is gone, and only then is the call marked CPU-only. Test: test_oom_retry_frees_the_failed_attempt_before_reading_cpu_only.

Comment on lines +236 to +238
if (result.instances.length > 0 || additive === false) {
// Nothing found with Replace still clears the mask: the painter shows exactly what the text selected.
onMask({ dataUrl: result.mask, additive });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep an empty replacement mask logically empty

When SAM finds nothing and Replace is selected, this deliberately sends the all-black PNG to the painter, but both painters then store its data URL as a non-null mask/layer. That bypasses the page's existing !maskImage/!localizedLayer validation: localized mask mode reaches the backend only to fail its empty-mask check, while paint mode can submit an unchanged source as if a region had been selected. Clear the painter's logical value to null for a no-match replacement while still clearing its displayed canvas.

Useful? React with 👍 / 👎.

@danielhanchen danielhanchen Oct 19, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1c46537. A Replace with zero detections still clears the canvas but marks the result empty, so both painters report no mask (null), and Generate keeps refusing an unpainted inpaint or localized edit. Test: a Replace that found nothing leaves both painters holding no mask.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

The OOM retry leaves the except block before unloading, so the failed
attempt's tensors are freed and the cache emptied before the call reads
CPU-only. The arbiter marks a handover in progress until the new owner's
register returns, and mask calls refuse the card meanwhile. A render on a
resident image model and a training start beside an off-torch image model
release the segmenter first. A sharded UNSLOTH_SAM3_PATH needs every shard its
index names, and a Replace that finds nothing leaves the painter with no mask.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1c46537a92

ℹ️ 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".

Comment on lines +628 to +631
if not acquired:
with self._state_lock:
self._release_pending = True
if handover and self._call_on_accelerator():

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Recheck the call under the run lock after timeout

Fresh evidence beyond the timeout fix is a completion race here: if _run_lock.acquire() times out just as the segment call finishes, that call can run _after_call(), clear _call_device, and release the lock before _release_pending is set. The handover then sees no accelerator call and returns False, while the CUDA model remains resident because no call remains to honor the late pending flag, allowing the new GPU owner to register beside SAM. Reacquire/recheck the run lock before permitting the handover rather than relying on the unsynchronized _call_device snapshot.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 709a30a. The call sets its device and a settled flag together under a state lock, and after a timeout release() sets the pending flag and reads both under that same lock. A call that has not settled sees the flag and unloads itself (a GPU handover still raises meanwhile); a call that already settled or cleared its device can no longer honour it, so release() waits briefly for the run lock, unloads inside it and returns True. Test: test_a_release_timing_out_as_the_call_settles_still_unloads.

Comment on lines +797 to +804
kept[concept.text] = select_detections(
out.pred_logits[0],
out.pred_boxes[0],
out.pred_masks[0],
max_detections = caps[concept.text],
threshold = threshold,
presence_logit = None if presence is None else presence[0],
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Discard cached detections after their final concept use

Fresh evidence after the raw-output caching fix is that an allowed prompt such as 16 unique concepts each suffixed with :200, together with threshold 0, still stores all 200 mask planes for every concept in kept until the request ends. This retains hundreds of MiB on CUDA and substantially more in CPU float32 even though none of those unique concepts is reused, so the request can still trigger the OOM fallback or exhaust host memory; evict each entry after its final occurrence or cache only concepts known to repeat.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 709a30a. Each distinct text still runs once at its largest cap, but its kept masks are folded into the union right after its forward and dropped; only scores and boxes stay for later occurrences, and the union is unchanged since a smaller cap's best detections are a prefix of the larger cap's. Test: test_mask_planes_do_not_outlive_their_text (cat:200, dog:200, cat:2, bird:200 at threshold 0).

A release whose wait runs out just as the call settles (it already read its
release flag, or only still holds the lock) now waits out that short tail and
unloads, instead of letting the next GPU owner in beside the resident weights.
Each text's kept masks are OR-ed into the union right after its forward, so
only its scores and boxes outlive it.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ 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 module is None:
return
try:
module.release_segmenter(reason, wait = True, handover = handover)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Block training when the segmenter release times out

Fresh evidence after the earlier training coordination fix is that both off-torch training branches reach this helper with handover=False, so when a GPU-backed mask call exceeds the 30-second wait, release_segmenter() returns False and this wrapper silently allows the training start to continue. A slow first SAM load can therefore still overlap the trainer's GPU allocations; the training cleanup must either keep waiting or abort the start when the segmenter has not released the accelerator.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ba01db9. release_mask_segmenter() runs as a handover and raises SegmenterStillRunningError (blocks_training, like ManagedEngineStillRunning) when a GPU call outlives the wait. Both training starts call it before the engine branch and re-raise it, so the start is refused with a 409 ("A mask from text is still running on the GPU; try again when it finishes.") instead of proceeding. Test: test_training_start_refuses_while_a_mask_call_holds_the_gpu.

# not wait it out.
_cancel_upsampler_warm_start()
# As the upsampler leaves before the DiT denoises, so does the mask segmenter (Find's SAM 3 on its keep-alive).
await asyncio.to_thread(_release_mask_segmenter_for_render)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Fence new mask calls until the render owns the slot

Fresh evidence beyond the earlier render-release fix is the gap after this call and before backend.generate() acquires the engine's generation lock. A concurrent /images/segment request can acquire that lock in the gap, run after SAM was released, re-arm SAM's keep-alive, and then unlock directly into the queued render; the render consequently denoises with SAM resident again and can fail its activation-memory check or OOM. Hold the generation slot across this release or otherwise prevent mask admission until the render has acquired it.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ba01db9. The generate core holds a render fence for the whole run, raised before SAM is released; a Find that arrives while it is up gives back any slot it took and is refused (409), and one that already held the slot is waited for by the render's release. Test: test_no_find_starts_while_a_render_is_on_its_way.

complete = (
has("config.json")
and (has(SEGMENTER_WEIGHTS_FILE) or _shards_complete(path / (SEGMENTER_WEIGHTS_FILE + ".index.json")))
and has("tokenizer.json", "vocab.json")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require the complete fallback tokenizer files

Fresh evidence after the earlier override validation fix is that a directory containing only vocab.json is still accepted as having a tokenizer. Without tokenizer.json, the fallback tokenizer needs its companion metadata and BPE merge data; a copied directory with config, weights, and only vocab.json therefore reports downloaded: true, but the subsequent AutoTokenizer.from_pretrained(path) fails and the override prevents recovery through the download endpoint. Accept tokenizer.json, or require the complete legacy tokenizer file set.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ba01db9. Checked by loading every combination with AutoTokenizer (CLIPTokenizer for sam3): tokenizer.json alone, or vocab.json with merges.txt, load; either of the pair alone does not. The override now requires tokenizer.json or both of vocab.json and merges.txt. Test: test_partial_override_does_not_read_as_downloaded.

Comment on lines +370 to +381
if allow_gpu and torch.cuda.is_available():
ordinal = _resident_cuda_ordinal()
if ordinal is None or ordinal >= torch.cuda.device_count():
ordinal = torch.cuda.current_device()
free_mib, _total = _cuda_free_mib(ordinal)
if free_mib is None or free_mib >= _GPU_NEED_MIB:
bf16 = False
with suppress(Exception):
# is_bf16_supported reads the CURRENT card; the segmenter runs on ``ordinal``.
with torch.cuda.device(ordinal):
bf16 = bool(torch.cuda.is_bf16_supported())
return f"cuda:{ordinal}", torch.bfloat16 if bf16 else torch.float16

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Fence CUDA segmentation against existing GPU owners

When a chat or video model already owns the card—especially when the image model has been evicted—this branch selects the current CUDA device solely from its free-memory snapshot. The segment route only takes the image engine's generation lock and never acquires or checks the GPU arbiter, so a same-account Find can load and run SAM beside an active chat/video inference; those owners can then grow their working memory concurrently and OOM either request. Coordinate segment admission with every arbiter resident, or fall back to CPU unless the segmenter is allowed to share the selected card.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ba01db9. choose_device now reads the arbiter's residents and keeps SAM 3 off any card another owner holds (a resident with unknown GPUs counts as every card): only the image model, nobody, or an owner on a different card leaves the GPU available, else the call runs on the CPU and the response reports device cpu. The check runs in segment() under the run lock after the handover fence. Test: test_choose_device_never_shares_a_card_another_owner_holds.

…training

Find runs on the CPU when a chat, video or other non-image model holds the
CUDA card, read from the GPU arbiter under the run lock behind the handover
fence. A render fences new Finds from before it releases SAM 3 until it ends,
so none reloads it before the render takes the generation slot. A training
start whose segmenter release outlives the wait is refused with a 409 instead
of spawning beside it, on both start paths and either image engine. An
UNSLOTH_SAM3_PATH tokenizer needs tokenizer.json, or vocab.json with
merges.txt.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

https://github.com/unslothai/unsloth/blob/ba01db94ad3327f3a0e21bdcf146afb961aa31c0/studio/backend/routes/inference.py#L51729
P1 Badge Fence prompt upsampling against an active SAM call

When a same-account Find is already running and a FLUX.3 render with prompt enhancement begins, this calls _enhance_generate_prompts before releasing the segmenter. The existing Find holds the image engine's generation lock, but PromptUpsamplerSidecar.generate() does not acquire that lock, so it can launch or use its GPU sidecar concurrently with SAM; the render fence only rejects new Find requests. This can make either operation OOM, so wait for/release the active segmenter before upsampling or make the upsampler share the same execution fence.

ℹ️ 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".

and getattr(getattr(torch, "backends", None), "mps", None) is not None
and torch.backends.mps.is_available()
):
return "mps", torch.float32

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Check GPU ownership before selecting MPS

Fresh evidence beyond the CUDA-owner fix is that the MPS branch still selects the accelerator without consulting the arbiter. On Apple Silicon, a same-account Find can therefore load the fp32 SAM model into unified Metal memory while a resident chat or video model owns and actively uses Metal; require_idle_other_accounts() does not exclude that case, so either workload can exhaust unified memory. Apply the non-diffusion-owner check to MPS as well, falling back to CPU when another owner is resident.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c6adbd0. Apple's single Metal device now gets the same rule: any arbiter resident other than the image model, whatever GPU ids it reports, keeps SAM 3 off Metal and the call runs on the CPU. Test: test_metal_is_not_shared_with_another_owner.

Comment on lines +603 to +604
self._tokenizer = AutoTokenizer.from_pretrained(path)
self._model, self._path, self.device, self._dtype = model, path, device, dtype

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Free partial model loads when tokenizer setup fails

When Sam3Model.from_pretrained successfully allocates the model on CUDA but AutoTokenizer.from_pretrained then fails—for example with an incomplete or incompatible local override—the model exists only in the local model variable and is never assigned to self._model. The non-OOM exception path calls _after_call(), which therefore has nothing to unload; once the traceback unwinds, PyTorch's caching allocator can continue reserving the model's GPU blocks, and a later external GPU owner can OOM even though the segmenter reports unloaded. Load the tokenizer first or explicitly delete the partial model and release the device cache on this failure path.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c6adbd0. The tokenizer loads before the weights, so a broken tokenizer fails before anything reaches the card; a failure after the weights were placed drops the local model and frees the device cache before re-raising, and nothing is kept until both succeed. Test: test_a_failed_load_places_no_weights.

On Apple's single Metal device any resident other than the image model sends
Find to the CPU, as another owner's CUDA card already does. The segmenter
loads its tokenizer before the weights, and weights placed by a load that then
fails are dropped and the device cache released.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 80bcc2410f

ℹ️ 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".

@danielhanchen
danielhanchen merged commit bff0a25 into main Oct 19, 2026
@danielhanchen
danielhanchen deleted the studio-images-sam3-mask branch October 19, 2026 14:08
danielhanchen added a commit that referenced this pull request Oct 19, 2026
…14272)

## Summary

`Frontend build + bundle sanity` fails its `Typecheck` step (`npm run
typecheck`, tests included) on PRs based on current main (seen on
#14245):

```
tests/image-engine-choice.test.ts(305,48): error TS2339: Property 'baseRepo' does not exist on type '{ repoId: string; kind?: ...; filename?: ...; } | { repoId: string; kind: "gguf"; filename: string; displayRepoId?: string; baseRepo?: string; }'.
tests/image-mask-from-text.test.ts(246,30): error TS2345: Argument of type '"drawImage"' is not assignable to parameter of type 'never'.
tests/image-mask-from-text.test.ts(246,61): error TS2345: Argument of type '"putImageData"' is not assignable to parameter of type 'never'.
```

Reproduced on main `6c159816c5` with `node scripts/typecheck.mjs
--tests` (TypeScript 7.0.2, as CI). The product code typechecks. Both
errors are in tests:

- **`image-engine-choice.test.ts` (from #14232):**
`nativeReloadTarget(null, gguf)?.baseRepo`. With `null` as the last
load, `T` falls back to its constraint, which has no `baseRepo`, so one
branch of the return union lacks the property.
- **`image-mask-from-text.test.ts` (from #14235):**
`assert.deepEqual(calls, [])` from `node:assert/strict` is an assertion
signature. It narrows `calls` to `never[]`, so the later
`calls.includes("drawImage")` no longer typechecks.

## Change

Test-only:

- **`image-engine-choice.test.ts`:** `nativeReloadTarget<{ repoId:
string; baseRepo?: string }>(null, gguf)?.baseRepo`. This names `T`, so
the status-built branch, the one that carries `baseRepo`, is what is
read. The assertion is unchanged.
- **`image-mask-from-text.test.ts`:** `assert.equal(calls.length, 0)` in
place of `assert.deepEqual(calls, [])`. It asserts the same thing
without the narrowing, with a comment saying why.

## Testing

- **`node scripts/typecheck.mjs --tests`:** clean (exit 0), from the
three errors above on main.
- **`node --experimental-strip-types --test` on both files:** 30 passed.
danielhanchen added a commit that referenced this pull request Oct 19, 2026
#14271)

## Summary

Two tests in `studio/backend/tests/test_diffusion_segment.py` fail in
the `(Python 3.13, a-k)` shard on PRs with different bases (#14229,
#14245):

```
test_choose_device_needs_room_on_the_card
test_choose_device_reads_bf16_on_the_chosen_card
E   AssertionError: assert ('cpu', torch.float32) == ('cuda:1', torch.bfloat16)
```

Both pass when the file runs on its own (64 passed).

## Cause

`choose_device()` (from #14235, SAM 3 masks) puts SAM 3 on the CPU when
another GPU arbiter owner holds the card (`_other_owner_on` ->
`gpu_arbiter.residents()`). The arbiter's `_owner` / `_residents` are
module globals. These two tests stub torch and the free-memory probe but
not the arbiter. So when an earlier test in the same xdist worker leaves
a CHAT owner behind, they see the card as taken and pick the CPU. The
product is right to refuse a card another owner holds. The tests were
order dependent.

## Change

Test-only: an autouse fixture in `test_diffusion_segment.py` clears
`gpu_arbiter._owner` and `_residents` before each test (with
`monkeypatch`, so they are restored). Tests that exercise ownership
already set their own owner, and still do.

## Testing

- **`test_diffusion_segment.py`:** 64 passed.
- **Sabotage:** I added a throwaway test that sets `gpu_arbiter._owner =
gpu_arbiter.CHAT` and ran it first in the same process:
- **Without the fixture:** `test_choose_device_needs_room_on_the_card`
and `test_choose_device_reads_bf16_on_the_chosen_card` fail. These are
the two CI failures.
  - **With it:** all pass.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Use SAM3.1 for generating a prompt-based mask for inpainting

1 participant