Repository files navigation

sam3.cpp

State-of-the-art image and video segmentation in portable C/C++

SAM3 Image Segmentation DemoSAM3 Video Segmentation Demo


Why sam3.cpp?

Running Meta's Segment Anything models typically requires Python, PyTorch, and a CUDA GPU. sam3.cpp eliminates all of that. It's a single C++ library that runs SAM 2, SAM 2.1, SAM 3, and EdgeTAM inference on CPU and Apple Metal. No Python runtime, no GPU drivers, no heavyweight dependencies. Just compile and segment.

  • 4 model families: SAM 2, SAM 2.1 (Hiera), SAM 3 (ViT + text detection), EdgeTAM (RepViT, 22x faster than SAM 2 on mobile)
  • 4-bit quantization: EdgeTAM in 15 MB, SAM 2.1 Tiny in 22 MB at ~1 fps on Metal, SAM 3 down to 673 MB
  • Apple Metal GPU acceleration for the full backbone and transformer decoder
  • Text-prompted detection (SAM 3 only): type "cat" and get every cat in the image, no clicks needed
  • Point/box segmentation + video tracking with memory bank across all models
  • Single-file library: sam3.cpp + sam3.h, C++14, no exceptions, no inheritance
  • Zero dependencies beyond ggml and stb

Quick Start

# Clone
git clone --recursive https://github.com/PABannier/sam3.cpp
cd sam3.cpp
# Build (Metal GPU enabled automatically on macOS)
mkdir build &&cd build
cmake ..
make -j
# Download a model (SAM 2.1 Tiny, 75 MB)# See "Model Zoo" below for all available models and download links
curl -L -o ../models/sam2.1_hiera_tiny_f16.ggml \
https://huggingface.co/PABannier/sam3.cpp/resolve/main/sam2.1_hiera_tiny_f16.ggml
# Segment an image interactively (requires SDL2)
./examples/sam3_image --model ../models/sam2.1_hiera_tiny_f16.ggml --image ../data/test_image.jpg
# Track objects in a video interactively (requires SDL2)
./examples/sam3_video --model ../models/sam2.1_hiera_tiny_f16.ggml --video ../data/test_video.mp4

The interactive apps use SDL2 + ImGui. If SDL2 isn't found, only the benchmark and quantize tools are built.

Benchmarks

Video object tracking latency on Apple M4 Pro (24 GB), 5 frames at 1008x1008 resolution, 4 threads. Each run is isolated in a forked subprocess.

SAM 3 (Full: text detection + visual tracking)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam3-f323.2 GB-40.5-200.4
sam3-f161.7 GB7.723.838.1117.5
sam3-q8_01.0 GB7.823.338.7115.2
sam3-q4_1756 MB-24.5-120.9
sam3-q4_0673 MB7.823.938.7117.7

SAM 3 Visual-Only (no text encoder, tracking only)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam3-visual-f16901 MB6.622.632.7111.2
sam3-visual-q8_0493 MB6.722.033.0108.4
sam3-visual-q4_1318 MB-23.1-113.9
sam3-visual-q4_0275 MB6.722.333.0110.0

EdgeTAM (RepViT backbone + Perceiver)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
edgetam_f1627 MB0.41.12.25.2
edgetam_q8_019 MB0.41.12.15.1
edgetam_q4_015 MB0.41.12.15.1

SAM 2 / SAM 2.1 (Hiera backbone)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam2_hiera_tiny_f1675 MB0.92.74.012.6
sam2_hiera_tiny_q8_040 MB0.92.54.011.7
sam2_hiera_tiny_q4_022 MB0.92.54.011.7
sam2_hiera_small_f1689 MB0.92.94.113.7
sam2_hiera_small_q8_047 MB0.92.74.112.5
sam2_hiera_small_q4_026 MB0.92.74.112.7
sam2_hiera_base_plus_f16155 MB1.04.24.720.2
sam2_hiera_base_plus_q8_083 MB-3.9-18.9
sam2_hiera_large_f16429 MB-8.4-40.9
sam2_hiera_large_q8_0230 MB-7.6-37.1
sam2.1_hiera_tiny_f1675 MB0.82.64.012.3
sam2.1_hiera_tiny_q8_040 MB0.92.44.011.4
sam2.1_hiera_tiny_q4_022 MB0.92.54.011.5
sam2.1_hiera_small_f1689 MB0.92.94.113.5
sam2.1_hiera_small_q8_047 MB0.92.74.112.5
sam2.1_hiera_small_q4_026 MB0.92.74.112.6
sam2.1_hiera_base_plus_f16155 MB1.04.24.720.1
sam2.1_hiera_base_plus_q8_083 MB-3.9-18.6
sam2.1_hiera_large_f16430 MB-8.5-41.4
sam2.1_hiera_large_q8_0230 MB-7.7-37.7
Reproduce these benchmarks
# Full benchmark (all models, both backends)
./build/examples/sam3_benchmark
# GPU only, all models
./build/examples/sam3_benchmark --gpu-only
# Quick iteration (tiny models, 3 frames)
./build/examples/sam3_benchmark --filter tiny --n-frames 3 --gpu-only
# CPU only, specific model
./build/examples/sam3_benchmark --cpu-only --filter sam2.1_hiera_small

Options: --models-dir <path>, --video <path>, --n-frames <n>, --n-threads <n>, --filter <substr>, --cpu-only, --gpu-only

Model Zoo

All models are available in GGML format on Hugging Face:

PABannier/sam3.cpp: 52 model files covering 4 architectures x multiple sizes x up to 5 precisions.

SAM 3 (850M params, ViT-32 backbone + text encoder + DETR decoder)

VariantPrecisionSizeFeatures
sam3f323.4 GBText detection (PCS) + point/box segmentation (PVS) + video tracking
sam3f161.7 GBSame
sam3q8_01.0 GBSame
sam3q4_1756 MBSame
sam3q4_0707 MBSame
sam3-visualf16946 MBPoint/box segmentation (PVS) + video tracking (no text)
sam3-visualq8_0517 MBSame
sam3-visualq4_1318 MBSame
sam3-visualq4_0289 MBSame

SAM 2 / SAM 2.1 (Hiera backbone, 4 sizes)

FamilySizeParamsf32f16q8_0q4_1q4_0
SAM 2Tiny39M156 MB79 MB43 MB26 MB24 MB
SAM 2Small46M184 MB94 MB50 MB30 MB28 MB
SAM 2Base+81M323 MB163 MB88 MB53 MB48 MB
SAM 2Large224M898 MB451 MB241 MB144 MB130 MB
SAM 2.1Tiny39M156 MB79 MB43 MB26 MB24 MB
SAM 2.1Small46M184 MB94 MB50 MB30 MB28 MB
SAM 2.1Base+81M323 MB163 MB88 MB53 MB48 MB
SAM 2.1Large224M898 MB451 MB241 MB144 MB130 MB

EdgeTAM (RepViT-M1 backbone + Perceiver memory compressor)

VariantPrecisionSizeFeatures
edgetamf1627 MBPoint/box segmentation (PVS) + video tracking
edgetamq8_019 MBSame
edgetamq4_015 MBSame

Feature Matrix

CapabilitySAM 3SAM 3 VisualSAM 2 / 2.1EdgeTAM
Text-prompted detection (PCS)Yes---
Point/box segmentation (PVS)YesYesYesYes
Multi-mask outputYesYesYesYes
Video tracking (memory bank)YesYesYesYes
Interactive refinementYesYesYesYes
Quantization (Q4/Q8)YesYesYesYes
Metal GPUYesYesYesYes

Building from Source

Prerequisites

  • C++14 compiler (Clang, GCC, MSVC)
  • CMake 3.14+
  • (Optional) SDL2 for the interactive image/video examples
  • (Optional) ffmpeg for video frame decoding

Build

git clone --recursive https://github.com/PABannier/sam3.cpp
cd sam3.cpp
mkdir build &&cd build
cmake ..
make -j

Metal is enabled automatically on macOS. To disable it:

cmake .. -DSAM3_METAL=OFF

To build tests:

cmake .. -DSAM3_BUILD_TESTS=ON
make -j

Usage

Image Segmentation (Interactive GUI)

# Point/box segmentation with any model
./sam3_image --model models/sam2.1_hiera_tiny_f16.ggml --image photo.jpg
# Text-prompted detection (SAM 3 only)
./sam3_image --model models/sam3-f16.ggml --image photo.jpg
# → Type "cat" in the text field, click [Segment]

Controls:

  • Left-click: add positive point
  • Right-click: add negative point
  • Drag: draw bounding box
  • Text field + Segment: detect all instances matching the text prompt (SAM 3 only)
  • Export: save masks as PNG

Video Tracking (Interactive GUI)

# Visual tracking (SAM 2/2.1/3/EdgeTAM)
./sam3_video --model models/sam2.1_hiera_small_f16.ggml --video input.mp4
# Text-prompted tracking (SAM 3 only)
./sam3_video --model models/sam3-f16.ggml --video input.mp4

Controls:

  • Click a point or draw a box on a paused frame to add an instance
  • Click on an existing tracked mask to refine it
  • Play/Pause/Step for playback
  • Export per-frame mask PNGs

C++ API

#include"sam3.h"// Load model
sam3_params params;
params.model_path = "models/sam2.1_hiera_tiny_f16.ggml";
params.use_gpu = true;
params.n_threads = 4;
auto model = sam3_load_model(params);
auto state = sam3_create_state(*model, params);
// Encode image (call once, reuse for multiple prompts)auto image = sam3_load_image("photo.jpg");
sam3_encode_image(*state, *model, image);
// Segment with a point click
sam3_pvs_params pvs;
pvs.pos_points.push_back({315.0f, 250.0f});
sam3_result result = sam3_segment_pvs(*state, *model, pvs);
for (auto& det : result.detections) {
sam3_save_mask(det.mask, "mask.png");
}
// Text-prompted detection (SAM 3 full model only)
sam3_pcs_params pcs;
pcs.text_prompt = "yellow school bus";
pcs.score_threshold = 0.5f;
sam3_result result = sam3_segment_pcs(*state, *model, pcs);
// → result.detections contains every matching instance
// Video trackingauto tracker = sam3_create_visual_tracker(*model, {});
// Frame 0: encode + add instance with a clicksam3_encode_image(*state, *model, frame0);
sam3_pvs_params pvs;
pvs.pos_points.push_back({315.0f, 250.0f});
sam3_tracker_add_instance(*tracker, *state, *model, pvs);
// Subsequent frames: propagate masksfor (int f = 1; f < n_frames; f++) {
sam3_result result = sam3_propagate_frame(*tracker, *state, *model, frames[f]);
// result.detections[i].mask - tracked mask for each instance
}

Quantization

Convert F32/F16 weights to smaller quantized formats:

./sam3_quantize models/sam3-f16.ggml models/sam3-q4_0.ggml q4_0
# Supported types: q4_0, q4_1, q8_0

Converting Weights

Convert official PyTorch checkpoints to GGML format:

# SAM 3
uv run python convert_sam3_to_ggml.py \
--model sam3.pt \
--output models/sam3-f16.ggml \
--ftype 1 \
--tokenizer /path/to/tokenizer
# SAM 3 visual-only (no text encoder, smaller file)
uv run python convert_sam3_to_ggml.py \
--model sam3.pt \
--output models/sam3-visual-f16.ggml \
--ftype 1 \
--visual-only
# SAM 2 / SAM 2.1
uv run python convert_sam2_to_ggml.py \
--model sam2.1_hiera_large.pt \
--config sam2.1_hiera_l.yaml \
--output models/sam2.1_hiera_large_f16.ggml \
--ftype 1
# EdgeTAM
uv run python convert_edgetam_to_ggml.py \
--model edgetam.pt \
--output models/edgetam_f16.ggml \
--ftype 1

--ftype 0 = float32, --ftype 1 = float16 (recommended). Then quantize with sam3_quantize.

Acknowledgments

  • Meta AI Research for SAM, SAM 2, SAM 3, and EdgeTAM
  • ggml, the tensor computation library that makes this possible
  • sam.cpp, the original SAM 1 C++ port that inspired this project's architecture

License

MIT

About

Fast state-of-the-art image and video segmentation in portable C/C++

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

sam3.cpp

State-of-the-art image and video segmentation in portable C/C++

SAM3 Image Segmentation DemoSAM3 Video Segmentation Demo


Why sam3.cpp?

Running Meta's Segment Anything models typically requires Python, PyTorch, and a CUDA GPU. sam3.cpp eliminates all of that. It's a single C++ library that runs SAM 2, SAM 2.1, SAM 3, and EdgeTAM inference on CPU and Apple Metal. No Python runtime, no GPU drivers, no heavyweight dependencies. Just compile and segment.

  • 4 model families: SAM 2, SAM 2.1 (Hiera), SAM 3 (ViT + text detection), EdgeTAM (RepViT, 22x faster than SAM 2 on mobile)
  • 4-bit quantization: EdgeTAM in 15 MB, SAM 2.1 Tiny in 22 MB at ~1 fps on Metal, SAM 3 down to 673 MB
  • Apple Metal GPU acceleration for the full backbone and transformer decoder
  • Text-prompted detection (SAM 3 only): type "cat" and get every cat in the image, no clicks needed
  • Point/box segmentation + video tracking with memory bank across all models
  • Single-file library: sam3.cpp + sam3.h, C++14, no exceptions, no inheritance
  • Zero dependencies beyond ggml and stb

Quick Start

# Clone
git clone --recursive https://github.com/PABannier/sam3.cpp
cd sam3.cpp
# Build (Metal GPU enabled automatically on macOS)
mkdir build &&cd build
cmake ..
make -j
# Download a model (SAM 2.1 Tiny, 75 MB)# See "Model Zoo" below for all available models and download links
curl -L -o ../models/sam2.1_hiera_tiny_f16.ggml \
https://huggingface.co/PABannier/sam3.cpp/resolve/main/sam2.1_hiera_tiny_f16.ggml
# Segment an image interactively (requires SDL2)
./examples/sam3_image --model ../models/sam2.1_hiera_tiny_f16.ggml --image ../data/test_image.jpg
# Track objects in a video interactively (requires SDL2)
./examples/sam3_video --model ../models/sam2.1_hiera_tiny_f16.ggml --video ../data/test_video.mp4

The interactive apps use SDL2 + ImGui. If SDL2 isn't found, only the benchmark and quantize tools are built.

Benchmarks

Video object tracking latency on Apple M4 Pro (24 GB), 5 frames at 1008x1008 resolution, 4 threads. Each run is isolated in a forked subprocess.

SAM 3 (Full: text detection + visual tracking)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam3-f323.2 GB-40.5-200.4
sam3-f161.7 GB7.723.838.1117.5
sam3-q8_01.0 GB7.823.338.7115.2
sam3-q4_1756 MB-24.5-120.9
sam3-q4_0673 MB7.823.938.7117.7

SAM 3 Visual-Only (no text encoder, tracking only)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam3-visual-f16901 MB6.622.632.7111.2
sam3-visual-q8_0493 MB6.722.033.0108.4
sam3-visual-q4_1318 MB-23.1-113.9
sam3-visual-q4_0275 MB6.722.333.0110.0

EdgeTAM (RepViT backbone + Perceiver)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
edgetam_f1627 MB0.41.12.25.2
edgetam_q8_019 MB0.41.12.15.1
edgetam_q4_015 MB0.41.12.15.1

SAM 2 / SAM 2.1 (Hiera backbone)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam2_hiera_tiny_f1675 MB0.92.74.012.6
sam2_hiera_tiny_q8_040 MB0.92.54.011.7
sam2_hiera_tiny_q4_022 MB0.92.54.011.7
sam2_hiera_small_f1689 MB0.92.94.113.7
sam2_hiera_small_q8_047 MB0.92.74.112.5
sam2_hiera_small_q4_026 MB0.92.74.112.7
sam2_hiera_base_plus_f16155 MB1.04.24.720.2
sam2_hiera_base_plus_q8_083 MB-3.9-18.9
sam2_hiera_large_f16429 MB-8.4-40.9
sam2_hiera_large_q8_0230 MB-7.6-37.1
sam2.1_hiera_tiny_f1675 MB0.82.64.012.3
sam2.1_hiera_tiny_q8_040 MB0.92.44.011.4
sam2.1_hiera_tiny_q4_022 MB0.92.54.011.5
sam2.1_hiera_small_f1689 MB0.92.94.113.5
sam2.1_hiera_small_q8_047 MB0.92.74.112.5
sam2.1_hiera_small_q4_026 MB0.92.74.112.6
sam2.1_hiera_base_plus_f16155 MB1.04.24.720.1
sam2.1_hiera_base_plus_q8_083 MB-3.9-18.6
sam2.1_hiera_large_f16430 MB-8.5-41.4
sam2.1_hiera_large_q8_0230 MB-7.7-37.7
Reproduce these benchmarks
# Full benchmark (all models, both backends)
./build/examples/sam3_benchmark
# GPU only, all models
./build/examples/sam3_benchmark --gpu-only
# Quick iteration (tiny models, 3 frames)
./build/examples/sam3_benchmark --filter tiny --n-frames 3 --gpu-only
# CPU only, specific model
./build/examples/sam3_benchmark --cpu-only --filter sam2.1_hiera_small

Options: --models-dir <path>, --video <path>, --n-frames <n>, --n-threads <n>, --filter <substr>, --cpu-only, --gpu-only

Model Zoo

All models are available in GGML format on Hugging Face:

PABannier/sam3.cpp: 52 model files covering 4 architectures x multiple sizes x up to 5 precisions.

SAM 3 (850M params, ViT-32 backbone + text encoder + DETR decoder)

VariantPrecisionSizeFeatures
sam3f323.4 GBText detection (PCS) + point/box segmentation (PVS) + video tracking
sam3f161.7 GBSame
sam3q8_01.0 GBSame
sam3q4_1756 MBSame
sam3q4_0707 MBSame
sam3-visualf16946 MBPoint/box segmentation (PVS) + video tracking (no text)
sam3-visualq8_0517 MBSame
sam3-visualq4_1318 MBSame
sam3-visualq4_0289 MBSame

SAM 2 / SAM 2.1 (Hiera backbone, 4 sizes)

FamilySizeParamsf32f16q8_0q4_1q4_0
SAM 2Tiny39M156 MB79 MB43 MB26 MB24 MB
SAM 2Small46M184 MB94 MB50 MB30 MB28 MB
SAM 2Base+81M323 MB163 MB88 MB53 MB48 MB
SAM 2Large224M898 MB451 MB241 MB144 MB130 MB
SAM 2.1Tiny39M156 MB79 MB43 MB26 MB24 MB
SAM 2.1Small46M184 MB94 MB50 MB30 MB28 MB
SAM 2.1Base+81M323 MB163 MB88 MB53 MB48 MB
SAM 2.1Large224M898 MB451 MB241 MB144 MB130 MB

EdgeTAM (RepViT-M1 backbone + Perceiver memory compressor)

VariantPrecisionSizeFeatures
edgetamf1627 MBPoint/box segmentation (PVS) + video tracking
edgetamq8_019 MBSame
edgetamq4_015 MBSame

Feature Matrix

CapabilitySAM 3SAM 3 VisualSAM 2 / 2.1EdgeTAM
Text-prompted detection (PCS)Yes---
Point/box segmentation (PVS)YesYesYesYes
Multi-mask outputYesYesYesYes
Video tracking (memory bank)YesYesYesYes
Interactive refinementYesYesYesYes
Quantization (Q4/Q8)YesYesYesYes
Metal GPUYesYesYesYes

Building from Source

Prerequisites

  • C++14 compiler (Clang, GCC, MSVC)
  • CMake 3.14+
  • (Optional) SDL2 for the interactive image/video examples
  • (Optional) ffmpeg for video frame decoding

Build

git clone --recursive https://github.com/PABannier/sam3.cpp
cd sam3.cpp
mkdir build &&cd build
cmake ..
make -j

Metal is enabled automatically on macOS. To disable it:

cmake .. -DSAM3_METAL=OFF

To build tests:

cmake .. -DSAM3_BUILD_TESTS=ON
make -j

Usage

Image Segmentation (Interactive GUI)

# Point/box segmentation with any model
./sam3_image --model models/sam2.1_hiera_tiny_f16.ggml --image photo.jpg
# Text-prompted detection (SAM 3 only)
./sam3_image --model models/sam3-f16.ggml --image photo.jpg
# → Type "cat" in the text field, click [Segment]

Controls:

  • Left-click: add positive point
  • Right-click: add negative point
  • Drag: draw bounding box
  • Text field + Segment: detect all instances matching the text prompt (SAM 3 only)
  • Export: save masks as PNG

Video Tracking (Interactive GUI)

# Visual tracking (SAM 2/2.1/3/EdgeTAM)
./sam3_video --model models/sam2.1_hiera_small_f16.ggml --video input.mp4
# Text-prompted tracking (SAM 3 only)
./sam3_video --model models/sam3-f16.ggml --video input.mp4

Controls:

  • Click a point or draw a box on a paused frame to add an instance
  • Click on an existing tracked mask to refine it
  • Play/Pause/Step for playback
  • Export per-frame mask PNGs

C++ API

#include"sam3.h"// Load model
sam3_params params;
params.model_path = "models/sam2.1_hiera_tiny_f16.ggml";
params.use_gpu = true;
params.n_threads = 4;
auto model = sam3_load_model(params);
auto state = sam3_create_state(*model, params);
// Encode image (call once, reuse for multiple prompts)auto image = sam3_load_image("photo.jpg");
sam3_encode_image(*state, *model, image);
// Segment with a point click
sam3_pvs_params pvs;
pvs.pos_points.push_back({315.0f, 250.0f});
sam3_result result = sam3_segment_pvs(*state, *model, pvs);
for (auto& det : result.detections) {
sam3_save_mask(det.mask, "mask.png");
}
// Text-prompted detection (SAM 3 full model only)
sam3_pcs_params pcs;
pcs.text_prompt = "yellow school bus";
pcs.score_threshold = 0.5f;
sam3_result result = sam3_segment_pcs(*state, *model, pcs);
// → result.detections contains every matching instance
// Video trackingauto tracker = sam3_create_visual_tracker(*model, {});
// Frame 0: encode + add instance with a clicksam3_encode_image(*state, *model, frame0);
sam3_pvs_params pvs;
pvs.pos_points.push_back({315.0f, 250.0f});
sam3_tracker_add_instance(*tracker, *state, *model, pvs);
// Subsequent frames: propagate masksfor (int f = 1; f < n_frames; f++) {
sam3_result result = sam3_propagate_frame(*tracker, *state, *model, frames[f]);
// result.detections[i].mask - tracked mask for each instance
}

Quantization

Convert F32/F16 weights to smaller quantized formats:

./sam3_quantize models/sam3-f16.ggml models/sam3-q4_0.ggml q4_0
# Supported types: q4_0, q4_1, q8_0

Converting Weights

Convert official PyTorch checkpoints to GGML format:

# SAM 3
uv run python convert_sam3_to_ggml.py \
--model sam3.pt \
--output models/sam3-f16.ggml \
--ftype 1 \
--tokenizer /path/to/tokenizer
# SAM 3 visual-only (no text encoder, smaller file)
uv run python convert_sam3_to_ggml.py \
--model sam3.pt \
--output models/sam3-visual-f16.ggml \
--ftype 1 \
--visual-only
# SAM 2 / SAM 2.1
uv run python convert_sam2_to_ggml.py \
--model sam2.1_hiera_large.pt \
--config sam2.1_hiera_l.yaml \
--output models/sam2.1_hiera_large_f16.ggml \
--ftype 1
# EdgeTAM
uv run python convert_edgetam_to_ggml.py \
--model edgetam.pt \
--output models/edgetam_f16.ggml \
--ftype 1

--ftype 0 = float32, --ftype 1 = float16 (recommended). Then quantize with sam3_quantize.

Acknowledgments

  • Meta AI Research for SAM, SAM 2, SAM 3, and EdgeTAM
  • ggml, the tensor computation library that makes this possible
  • sam.cpp, the original SAM 1 C++ port that inspired this project's architecture

License

MIT

About

Fast state-of-the-art image and video segmentation in portable C/C++

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

sam3.cpp

State-of-the-art image and video segmentation in portable C/C++

SAM3 Image Segmentation DemoSAM3 Video Segmentation Demo


Why sam3.cpp?

Running Meta's Segment Anything models typically requires Python, PyTorch, and a CUDA GPU. sam3.cpp eliminates all of that. It's a single C++ library that runs SAM 2, SAM 2.1, SAM 3, and EdgeTAM inference on CPU and Apple Metal. No Python runtime, no GPU drivers, no heavyweight dependencies. Just compile and segment.

  • 4 model families: SAM 2, SAM 2.1 (Hiera), SAM 3 (ViT + text detection), EdgeTAM (RepViT, 22x faster than SAM 2 on mobile)
  • 4-bit quantization: EdgeTAM in 15 MB, SAM 2.1 Tiny in 22 MB at ~1 fps on Metal, SAM 3 down to 673 MB
  • Apple Metal GPU acceleration for the full backbone and transformer decoder
  • Text-prompted detection (SAM 3 only): type "cat" and get every cat in the image, no clicks needed
  • Point/box segmentation + video tracking with memory bank across all models
  • Single-file library: sam3.cpp + sam3.h, C++14, no exceptions, no inheritance
  • Zero dependencies beyond ggml and stb

Quick Start

# Clone
git clone --recursive https://github.com/PABannier/sam3.cpp
cd sam3.cpp
# Build (Metal GPU enabled automatically on macOS)
mkdir build &&cd build
cmake ..
make -j
# Download a model (SAM 2.1 Tiny, 75 MB)# See "Model Zoo" below for all available models and download links
curl -L -o ../models/sam2.1_hiera_tiny_f16.ggml \
https://huggingface.co/PABannier/sam3.cpp/resolve/main/sam2.1_hiera_tiny_f16.ggml
# Segment an image interactively (requires SDL2)
./examples/sam3_image --model ../models/sam2.1_hiera_tiny_f16.ggml --image ../data/test_image.jpg
# Track objects in a video interactively (requires SDL2)
./examples/sam3_video --model ../models/sam2.1_hiera_tiny_f16.ggml --video ../data/test_video.mp4

The interactive apps use SDL2 + ImGui. If SDL2 isn't found, only the benchmark and quantize tools are built.

Benchmarks

Video object tracking latency on Apple M4 Pro (24 GB), 5 frames at 1008x1008 resolution, 4 threads. Each run is isolated in a forked subprocess.

SAM 3 (Full: text detection + visual tracking)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam3-f323.2 GB-40.5-200.4
sam3-f161.7 GB7.723.838.1117.5
sam3-q8_01.0 GB7.823.338.7115.2
sam3-q4_1756 MB-24.5-120.9
sam3-q4_0673 MB7.823.938.7117.7

SAM 3 Visual-Only (no text encoder, tracking only)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam3-visual-f16901 MB6.622.632.7111.2
sam3-visual-q8_0493 MB6.722.033.0108.4
sam3-visual-q4_1318 MB-23.1-113.9
sam3-visual-q4_0275 MB6.722.333.0110.0

EdgeTAM (RepViT backbone + Perceiver)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
edgetam_f1627 MB0.41.12.25.2
edgetam_q8_019 MB0.41.12.15.1
edgetam_q4_015 MB0.41.12.15.1

SAM 2 / SAM 2.1 (Hiera backbone)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam2_hiera_tiny_f1675 MB0.92.74.012.6
sam2_hiera_tiny_q8_040 MB0.92.54.011.7
sam2_hiera_tiny_q4_022 MB0.92.54.011.7
sam2_hiera_small_f1689 MB0.92.94.113.7
sam2_hiera_small_q8_047 MB0.92.74.112.5
sam2_hiera_small_q4_026 MB0.92.74.112.7
sam2_hiera_base_plus_f16155 MB1.04.24.720.2
sam2_hiera_base_plus_q8_083 MB-3.9-18.9
sam2_hiera_large_f16429 MB-8.4-40.9
sam2_hiera_large_q8_0230 MB-7.6-37.1
sam2.1_hiera_tiny_f1675 MB0.82.64.012.3
sam2.1_hiera_tiny_q8_040 MB0.92.44.011.4
sam2.1_hiera_tiny_q4_022 MB0.92.54.011.5
sam2.1_hiera_small_f1689 MB0.92.94.113.5
sam2.1_hiera_small_q8_047 MB0.92.74.112.5
sam2.1_hiera_small_q4_026 MB0.92.74.112.6
sam2.1_hiera_base_plus_f16155 MB1.04.24.720.1
sam2.1_hiera_base_plus_q8_083 MB-3.9-18.6
sam2.1_hiera_large_f16430 MB-8.5-41.4
sam2.1_hiera_large_q8_0230 MB-7.7-37.7
Reproduce these benchmarks
# Full benchmark (all models, both backends)
./build/examples/sam3_benchmark
# GPU only, all models
./build/examples/sam3_benchmark --gpu-only
# Quick iteration (tiny models, 3 frames)
./build/examples/sam3_benchmark --filter tiny --n-frames 3 --gpu-only
# CPU only, specific model
./build/examples/sam3_benchmark --cpu-only --filter sam2.1_hiera_small

Options: --models-dir <path>, --video <path>, --n-frames <n>, --n-threads <n>, --filter <substr>, --cpu-only, --gpu-only

Model Zoo

All models are available in GGML format on Hugging Face:

PABannier/sam3.cpp: 52 model files covering 4 architectures x multiple sizes x up to 5 precisions.

SAM 3 (850M params, ViT-32 backbone + text encoder + DETR decoder)

VariantPrecisionSizeFeatures
sam3f323.4 GBText detection (PCS) + point/box segmentation (PVS) + video tracking
sam3f161.7 GBSame
sam3q8_01.0 GBSame
sam3q4_1756 MBSame
sam3q4_0707 MBSame
sam3-visualf16946 MBPoint/box segmentation (PVS) + video tracking (no text)
sam3-visualq8_0517 MBSame
sam3-visualq4_1318 MBSame
sam3-visualq4_0289 MBSame

SAM 2 / SAM 2.1 (Hiera backbone, 4 sizes)

FamilySizeParamsf32f16q8_0q4_1q4_0
SAM 2Tiny39M156 MB79 MB43 MB26 MB24 MB
SAM 2Small46M184 MB94 MB50 MB30 MB28 MB
SAM 2Base+81M323 MB163 MB88 MB53 MB48 MB
SAM 2Large224M898 MB451 MB241 MB144 MB130 MB
SAM 2.1Tiny39M156 MB79 MB43 MB26 MB24 MB
SAM 2.1Small46M184 MB94 MB50 MB30 MB28 MB
SAM 2.1Base+81M323 MB163 MB88 MB53 MB48 MB
SAM 2.1Large224M898 MB451 MB241 MB144 MB130 MB

EdgeTAM (RepViT-M1 backbone + Perceiver memory compressor)

VariantPrecisionSizeFeatures
edgetamf1627 MBPoint/box segmentation (PVS) + video tracking
edgetamq8_019 MBSame
edgetamq4_015 MBSame

Feature Matrix

CapabilitySAM 3SAM 3 VisualSAM 2 / 2.1EdgeTAM
Text-prompted detection (PCS)Yes---
Point/box segmentation (PVS)YesYesYesYes
Multi-mask outputYesYesYesYes
Video tracking (memory bank)YesYesYesYes
Interactive refinementYesYesYesYes
Quantization (Q4/Q8)YesYesYesYes
Metal GPUYesYesYesYes

Building from Source

Prerequisites

  • C++14 compiler (Clang, GCC, MSVC)
  • CMake 3.14+
  • (Optional) SDL2 for the interactive image/video examples
  • (Optional) ffmpeg for video frame decoding

Build

git clone --recursive https://github.com/PABannier/sam3.cpp
cd sam3.cpp
mkdir build &&cd build
cmake ..
make -j

Metal is enabled automatically on macOS. To disable it:

cmake .. -DSAM3_METAL=OFF

To build tests:

cmake .. -DSAM3_BUILD_TESTS=ON
make -j

Usage

Image Segmentation (Interactive GUI)

# Point/box segmentation with any model
./sam3_image --model models/sam2.1_hiera_tiny_f16.ggml --image photo.jpg
# Text-prompted detection (SAM 3 only)
./sam3_image --model models/sam3-f16.ggml --image photo.jpg
# → Type "cat" in the text field, click [Segment]

Controls:

  • Left-click: add positive point
  • Right-click: add negative point
  • Drag: draw bounding box
  • Text field + Segment: detect all instances matching the text prompt (SAM 3 only)
  • Export: save masks as PNG

Video Tracking (Interactive GUI)

# Visual tracking (SAM 2/2.1/3/EdgeTAM)
./sam3_video --model models/sam2.1_hiera_small_f16.ggml --video input.mp4
# Text-prompted tracking (SAM 3 only)
./sam3_video --model models/sam3-f16.ggml --video input.mp4

Controls:

  • Click a point or draw a box on a paused frame to add an instance
  • Click on an existing tracked mask to refine it
  • Play/Pause/Step for playback
  • Export per-frame mask PNGs

C++ API

#include"sam3.h"// Load model
sam3_params params;
params.model_path = "models/sam2.1_hiera_tiny_f16.ggml";
params.use_gpu = true;
params.n_threads = 4;
auto model = sam3_load_model(params);
auto state = sam3_create_state(*model, params);
// Encode image (call once, reuse for multiple prompts)auto image = sam3_load_image("photo.jpg");
sam3_encode_image(*state, *model, image);
// Segment with a point click
sam3_pvs_params pvs;
pvs.pos_points.push_back({315.0f, 250.0f});
sam3_result result = sam3_segment_pvs(*state, *model, pvs);
for (auto& det : result.detections) {
sam3_save_mask(det.mask, "mask.png");
}
// Text-prompted detection (SAM 3 full model only)
sam3_pcs_params pcs;
pcs.text_prompt = "yellow school bus";
pcs.score_threshold = 0.5f;
sam3_result result = sam3_segment_pcs(*state, *model, pcs);
// → result.detections contains every matching instance
// Video trackingauto tracker = sam3_create_visual_tracker(*model, {});
// Frame 0: encode + add instance with a clicksam3_encode_image(*state, *model, frame0);
sam3_pvs_params pvs;
pvs.pos_points.push_back({315.0f, 250.0f});
sam3_tracker_add_instance(*tracker, *state, *model, pvs);
// Subsequent frames: propagate masksfor (int f = 1; f < n_frames; f++) {
sam3_result result = sam3_propagate_frame(*tracker, *state, *model, frames[f]);
// result.detections[i].mask - tracked mask for each instance
}

Quantization

Convert F32/F16 weights to smaller quantized formats:

./sam3_quantize models/sam3-f16.ggml models/sam3-q4_0.ggml q4_0
# Supported types: q4_0, q4_1, q8_0

Converting Weights

Convert official PyTorch checkpoints to GGML format:

# SAM 3
uv run python convert_sam3_to_ggml.py \
--model sam3.pt \
--output models/sam3-f16.ggml \
--ftype 1 \
--tokenizer /path/to/tokenizer
# SAM 3 visual-only (no text encoder, smaller file)
uv run python convert_sam3_to_ggml.py \
--model sam3.pt \
--output models/sam3-visual-f16.ggml \
--ftype 1 \
--visual-only
# SAM 2 / SAM 2.1
uv run python convert_sam2_to_ggml.py \
--model sam2.1_hiera_large.pt \
--config sam2.1_hiera_l.yaml \
--output models/sam2.1_hiera_large_f16.ggml \
--ftype 1
# EdgeTAM
uv run python convert_edgetam_to_ggml.py \
--model edgetam.pt \
--output models/edgetam_f16.ggml \
--ftype 1

--ftype 0 = float32, --ftype 1 = float16 (recommended). Then quantize with sam3_quantize.

Acknowledgments

  • Meta AI Research for SAM, SAM 2, SAM 3, and EdgeTAM
  • ggml, the tensor computation library that makes this possible
  • sam.cpp, the original SAM 1 C++ port that inspired this project's architecture

License

MIT

About

Fast state-of-the-art image and video segmentation in portable C/C++

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

sam3.cpp

State-of-the-art image and video segmentation in portable C/C++

SAM3 Image Segmentation DemoSAM3 Video Segmentation Demo


Why sam3.cpp?

Running Meta's Segment Anything models typically requires Python, PyTorch, and a CUDA GPU. sam3.cpp eliminates all of that. It's a single C++ library that runs SAM 2, SAM 2.1, SAM 3, and EdgeTAM inference on CPU and Apple Metal. No Python runtime, no GPU drivers, no heavyweight dependencies. Just compile and segment.

  • 4 model families: SAM 2, SAM 2.1 (Hiera), SAM 3 (ViT + text detection), EdgeTAM (RepViT, 22x faster than SAM 2 on mobile)
  • 4-bit quantization: EdgeTAM in 15 MB, SAM 2.1 Tiny in 22 MB at ~1 fps on Metal, SAM 3 down to 673 MB
  • Apple Metal GPU acceleration for the full backbone and transformer decoder
  • Text-prompted detection (SAM 3 only): type "cat" and get every cat in the image, no clicks needed
  • Point/box segmentation + video tracking with memory bank across all models
  • Single-file library: sam3.cpp + sam3.h, C++14, no exceptions, no inheritance
  • Zero dependencies beyond ggml and stb

Quick Start

# Clone
git clone --recursive https://github.com/PABannier/sam3.cpp
cd sam3.cpp
# Build (Metal GPU enabled automatically on macOS)
mkdir build &&cd build
cmake ..
make -j
# Download a model (SAM 2.1 Tiny, 75 MB)# See "Model Zoo" below for all available models and download links
curl -L -o ../models/sam2.1_hiera_tiny_f16.ggml \
https://huggingface.co/PABannier/sam3.cpp/resolve/main/sam2.1_hiera_tiny_f16.ggml
# Segment an image interactively (requires SDL2)
./examples/sam3_image --model ../models/sam2.1_hiera_tiny_f16.ggml --image ../data/test_image.jpg
# Track objects in a video interactively (requires SDL2)
./examples/sam3_video --model ../models/sam2.1_hiera_tiny_f16.ggml --video ../data/test_video.mp4

The interactive apps use SDL2 + ImGui. If SDL2 isn't found, only the benchmark and quantize tools are built.

Benchmarks

Video object tracking latency on Apple M4 Pro (24 GB), 5 frames at 1008x1008 resolution, 4 threads. Each run is isolated in a forked subprocess.

SAM 3 (Full: text detection + visual tracking)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam3-f323.2 GB-40.5-200.4
sam3-f161.7 GB7.723.838.1117.5
sam3-q8_01.0 GB7.823.338.7115.2
sam3-q4_1756 MB-24.5-120.9
sam3-q4_0673 MB7.823.938.7117.7

SAM 3 Visual-Only (no text encoder, tracking only)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam3-visual-f16901 MB6.622.632.7111.2
sam3-visual-q8_0493 MB6.722.033.0108.4
sam3-visual-q4_1318 MB-23.1-113.9
sam3-visual-q4_0275 MB6.722.333.0110.0

EdgeTAM (RepViT backbone + Perceiver)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
edgetam_f1627 MB0.41.12.25.2
edgetam_q8_019 MB0.41.12.15.1
edgetam_q4_015 MB0.41.12.15.1

SAM 2 / SAM 2.1 (Hiera backbone)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam2_hiera_tiny_f1675 MB0.92.74.012.6
sam2_hiera_tiny_q8_040 MB0.92.54.011.7
sam2_hiera_tiny_q4_022 MB0.92.54.011.7
sam2_hiera_small_f1689 MB0.92.94.113.7
sam2_hiera_small_q8_047 MB0.92.74.112.5
sam2_hiera_small_q4_026 MB0.92.74.112.7
sam2_hiera_base_plus_f16155 MB1.04.24.720.2
sam2_hiera_base_plus_q8_083 MB-3.9-18.9
sam2_hiera_large_f16429 MB-8.4-40.9
sam2_hiera_large_q8_0230 MB-7.6-37.1
sam2.1_hiera_tiny_f1675 MB0.82.64.012.3
sam2.1_hiera_tiny_q8_040 MB0.92.44.011.4
sam2.1_hiera_tiny_q4_022 MB0.92.54.011.5
sam2.1_hiera_small_f1689 MB0.92.94.113.5
sam2.1_hiera_small_q8_047 MB0.92.74.112.5
sam2.1_hiera_small_q4_026 MB0.92.74.112.6
sam2.1_hiera_base_plus_f16155 MB1.04.24.720.1
sam2.1_hiera_base_plus_q8_083 MB-3.9-18.6
sam2.1_hiera_large_f16430 MB-8.5-41.4
sam2.1_hiera_large_q8_0230 MB-7.7-37.7
Reproduce these benchmarks
# Full benchmark (all models, both backends)
./build/examples/sam3_benchmark
# GPU only, all models
./build/examples/sam3_benchmark --gpu-only
# Quick iteration (tiny models, 3 frames)
./build/examples/sam3_benchmark --filter tiny --n-frames 3 --gpu-only
# CPU only, specific model
./build/examples/sam3_benchmark --cpu-only --filter sam2.1_hiera_small

Options: --models-dir <path>, --video <path>, --n-frames <n>, --n-threads <n>, --filter <substr>, --cpu-only, --gpu-only

Model Zoo

All models are available in GGML format on Hugging Face:

PABannier/sam3.cpp: 52 model files covering 4 architectures x multiple sizes x up to 5 precisions.

SAM 3 (850M params, ViT-32 backbone + text encoder + DETR decoder)

VariantPrecisionSizeFeatures
sam3f323.4 GBText detection (PCS) + point/box segmentation (PVS) + video tracking
sam3f161.7 GBSame
sam3q8_01.0 GBSame
sam3q4_1756 MBSame
sam3q4_0707 MBSame
sam3-visualf16946 MBPoint/box segmentation (PVS) + video tracking (no text)
sam3-visualq8_0517 MBSame
sam3-visualq4_1318 MBSame
sam3-visualq4_0289 MBSame

SAM 2 / SAM 2.1 (Hiera backbone, 4 sizes)

FamilySizeParamsf32f16q8_0q4_1q4_0
SAM 2Tiny39M156 MB79 MB43 MB26 MB24 MB
SAM 2Small46M184 MB94 MB50 MB30 MB28 MB
SAM 2Base+81M323 MB163 MB88 MB53 MB48 MB
SAM 2Large224M898 MB451 MB241 MB144 MB130 MB
SAM 2.1Tiny39M156 MB79 MB43 MB26 MB24 MB
SAM 2.1Small46M184 MB94 MB50 MB30 MB28 MB
SAM 2.1Base+81M323 MB163 MB88 MB53 MB48 MB
SAM 2.1Large224M898 MB451 MB241 MB144 MB130 MB

EdgeTAM (RepViT-M1 backbone + Perceiver memory compressor)

VariantPrecisionSizeFeatures
edgetamf1627 MBPoint/box segmentation (PVS) + video tracking
edgetamq8_019 MBSame
edgetamq4_015 MBSame

Feature Matrix

CapabilitySAM 3SAM 3 VisualSAM 2 / 2.1EdgeTAM
Text-prompted detection (PCS)Yes---
Point/box segmentation (PVS)YesYesYesYes
Multi-mask outputYesYesYesYes
Video tracking (memory bank)YesYesYesYes
Interactive refinementYesYesYesYes
Quantization (Q4/Q8)YesYesYesYes
Metal GPUYesYesYesYes

Building from Source

Prerequisites

  • C++14 compiler (Clang, GCC, MSVC)
  • CMake 3.14+
  • (Optional) SDL2 for the interactive image/video examples
  • (Optional) ffmpeg for video frame decoding

Build

git clone --recursive https://github.com/PABannier/sam3.cpp
cd sam3.cpp
mkdir build &&cd build
cmake ..
make -j

Metal is enabled automatically on macOS. To disable it:

cmake .. -DSAM3_METAL=OFF

To build tests:

cmake .. -DSAM3_BUILD_TESTS=ON
make -j

Usage

Image Segmentation (Interactive GUI)

# Point/box segmentation with any model
./sam3_image --model models/sam2.1_hiera_tiny_f16.ggml --image photo.jpg
# Text-prompted detection (SAM 3 only)
./sam3_image --model models/sam3-f16.ggml --image photo.jpg
# → Type "cat" in the text field, click [Segment]

Controls:

  • Left-click: add positive point
  • Right-click: add negative point
  • Drag: draw bounding box
  • Text field + Segment: detect all instances matching the text prompt (SAM 3 only)
  • Export: save masks as PNG

Video Tracking (Interactive GUI)

# Visual tracking (SAM 2/2.1/3/EdgeTAM)
./sam3_video --model models/sam2.1_hiera_small_f16.ggml --video input.mp4
# Text-prompted tracking (SAM 3 only)
./sam3_video --model models/sam3-f16.ggml --video input.mp4

Controls:

  • Click a point or draw a box on a paused frame to add an instance
  • Click on an existing tracked mask to refine it
  • Play/Pause/Step for playback
  • Export per-frame mask PNGs

C++ API

#include"sam3.h"// Load model
sam3_params params;
params.model_path = "models/sam2.1_hiera_tiny_f16.ggml";
params.use_gpu = true;
params.n_threads = 4;
auto model = sam3_load_model(params);
auto state = sam3_create_state(*model, params);
// Encode image (call once, reuse for multiple prompts)auto image = sam3_load_image("photo.jpg");
sam3_encode_image(*state, *model, image);
// Segment with a point click
sam3_pvs_params pvs;
pvs.pos_points.push_back({315.0f, 250.0f});
sam3_result result = sam3_segment_pvs(*state, *model, pvs);
for (auto& det : result.detections) {
sam3_save_mask(det.mask, "mask.png");
}
// Text-prompted detection (SAM 3 full model only)
sam3_pcs_params pcs;
pcs.text_prompt = "yellow school bus";
pcs.score_threshold = 0.5f;
sam3_result result = sam3_segment_pcs(*state, *model, pcs);
// → result.detections contains every matching instance
// Video trackingauto tracker = sam3_create_visual_tracker(*model, {});
// Frame 0: encode + add instance with a clicksam3_encode_image(*state, *model, frame0);
sam3_pvs_params pvs;
pvs.pos_points.push_back({315.0f, 250.0f});
sam3_tracker_add_instance(*tracker, *state, *model, pvs);
// Subsequent frames: propagate masksfor (int f = 1; f < n_frames; f++) {
sam3_result result = sam3_propagate_frame(*tracker, *state, *model, frames[f]);
// result.detections[i].mask - tracked mask for each instance
}

Quantization

Convert F32/F16 weights to smaller quantized formats:

./sam3_quantize models/sam3-f16.ggml models/sam3-q4_0.ggml q4_0
# Supported types: q4_0, q4_1, q8_0

Converting Weights

Convert official PyTorch checkpoints to GGML format:

# SAM 3
uv run python convert_sam3_to_ggml.py \
--model sam3.pt \
--output models/sam3-f16.ggml \
--ftype 1 \
--tokenizer /path/to/tokenizer
# SAM 3 visual-only (no text encoder, smaller file)
uv run python convert_sam3_to_ggml.py \
--model sam3.pt \
--output models/sam3-visual-f16.ggml \
--ftype 1 \
--visual-only
# SAM 2 / SAM 2.1
uv run python convert_sam2_to_ggml.py \
--model sam2.1_hiera_large.pt \
--config sam2.1_hiera_l.yaml \
--output models/sam2.1_hiera_large_f16.ggml \
--ftype 1
# EdgeTAM
uv run python convert_edgetam_to_ggml.py \
--model edgetam.pt \
--output models/edgetam_f16.ggml \
--ftype 1

--ftype 0 = float32, --ftype 1 = float16 (recommended). Then quantize with sam3_quantize.

Acknowledgments

  • Meta AI Research for SAM, SAM 2, SAM 3, and EdgeTAM
  • ggml, the tensor computation library that makes this possible
  • sam.cpp, the original SAM 1 C++ port that inspired this project's architecture

License

MIT

About

Fast state-of-the-art image and video segmentation in portable C/C++

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

sam3.cpp

State-of-the-art image and video segmentation in portable C/C++

SAM3 Image Segmentation DemoSAM3 Video Segmentation Demo


Why sam3.cpp?

Running Meta's Segment Anything models typically requires Python, PyTorch, and a CUDA GPU. sam3.cpp eliminates all of that. It's a single C++ library that runs SAM 2, SAM 2.1, SAM 3, and EdgeTAM inference on CPU and Apple Metal. No Python runtime, no GPU drivers, no heavyweight dependencies. Just compile and segment.

  • 4 model families: SAM 2, SAM 2.1 (Hiera), SAM 3 (ViT + text detection), EdgeTAM (RepViT, 22x faster than SAM 2 on mobile)
  • 4-bit quantization: EdgeTAM in 15 MB, SAM 2.1 Tiny in 22 MB at ~1 fps on Metal, SAM 3 down to 673 MB
  • Apple Metal GPU acceleration for the full backbone and transformer decoder
  • Text-prompted detection (SAM 3 only): type "cat" and get every cat in the image, no clicks needed
  • Point/box segmentation + video tracking with memory bank across all models
  • Single-file library: sam3.cpp + sam3.h, C++14, no exceptions, no inheritance
  • Zero dependencies beyond ggml and stb

Quick Start

# Clone
git clone --recursive https://github.com/PABannier/sam3.cpp
cd sam3.cpp
# Build (Metal GPU enabled automatically on macOS)
mkdir build &&cd build
cmake ..
make -j
# Download a model (SAM 2.1 Tiny, 75 MB)# See "Model Zoo" below for all available models and download links
curl -L -o ../models/sam2.1_hiera_tiny_f16.ggml \
https://huggingface.co/PABannier/sam3.cpp/resolve/main/sam2.1_hiera_tiny_f16.ggml
# Segment an image interactively (requires SDL2)
./examples/sam3_image --model ../models/sam2.1_hiera_tiny_f16.ggml --image ../data/test_image.jpg
# Track objects in a video interactively (requires SDL2)
./examples/sam3_video --model ../models/sam2.1_hiera_tiny_f16.ggml --video ../data/test_video.mp4

The interactive apps use SDL2 + ImGui. If SDL2 isn't found, only the benchmark and quantize tools are built.

Benchmarks

Video object tracking latency on Apple M4 Pro (24 GB), 5 frames at 1008x1008 resolution, 4 threads. Each run is isolated in a forked subprocess.

SAM 3 (Full: text detection + visual tracking)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam3-f323.2 GB-40.5-200.4
sam3-f161.7 GB7.723.838.1117.5
sam3-q8_01.0 GB7.823.338.7115.2
sam3-q4_1756 MB-24.5-120.9
sam3-q4_0673 MB7.823.938.7117.7

SAM 3 Visual-Only (no text encoder, tracking only)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam3-visual-f16901 MB6.622.632.7111.2
sam3-visual-q8_0493 MB6.722.033.0108.4
sam3-visual-q4_1318 MB-23.1-113.9
sam3-visual-q4_0275 MB6.722.333.0110.0

EdgeTAM (RepViT backbone + Perceiver)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
edgetam_f1627 MB0.41.12.25.2
edgetam_q8_019 MB0.41.12.15.1
edgetam_q4_015 MB0.41.12.15.1

SAM 2 / SAM 2.1 (Hiera backbone)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam2_hiera_tiny_f1675 MB0.92.74.012.6
sam2_hiera_tiny_q8_040 MB0.92.54.011.7
sam2_hiera_tiny_q4_022 MB0.92.54.011.7
sam2_hiera_small_f1689 MB0.92.94.113.7
sam2_hiera_small_q8_047 MB0.92.74.112.5
sam2_hiera_small_q4_026 MB0.92.74.112.7
sam2_hiera_base_plus_f16155 MB1.04.24.720.2
sam2_hiera_base_plus_q8_083 MB-3.9-18.9
sam2_hiera_large_f16429 MB-8.4-40.9
sam2_hiera_large_q8_0230 MB-7.6-37.1
sam2.1_hiera_tiny_f1675 MB0.82.64.012.3
sam2.1_hiera_tiny_q8_040 MB0.92.44.011.4
sam2.1_hiera_tiny_q4_022 MB0.92.54.011.5
sam2.1_hiera_small_f1689 MB0.92.94.113.5
sam2.1_hiera_small_q8_047 MB0.92.74.112.5
sam2.1_hiera_small_q4_026 MB0.92.74.112.6
sam2.1_hiera_base_plus_f16155 MB1.04.24.720.1
sam2.1_hiera_base_plus_q8_083 MB-3.9-18.6
sam2.1_hiera_large_f16430 MB-8.5-41.4
sam2.1_hiera_large_q8_0230 MB-7.7-37.7
Reproduce these benchmarks
# Full benchmark (all models, both backends)
./build/examples/sam3_benchmark
# GPU only, all models
./build/examples/sam3_benchmark --gpu-only
# Quick iteration (tiny models, 3 frames)
./build/examples/sam3_benchmark --filter tiny --n-frames 3 --gpu-only
# CPU only, specific model
./build/examples/sam3_benchmark --cpu-only --filter sam2.1_hiera_small

Options: --models-dir <path>, --video <path>, --n-frames <n>, --n-threads <n>, --filter <substr>, --cpu-only, --gpu-only

Model Zoo

All models are available in GGML format on Hugging Face:

PABannier/sam3.cpp: 52 model files covering 4 architectures x multiple sizes x up to 5 precisions.

SAM 3 (850M params, ViT-32 backbone + text encoder + DETR decoder)

VariantPrecisionSizeFeatures
sam3f323.4 GBText detection (PCS) + point/box segmentation (PVS) + video tracking
sam3f161.7 GBSame
sam3q8_01.0 GBSame
sam3q4_1756 MBSame
sam3q4_0707 MBSame
sam3-visualf16946 MBPoint/box segmentation (PVS) + video tracking (no text)
sam3-visualq8_0517 MBSame
sam3-visualq4_1318 MBSame
sam3-visualq4_0289 MBSame

SAM 2 / SAM 2.1 (Hiera backbone, 4 sizes)

FamilySizeParamsf32f16q8_0q4_1q4_0
SAM 2Tiny39M156 MB79 MB43 MB26 MB24 MB
SAM 2Small46M184 MB94 MB50 MB30 MB28 MB
SAM 2Base+81M323 MB163 MB88 MB53 MB48 MB
SAM 2Large224M898 MB451 MB241 MB144 MB130 MB
SAM 2.1Tiny39M156 MB79 MB43 MB26 MB24 MB
SAM 2.1Small46M184 MB94 MB50 MB30 MB28 MB
SAM 2.1Base+81M323 MB163 MB88 MB53 MB48 MB
SAM 2.1Large224M898 MB451 MB241 MB144 MB130 MB

EdgeTAM (RepViT-M1 backbone + Perceiver memory compressor)

VariantPrecisionSizeFeatures
edgetamf1627 MBPoint/box segmentation (PVS) + video tracking
edgetamq8_019 MBSame
edgetamq4_015 MBSame

Feature Matrix

CapabilitySAM 3SAM 3 VisualSAM 2 / 2.1EdgeTAM
Text-prompted detection (PCS)Yes---
Point/box segmentation (PVS)YesYesYesYes
Multi-mask outputYesYesYesYes
Video tracking (memory bank)YesYesYesYes
Interactive refinementYesYesYesYes
Quantization (Q4/Q8)YesYesYesYes
Metal GPUYesYesYesYes

Building from Source

Prerequisites

  • C++14 compiler (Clang, GCC, MSVC)
  • CMake 3.14+
  • (Optional) SDL2 for the interactive image/video examples
  • (Optional) ffmpeg for video frame decoding

Build

git clone --recursive https://github.com/PABannier/sam3.cpp
cd sam3.cpp
mkdir build &&cd build
cmake ..
make -j

Metal is enabled automatically on macOS. To disable it:

cmake .. -DSAM3_METAL=OFF

To build tests:

cmake .. -DSAM3_BUILD_TESTS=ON
make -j

Usage

Image Segmentation (Interactive GUI)

# Point/box segmentation with any model
./sam3_image --model models/sam2.1_hiera_tiny_f16.ggml --image photo.jpg
# Text-prompted detection (SAM 3 only)
./sam3_image --model models/sam3-f16.ggml --image photo.jpg
# → Type "cat" in the text field, click [Segment]

Controls:

  • Left-click: add positive point
  • Right-click: add negative point
  • Drag: draw bounding box
  • Text field + Segment: detect all instances matching the text prompt (SAM 3 only)
  • Export: save masks as PNG

Video Tracking (Interactive GUI)

# Visual tracking (SAM 2/2.1/3/EdgeTAM)
./sam3_video --model models/sam2.1_hiera_small_f16.ggml --video input.mp4
# Text-prompted tracking (SAM 3 only)
./sam3_video --model models/sam3-f16.ggml --video input.mp4

Controls:

  • Click a point or draw a box on a paused frame to add an instance
  • Click on an existing tracked mask to refine it
  • Play/Pause/Step for playback
  • Export per-frame mask PNGs

C++ API

#include"sam3.h"// Load model
sam3_params params;
params.model_path = "models/sam2.1_hiera_tiny_f16.ggml";
params.use_gpu = true;
params.n_threads = 4;
auto model = sam3_load_model(params);
auto state = sam3_create_state(*model, params);
// Encode image (call once, reuse for multiple prompts)auto image = sam3_load_image("photo.jpg");
sam3_encode_image(*state, *model, image);
// Segment with a point click
sam3_pvs_params pvs;
pvs.pos_points.push_back({315.0f, 250.0f});
sam3_result result = sam3_segment_pvs(*state, *model, pvs);
for (auto& det : result.detections) {
sam3_save_mask(det.mask, "mask.png");
}
// Text-prompted detection (SAM 3 full model only)
sam3_pcs_params pcs;
pcs.text_prompt = "yellow school bus";
pcs.score_threshold = 0.5f;
sam3_result result = sam3_segment_pcs(*state, *model, pcs);
// → result.detections contains every matching instance
// Video trackingauto tracker = sam3_create_visual_tracker(*model, {});
// Frame 0: encode + add instance with a clicksam3_encode_image(*state, *model, frame0);
sam3_pvs_params pvs;
pvs.pos_points.push_back({315.0f, 250.0f});
sam3_tracker_add_instance(*tracker, *state, *model, pvs);
// Subsequent frames: propagate masksfor (int f = 1; f < n_frames; f++) {
sam3_result result = sam3_propagate_frame(*tracker, *state, *model, frames[f]);
// result.detections[i].mask - tracked mask for each instance
}

Quantization

Convert F32/F16 weights to smaller quantized formats:

./sam3_quantize models/sam3-f16.ggml models/sam3-q4_0.ggml q4_0
# Supported types: q4_0, q4_1, q8_0

Converting Weights

Convert official PyTorch checkpoints to GGML format:

# SAM 3
uv run python convert_sam3_to_ggml.py \
--model sam3.pt \
--output models/sam3-f16.ggml \
--ftype 1 \
--tokenizer /path/to/tokenizer
# SAM 3 visual-only (no text encoder, smaller file)
uv run python convert_sam3_to_ggml.py \
--model sam3.pt \
--output models/sam3-visual-f16.ggml \
--ftype 1 \
--visual-only
# SAM 2 / SAM 2.1
uv run python convert_sam2_to_ggml.py \
--model sam2.1_hiera_large.pt \
--config sam2.1_hiera_l.yaml \
--output models/sam2.1_hiera_large_f16.ggml \
--ftype 1
# EdgeTAM
uv run python convert_edgetam_to_ggml.py \
--model edgetam.pt \
--output models/edgetam_f16.ggml \
--ftype 1

--ftype 0 = float32, --ftype 1 = float16 (recommended). Then quantize with sam3_quantize.

Acknowledgments

  • Meta AI Research for SAM, SAM 2, SAM 3, and EdgeTAM
  • ggml, the tensor computation library that makes this possible
  • sam.cpp, the original SAM 1 C++ port that inspired this project's architecture

License

MIT

About

Fast state-of-the-art image and video segmentation in portable C/C++

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

sam3.cpp

State-of-the-art image and video segmentation in portable C/C++

SAM3 Image Segmentation DemoSAM3 Video Segmentation Demo


Why sam3.cpp?

Running Meta's Segment Anything models typically requires Python, PyTorch, and a CUDA GPU. sam3.cpp eliminates all of that. It's a single C++ library that runs SAM 2, SAM 2.1, SAM 3, and EdgeTAM inference on CPU and Apple Metal. No Python runtime, no GPU drivers, no heavyweight dependencies. Just compile and segment.

  • 4 model families: SAM 2, SAM 2.1 (Hiera), SAM 3 (ViT + text detection), EdgeTAM (RepViT, 22x faster than SAM 2 on mobile)
  • 4-bit quantization: EdgeTAM in 15 MB, SAM 2.1 Tiny in 22 MB at ~1 fps on Metal, SAM 3 down to 673 MB
  • Apple Metal GPU acceleration for the full backbone and transformer decoder
  • Text-prompted detection (SAM 3 only): type "cat" and get every cat in the image, no clicks needed
  • Point/box segmentation + video tracking with memory bank across all models
  • Single-file library: sam3.cpp + sam3.h, C++14, no exceptions, no inheritance
  • Zero dependencies beyond ggml and stb

Quick Start

# Clone
git clone --recursive https://github.com/PABannier/sam3.cpp
cd sam3.cpp
# Build (Metal GPU enabled automatically on macOS)
mkdir build &&cd build
cmake ..
make -j
# Download a model (SAM 2.1 Tiny, 75 MB)# See "Model Zoo" below for all available models and download links
curl -L -o ../models/sam2.1_hiera_tiny_f16.ggml \
https://huggingface.co/PABannier/sam3.cpp/resolve/main/sam2.1_hiera_tiny_f16.ggml
# Segment an image interactively (requires SDL2)
./examples/sam3_image --model ../models/sam2.1_hiera_tiny_f16.ggml --image ../data/test_image.jpg
# Track objects in a video interactively (requires SDL2)
./examples/sam3_video --model ../models/sam2.1_hiera_tiny_f16.ggml --video ../data/test_video.mp4

The interactive apps use SDL2 + ImGui. If SDL2 isn't found, only the benchmark and quantize tools are built.

Benchmarks

Video object tracking latency on Apple M4 Pro (24 GB), 5 frames at 1008x1008 resolution, 4 threads. Each run is isolated in a forked subprocess.

SAM 3 (Full: text detection + visual tracking)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam3-f323.2 GB-40.5-200.4
sam3-f161.7 GB7.723.838.1117.5
sam3-q8_01.0 GB7.823.338.7115.2
sam3-q4_1756 MB-24.5-120.9
sam3-q4_0673 MB7.823.938.7117.7

SAM 3 Visual-Only (no text encoder, tracking only)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam3-visual-f16901 MB6.622.632.7111.2
sam3-visual-q8_0493 MB6.722.033.0108.4
sam3-visual-q4_1318 MB-23.1-113.9
sam3-visual-q4_0275 MB6.722.333.0110.0

EdgeTAM (RepViT backbone + Perceiver)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
edgetam_f1627 MB0.41.12.25.2
edgetam_q8_019 MB0.41.12.15.1
edgetam_q4_015 MB0.41.12.15.1

SAM 2 / SAM 2.1 (Hiera backbone)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam2_hiera_tiny_f1675 MB0.92.74.012.6
sam2_hiera_tiny_q8_040 MB0.92.54.011.7
sam2_hiera_tiny_q4_022 MB0.92.54.011.7
sam2_hiera_small_f1689 MB0.92.94.113.7
sam2_hiera_small_q8_047 MB0.92.74.112.5
sam2_hiera_small_q4_026 MB0.92.74.112.7
sam2_hiera_base_plus_f16155 MB1.04.24.720.2
sam2_hiera_base_plus_q8_083 MB-3.9-18.9
sam2_hiera_large_f16429 MB-8.4-40.9
sam2_hiera_large_q8_0230 MB-7.6-37.1
sam2.1_hiera_tiny_f1675 MB0.82.64.012.3
sam2.1_hiera_tiny_q8_040 MB0.92.44.011.4
sam2.1_hiera_tiny_q4_022 MB0.92.54.011.5
sam2.1_hiera_small_f1689 MB0.92.94.113.5
sam2.1_hiera_small_q8_047 MB0.92.74.112.5
sam2.1_hiera_small_q4_026 MB0.92.74.112.6
sam2.1_hiera_base_plus_f16155 MB1.04.24.720.1
sam2.1_hiera_base_plus_q8_083 MB-3.9-18.6
sam2.1_hiera_large_f16430 MB-8.5-41.4
sam2.1_hiera_large_q8_0230 MB-7.7-37.7
Reproduce these benchmarks
# Full benchmark (all models, both backends)
./build/examples/sam3_benchmark
# GPU only, all models
./build/examples/sam3_benchmark --gpu-only
# Quick iteration (tiny models, 3 frames)
./build/examples/sam3_benchmark --filter tiny --n-frames 3 --gpu-only
# CPU only, specific model
./build/examples/sam3_benchmark --cpu-only --filter sam2.1_hiera_small

Options: --models-dir <path>, --video <path>, --n-frames <n>, --n-threads <n>, --filter <substr>, --cpu-only, --gpu-only

Model Zoo

All models are available in GGML format on Hugging Face:

PABannier/sam3.cpp: 52 model files covering 4 architectures x multiple sizes x up to 5 precisions.

SAM 3 (850M params, ViT-32 backbone + text encoder + DETR decoder)

VariantPrecisionSizeFeatures
sam3f323.4 GBText detection (PCS) + point/box segmentation (PVS) + video tracking
sam3f161.7 GBSame
sam3q8_01.0 GBSame
sam3q4_1756 MBSame
sam3q4_0707 MBSame
sam3-visualf16946 MBPoint/box segmentation (PVS) + video tracking (no text)
sam3-visualq8_0517 MBSame
sam3-visualq4_1318 MBSame
sam3-visualq4_0289 MBSame

SAM 2 / SAM 2.1 (Hiera backbone, 4 sizes)

FamilySizeParamsf32f16q8_0q4_1q4_0
SAM 2Tiny39M156 MB79 MB43 MB26 MB24 MB
SAM 2Small46M184 MB94 MB50 MB30 MB28 MB
SAM 2Base+81M323 MB163 MB88 MB53 MB48 MB
SAM 2Large224M898 MB451 MB241 MB144 MB130 MB
SAM 2.1Tiny39M156 MB79 MB43 MB26 MB24 MB
SAM 2.1Small46M184 MB94 MB50 MB30 MB28 MB
SAM 2.1Base+81M323 MB163 MB88 MB53 MB48 MB
SAM 2.1Large224M898 MB451 MB241 MB144 MB130 MB

EdgeTAM (RepViT-M1 backbone + Perceiver memory compressor)

VariantPrecisionSizeFeatures
edgetamf1627 MBPoint/box segmentation (PVS) + video tracking
edgetamq8_019 MBSame
edgetamq4_015 MBSame

Feature Matrix

CapabilitySAM 3SAM 3 VisualSAM 2 / 2.1EdgeTAM
Text-prompted detection (PCS)Yes---
Point/box segmentation (PVS)YesYesYesYes
Multi-mask outputYesYesYesYes
Video tracking (memory bank)YesYesYesYes
Interactive refinementYesYesYesYes
Quantization (Q4/Q8)YesYesYesYes
Metal GPUYesYesYesYes

Building from Source

Prerequisites

  • C++14 compiler (Clang, GCC, MSVC)
  • CMake 3.14+
  • (Optional) SDL2 for the interactive image/video examples
  • (Optional) ffmpeg for video frame decoding

Build

git clone --recursive https://github.com/PABannier/sam3.cpp
cd sam3.cpp
mkdir build &&cd build
cmake ..
make -j

Metal is enabled automatically on macOS. To disable it:

cmake .. -DSAM3_METAL=OFF

To build tests:

cmake .. -DSAM3_BUILD_TESTS=ON
make -j

Usage

Image Segmentation (Interactive GUI)

# Point/box segmentation with any model
./sam3_image --model models/sam2.1_hiera_tiny_f16.ggml --image photo.jpg
# Text-prompted detection (SAM 3 only)
./sam3_image --model models/sam3-f16.ggml --image photo.jpg
# → Type "cat" in the text field, click [Segment]

Controls:

  • Left-click: add positive point
  • Right-click: add negative point
  • Drag: draw bounding box
  • Text field + Segment: detect all instances matching the text prompt (SAM 3 only)
  • Export: save masks as PNG

Video Tracking (Interactive GUI)

# Visual tracking (SAM 2/2.1/3/EdgeTAM)
./sam3_video --model models/sam2.1_hiera_small_f16.ggml --video input.mp4
# Text-prompted tracking (SAM 3 only)
./sam3_video --model models/sam3-f16.ggml --video input.mp4

Controls:

  • Click a point or draw a box on a paused frame to add an instance
  • Click on an existing tracked mask to refine it
  • Play/Pause/Step for playback
  • Export per-frame mask PNGs

C++ API

#include"sam3.h"// Load model
sam3_params params;
params.model_path = "models/sam2.1_hiera_tiny_f16.ggml";
params.use_gpu = true;
params.n_threads = 4;
auto model = sam3_load_model(params);
auto state = sam3_create_state(*model, params);
// Encode image (call once, reuse for multiple prompts)auto image = sam3_load_image("photo.jpg");
sam3_encode_image(*state, *model, image);
// Segment with a point click
sam3_pvs_params pvs;
pvs.pos_points.push_back({315.0f, 250.0f});
sam3_result result = sam3_segment_pvs(*state, *model, pvs);
for (auto& det : result.detections) {
sam3_save_mask(det.mask, "mask.png");
}
// Text-prompted detection (SAM 3 full model only)
sam3_pcs_params pcs;
pcs.text_prompt = "yellow school bus";
pcs.score_threshold = 0.5f;
sam3_result result = sam3_segment_pcs(*state, *model, pcs);
// → result.detections contains every matching instance
// Video trackingauto tracker = sam3_create_visual_tracker(*model, {});
// Frame 0: encode + add instance with a clicksam3_encode_image(*state, *model, frame0);
sam3_pvs_params pvs;
pvs.pos_points.push_back({315.0f, 250.0f});
sam3_tracker_add_instance(*tracker, *state, *model, pvs);
// Subsequent frames: propagate masksfor (int f = 1; f < n_frames; f++) {
sam3_result result = sam3_propagate_frame(*tracker, *state, *model, frames[f]);
// result.detections[i].mask - tracked mask for each instance
}

Quantization

Convert F32/F16 weights to smaller quantized formats:

./sam3_quantize models/sam3-f16.ggml models/sam3-q4_0.ggml q4_0
# Supported types: q4_0, q4_1, q8_0

Converting Weights

Convert official PyTorch checkpoints to GGML format:

# SAM 3
uv run python convert_sam3_to_ggml.py \
--model sam3.pt \
--output models/sam3-f16.ggml \
--ftype 1 \
--tokenizer /path/to/tokenizer
# SAM 3 visual-only (no text encoder, smaller file)
uv run python convert_sam3_to_ggml.py \
--model sam3.pt \
--output models/sam3-visual-f16.ggml \
--ftype 1 \
--visual-only
# SAM 2 / SAM 2.1
uv run python convert_sam2_to_ggml.py \
--model sam2.1_hiera_large.pt \
--config sam2.1_hiera_l.yaml \
--output models/sam2.1_hiera_large_f16.ggml \
--ftype 1
# EdgeTAM
uv run python convert_edgetam_to_ggml.py \
--model edgetam.pt \
--output models/edgetam_f16.ggml \
--ftype 1

--ftype 0 = float32, --ftype 1 = float16 (recommended). Then quantize with sam3_quantize.

Acknowledgments

  • Meta AI Research for SAM, SAM 2, SAM 3, and EdgeTAM
  • ggml, the tensor computation library that makes this possible
  • sam.cpp, the original SAM 1 C++ port that inspired this project's architecture

License

MIT

About

Fast state-of-the-art image and video segmentation in portable C/C++

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

sam3.cpp

State-of-the-art image and video segmentation in portable C/C++

SAM3 Image Segmentation DemoSAM3 Video Segmentation Demo


Why sam3.cpp?

Running Meta's Segment Anything models typically requires Python, PyTorch, and a CUDA GPU. sam3.cpp eliminates all of that. It's a single C++ library that runs SAM 2, SAM 2.1, SAM 3, and EdgeTAM inference on CPU and Apple Metal. No Python runtime, no GPU drivers, no heavyweight dependencies. Just compile and segment.

  • 4 model families: SAM 2, SAM 2.1 (Hiera), SAM 3 (ViT + text detection), EdgeTAM (RepViT, 22x faster than SAM 2 on mobile)
  • 4-bit quantization: EdgeTAM in 15 MB, SAM 2.1 Tiny in 22 MB at ~1 fps on Metal, SAM 3 down to 673 MB
  • Apple Metal GPU acceleration for the full backbone and transformer decoder
  • Text-prompted detection (SAM 3 only): type "cat" and get every cat in the image, no clicks needed
  • Point/box segmentation + video tracking with memory bank across all models
  • Single-file library: sam3.cpp + sam3.h, C++14, no exceptions, no inheritance
  • Zero dependencies beyond ggml and stb

Quick Start

# Clone
git clone --recursive https://github.com/PABannier/sam3.cpp
cd sam3.cpp
# Build (Metal GPU enabled automatically on macOS)
mkdir build &&cd build
cmake ..
make -j
# Download a model (SAM 2.1 Tiny, 75 MB)# See "Model Zoo" below for all available models and download links
curl -L -o ../models/sam2.1_hiera_tiny_f16.ggml \
https://huggingface.co/PABannier/sam3.cpp/resolve/main/sam2.1_hiera_tiny_f16.ggml
# Segment an image interactively (requires SDL2)
./examples/sam3_image --model ../models/sam2.1_hiera_tiny_f16.ggml --image ../data/test_image.jpg
# Track objects in a video interactively (requires SDL2)
./examples/sam3_video --model ../models/sam2.1_hiera_tiny_f16.ggml --video ../data/test_video.mp4

The interactive apps use SDL2 + ImGui. If SDL2 isn't found, only the benchmark and quantize tools are built.

Benchmarks

Video object tracking latency on Apple M4 Pro (24 GB), 5 frames at 1008x1008 resolution, 4 threads. Each run is isolated in a forked subprocess.

SAM 3 (Full: text detection + visual tracking)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam3-f323.2 GB-40.5-200.4
sam3-f161.7 GB7.723.838.1117.5
sam3-q8_01.0 GB7.823.338.7115.2
sam3-q4_1756 MB-24.5-120.9
sam3-q4_0673 MB7.823.938.7117.7

SAM 3 Visual-Only (no text encoder, tracking only)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam3-visual-f16901 MB6.622.632.7111.2
sam3-visual-q8_0493 MB6.722.033.0108.4
sam3-visual-q4_1318 MB-23.1-113.9
sam3-visual-q4_0275 MB6.722.333.0110.0

EdgeTAM (RepViT backbone + Perceiver)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
edgetam_f1627 MB0.41.12.25.2
edgetam_q8_019 MB0.41.12.15.1
edgetam_q4_015 MB0.41.12.15.1

SAM 2 / SAM 2.1 (Hiera backbone)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam2_hiera_tiny_f1675 MB0.92.74.012.6
sam2_hiera_tiny_q8_040 MB0.92.54.011.7
sam2_hiera_tiny_q4_022 MB0.92.54.011.7
sam2_hiera_small_f1689 MB0.92.94.113.7
sam2_hiera_small_q8_047 MB0.92.74.112.5
sam2_hiera_small_q4_026 MB0.92.74.112.7
sam2_hiera_base_plus_f16155 MB1.04.24.720.2
sam2_hiera_base_plus_q8_083 MB-3.9-18.9
sam2_hiera_large_f16429 MB-8.4-40.9
sam2_hiera_large_q8_0230 MB-7.6-37.1
sam2.1_hiera_tiny_f1675 MB0.82.64.012.3
sam2.1_hiera_tiny_q8_040 MB0.92.44.011.4
sam2.1_hiera_tiny_q4_022 MB0.92.54.011.5
sam2.1_hiera_small_f1689 MB0.92.94.113.5
sam2.1_hiera_small_q8_047 MB0.92.74.112.5
sam2.1_hiera_small_q4_026 MB0.92.74.112.6
sam2.1_hiera_base_plus_f16155 MB1.04.24.720.1
sam2.1_hiera_base_plus_q8_083 MB-3.9-18.6
sam2.1_hiera_large_f16430 MB-8.5-41.4
sam2.1_hiera_large_q8_0230 MB-7.7-37.7
Reproduce these benchmarks
# Full benchmark (all models, both backends)
./build/examples/sam3_benchmark
# GPU only, all models
./build/examples/sam3_benchmark --gpu-only
# Quick iteration (tiny models, 3 frames)
./build/examples/sam3_benchmark --filter tiny --n-frames 3 --gpu-only
# CPU only, specific model
./build/examples/sam3_benchmark --cpu-only --filter sam2.1_hiera_small

Options: --models-dir <path>, --video <path>, --n-frames <n>, --n-threads <n>, --filter <substr>, --cpu-only, --gpu-only

Model Zoo

All models are available in GGML format on Hugging Face:

PABannier/sam3.cpp: 52 model files covering 4 architectures x multiple sizes x up to 5 precisions.

SAM 3 (850M params, ViT-32 backbone + text encoder + DETR decoder)

VariantPrecisionSizeFeatures
sam3f323.4 GBText detection (PCS) + point/box segmentation (PVS) + video tracking
sam3f161.7 GBSame
sam3q8_01.0 GBSame
sam3q4_1756 MBSame
sam3q4_0707 MBSame
sam3-visualf16946 MBPoint/box segmentation (PVS) + video tracking (no text)
sam3-visualq8_0517 MBSame
sam3-visualq4_1318 MBSame
sam3-visualq4_0289 MBSame

SAM 2 / SAM 2.1 (Hiera backbone, 4 sizes)

FamilySizeParamsf32f16q8_0q4_1q4_0
SAM 2Tiny39M156 MB79 MB43 MB26 MB24 MB
SAM 2Small46M184 MB94 MB50 MB30 MB28 MB
SAM 2Base+81M323 MB163 MB88 MB53 MB48 MB
SAM 2Large224M898 MB451 MB241 MB144 MB130 MB
SAM 2.1Tiny39M156 MB79 MB43 MB26 MB24 MB
SAM 2.1Small46M184 MB94 MB50 MB30 MB28 MB
SAM 2.1Base+81M323 MB163 MB88 MB53 MB48 MB
SAM 2.1Large224M898 MB451 MB241 MB144 MB130 MB

EdgeTAM (RepViT-M1 backbone + Perceiver memory compressor)

VariantPrecisionSizeFeatures
edgetamf1627 MBPoint/box segmentation (PVS) + video tracking
edgetamq8_019 MBSame
edgetamq4_015 MBSame

Feature Matrix

CapabilitySAM 3SAM 3 VisualSAM 2 / 2.1EdgeTAM
Text-prompted detection (PCS)Yes---
Point/box segmentation (PVS)YesYesYesYes
Multi-mask outputYesYesYesYes
Video tracking (memory bank)YesYesYesYes
Interactive refinementYesYesYesYes
Quantization (Q4/Q8)YesYesYesYes
Metal GPUYesYesYesYes

Building from Source

Prerequisites

  • C++14 compiler (Clang, GCC, MSVC)
  • CMake 3.14+
  • (Optional) SDL2 for the interactive image/video examples
  • (Optional) ffmpeg for video frame decoding

Build

git clone --recursive https://github.com/PABannier/sam3.cpp
cd sam3.cpp
mkdir build &&cd build
cmake ..
make -j

Metal is enabled automatically on macOS. To disable it:

cmake .. -DSAM3_METAL=OFF

To build tests:

cmake .. -DSAM3_BUILD_TESTS=ON
make -j

Usage

Image Segmentation (Interactive GUI)

# Point/box segmentation with any model
./sam3_image --model models/sam2.1_hiera_tiny_f16.ggml --image photo.jpg
# Text-prompted detection (SAM 3 only)
./sam3_image --model models/sam3-f16.ggml --image photo.jpg
# → Type "cat" in the text field, click [Segment]

Controls:

  • Left-click: add positive point
  • Right-click: add negative point
  • Drag: draw bounding box
  • Text field + Segment: detect all instances matching the text prompt (SAM 3 only)
  • Export: save masks as PNG

Video Tracking (Interactive GUI)

# Visual tracking (SAM 2/2.1/3/EdgeTAM)
./sam3_video --model models/sam2.1_hiera_small_f16.ggml --video input.mp4
# Text-prompted tracking (SAM 3 only)
./sam3_video --model models/sam3-f16.ggml --video input.mp4

Controls:

  • Click a point or draw a box on a paused frame to add an instance
  • Click on an existing tracked mask to refine it
  • Play/Pause/Step for playback
  • Export per-frame mask PNGs

C++ API

#include"sam3.h"// Load model
sam3_params params;
params.model_path = "models/sam2.1_hiera_tiny_f16.ggml";
params.use_gpu = true;
params.n_threads = 4;
auto model = sam3_load_model(params);
auto state = sam3_create_state(*model, params);
// Encode image (call once, reuse for multiple prompts)auto image = sam3_load_image("photo.jpg");
sam3_encode_image(*state, *model, image);
// Segment with a point click
sam3_pvs_params pvs;
pvs.pos_points.push_back({315.0f, 250.0f});
sam3_result result = sam3_segment_pvs(*state, *model, pvs);
for (auto& det : result.detections) {
sam3_save_mask(det.mask, "mask.png");
}
// Text-prompted detection (SAM 3 full model only)
sam3_pcs_params pcs;
pcs.text_prompt = "yellow school bus";
pcs.score_threshold = 0.5f;
sam3_result result = sam3_segment_pcs(*state, *model, pcs);
// → result.detections contains every matching instance
// Video trackingauto tracker = sam3_create_visual_tracker(*model, {});
// Frame 0: encode + add instance with a clicksam3_encode_image(*state, *model, frame0);
sam3_pvs_params pvs;
pvs.pos_points.push_back({315.0f, 250.0f});
sam3_tracker_add_instance(*tracker, *state, *model, pvs);
// Subsequent frames: propagate masksfor (int f = 1; f < n_frames; f++) {
sam3_result result = sam3_propagate_frame(*tracker, *state, *model, frames[f]);
// result.detections[i].mask - tracked mask for each instance
}

Quantization

Convert F32/F16 weights to smaller quantized formats:

./sam3_quantize models/sam3-f16.ggml models/sam3-q4_0.ggml q4_0
# Supported types: q4_0, q4_1, q8_0

Converting Weights

Convert official PyTorch checkpoints to GGML format:

# SAM 3
uv run python convert_sam3_to_ggml.py \
--model sam3.pt \
--output models/sam3-f16.ggml \
--ftype 1 \
--tokenizer /path/to/tokenizer
# SAM 3 visual-only (no text encoder, smaller file)
uv run python convert_sam3_to_ggml.py \
--model sam3.pt \
--output models/sam3-visual-f16.ggml \
--ftype 1 \
--visual-only
# SAM 2 / SAM 2.1
uv run python convert_sam2_to_ggml.py \
--model sam2.1_hiera_large.pt \
--config sam2.1_hiera_l.yaml \
--output models/sam2.1_hiera_large_f16.ggml \
--ftype 1
# EdgeTAM
uv run python convert_edgetam_to_ggml.py \
--model edgetam.pt \
--output models/edgetam_f16.ggml \
--ftype 1

--ftype 0 = float32, --ftype 1 = float16 (recommended). Then quantize with sam3_quantize.

Acknowledgments

  • Meta AI Research for SAM, SAM 2, SAM 3, and EdgeTAM
  • ggml, the tensor computation library that makes this possible
  • sam.cpp, the original SAM 1 C++ port that inspired this project's architecture

License

MIT

About

Fast state-of-the-art image and video segmentation in portable C/C++

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

sam3.cpp

State-of-the-art image and video segmentation in portable C/C++

SAM3 Image Segmentation DemoSAM3 Video Segmentation Demo


Why sam3.cpp?

Running Meta's Segment Anything models typically requires Python, PyTorch, and a CUDA GPU. sam3.cpp eliminates all of that. It's a single C++ library that runs SAM 2, SAM 2.1, SAM 3, and EdgeTAM inference on CPU and Apple Metal. No Python runtime, no GPU drivers, no heavyweight dependencies. Just compile and segment.

  • 4 model families: SAM 2, SAM 2.1 (Hiera), SAM 3 (ViT + text detection), EdgeTAM (RepViT, 22x faster than SAM 2 on mobile)
  • 4-bit quantization: EdgeTAM in 15 MB, SAM 2.1 Tiny in 22 MB at ~1 fps on Metal, SAM 3 down to 673 MB
  • Apple Metal GPU acceleration for the full backbone and transformer decoder
  • Text-prompted detection (SAM 3 only): type "cat" and get every cat in the image, no clicks needed
  • Point/box segmentation + video tracking with memory bank across all models
  • Single-file library: sam3.cpp + sam3.h, C++14, no exceptions, no inheritance
  • Zero dependencies beyond ggml and stb

Quick Start

# Clone
git clone --recursive https://github.com/PABannier/sam3.cpp
cd sam3.cpp
# Build (Metal GPU enabled automatically on macOS)
mkdir build &&cd build
cmake ..
make -j
# Download a model (SAM 2.1 Tiny, 75 MB)# See "Model Zoo" below for all available models and download links
curl -L -o ../models/sam2.1_hiera_tiny_f16.ggml \
https://huggingface.co/PABannier/sam3.cpp/resolve/main/sam2.1_hiera_tiny_f16.ggml
# Segment an image interactively (requires SDL2)
./examples/sam3_image --model ../models/sam2.1_hiera_tiny_f16.ggml --image ../data/test_image.jpg
# Track objects in a video interactively (requires SDL2)
./examples/sam3_video --model ../models/sam2.1_hiera_tiny_f16.ggml --video ../data/test_video.mp4

The interactive apps use SDL2 + ImGui. If SDL2 isn't found, only the benchmark and quantize tools are built.

Benchmarks

Video object tracking latency on Apple M4 Pro (24 GB), 5 frames at 1008x1008 resolution, 4 threads. Each run is isolated in a forked subprocess.

SAM 3 (Full: text detection + visual tracking)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam3-f323.2 GB-40.5-200.4
sam3-f161.7 GB7.723.838.1117.5
sam3-q8_01.0 GB7.823.338.7115.2
sam3-q4_1756 MB-24.5-120.9
sam3-q4_0673 MB7.823.938.7117.7

SAM 3 Visual-Only (no text encoder, tracking only)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam3-visual-f16901 MB6.622.632.7111.2
sam3-visual-q8_0493 MB6.722.033.0108.4
sam3-visual-q4_1318 MB-23.1-113.9
sam3-visual-q4_0275 MB6.722.333.0110.0

EdgeTAM (RepViT backbone + Perceiver)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
edgetam_f1627 MB0.41.12.25.2
edgetam_q8_019 MB0.41.12.15.1
edgetam_q4_015 MB0.41.12.15.1

SAM 2 / SAM 2.1 (Hiera backbone)

ModelSizeTrack/frame Metal (s)Track/frame CPU (s)Total Metal (s)Total CPU (s)
sam2_hiera_tiny_f1675 MB0.92.74.012.6
sam2_hiera_tiny_q8_040 MB0.92.54.011.7
sam2_hiera_tiny_q4_022 MB0.92.54.011.7
sam2_hiera_small_f1689 MB0.92.94.113.7
sam2_hiera_small_q8_047 MB0.92.74.112.5
sam2_hiera_small_q4_026 MB0.92.74.112.7
sam2_hiera_base_plus_f16155 MB1.04.24.720.2
sam2_hiera_base_plus_q8_083 MB-3.9-18.9
sam2_hiera_large_f16429 MB-8.4-40.9
sam2_hiera_large_q8_0230 MB-7.6-37.1
sam2.1_hiera_tiny_f1675 MB0.82.64.012.3
sam2.1_hiera_tiny_q8_040 MB0.92.44.011.4
sam2.1_hiera_tiny_q4_022 MB0.92.54.011.5
sam2.1_hiera_small_f1689 MB0.92.94.113.5
sam2.1_hiera_small_q8_047 MB0.92.74.112.5
sam2.1_hiera_small_q4_026 MB0.92.74.112.6
sam2.1_hiera_base_plus_f16155 MB1.04.24.720.1
sam2.1_hiera_base_plus_q8_083 MB-3.9-18.6
sam2.1_hiera_large_f16430 MB-8.5-41.4
sam2.1_hiera_large_q8_0230 MB-7.7-37.7
Reproduce these benchmarks
# Full benchmark (all models, both backends)
./build/examples/sam3_benchmark
# GPU only, all models
./build/examples/sam3_benchmark --gpu-only
# Quick iteration (tiny models, 3 frames)
./build/examples/sam3_benchmark --filter tiny --n-frames 3 --gpu-only
# CPU only, specific model
./build/examples/sam3_benchmark --cpu-only --filter sam2.1_hiera_small

Options: --models-dir <path>, --video <path>, --n-frames <n>, --n-threads <n>, --filter <substr>, --cpu-only, --gpu-only

Model Zoo

All models are available in GGML format on Hugging Face:

PABannier/sam3.cpp: 52 model files covering 4 architectures x multiple sizes x up to 5 precisions.

SAM 3 (850M params, ViT-32 backbone + text encoder + DETR decoder)

VariantPrecisionSizeFeatures
sam3f323.4 GBText detection (PCS) + point/box segmentation (PVS) + video tracking
sam3f161.7 GBSame
sam3q8_01.0 GBSame
sam3q4_1756 MBSame
sam3q4_0707 MBSame
sam3-visualf16946 MBPoint/box segmentation (PVS) + video tracking (no text)
sam3-visualq8_0517 MBSame
sam3-visualq4_1318 MBSame
sam3-visualq4_0289 MBSame

SAM 2 / SAM 2.1 (Hiera backbone, 4 sizes)

FamilySizeParamsf32f16q8_0q4_1q4_0
SAM 2Tiny39M156 MB79 MB43 MB26 MB24 MB
SAM 2Small46M184 MB94 MB50 MB30 MB28 MB
SAM 2Base+81M323 MB163 MB88 MB53 MB48 MB
SAM 2Large224M898 MB451 MB241 MB144 MB130 MB
SAM 2.1Tiny39M156 MB79 MB43 MB26 MB24 MB
SAM 2.1Small46M184 MB94 MB50 MB30 MB28 MB
SAM 2.1Base+81M323 MB163 MB88 MB53 MB48 MB
SAM 2.1Large224M898 MB451 MB241 MB144 MB130 MB

EdgeTAM (RepViT-M1 backbone + Perceiver memory compressor)

VariantPrecisionSizeFeatures
edgetamf1627 MBPoint/box segmentation (PVS) + video tracking
edgetamq8_019 MBSame
edgetamq4_015 MBSame

Feature Matrix

CapabilitySAM 3SAM 3 VisualSAM 2 / 2.1EdgeTAM
Text-prompted detection (PCS)Yes---
Point/box segmentation (PVS)YesYesYesYes
Multi-mask outputYesYesYesYes
Video tracking (memory bank)YesYesYesYes
Interactive refinementYesYesYesYes
Quantization (Q4/Q8)YesYesYesYes
Metal GPUYesYesYesYes

Building from Source

Prerequisites

  • C++14 compiler (Clang, GCC, MSVC)
  • CMake 3.14+
  • (Optional) SDL2 for the interactive image/video examples
  • (Optional) ffmpeg for video frame decoding

Build

git clone --recursive https://github.com/PABannier/sam3.cpp
cd sam3.cpp
mkdir build &&cd build
cmake ..
make -j

Metal is enabled automatically on macOS. To disable it:

cmake .. -DSAM3_METAL=OFF

To build tests:

cmake .. -DSAM3_BUILD_TESTS=ON
make -j

Usage

Image Segmentation (Interactive GUI)

# Point/box segmentation with any model
./sam3_image --model models/sam2.1_hiera_tiny_f16.ggml --image photo.jpg
# Text-prompted detection (SAM 3 only)
./sam3_image --model models/sam3-f16.ggml --image photo.jpg
# → Type "cat" in the text field, click [Segment]

Controls:

  • Left-click: add positive point
  • Right-click: add negative point
  • Drag: draw bounding box
  • Text field + Segment: detect all instances matching the text prompt (SAM 3 only)
  • Export: save masks as PNG

Video Tracking (Interactive GUI)

# Visual tracking (SAM 2/2.1/3/EdgeTAM)
./sam3_video --model models/sam2.1_hiera_small_f16.ggml --video input.mp4
# Text-prompted tracking (SAM 3 only)
./sam3_video --model models/sam3-f16.ggml --video input.mp4

Controls:

  • Click a point or draw a box on a paused frame to add an instance
  • Click on an existing tracked mask to refine it
  • Play/Pause/Step for playback
  • Export per-frame mask PNGs

C++ API

#include"sam3.h"// Load model
sam3_params params;
params.model_path = "models/sam2.1_hiera_tiny_f16.ggml";
params.use_gpu = true;
params.n_threads = 4;
auto model = sam3_load_model(params);
auto state = sam3_create_state(*model, params);
// Encode image (call once, reuse for multiple prompts)auto image = sam3_load_image("photo.jpg");
sam3_encode_image(*state, *model, image);
// Segment with a point click
sam3_pvs_params pvs;
pvs.pos_points.push_back({315.0f, 250.0f});
sam3_result result = sam3_segment_pvs(*state, *model, pvs);
for (auto& det : result.detections) {
sam3_save_mask(det.mask, "mask.png");
}
// Text-prompted detection (SAM 3 full model only)
sam3_pcs_params pcs;
pcs.text_prompt = "yellow school bus";
pcs.score_threshold = 0.5f;
sam3_result result = sam3_segment_pcs(*state, *model, pcs);
// → result.detections contains every matching instance
// Video trackingauto tracker = sam3_create_visual_tracker(*model, {});
// Frame 0: encode + add instance with a clicksam3_encode_image(*state, *model, frame0);
sam3_pvs_params pvs;
pvs.pos_points.push_back({315.0f, 250.0f});
sam3_tracker_add_instance(*tracker, *state, *model, pvs);
// Subsequent frames: propagate masksfor (int f = 1; f < n_frames; f++) {
sam3_result result = sam3_propagate_frame(*tracker, *state, *model, frames[f]);
// result.detections[i].mask - tracked mask for each instance
}

Quantization

Convert F32/F16 weights to smaller quantized formats:

./sam3_quantize models/sam3-f16.ggml models/sam3-q4_0.ggml q4_0
# Supported types: q4_0, q4_1, q8_0

Converting Weights

Convert official PyTorch checkpoints to GGML format:

# SAM 3
uv run python convert_sam3_to_ggml.py \
--model sam3.pt \
--output models/sam3-f16.ggml \
--ftype 1 \
--tokenizer /path/to/tokenizer
# SAM 3 visual-only (no text encoder, smaller file)
uv run python convert_sam3_to_ggml.py \
--model sam3.pt \
--output models/sam3-visual-f16.ggml \
--ftype 1 \
--visual-only
# SAM 2 / SAM 2.1
uv run python convert_sam2_to_ggml.py \
--model sam2.1_hiera_large.pt \
--config sam2.1_hiera_l.yaml \
--output models/sam2.1_hiera_large_f16.ggml \
--ftype 1
# EdgeTAM
uv run python convert_edgetam_to_ggml.py \
--model edgetam.pt \
--output models/edgetam_f16.ggml \
--ftype 1

--ftype 0 = float32, --ftype 1 = float16 (recommended). Then quantize with sam3_quantize.

Acknowledgments

  • Meta AI Research for SAM, SAM 2, SAM 3, and EdgeTAM
  • ggml, the tensor computation library that makes this possible
  • sam.cpp, the original SAM 1 C++ port that inspired this project's architecture

License

MIT

About

Fast state-of-the-art image and video segmentation in portable C/C++

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages