Sub topic 4
Encoding prompts
This chapter covers the prompt encoder in SAM, the Segment Anything Model. It assumes you know the three-part layout from the previous chapters: a heavy image encoder, a light prompt encoder, and a mask decoder. You should also be comfortable with PyTorch tensors and with the idea of positional encoding in transformers.
What the prompt encoder has to do
The image encoder turns an image into one embedding of shape 256 x 64 x 64. The mask decoder then needs the user's prompt in a form it can attend to. A prompt is a few pixel coordinates, a box, or a rough mask, and none of these look like image features. The prompt encoder converts each one into vectors of the same width, 256, that the decoder uses.
SAM splits prompts into two families, and each family gets a different treatment.
| Family | Prompt types | Encoded as | Shape |
|---|---|---|---|
| Sparse | Points, boxes, text | A set of 256-dimensional tokens | `(B, N, 256)` |
| Dense | Masks | A feature map added to the image embedding | `(B, 256, 64, 64)` |
The encoder is very small. It has about 6,000 trainable parameters, while the image encoder has tens of millions. The cost of a prompt is negligible next to the cost of the image, which is why you can change prompts in real time.
Sparse prompts: points
A point has two parts, a position and a label. The encoder handles them separately and then sums them.
- Position. The (x, y) coordinate is shifted by 0.5 pixels to the pixel center and divided by the input size (1024) to land in [0, 1]. It is then mapped to [-1, 1] and multiplied by a fixed random Gaussian matrix of shape
2 x 128. The encoder applies sine and cosine to the result, which gives 128 + 128 = 256 numbers. These are random Fourier features. The matrix is not trained, but it is stored in the checkpoint as a buffer, so a checkpoint always pairs with its own matrix. - Label. The encoder adds a learned 256-dimensional vector chosen by the label. Label 1 (foreground) and label 0 (background) each have their own vector.
- Padding. Label -1 means "not a point". Its position encoding is zeroed and replaced by a separate learned
not_a_pointvector.
Padding exists for a reason. When you give points but no box, the encoder appends one extra point with label -1. This keeps the token count consistent with training, where a box was sometimes present. A prompt with two points therefore yields three sparse tokens, not two.
Sparse prompts: boxes
A box is treated as two points, its top-left and bottom-right corners. Each corner gets the same positional encoding as a point. Then each gets its own learned corner embedding, one for "top-left" and one for "bottom-right". A box yields exactly two tokens and no padding token. When you pass points and a box together, the point tokens come first and the two corner tokens follow.
Sparse prompts: text
The SAM paper also describes text prompts. It used the text encoder of CLIP, a model that places images and text in a shared embedding space. During training, SAM was given the CLIP image embedding of an object. At test time the CLIP text embedding stands in for it. The paper presents this as a proof of concept. The public segment_anything package has no text input, so predict accepts only points, boxes, and masks. Combining SAM with a text-to-box detector is the usual workaround, and it needs other models.
Dense prompts: masks
A mask prompt is a previous prediction that you want the model to improve. It must be a 1 x 256 x 256 array of low-resolution logits. That is 4 times smaller than the 1024 input. The prompt encoder downscales it with a small stack:
- A 2x2 convolution with stride 2 to 4 channels, then layer normalization and GELU.
- A 2x2 convolution with stride 2 to 16 channels, then layer normalization and GELU.
- A 1x1 convolution to 256 channels.
The output is 256 x 64 x 64, the same grid as the image embedding. The decoder adds it to the image embedding element by element. If you give no mask, the encoder adds a learned no_mask vector, repeated over all 64 x 64 positions. A first-time prompt therefore still gets a dense input, but it carries no spatial information.
Looking at the encoder directly
You do not normally call the prompt encoder yourself, because SamPredictor.predict does it. Calling it once is the quickest way to confirm the shapes above. The key detail is the coordinate frame. The predictor resizes the image so its longest side is 1024, and the encoder expects coordinates in that resized frame. predictor.transform.apply_coords does the conversion.
import numpy as np
import torch
from segment_anything import sam_model_registry, SamPredictor
sam = sam_model_registry["vit_b"](checkpoint="sam_vit_b_01ec64.pth")
sam.eval()
predictor = SamPredictor(sam)
pe = sam.prompt_encoder
original_size = (750, 1000) # (height, width) of the original image
# (x, y) in original pixels -> 1024-long-side frame
pts = predictor.transform.apply_coords(np.array([[500, 375]]), original_size)
coords = torch.as_tensor(pts, dtype=torch.float)[None, :, :] # (1, 1, 2)
with torch.no_grad():
fg, dense = pe(points=(coords, torch.tensor([[1]])), boxes=None, masks=None)
bg, _ = pe(points=(coords, torch.tensor([[0]])), boxes=None, masks=None)
box = predictor.transform.apply_boxes(np.array([[425, 100, 700, 400]]), original_size)
box_tokens, _ = pe(points=None, boxes=torch.as_tensor(box, dtype=torch.float), masks=None)
prev = torch.zeros(1, 1, 256, 256)
_, dense_from_mask = pe(points=None, boxes=None, masks=prev)
print("one point :", fg.shape) # (1, 2, 256): point + padding token
print("one box :", box_tokens.shape) # (1, 2, 256): two corner tokens
print("no mask :", dense.shape) # (1, 256, 64, 64)
print("mask input:", dense_from_mask.shape) # (1, 256, 64, 64)
# Same position, different label: tokens differ only by the learned label vectors
diff = fg[0, 0] - bg[0, 0]
expected = (pe.point_embeddings[1].weight - pe.point_embeddings[0].weight)[0]
print("label-only difference:", torch.allclose(diff, expected, atol=1e-5))
# With no mask prompt, the dense embedding is identical at every location
print("constant map:", torch.allclose(dense[0, :, 0, 0], dense[0, :, 10, 10]))The last two checks show the design. Position and label are separable, and the no-mask case carries no spatial signal.
How the predictor feeds the encoder
Here is how the arguments of predict map onto the encoder inputs, so you can predict the token count.
| `predict` argument | Transformed by | Encoder input | Tokens produced |
|---|---|---|---|
| `point_coords`, `point_labels` (N points) | `apply_coords` | `points` | N, plus 1 padding token if no box |
| `box` | `apply_boxes` | `boxes` | 2 |
| `mask_input` | none, must be `1 x 256 x 256` | `masks` | dense map |
| none of the above | none | none | 1 padding token plus no-mask map |
The predictor converts numpy arrays to tensors and adds a batch dimension. It does not check that coordinates are in range. A coordinate outside the image still produces a valid-looking encoding, and the result is a poor mask with no error.
Common errors
- Swapping x and y. Points are
(x, y), meaning column then row. NumPy indexing is(row, col). A swapped point lands on a different object and the mask looks unrelated to your click. - Skipping the coordinate transform.
predictor.predicttransforms coordinates for you. If you callsam.prompt_encoderorpredict_torchyourself, you must pass 1024-frame coordinates. Raw coordinates on a 4000-pixel image fall far off the model's grid. - Wrong label dtype or values. Labels are integers: 1, 0, or -1. Using 2 for "maybe" does nothing useful, because it matches no learned embedding.
- Mask prompts at the wrong size.
mask_inputmust be the1 x 256 x 256logits from an earlier call. A full-resolution binary mask raises a shape error. Even at the right size, a binary mask is a poor input because the encoder was trained on soft logits. - Box in the wrong format. The box is
x_min, y_min, x_max, y_max. Ax, y, w, hbox, such as thebboxfield from the automatic generator, produces a wrong region. Convert it first. - Expecting a padding token with a box. Counting tokens by hand and finding a mismatch usually means a missed rule. Points only get the padding token when no box is present.
Why this design is useful
Keeping prompts separate from the image gives SAM its interactive speed. The image embedding is computed once, and each new prompt costs one pass through a tiny encoder and the light decoder. Using positional encodings for points and boxes means that any prompt in the 1024 frame is valid. A new prompt type needs only a new way to produce tokens or a dense map. This is how the text prompt was added without changing the image encoder.
Exercise
You call predict with three points and no box. How many sparse tokens does the prompt encoder produce, and why? How many if you add a box?
Show answer
Three points and no box gives four tokens: one per point plus one padding token with label -1. Adding a box makes the encoder skip padding, so you get three point tokens plus two box-corner tokens, five in total.
Exercise
You get a poor mask for a click at pixel (x=800, y=200) on a 1600x1200 image. You called predictor.predict correctly but, while debugging, you separately called sam.prompt_encoder with the raw coordinates (800, 200). What is wrong with the debugging call, and what should the coordinates be?
Show answer
The prompt encoder expects coordinates in the resized frame, where the longest side is 1024. The scale factor is 1024 / 1600 = 0.64, so the point should be (512, 128). Use predictor.transform.apply_coords(np.array([[800, 200]]), (1200, 1600)) to get it. Raw (800, 200) would be encoded as a position about 1.56 times too far from the origin.