Sub topic 3
The image encoder: one expensive pass per image
This chapter covers the largest part of the Segment Anything Model (SAM): the image encoder. It explains what the encoder produces, why it runs once per image, and what that means for your code. It assumes you know basic Python and NumPy, can load a pretrained PyTorch checkpoint, and have a rough idea of how a Vision Transformer (ViT) uses attention.
Where the encoder fits
SAM has three parts. The image encoder turns a picture into a feature map. The prompt encoder turns your points, boxes, or masks into vectors. The mask decoder combines the two and produces masks.
The image encoder holds almost all of the model's weights and does almost all of the computation. It is a Vision Transformer pretrained with masked autoencoding (MAE) and adapted for high-resolution input. Its output is called the image embedding. The embedding depends only on the image. It does not depend on any prompt.
Because of that, the design splits the work into two phases:
- A slow phase that runs once per image and builds the embedding.
- A fast phase that runs once per prompt and reads the embedding.
What the encoder does to your image
The encoder expects a fixed input size. The official package resizes the image so its longest side is 1024 pixels, keeps the aspect ratio, and pads the shorter side with zeros to make a 1024 x 1024 square. It also normalizes pixel values with the mean and standard deviation used during training.
The ViT then cuts the image into 16 x 16 pixel patches. A 1024 x 1024 input gives a 64 x 64 grid of patches. The transformer processes these patches and a small "neck" of convolutions produces the final embedding. For every checkpoint the embedding has shape (1, 256, 64, 64): one image, 256 channels, and a 64 x 64 spatial grid.
Each cell of the grid summarizes a region of about 16 x 16 pixels of the resized image. That is the resolution the decoder works from. The decoder upsamples to get finer masks, which is one reason thin structures and sharp edges can come out slightly rough.
Windowed attention
Full self-attention over 4096 patches (64 x 64) would be costly, because its cost grows with the square of the number of patches. SAM's encoder mostly uses windowed attention. Each patch attends only to patches inside a 14 x 14 window. A few layers (four in each checkpoint) use global attention so information can still travel across the whole image. Relative position information is added inside the attention layers.
Model sizes
The official package ships three checkpoints. They differ only in the size of the image encoder. The prompt encoder and mask decoder are the same in all of them.
| Checkpoint key | Encoder | Approximate parameters | Typical use |
|---|---|---|---|
| `vit_b` | ViT-B | 91 million | Low memory, fastest, lowest quality |
| `vit_l` | ViT-L | 308 million | Middle ground |
| `vit_h` | ViT-H | 636 million | Best quality, slowest |
The numbers are approximate. Check the model card for the exact figures if you need them.
Why one expensive pass per image makes sense
Suppose you want a mask for one object. You click once and the model returns a mask. If you are not happy, you click again. Each click is a new prompt on the same image.
If the encoder ran for every click, every click would cost a full ViT-H forward pass. That is a few hundred milliseconds on a strong GPU, and far longer on a CPU. By caching the embedding, each new prompt only costs a pass through the prompt encoder and the small mask decoder. That takes a few tens of milliseconds on a GPU, and the SAM authors report that the decoder runs fast enough for a browser. This is what makes interactive use practical.
The same property is useful outside of interactive tools:
- You can try many prompts on one image, such as one box per detected object, at almost no extra cost.
- You can refine a mask with extra points without recomputing anything heavy.
- You can compute embeddings once on a server, store them, and run only the decoder on a client.
The trade-off is that the embedding is tied to one image. Change the image, even slightly, and you must pay for the encoder again.
Running the encoder with SamPredictor
In the official package, SamPredictor.set_image runs the encoder and stores the result. Later predict calls reuse it.
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)
image = cv2.cvtColor(cv2.imread("photo.jpg"), cv2.COLOR_BGR2RGB)
predictor.set_image(image) # the expensive pass
emb = predictor.get_image_embedding()
print(emb.shape) # torch.Size([1, 256, 64, 64])
print(predictor.original_size, predictor.input_size) # (H, W) before and after resizingTwo details matter here:
set_imageexpects an RGBuint8array of shape(H, W, 3). OpenCV loads images as BGR, so thecvtColorcall is required. Passing BGR does not raise an error. It silently gives worse masks.original_sizeandinput_sizeare stored so that later prompts, given in original pixel coordinates, can be rescaled into the 1024-pixel frame. You pass coordinates in the original image's pixels and the predictor handles the mapping.
You can measure the split between the two phases yourself:
import time
def timed(fn, *args, **kwargs):
if torch.cuda.is_available():
torch.cuda.synchronize()
start = time.perf_counter()
out = fn(*args, **kwargs)
if torch.cuda.is_available():
torch.cuda.synchronize()
return out, time.perf_counter() - start
_, t_encode = timed(predictor.set_image, image)
(masks, scores, _), t_predict = timed(
predictor.predict,
point_coords=np.array([[500, 375]]),
point_labels=np.array([1]),
multimask_output=True,
)
print(f"encoder: {t_encode:.3f}s decoder: {t_predict:.3f}s")The synchronize calls matter on a GPU. CUDA runs asynchronously, so without them the timer can stop before the work finishes. The first call is also slower because of warm-up, so run the measurement twice and trust the second result.
The embedding is cached state
Because the predictor stores the embedding inside itself, it behaves like a small state machine. Knowing its states helps you avoid several common errors.
The consequences:
- Calling
predictbeforeset_imageraises aRuntimeError, because there is no embedding yet. - Calling
set_imagea second time discards the first embedding. If you need to prompt two images in alternation, you pay the encoder cost on each switch. Either use two predictor objects (both embeddings stay in memory) or process one image fully before moving on. reset_imageclears the stored embedding and frees GPU memory.
Memory and speed in practice
The embedding itself is small: 256 x 64 x 64 float32 values is 4 MiB. The encoder's activations and weights are what use memory. Weights for vit_h alone are about 2.5 GB in float32, and the forward pass needs more on top.
Practical points:
- If you run out of GPU memory, switch to
vit_bor run on CPU. On a CPU,vit_hcan take many seconds per image, which is whyvit_bis a common choice for experiments. - Wrap inference in
torch.no_grad()if you call the model parts directly.SamPredictoralready does this insideset_imageandpredict. - The input is always resized to 1024 on the long side, so a 4000 x 3000 photo and a 640 x 480 photo cost the same to encode. Small objects in a large photo lose detail through the downscale. If that is a problem, crop the region of interest and encode the crop.
- Each embedding is tied to the exact image you gave. If you crop, the box and point coordinates must be in the crop's pixel frame.
Saving and reusing embeddings
Since the embedding is only 4 MiB, you can keep it on disk. The official package does not offer a one-line API for loading a saved embedding into SamPredictor, but the pieces are public. You can save the tensor and the two sizes, then restore the predictor's internal state.
import torch
emb = predictor.get_image_embedding().cpu()
torch.save(
{
"embedding": emb,
"original_size": predictor.original_size,
"input_size": predictor.input_size,
},
"photo_embedding.pt",
)saved = torch.load("photo_embedding.pt")
predictor.reset_image()
predictor.features = saved["embedding"].to(sam.device)
predictor.original_size = saved["original_size"]
predictor.input_size = saved["input_size"]
predictor.is_image_set = True
masks, scores, _ = predictor.predict(
point_coords=np.array([[500, 375]]),
point_labels=np.array([1]),
multimask_output=True,
)This relies on attribute names inside SamPredictor (features, original_size, input_size, is_image_set). They are not a documented interface and may change between versions, so pin your segment_anything version if you depend on this.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `RuntimeError` saying an image must be set | `predict` called before `set_image` | Call `set_image` first |
| Masks look wrong or shifted | BGR image, or coordinates given in the resized frame | Convert to RGB, and pass coordinates in original image pixels |
| Out-of-memory in `set_image` | `vit_h` on a small GPU | Use `vit_b` or `vit_l`, or run on CPU |
| Masks for the wrong image after switching | Forgot to call `set_image` for the new image | Call `set_image` again, or keep one predictor per image |
| Timings show a tiny encoder cost on GPU | No `torch.cuda.synchronize()` | Synchronize before and after the timed call |
Summary
The image encoder is a large ViT that converts a 1024 x 1024 resized, padded image into a (1, 256, 64, 64) embedding. It runs once per image through set_image. The prompt encoder and mask decoder then answer each prompt quickly by reusing that embedding. This split is what lets SAM feel interactive, and it explains most of the practical advice above: pick the model size for your hardware, encode once, prompt many times, and expect to re-encode when the image changes.
Exercise
You have 200 photos and want to run 15 different box prompts on each one. How many times should you call set_image and how many times predict, and why? Which checkpoint choice affects the cost of the set_image calls but not the predict calls?
Show answer
Call set_image 200 times (once per photo) and predict 3000 times (15 per photo, 200 x 15). The embedding depends only on the image, so it can be reused for all 15 boxes on that photo. The checkpoint choice (vit_b, vit_l, or vit_h) changes the size of the image encoder, so it affects set_image cost. The prompt encoder and mask decoder are identical across checkpoints, so predict cost stays about the same.
Exercise
A colleague loads a photo with cv2.imread, passes it directly to set_image, and finds that the masks are of poor quality but no error appears. What is the likely cause, and what shape and dtype should the array have?
Show answer
OpenCV returns channels in BGR order, but SAM expects RGB, so the colors are swapped and no error is raised. Convert with cv2.cvtColor(img, cv2.COLOR_BGR2RGB). The array should be uint8 with shape (H, W, 3).
Exercise
The embedding returned by get_image_embedding() has shape (1, 256, 64, 64). Explain where the 64 x 64 comes from, and say how large in input pixels the area covered by one grid cell is.
Show answer
The image is resized so its long side is 1024 pixels and padded to 1024 x 1024. The ViT uses 16 x 16 pixel patches, and 1024 / 16 = 64, which gives a 64 x 64 grid. Each cell therefore covers about 16 x 16 pixels of the resized image.