Promptable segmentation
MobileSAM
Cuts out any object you point at: tap it, draw a box around it, or mark what to leave out. Segment Anything made small for phones (about 10 million parameters). Apache-2.0.
About this model
MobileSAM cuts an object out of a photo from a hint: a tap on it, a box around it, points to leave out, or any mix. It returns the object's mask at the photo's size. It needs no list of classes: it cuts out whatever the hint points at, an animal, a car, a cup, a person's shirt.
It is Segment Anything (Meta's SAM) with the large image encoder replaced by a small one (TinyViT, distilled from SAM's), so it runs on phones; the prompt decoder is SAM's own. The pack holds the image encoder with the prompt decoder attached in the same file.
The photo is encoded once (about 43 ms on the GPU); every later prompt on the same Frame reuses the encoding and takes about 11 ms, so an app can follow taps as they come. Slab prepares the photo and picks the mask the way MobileSAM's own predictor does.
What you can build
- Tap to cut out an object for a sticker, collage or photo edit
- Remove or blur the background around any object, not only people
- Label objects for training data with a tap instead of a polygon
- Select a product, plant or part in a photo to measure or recolor it
One tap on the dog
f16Karen Arnold, CC0, https://commons.wikimedia.org/wiki/File:Golden-retriever-dog-1362597631o6g.jpg
Input(points=[(205, 384)]) on Metal: mask covering 59% of the photo, predicted quality 1.01.
A box around the car
f16Leon Brooks, Public domain, https://commons.wikimedia.org/wiki/File:Red_sports_coupe_car.jpg
Input(box=(50, 224, 900, 510)) on Metal: mask covering 23% of the photo, predicted quality 1.00.
A tap on the macaw and a point to leave out on the branch
f16Christopher Kuszajewski, CC0, https://commons.wikimedia.org/wiki/File:Macaw_parrot_sitting_on_a_tree_branch.jpg_.jpg
Input(points=[(400, 460)], exclude=[(430, 770)]) on Metal: mask covering 32% of the photo, predicted quality 0.93.
Variants & downloads
Choose the build for your appModel files are hosted on Google Drive. Large files may open a confirmation page before downloading.
Standard
SlabWeights stored in FP16, decoded to FP32 when loading. The prompt decoder is attached in the same file.
Platforms: macos · android
mobilesam-f16.slab
27.1 MB · Hosted download
SHA-256 checksum
7fe11dc6296def0942bf9885e38719424cc403cc8108a22664917641eb738053LICENSE-MobileSAM.txt
11 KB
SHA-256 checksum
c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4Conversion details
- command
- git clone https://github.com/ChaoningZhang/MobileSAM && git -C MobileSAM checkout f706ad9c4eb7f219c00d9050e46328518ffb65d2 python - <<'EOF' # Two graphs: the image encoder, and the prompt decoder with 8 point slots # (labels 1 / 0: points to include / exclude, 2 / 3: box corners, -1: SAM's # padding point, -2: unused) giving the four low-resolution masks and their # predicted IoU. Unused slots are hidden from attention, so the slots give what # SAM gives for the prompts alone. import math, sys, torch sys.path.insert(0, "MobileSAM") from mobile_sam import sam_model_registry from mobile_sam.modeling import transformer as T torch.set_grad_enabled(False) sam = sam_model_registry["vit_t"](checkpoint="MobileSAM/weights/mobile_sam.pt").eval() hide = [None] def attention(self, q, k, v): q = self._separate_heads(self.q_proj(q), self.num_heads) k = self._separate_heads(self.k_proj(k), self.num_heads) v = self._separate_heads(self.v_proj(v), self.num_heads) a = q @ k.permute(0, 1, 3, 2) / math.sqrt(q.shape[-1]) if hide[0] is not None and k.shape[-2] == hide[0].shape[-1]: a = a + hide[0] return self.out_proj(self._recombine_heads(torch.softmax(a, dim=-1) @ v)) T.Attention.forward = attention class Encoder(torch.nn.Module): def forward(self, image): return self.s.image_encoder(image) class Decoder(torch.nn.Module): def forward(self, image_embeddings, point_coords, point_labels, mask_input, has_mask_input): pe = self.s.prompt_encoder c = pe.pe_layer._pe_encoding((point_coords + 0.5) / 1024.0) lab = point_labels.unsqueeze(-1).expand_as(c) e = c * (lab > -0.5) + pe.not_a_point_embed.weight * (lab == -1) for i in range(pe.num_point_embeddings): e = e + pe.point_embeddings[i].weight * (lab == i) dense = has_mask_input * pe.mask_downscaling(mask_input) + (1 - has_mask_input) * pe.no_mask_embed.weight.reshape(1, -1, 1, 1) hide[0] = torch.cat([torch.zeros(1, 5), (point_labels == -2).float() * -1e9], 1)[:, None, None, :] return self.s.mask_decoder.predict_masks(image_embeddings=image_embeddings, image_pe=pe.get_dense_pe(), sparse_prompt_embeddings=e, dense_prompt_embeddings=dense) enc = Encoder(); enc.s = sam; dec = Decoder(); dec.s = sam torch.onnx.export(enc, (torch.zeros(1, 3, 1024, 1024),), "encoder.onnx", input_names=["image"], output_names=["image_embeddings"], opset_version=17, dynamo=False) torch.onnx.export(dec, (torch.zeros(1, 256, 64, 64), torch.zeros(1, 8, 2), -2 * torch.ones(1, 8), torch.zeros(1, 1, 256, 256), torch.zeros(1)), "decoder.onnx", input_names=["image_embeddings", "point_coords", "point_labels", "mask_input", "has_mask_input"], output_names=["masks", "iou_predictions"], opset_version=17, dynamo=False) EOF slab-load convert encoder.onnx encoder.slab --input image=1x3x1024x1024 --meta task=segment_prompt --meta resize=letterbox --meta letterbox_align=top_left_round --meta letterbox_pad:i64=-1 --meta interpolation=bilinear --meta antialias:bool=true --meta normalize=imagenet --meta color=rgb slab-load convert decoder.onnx decoder.slab --input image_embeddings=1x256x64x64 --input point_coords=1x8x2 --input point_labels=1x8 --input mask_input=1x1x256x256 --input has_mask_input=1 slab-load quantize encoder.slab mobilesam-f16.slab --f16 slab-load quantize decoder.slab decoder-f16.slab --f16 slab-load meta set mobilesam-f16.slab default_backend.macos=gpu npu.macos=no slab-load meta set decoder-f16.slab default_backend.macos=gpu slab-load attach mobilesam-f16.slab decoder decoder-f16.slab
Integration examples
Python
python
import slab
cfg = slab.Config(cache_dir="/tmp/slab_cache", license=open("license.slablic.txt").read())
sam = slab.Session(cfg, "mobilesam-f16.slab")
photo = slab.Frame.open("photo.jpg")
out = sam.run(slab.Input(frame=photo, points=[(205, 384)])) # encodes the photo, then cuts out
mask = out.mask() # Frame, photo size, 255 = object
print(out.score)
# the same photo: only the prompt part runs
out = sam.run(slab.Input(frame=photo, points=[(205, 384)], exclude=[(60, 500)]))
out = sam.run(slab.Input(frame=photo, box=(50, 60, 400, 600)))
Device & backend compatibility
Pack default: macos / GPU. Interactive on the GPU: 43 ms to encode a 1080p photo and 11 ms per prompt, against 612 ms and 51 ms on the CPU.
| Platform | Engine | Status | Precision |
|---|---|---|---|
| apple | CPU CPU | Supported Measured on macOS. | f32 |
| apple | Metal GPU | Supported Measured on macOS. The default. | f32 |
| apple | Apple Neural Engine NPU | Not supported Apple's Neural Engine compiler had not finished preparing the encoder after 20 minutes; the pack is marked npu.macos = no. | — |
| android | CPU CPU | Supported Measured on a Samsung Galaxy S23 Ultra (Snapdragon 8 Gen 2, Adreno 740), Android 17. | f32 |
| android | Vulkan GPU | Supported Measured on a Samsung Galaxy S23 Ultra (Snapdragon 8 Gen 2, Adreno 740), Android 17. | f32 |
Performance
Results depend on the device, runtime, and test conditions. Each measurement keeps its own context.
Mac with Apple M1 Max
Slab · GPU
macOS 26.6.2
11.3 ms
Measured time · scope below
Session.run with one point on a photo already encoded (the decoder and the mask at photo size): median of 20. The first prompt on a new photo, encoding included: 43 ms (median of 5). Peak memory after opening and one prompt: 251 MB.
Mac with Apple M1 Max
Slab · CPU
macOS 26.6.2
51.1 ms
Measured time · scope below
Session.run with one point on a photo already encoded (the decoder and the mask at photo size): median of 20. The first prompt on a new photo, encoding included: 612 ms (median of 5). Peak memory after opening and one prompt: 586 MB.
Samsung Galaxy S23 Ultra (Snapdragon 8 Gen 2)
Slab · CPU
Android 17
160.0 ms
Measured time · scope below
Session.run with one point on a photo already encoded (the decoder and the mask at photo size): median of 20. The first prompt on a new photo, encoding included: 1887 ms (median of 5). open_ms: opening the session. Peak memory (resident) after the runs: 524 MB.
Samsung Galaxy S23 Ultra (Snapdragon 8 Gen 2)
Slab · GPU
Android 17
224.0 ms
Measured time · scope below
Session.run with one point on a photo already encoded (the decoder and the mask at photo size): median of 20. The first prompt on a new photo, encoding included: 1382 ms (median of 5). open_ms: opening the session with the GPU programs already in the cache folder (the first open on a device compiles them, about 0.3 s more). Peak memory (resident) after the runs: 164 MB.
Accuracy checks
macos · GPU · f16
MobileSAM's own SamPredictor (code and weights at commit f706ad9c4eb7, FP32) with SAM's single-mask choice, on the 53 public photos of the gallery set with four prompts each (one point, a point and a point to leave out, a box, a box and a point)
Mask IoU with the reference 0.9981 on average over 212 prompts, 0.958 at worst; 207 of 212 at 0.99 or more. Slab resizes the photo itself (the reference resizes it with PIL).
macos · CPU · f16
MobileSAM's own SamPredictor (code and weights at commit f706ad9c4eb7, FP32) with SAM's single-mask choice, on the 53 public photos of the gallery set with four prompts each (one point, a point and a point to leave out, a box, a box and a point)
Mask IoU with the reference 0.9981 on average over 212 prompts, 0.958 at worst; 207 of 212 at 0.99 or more. Slab resizes the photo itself (the reference resizes it with PIL).
Before you choose this model
- It does not say what the object is: pair it with a detector or classifier for labels (a detector's box makes a good prompt).
- One point can be read as a part or the whole (a shirt or the person); add points, points to leave out, or a box to settle it. Thin, open structures are hard: a tap between a bicycle's tubes cut out the snow behind them in our tests.
- The photo is resized to 1024 pixels on its longest side, so very fine detail at the edges of large photos is approximate.
- Up to 7 points, or 6 with a box, per prompt.
- No int8 variant: int8 weights moved too many masks (mask IoU 0.955 on average against the reference, 129 of 212 below 0.99) for a pack only 6 MB smaller.
- Not on Apple's Neural Engine: its compiler had not finished preparing the encoder after 20 minutes, so the pack says so (npu.macos = no) and a Neural Engine request is refused at once. AUTO uses the GPU.