Sub topic 5
The mask decoder: fast masks from embeddings
This chapter covers the third component of SAM: the mask decoder. It assumes you have read the chapters on the image encoder and prompt encoder. You should know that the encoder produces a 256-channel image embedding on a 64×64 grid, and that the prompt encoder turns points and boxes into 256-dimensional tokens. You should also be comfortable with transformer attention (queries, keys, values) and with PyTorch tensor shapes.
Why the decoder is a separate, small module
The image encoder is a large Vision Transformer and costs most of SAM's compute. The decoder is small: about 4 million parameters, compared with roughly 91 million for the ViT-B encoder and 636 million for ViT-H. The design goal is interactive use. The encoder runs once per image, and the decoder then runs again for every click or box, so each new prompt should cost milliseconds.
The decoder receives two inputs and returns two outputs:
- Inputs: the image embedding (256×64×64) and the prompt tokens from the prompt encoder. An optional dense prompt (a previous mask) is added to the image embedding.
- Outputs: several low-resolution mask logits (256×256) and one predicted quality score for each mask.
Output tokens
Before decoding, SAM inserts learned tokens in front of the prompt tokens. These tokens are model parameters, like a [CLS] token in a ViT, and they carry the answers out of the transformer.
| Token | Count | Purpose |
|---|---|---|
| IoU token | 1 | Its final state is fed to an MLP that predicts one quality score per mask. |
| Mask tokens | 4 | Each one produces one mask. Token 0 serves single-mask output, and tokens 1 to 3 serve the three-mask output for ambiguous prompts. |
| Prompt tokens | 1 per point, 2 per box | Positional and label information from the prompt encoder. |
This layout explains the multimask_output flag in SamPredictor.predict. The decoder always computes all four masks. With multimask_output=True the package returns masks 1 to 3. With multimask_output=False it returns only mask 0. The next chapter explains why the multi-mask outputs exist. Here the point is that no extra computation is involved. You are choosing which of the four decoder outputs to keep.
Two-way attention
The decoder is a stack of two blocks. Each block uses a "two-way" attention scheme, so information flows from the prompt to the image and back. A block does four things in order:
- Self-attention over the tokens. The output tokens and prompt tokens exchange information with each other.
- Cross-attention from tokens to the image. The tokens are the queries, and the 4,096 image embedding positions are the keys and values. The tokens look up what is in the image.
- A pointwise MLP on the tokens.
- Cross-attention from the image to the tokens. The image positions are the queries, and the tokens are the keys and values. Each image location is updated according to the prompt.
Step 4 is what makes this different from a standard transformer decoder. The image embedding is rewritten after seeing the prompt, so the features that make the final mask are prompt-conditioned. After the second block, one more token-to-image attention layer produces the final token states.
Two implementation details matter for debugging. First, the positional encoding of the image grid is added to the keys at every attention layer, and the original prompt tokens (with their positional information) are re-added to the queries and keys at every layer. Second, the cross-attention layers project to half the embedding dimension (128), which keeps the cost low.
From tokens to masks
After attention, two things happen in parallel.
Upscaling. The updated image features go through two transposed convolutions. These raise the resolution 4× (64×64 to 256×256) and reduce the channels from 256 to 32.
Dynamic mask heads. Each mask token's final state goes through a small three-layer MLP. The MLP outputs a 32-dimensional vector. That vector is used as the weights of a linear classifier applied at every pixel of the upscaled features. In effect, each mask token predicts the weights that decide which pixels belong to its mask. A single dot product per pixel yields one logit map per token.
The IoU token goes through its own MLP and outputs one score per mask token. This score is a prediction of how well each mask overlaps the true object. It is not a measured value.
The result is four 256×256 logit maps and four scores. A logit above 0 means "inside the mask" because the package thresholds at mask_threshold = 0.0.
What the predictor does around the decoder
SamPredictor.predict wraps the decoder with a few steps that are easy to forget:
- It transforms your point and box coordinates to the resized input frame, where the longest image side is 1024 pixels.
- It runs the prompt encoder and the decoder.
- It bilinearly upsamples the 256×256 logits to the padded 1024×1024 frame, crops away the padding, and resizes to your original image size.
- It thresholds the result at 0 to give boolean masks.
The third return value of predict is the raw 256×256 logits. These are the low-resolution outputs, still in the padded square frame. They are the right thing to pass back as mask_input, as the refinement chapter shows. They are not the right thing to overlay on your original image without cropping and resizing.
Inspecting the decoder in code
The following script measures how small and fast the decoder is. It reuses the checkpoint from earlier chapters. It prints the parameter counts, times the one-off set_image call, and then times repeated predict calls on the cached embedding.
import time
import cv2
import numpy as np
import torch
from segment_anything import sam_model_registry, SamPredictor
device = "cuda" if torch.cuda.is_available() else "cpu"
sam = sam_model_registry["vit_b"](checkpoint="sam_vit_b_01ec64.pth")
sam.to(device=device)
predictor = SamPredictor(sam)
def n_params(module):
return sum(p.numel() for p in module.parameters())
print("image encoder :", n_params(sam.image_encoder))
print("prompt encoder:", n_params(sam.prompt_encoder))
print("mask decoder :", n_params(sam.mask_decoder))
def sync():
if device == "cuda":
torch.cuda.synchronize()
image = cv2.cvtColor(cv2.imread("photo.jpg"), cv2.COLOR_BGR2RGB)
t0 = time.perf_counter()
predictor.set_image(image)
sync()
print(f"set_image: {time.perf_counter() - t0:.3f} s")
h, w = image.shape[:2]
runs = 20
t0 = time.perf_counter()
for i in range(runs):
# A different point each time, so every call really re-runs the decoder.
point = np.array([[(i + 1) * w // (runs + 1), h // 2]])
masks, scores, logits = predictor.predict(
point_coords=point,
point_labels=np.array([1]),
multimask_output=True,
)
sync()
print(f"predict : {(time.perf_counter() - t0) / runs * 1000:.1f} ms per call")
print(masks.shape, logits.shape) # (3, H, W) and (3, 256, 256)On a GPU you should see predict run orders of magnitude faster than set_image. The prompt encoder holds only a few thousand parameters. The exact timings depend on your hardware, and the first calls include warm-up costs.
You can also confirm the thresholding rule yourself. Request logits at full resolution and compare:
point = np.array([[w // 2, h // 2]])
label = np.array([1])
bool_masks, _, _ = predictor.predict(
point_coords=point, point_labels=label, multimask_output=True
)
full_logits, _, _ = predictor.predict(
point_coords=point, point_labels=label, multimask_output=True,
return_logits=True,
)
same = (full_logits > predictor.model.mask_threshold) == bool_masks
print(same.all()) # TrueHow the decoder was trained
The training objective explains several behaviors you will see later.
- Mask loss. A weighted sum of focal loss and Dice loss, with a 20:1 ratio in favor of focal loss.
- Quality loss. The IoU head is trained with mean squared error against the actual IoU of each predicted mask with the ground truth.
- Minimum-loss rule for ambiguity. When the decoder predicts several masks, the loss is computed for each one, but only the lowest is back-propagated. The masks can therefore specialize in different interpretations, such as part, object, and group.
- Simulated interaction. Training simulates 11 rounds of prompting per mask. The first prompt is a random foreground point or a box. Later points are sampled from the error regions of the previous prediction, and the previous mask's logits are fed back as input.
Single-mask output (token 0) is used when a prompt has several points or a box, because those prompts are usually unambiguous. Only the multi-mask tokens receive the minimum-loss treatment on the first, single-point prompt. For this reason, the single-mask output of a lone point can be worse than the best of the three multi-mask outputs.
Common errors
- Re-running
set_imagefor every prompt. This repeats the expensive encoder pass. Call it once per image and callpredictas many times as you like. - Overlaying
logitsdirectly on the image. The third return value is 256×256 in the padded 1024 frame. Use the first return value for display, orreturn_logits=Truefor full-resolution logits. - Reading
scoresfrom a single-mask call as a ranking. Withmultimask_output=Falseyou get one mask and one score, so there is nothing to rank. - Expecting pixel-perfect edges. The decoder works from a 256×256 prediction, which was upsampled. Thin structures and sharp corners can be blurred.
- Feeding the wrong shape as
mask_input. It must have shape(1, 256, 256), so index one mask fromlogitsand add a leading axis.
Exercise
The decoder always computes four mask tokens. What does multimask_output=True actually change in SamPredictor.predict, and does it cost extra decoder compute?
Show answer
It only changes which outputs are returned. With True you get mask tokens 1 to 3 (three masks and three scores). With False you get token 0 (one mask and one score). The decoder computes all four either way, so there is no extra compute.
Exercise
Why is the decoder cheap to run repeatedly on the same image, and what is cached between calls?
Show answer
The decoder works on the cached image embedding (256x64x64) and a handful of tokens, and it has about 4 million parameters. set_image stores the embedding, so each predict call runs only the prompt encoder and decoder, not the heavy image encoder.
Exercise
A colleague overlays the third value returned by predict on the original photo and finds it misaligned and blocky. Name the two reasons.
Show answer
The value is 256x256 low-resolution logits, not full-size masks. It also lives in SAM's padded 1024x1024 input frame, so it must be cropped and resized to match the original image. Use the boolean masks (the first value), or return_logits=True, for display.