Sub topic 11
How SA-1B and the data engine built SAM
This chapter assumes you have read the earlier chapters on the promptable task, the three model components, and SamAutomaticMaskGenerator. You should also be comfortable reading JSON and NumPy arrays. No training code appears here. The goal is to understand where the training data came from and what that means for how you use the model.
Why SAM needed a new kind of dataset
Segmentation datasets such as COCO and LVIS are small and cover a fixed list of categories. A model meant to segment any object from a prompt needs far more masks, and they must not be tied to class labels. Nobody could draw that many masks by hand. The SAM authors built the dataset and the model together, in a loop called the data engine. A weak version of SAM helped people annotate. Those annotations trained a better SAM, and the better SAM made annotation faster. After three rounds the model was good enough to produce masks without people.
The result is SA-1B, which contains about 11 million licensed, privacy-protected images and about 1.1 billion masks. That is roughly 100 masks per image. The masks carry no class names. They only mark regions that a prompt could plausibly select.
The three stages of the data engine
The engine ran in three stages. Each one shifted more work from annotators to the model.
Stage 1: assisted-manual
Professional annotators worked in a browser tool backed by SAM. They clicked foreground and background points, and the model proposed a mask. They then refined it with brush and eraser tools. This is the same interaction you built earlier with predict and mask_input. Annotators labeled objects in whatever order they liked, and they were asked to prioritize prominent objects.
The model was retrained several times as new masks arrived. As it improved, the average time to annotate a mask dropped from about 34 seconds to about 14 seconds. Masks per image rose from about 20 to about 44. This stage produced 4.3 million masks from 120 thousand images.
The lightweight mask decoder is the reason this worked. The image embedding is computed once, and each click then costs only a decoder pass, so the tool felt interactive in a browser.
Stage 2: semi-automatic
Stage 1 tends to produce masks for obvious objects. Stage 2 aimed to increase the diversity of masks. A detector, trained on the stage 1 masks using a generic "object" category, first found confident masks automatically. Annotators were shown those masks pre-filled and were asked to label everything else that was left unannotated. This pushed their effort toward less prominent objects.
This stage added about 5.9 million masks from 180 thousand images, for about 10.2 million masks in total. Masks per image rose from about 44 to about 72. The model was retrained a few more times.
Stage 3: fully automatic
By this point the model had two properties that made removing humans possible:
- It had enough masks to learn ambiguity, so it could return several valid masks per prompt.
- It predicted its own quality with an IoU score, so it could rank its own outputs.
The pipeline prompted the model with a regular 32 by 32 grid of points on each image. Each point produced multiple masks (whole, part, subpart). Then the pipeline filtered them:
- Keep masks whose predicted IoU is high.
- Keep masks that are stable, meaning that thresholding the logits at slightly different levels gives nearly the same mask.
- Apply non-maximum suppression (NMS) to remove near-duplicates.
- Also run on zoomed-in image crops to catch small objects.
- Post-process to remove small disconnected regions and fill small holes.
This ran over all 11 million images and produced the 1.1 billion masks. About 99.1% of the masks in SA-1B come from this stage.
| Stage | Who proposes masks | Images | Masks added | Main purpose |
|---|---|---|---|---|
| Assisted-manual | SAM, guided by annotator clicks | ~120k | ~4.3M | Bootstrap quality, speed up annotation |
| Semi-automatic | Detector for confident objects, annotators for the rest | ~180k | ~5.9M | Increase diversity of masks |
| Fully automatic | SAM alone, on a point grid | ~11M | ~1.1B | Reach scale |
The counts are approximate figures from the SAM paper. Treat them as orders of magnitude.
The connection to `SamAutomaticMaskGenerator`
The stage 3 pipeline is the same idea as the generator in the segment_anything package. Its parameters map to the filtering steps above:
| Pipeline step | Generator parameter | Default |
|---|---|---|
| Grid of prompts | `points_per_side` | 32 |
| Predicted IoU filter | `pred_iou_thresh` | 0.88 |
| Stability filter | `stability_score_thresh` | 0.95 |
| NMS of near-duplicates | `box_nms_thresh` | 0.7 |
| Zoomed-in crops | `crop_n_layers` | 0 (off) |
| Remove small regions and holes | `min_mask_region_area` | 0 (off) |
The next example configures a generator that turns on the optional steps. It is close in spirit to the data engine's last stage, but it is not an exact reproduction of the settings used for SA-1B.
import cv2
from segment_anything import sam_model_registry, SamAutomaticMaskGenerator
sam = sam_model_registry["vit_b"](checkpoint="sam_vit_b_01ec64.pth")
sam.to(device="cuda") # use "cpu" if no GPU is available
mask_generator = SamAutomaticMaskGenerator(
sam,
points_per_side=32, # 32 x 32 grid of point prompts
pred_iou_thresh=0.88, # drop masks with low predicted IoU
stability_score_thresh=0.95, # drop masks that change a lot with the threshold
box_nms_thresh=0.7, # suppress near-duplicate masks
crop_n_layers=1, # also run on zoomed-in crops
min_mask_region_area=100, # remove tiny regions and holes (needs OpenCV)
)
image = cv2.cvtColor(cv2.imread("photo.jpg"), cv2.COLOR_BGR2RGB)
results = mask_generator.generate(image)
print(len(results), "masks")Setting crop_n_layers=1 makes generation noticeably slower, because the model runs again on image crops. It is the knob to try when small objects are missing.
What the released data looks like
SA-1B ships as image files plus one JSON file per image. Masks are stored in COCO run-length encoding (RLE), a compact format that lists runs of identical pixels. Each annotation also records the quality signals from stage 3, so you can re-filter the dataset yourself. The released images are downsampled so the shorter side is 1500 pixels, and faces and license plates are blurred.
Each JSON file has an image entry and an annotations list. Each annotation has fields such as segmentation (the RLE), bbox in XYWH format, area, predicted_iou, stability_score, crop_box, and point_coords (the grid point that produced it).
This script reads one file and decodes its masks. It assumes you downloaded a tar shard of SA-1B and extracted a JSON file named sa_1.json. It also assumes pycocotools is installed.
import json
from pycocotools import mask as mask_utils
with open("sa_1.json") as f:
data = json.load(f)
print(data["image"]["width"], data["image"]["height"])
annotations = data["annotations"]
print(len(annotations), "masks in this image")
# Keep only masks the model was most confident about.
confident = [a for a in annotations if a["predicted_iou"] > 0.95]
print(len(confident), "with predicted_iou > 0.95")
for ann in confident[:3]:
binary_mask = mask_utils.decode(ann["segmentation"]) # uint8 array, shape (H, W)
print(ann["area"], ann["bbox"], binary_mask.sum())The area field should match the pixel count of the decoded mask, which makes a handy sanity check on your download.
How good are the automatic masks?
The authors checked quality by taking a random sample of about 500 images (about 50 thousand masks). Professional annotators corrected the automatic masks in those images. Comparing the original and corrected masks gave an IoU for each pair. Around 94% of pairs had IoU above 90%, and 97% had IoU above 75%. That is close to the agreement you see between human annotators, which is why the authors accepted a fully automatic final stage.
A callout on how to read this claim follows.
What the data engine means for your use of SAM
- Masks are class-agnostic. SA-1B has no labels, so SAM never learned names. If you need "dog" masks, pair SAM with a detector or a text model and use their boxes as prompts.
- Granularity is a product of the data. Whole, part, and subpart masks exist because stage 3 asked for three masks per point. That is why one click on a shirt can return the sleeve, the shirt, or the person.
- Annotation bias carries over. Stage 1 and 2 annotators favored salient objects, and the stage 3 grid favors regions that a point lands on. Thin structures and tiny objects are under-covered. This links directly to the failure modes in the next chapter.
- Coverage is skewed. The images come from a licensed photo provider and span many countries, but they are mostly photographs. Specialized domains such as medical scans or aerial images are thinly represented, so expect weaker zero-shot results there.
- Self-training has a ceiling. Stage 3 masks come from the model itself. Errors the model makes systematically can be amplified when it is trained on that data.
Common mistakes
- Treating
predicted_iouas a true IoU. It is the model's own estimate and can be overconfident on out-of-domain images. - Forgetting that
bboxis XYWH and mixing it with the XYXY box thatSamPredictor.predictexpects. - Decoding RLE without
pycocotoolsand assuming a plain array of pixels. - Assuming SA-1B masks are labeled or exhaustive. They are neither.
Exercise
The stage 3 pipeline of the data engine can run with no human in the loop. Name two signals the model produces that make this possible, and say what each one filters out.
Show answer
The first is the predicted IoU, which is the model's estimate of its own mask quality. It removes masks the model itself considers poor. The second is the stability score, which measures how much a mask changes when the logit threshold is shifted slightly. It removes masks with unstable boundaries. NMS then removes near-duplicates among the masks that remain.
Exercise
You run SamAutomaticMaskGenerator on a street photo and small distant signs are missing. Which stage 3 idea would you turn on, which parameter controls it, and what is the cost?
Show answer
Run the model on zoomed-in image crops, which the data engine also did. Set cropnlayers to 1 or more. The cost is longer run time, because the model processes extra crops of the image.