Skip to content

About

Export Meta's SAM3 open-vocabulary segmenter to ONNX, deploy on Triton, and run it from a simple Python client.

Resources

Stars

9 stars

Watchers

0 watching

Forks

Latest commit

 

History

3 Commits

Folders and files

Repository files navigation

sam3‑triton

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.

MIT license Python 3.12+ Triton 25.07-py3 ONNX fp32

142 buildings segmented from a single text prompt

142 buildings from one word. segment(tile, "building") on the bundled 1008Γ—1008 sample tile β€” real output, no cherry-picking.


What's inside

Three self-contained pieces β€” export the graphs, serve them, call them:

πŸ“¦ export/

ONNX export scripts β€” vision, text, decoder, PVS, and the cross-crop concept split. Each is self-contained, ships a sample tile, and validates its graph against the torch reference.

πŸš€ triton/

The Triton model repository β€” config.pbtxt + Python backends for all 13 models and ensembles, plus Docker / compose instructions. Weights are gitignored; this repo ships no model weights.

🐍 client/

sam3_triton_client β€” a small pip-installable Sam3Client. Tokenizes the prompt, calls the ensembles, hands back a pandas.DataFrame. Four methods, no ceremony.

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.


How it works

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.


Quick start

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_ct

See 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 ./client
from 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

Every figure and number below is real output, captured by examples.py against a live Triton on the bundled export/sample_tile.jpg.
Reproduce with python examples.py <host:8001>.

segment Β· one text prompt, every instance

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
segment: 142 building instances

multi Β· several concepts, one encode

multi-keyword: buildings, roads, vegetation
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_exemplars + concept= Β· segment by example, across crops

# 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
concept exemplar and the 132 matches it finds

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.)


interactive Β· click to segment, refine as you go

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"]
interactive: one click, three ranked candidate masks

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.


exemplar_boxes Β· steer the concept with examples in this image

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])                              # 132
text-only vs positive exemplar vs positive+negative exemplar

On 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.


interactive Β· box, mask, and undo

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 back
box prompt, positive click, and negative-click refinement

You 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.


everything Β· automatic mask generation

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 / mask
automatic mask generation, 47 objects

Seed 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.


Tuning the output

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.


API

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.


Notes

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.

License & third-party components

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's sam3 package to produce ONNX graphs, and ARCHITECTURE.md documents 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.

About

Export Meta's SAM3 open-vocabulary segmenter to ONNX, deploy on Triton, and run it from a simple Python client.

Resources

Stars

9 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages