Sub topic 5
The Mask Decoder: Fast Masks from Embeddings
This chapter assumes basic Python and NumPy, familiarity with PyTorch checkpoints and tensors, and a working understanding of image segmentation. You should also know that a Vision Transformer can convert an image into a grid of feature vectors.
What the decoder receives
SAM's mask decoder turns two kinds of information into a segmentation mask:
- An image embedding, which describes the whole image.
- A prompt embedding, which describes points, boxes, or an earlier mask.
The image encoder creates the image embedding once. The prompt encoder represents the current prompt. The mask decoder combines both embeddings and predicts the pixels that belong to the requested object.
For the ViT-B version, a resized image produces an image embedding with 256 channels and a 64 × 64 spatial grid. This representation is much smaller than the original image, but it preserves useful visual information.
How the decoder combines embeddings
The decoder is a small Transformer module. It uses attention in both directions:
- Prompt tokens attend to image features to gather visual evidence.
- Image features attend to prompt tokens to update the features near the requested object.
- Output tokens produce masks and a predicted quality score.
This module is lightweight compared with the image encoder. The decoder can therefore run many times for one image. An interactive application can keep the image embedding in memory while a user adds or moves prompts.
The decoder does not directly output a full-resolution Boolean mask. It first produces low-resolution mask logits. A logit is an unnormalized score. Positive values usually indicate foreground, while negative values usually indicate background. SAM then upsamples these logits, removes padding added during preprocessing, and thresholds them to create Boolean masks.
Mask tokens and quality prediction
SAM includes special output tokens in the decoder:
- An IoU token predicts the quality of each candidate mask.
- Mask tokens produce the masks themselves.
With multimask_output=True, SAM normally uses several mask tokens and returns three alternatives. Each alternative may represent a different reasonable interpretation of an uncertain prompt. With multimask_output=False, the decoder returns one mask.
Internally, each mask token is transformed into weights that are applied to the upsampled image features. This is similar to generating a small linear classifier over the feature grid. The decoder can produce a new mask without rerunning the expensive image encoder.
The returned quality score is useful for ranking candidates, but it is not a guarantee of correctness. A high score can still occur when the prompt identifies the wrong object or when the image contains unusual content.
Inspecting decoder outputs
The SamPredictor API exposes both the final masks and the decoder's low-resolution logits. The logits are useful when refining a mask because SAM can use them as a starting point for the next decoding pass.
import cv2
import numpy as np
from segment_anything import sam_model_registry, SamPredictor
sam = sam_model_registry["vit_b"](
checkpoint="sam_vit_b_01ec64.pth"
)
sam.to(device="cuda")
predictor = SamPredictor(sam)
image = cv2.cvtColor(
cv2.imread("photo.jpg"),
cv2.COLOR_BGR2RGB,
)
predictor.set_image(image)
masks, scores, low_res_logits = predictor.predict(
point_coords=np.array([[500, 375]]),
point_labels=np.array([1]),
multimask_output=True,
)
print("masks:", masks.shape)
print("scores:", scores)
print("decoder logits:", low_res_logits.shape)For the standard SAM implementation, low_res_logits has one 256 × 256 logit map per returned mask. The final masks array has the original image height and width after postprocessing.
Decoder trade-offs
The decoder's speed makes interactive segmentation practical, but it creates boundaries from compressed image features. Very thin structures, tiny objects, and fine textures can disappear during this process. Increasing the image encoder size can improve visual features, but it also increases memory use and the cost of the first pass.
Use multiple masks when a prompt is ambiguous. Use one mask when the prompt is already specific, such as a tight bounding box. In either case, inspect the result rather than trusting the score alone.
Exercise
Why can SAM answer many prompts quickly after the first prompt, and what part of the output should you inspect when you need to refine a result?
Show answer
The expensive image encoder has already created a reusable image embedding, so later calls mainly run the prompt encoder and mask decoder. Inspect the low-resolution logits and pass the selected logits back as mask_input together with additional prompts.