Export Meta's SAM3 open-vocabulary segmenter to ONNX, serve it on Triton, drive it from Python.
Segment anything you can name β "building", "swimming pool", "a red car".
The prompt is a runtime input: nothing is baked in, no retraining, no re-export.
142 buildings from one word. segment(tile, "building") on the bundled 1008Γ1008 sample tile β real output, no cherry-picking.
Three self-contained pieces β export the graphs, serve them, call them:
π¦ |
π |
π |
New here? Start with
ARCHITECTURE.mdβ how SAM3's monolithic image model is cut into the deployed graphs, the exact tensors crossing every cut, and why the cuts fall where they do.
prompt str ββ(SAM3 BPE tokenizer, padβ32; client-side Python)βββΊ token_ids[1,32]
image β sam3_unified_encoder (baked resize+normalize, one ViT pass) ββΊ 7 vision tensors
token_ids β sam3_text ββΊ 3 text tensors
7 vision + 3 text (+ optional box/concept exemplars) β sam3_decoder ββΊ 200-query head
β
ββ sam3_postprocess ββΊ per-instance RLE ββΊ DataFrame[box, score, mask]
The heavy ViT backbone (~1.9 GB) runs once per image; every prompt and exemplar is a cheap runtime input on the light grounding head. That single property is what makes the multi-keyword, cross-crop-concept, and interactive paths practically free.
1 Β· Export the ONNX graphs β on a box with the sam3 package + a GPU
cd export
python sam3_vision_export.py --export # -> onnx/sam3_vision.onnx
python sam3_text_export.py --export # -> onnx/sam3_text.onnx
python sam3_decoder_export.py --export # -> onnx/sam3_decoder.onnx
python sam3_concept_split_export.py --export # -> concept encoder + decoder_ctSee export/README.md for flags, validation output, and the export gotchas.
2 Β· Serve it on Triton β drop the ONNX into each version dir, then run Docker
docker run --gpus=1 --rm --name sam3-triton \
--shm-size=1g \
-p 8000:8000 -p 8001:8001 -p 8002:8002 \
-v "$PWD/triton/models:/models:ro" \
nvcr.io/nvidia/tritonserver:25.07-py3 \
tritonserver --model-repository=/models/sam3--shm-size=1g is not optional β Triton's Python backend uses shared memory, and Docker's
64 MB default makes the python stubs hang. Full setup, compose file, GPU requirements and
troubleshooting: triton/README.md.
3 Β· Call it from Python
pip install ./clientfrom sam3_triton_client import Sam3Client
c = Sam3Client("localhost:8001")
df = c.segment("export/sample_tile.jpg", "building")Every method returns a pandas.DataFrame with box ([x1,y1,x2,y2] in the original image's
pixels), score, and a full-frame mask.
examples.py against a live Triton on the bundled export/sample_tile.jpg.Reproduce with
python examples.py <host:8001>.
df = c.segment("export/sample_tile.jpg", "building") box score mask
0 [107.0, 0.0, 173.0, 44.0] 0.796 <1008x1008 px, 2277 fg>
1 [194.0, 59.0, 231.0, 90.0] 0.785 <1008x1008 px, 941 fg>
2 [456.0, 512.0, 504.0, 554.0] 0.785 <1008x1008 px, 1647 fg>
... 142 rows total
df = c.multi("export/sample_tile.jpg", ["building", "road", "vegetation"])keyword instances
building 142
road 13
vegetation 65
... 220 rows total, with a `keyword` column
The vision encoder runs once; the grounding decoder loops per keyword server-side. N keywords cost ~1Γ vision + NΓ the cheap decoder β not N full passes.
# encode one building's appearance into a portable concept, then find look-alikes
concept = c.encode_exemplars("export/sample_tile.jpg", boxes=[[107.0, 0.0, 173.0, 44.0]])
# concept.tokens (18, 1, 256) float32 β 2 active slots (1 box + 1 cls)
df = c.segment("export/sample_tile.jpg", prompt=None, concept=concept) box score mask
0 [107.0, 0.0, 174.0, 45.0] 0.955 <1008x1008 px, 2267 fg> # the exemplar itself
1 [194.0, 60.0, 231.0, 90.0] 0.733 <1008x1008 px, 900 fg>
... 132 rows total
A concept carries appearance, not location β bank it with concept.to_bytes() and reuse it on
any other crop, at any time. (Shown here encoded and applied on one tile so the demo is self-contained.)
s = c.interactive("export/sample_tile.jpg")
df = s.add_point((504, 504)) # 3 candidates, best predicted-IoU first
# df = s.add_point((520, 520), positive=False) # refine: exclude a region
best = df.iloc[0]["mask"]The heavy encoder runs once when the session opens; each click is a cheap decoder call. Here score
is the model's predicted mask IoU (quality), not a detection confidence.
A box exemplar is not a detection and not a spatial filter β it refines the concept across the whole image. A positive box says "things that look like this"; a negative box suppresses an appearance. Up to 16, combined freely with the text prompt.
POS = [107.0, 0.0, 173.0, 44.0] # a house
NEG = [232.0, 200.0, 470.0, 300.0] # bare lot / parking
c.segment(tile, "building") # 142
c.segment(tile, "building", exemplar_boxes=[POS]) # 133
c.segment(tile, "building", exemplar_boxes=[POS, NEG],
exemplar_labels=[1, 0]) # 132On this tile the effect is a modest narrowing (142 β 133 β 132), because "building" is already
a strong prompt for suburban housing β exemplars earn their keep on concepts that text describes
poorly ("this particular kind of roof"). Drop the text entirely with prompt=None for a pure
visual query.
Beyond clicks, a session accepts a box or an existing mask, and prompts accumulate so each call refines the last:
s = c.interactive(tile)
s.add_box([470, 480, 560, 545]) # box prompt -> best IoU 0.709
s.reset()
s.add_point((504, 504)) # positive click -> best IoU 0.845
s.add_point((470, 470), positive=False) # + negative -> best IoU 0.903
s.undo() # take the last prompt backYou can also hand a segment() result straight into the loop and refine it by hand β
s.add_mask(df.iloc[0]["mask"]) seeds the session with that mask as a logit prior, then clicks
take over. reset() clears the prompts but keeps the cached embedding, so it stays cheap.
Class-agnostic "segment everything": a grid of clicks fanned through the decoder, filtered by predicted IoU and mask stability, then de-duplicated by box NMS.
df = c.interactive(tile).everything(points_per_side=16)
# -> 47 objects; columns: box / score / stability / maskSeed points are batched over the one cached embedding, so a 16Γ16 grid is ~8 decoder calls, not
256. Raise points_per_side for recall on small objects; raise pred_iou_thresh /
stability_score_thresh for precision.
c.segment(tile, "building", score_thr=0.5) # confidence floor
c.segment(tile, "building", dedup=None) # keep nested duplicates
c.segment(tile, "building", max_det=20, mask_thr=0.6)score_thr |
0.2 | 0.3 (default) | 0.5 | 0.7 |
|---|---|---|---|---|
| instances | 153 | 142 | 93 | 17 |
dedup (default 0.85) suppresses masks nested inside a higher-scoring one, using the overlap
coefficient inter/min(area) β plain IoU-NMS misses those. SAM3 grounding has no server-side
NMS, so this is the client's job. On this tile at the default threshold it happens to change
nothing (dedup=None also gives 142); it earns its keep at lower score_thr, where the model
starts emitting nested near-duplicates.
| method | ensemble | returns |
|---|---|---|
segment(image, prompt, β¦) |
sam3_solver / sam3_concept_solver |
DataFrame[box, score, mask] |
multi(image, prompts, β¦) |
sam3_multi_solver |
DataFrame[β¦, keyword] |
encode_exemplars(image, boxes, β¦) |
sam3_concept_encode |
ConceptExemplars |
interactive(image) |
sam3_unified_encoder + sam3_pvs_decoder |
Sam3InteractiveSession |
A Sam3InteractiveSession (from interactive(...)) adds:
| method | does |
|---|---|
add_point(xy, positive=True) |
foreground / background click |
add_box([x1,y1,x2,y2]) |
box prompt (two labelled corners) |
add_mask(mask) |
seed with an existing HxW mask as a logit prior |
undo() / reset() |
drop the last prompt / clear all, keeping the cached embedding |
everything(...) |
automatic mask generation over a click grid |
exemplar_boxes refines a concept with boxes in the same image; concept= carries an appearance
encoded on a different crop (mutually exclusive). prompt=None runs a pure-exemplar query.
dedup (default 0.85) suppresses nested duplicate masks client-side β SAM3 grounding has no
server-side NMS.
Full argument-by-argument docs: client/README.md β every parameter, the
three ways to specify a concept, the output schema, and the connection/retry options.
The BPE tokenizer is a faithful copy of SAM3's SimpleTokenizer (CLIP BPE), so token ids match the
deployed text encoder exactly. The Triton configs, Python backends, and client are the source of
truth for the deployed tensor shapes and semantics β keep them in sync with the ONNX graphs when
you re-export.
This repository is tooling only β it contains no model weights. It is released under the MIT License. The components it works with carry their own terms:
- SAM3 (Meta). The scripts in
export/import and trace Meta'ssam3package to produce ONNX graphs, andARCHITECTURE.mddocuments that model's structure. You must obtain the SAM3 package and checkpoint yourself, and your use of the model and any exported weights is governed by Meta's SAM3 license, not by this repo's MIT license. Check those terms before redistributing anything you export. - CLIP BPE vocabulary (
client/sam3_triton_client/assets/bpe_simple_vocab_16e6.txt.gz) β the standard byte-pair-encoding vocab from OpenAI's CLIP, redistributed under its MIT license. SAM3's text tokenizer uses it, so token ids must match exactly. export/sample_tile.jpgβ a 1008Γ1008 aerial sample bundled for export validation and the examples above.





