AI Wiki中文/EN

Segment Anything: a prompt chooses what the mask should mean

Segment Anything

Follow point, box and mask prompts through SAM's two-way decoder, explain ambiguous outputs and coordinate transforms, and distinguish SAM, SAM 2 and SAM 3.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A click on a sleeve does not specify its owner

Imagine clicking a person’s sleeve in a photograph. Do you want the sleeve, the shirt or the whole person? The click provides a location, but not a complete definition of the object. Treating every other interpretation as an error would make an ambiguous request look falsely precise.

The original Segment Anything Model, or SAM, treats segmentation as a prompt-conditioned task. Points, a box or an earlier mask indicate the intended region; the model predicts plausible membership masks. Multiple outputs can preserve ambiguity until further input resolves it. A mask is not automatically a semantic class label, and three alternatives for one prompt are not three independently discovered objects. Task and model description

Alexander Kirillov and coauthors submitted Segment Anything on 5 April 2023. Here, “original SAM” means that image model and a fixed public inference implementation. Later SAM 2 and SAM 3 change the task and system in specific ways, described below; this article’s small program implements the original-style prompt encoder and mask decoder, not the entire family. First-submission record

The useful architectural split is to process the image once and reuse its features across prompts. A user can add a negative point or refine a mask without running the heavy image encoder again. If image encoding costs TIT_I, one prompt/decode costs TPT_P and there are n interactions, the idealized serial cost is:

Ttotal=TI+nTP,T‾=TP+TIn.T_{\mathrm{total}}=T_I+nT_P,\qquad \overline T=T_P+\frac{T_I}{n}.

This excludes image loading, output transfer and other overhead. A fast prompt response therefore does not imply a fast first response or end-to-end image encoding. The public predictor stores the image embedding and reuses it for subsequent calls. Predictor and image cache

Computed reduced SAM decoder path: a cached 2 by 3 by 32 image embedding and two sparse prompt tokens feed two-way attention, four mask logits, and separate single or three-mask selection.
Original diagram from the executable example. The shapes describe random-parameter computation, not pretrained segmentation quality.

Follow the prompt, the image and the output tokens

Encode the image once; encode each request separately

The paper’s default image encoder uses an MAE-pretrained ViT-H/16 adapted with windowed and periodic global attention. It scales and pads the input to 1024×1024, produces a 64×64 spatial grid, and projects features to 256 channels. The fixed builder also specifies two decoder blocks and eight attention heads. Those dimensions explain the original system; the example below deliberately uses smaller supplied features. Architecture appendix, fixed builder

A sparse prompt becomes one or more vectors. A dense prompt retains a spatial grid. The fixed point encoder uses random Fourier features of normalized XY coordinates. For normalized coordinate u and fixed Gaussian frequency matrix B, its position map is:

ϕ(u)=[sin⁡ ⁣(2π(2u−1)B),  cos⁡ ⁣(2π(2u−1)B)].\phi(u)=\left[\sin\!\left(2\pi(2u-1)B\right),\;\cos\!\left(2\pi(2u-1)B\right)\right].

B is a stored random buffer rather than a freshly resampled matrix per click. Moving a point changes its position vector reproducibly. The coordinates are shifted to pixel centers before dividing x by the padded image width and y by its height. A foreground or background point adds a different learned type vector:

epoint=ϕ ⁣(x+1/2WI,y+1/2HI)+tℓ,ℓ∈{0,1}.e_{\mathrm{point}}=\phi\!\left(\frac{x+1/2}{W_I},\frac{y+1/2}{H_I}\right)+t_{\ell},\qquad \ell\in\{0,1\}.

A box contributes two vectors, with distinct top-left and bottom-right corner types. A missing-point label −1 discards the coordinate vector and uses a learned placeholder. If points are supplied without a box, the fixed implementation appends another placeholder. Supplying no point argument and supplying an empty point array are consequently different code paths. The placeholder is still a token; it is not an attention mask that deletes a position. Complete prompt encoder

An earlier low-resolution mask is supplied as unthresholded logits, not just a binary foreground map. Two stride-two convolutions with channel normalization and GELU reduce its height and width by four; a 1×1 projection reaches the image-feature channel count. The result is added to image features. With no mask prompt, a learned no-mask vector is added at each location. A zero-valued mask prompt is not equivalent to omitting the mask. Prompt encoder, normalization and MLP helpers

Information moves in both directions

Concatenate learned output tokens with sparse prompt tokens. Each of the two decoder blocks performs four operations: token self-attention, token-to-image cross-attention, a token MLP, then image-to-token cross-attention. The final operation matters: image features become conditioned on the current request, rather than remaining passive keys and values throughout decoding.

Within one attention head of width dhd_h, projected queries, keys and values use the familiar scaled weighted sum:

Attention⁡(Q,K,V)=softmax⁡ ⁣(QKTdh)V.\operatorname{Attention}(Q,K,V)=\operatorname{softmax}\!\left(\frac{QK^{\mathsf T}}{\sqrt{d_h}}\right)V.

For token-to-image attention, rows of Q correspond to tokens and rows of K,V to image locations. Reverse those roles for image-to-token attention. The original cross-attention projections halve the 256-dimensional channel width to 128 before splitting into heads. This reduces arithmetic without changing the number of spatial locations. Initial prompt vectors and image positions are reintroduced in the specified query/key paths. Fixed two-way Transformer

There is an implementation detail worth checking instead of assuming every block is identical: the first token self-attention has neither the additional original-prompt encoding nor residual addition. Later self-attention blocks do. After both blocks, one more token-to-image attention and normalization run before the decoder upscales the image features. The program follows this public inference graph. It does not copy the paper’s prose ordering into a different execution order, and it does not claim to reproduce the training-time dropout recipe. Fixed block ordering

Each output token builds a different pixel classifier

The updated image grid is enlarged by two 2×2, stride-two transposed convolutions. In the original configuration, channels go from 256 through 64 to 32 while each spatial side grows fourfold. Each mask token passes through its own three-layer MLP to produce a vector with the same channel count as the enlarged features. A dot product at each location then gives a mask logit:

zj(y,x)=wjTU(y,x),wj=MLP⁡j(tj).z_j(y,x)=w_j^{\mathsf T}U(y,x),\qquad w_j=\operatorname{MLP}_j(t_j).

The vector wjw_j changes with the prompt through token decoding. This is a dynamic pixel classifier, not a fixed category head like the class-indexed mask channels in Mask R-CNN. A separate output token feeds an MLP that predicts mask quality, trained to estimate IoU. Its public implementation has no final sigmoid, so its raw estimates are not mathematically constrained to [0,1]. Mask decoder and output MLPs

Internally there are four mask tokens plus one quality token. Multi-mask mode returns mask indices 1–3; single-mask mode returns index 0. Disabling multi-mask mode does not select the highest-scoring mask from the other three. To select the best of those three, explicitly use their quality scores. The API exposes this choice to the caller; it does not automatically switch modes whenever the click count changes. Output slicing, public prediction options

For an ambiguous training prompt, the paper computes candidate mask losses and backpropagates through the lowest-loss candidate. Its mask supervision combines focal and Dice losses with weights 20:1:

Lambiguous=min⁡j∈J(20Lfocal(zj,y)+LDice(zj,y)).L_{\mathrm{ambiguous}}=\min_{j\in\mathcal J}\left(20L_{\mathrm{focal}}(z_j,y)+L_{\mathrm{Dice}}(z_j,y)\right).

Focal loss emphasizes difficult pixel decisions; Dice loss compares soft foreground overlap. Their smoothing and reduction conventions belong to a concrete training implementation. This expression records the paper’s weighting and candidate-selection rule rather than inventing unspecified implementation details. The quality head uses MSE against measured mask IoU with weight 1. The small program below performs inference only; it does not implement these training losses or claim verified training gradients. Training appendix

Coordinates survive resizing only if the rounding does too

Let the original image size be H×W. The longest-side resize computes integer dimensions H′,W′ by rounding the scaled dimensions. Points must use those actual dimensions:

x′=xW′W,y′=yH′H.x'=x\frac{W'}W,\qquad y'=y\frac{H'}H.

For a 333×1000 image resized to long side 1024, the result is 341×1024. The x scale is 1.024, but the y scale is 341/333. Reusing 1.024 for both axes introduces a small coordinate discrepancy. These coordinates then enter the prompt encoder’s pixel-center and normalization convention. Longest-side transformation

For final masks, the fixed model first bilinearly upsamples low-resolution logits to the padded square, crops the right/bottom padding, and resizes to the original image. It applies a strict zero-logit threshold only afterward. The example implements this logit interpolation order, not a replacement for every PIL/antialiased image-resize path. Mask postprocessing, image and tensor transform distinction

“Automatic” generation still supplies prompts

Automatic mask generation samples a point grid, predicts candidate masks and filters them. Predicted IoU is a learned estimate; stability asks whether the mask changes under nearby logit thresholds. With central threshold t and offset δ, let the high-threshold foreground set be A and the low-threshold set B. For nonnegative δ, A is contained in B:

S=∣A∣∣B∣,A={z>t+δ},B={z>t−δ}.S=\frac{|A|}{|B|},\qquad A=\{z>t+\delta\},\quad B=\{z>t-\delta\}.

This is overlap between two predictions, not IoU against a GT mask. The fixed helper leaves a zero union undefined. The example returns NaN for that case instead of assigning a perfect stability score. With default t=0 and δ=1, values exactly equal to a threshold are excluded because the comparisons are strict. Stability helper

The public generator defaults include a 32×32 point grid, predicted-IoU threshold 0.88, stability threshold 0.95 and box-NMS threshold 0.7. The first filter uses greater than 0.88; the second uses greater than or equal to 0.95. Default extra crop layers and small-region cleanup are both disabled. The paper’s SA-1B data-generation recipe instead used additional crops, postprocessing and a specially trained model; do not treat the public defaults as a reproduction of that dataset pipeline. Generator defaults and filtering, data-generation appendix

A complete small prompt-to-mask computation

This original Python 3.12/NumPy 1.26.4 program supplies one 2×3×32 image embedding and a single prompt set. Its rectangular grid is a permitted teaching configuration, not the output of the original square ViT pipeline. It implements sparse and dense prompt encoding, both two-way blocks, final attention, upscaling, all four dynamic mask heads, quality prediction and output selection. The weights are random; changing a point shows dependence on the prompt, not learned object understanding.

QuantityOriginal defaultThis example
Image embedding64×64×256Supplied 2×3×32
Decoder blocks / heads2 / 82 / 4
Token MLP width204864
Sparse vectors for one point without a box22
Tokens including outputs77
Enlarged mask features256×256×328×12×4
Internal / multi / single mask counts4 / 3 / 14 / 3 / 1

For P image locations, T tokens and total projected width d, cross-attention scores require O(TPd) arithmetic; token self-attention uses O(T²d). Projection and MLP work also depend on channel widths. This decoder avoids dense P×P image self-attention at every click, but the image encoder has its own cost. The NumPy loops and stored activations here are designed for small examples, not a latency claim for a browser or GPU.

"""Original reduced SAM-style prompt encoder and complete mask-decoder forward.

Single supplied HWC image embedding, one prompt set, no image encoder/training.
Float64 random parameters show computation, not useful pretrained segmentation.
Follows the explicitly studied SAM1 inference graph, not SAM2/SAM3 interfaces.
"""
import json
import math
import numpy as np


def shape2(value):
    if len(value) != 2 or any(type(n) is not int or n < 1 for n in value):
        raise ValueError('two positive integer dimensions required')
    return tuple(value)


def array(value, dimensions):
    x = np.asarray(value, float)
    if x.ndim != dimensions or not np.isfinite(x).all():
        raise ValueError('finite array with the specified rank required')
    return x


def linear(x, parameters):
    w, b = parameters
    return x @ w + b


def norm(x, parameters, eps=1e-5):
    weight, bias = parameters
    centered = x-x.mean(axis=-1, keepdims=True)
    return centered/np.sqrt(np.mean(centered**2, axis=-1, keepdims=True)+eps)*weight+bias


def gelu(x):
    return .5*x*(1+np.vectorize(math.erf, otypes=[float])(x/np.sqrt(2)))


def mlp(x, layers):
    for i, p in enumerate(layers):
        x = linear(x, p)
        if i+1 < len(layers):
            x = np.maximum(x, 0)
    return x


def attention(q, k, v, parameters, heads):
    q, k, v = [linear(x, parameters[name]) for x, name in zip([q, k, v], ['q', 'k', 'v'])]
    width = q.shape[-1]
    if width % heads or len(k) != len(v) or len(k) == 0:
        raise ValueError('compatible heads and nonempty key/value sequences required')
    d = width//heads
    q, k, v = [x.reshape(len(x), heads, d).transpose(1, 0, 2) for x in [q, k, v]]
    score = q @ k.transpose(0, 2, 1)/np.sqrt(d)
    score -= score.max(axis=-1, keepdims=True)
    weights = np.exp(score)
    weights /= weights.sum(axis=-1, keepdims=True)
    mixed = (weights@v).transpose(1, 0, 2).reshape(q.shape[1], width)
    return linear(mixed, parameters['out'])


def conv_stride2(x, parameters):
    kernel, bias = parameters
    if x.shape[0] % 2 or x.shape[1] % 2:
        raise ValueError('even spatial dimensions required')
    out = np.broadcast_to(bias, (x.shape[0]//2, x.shape[1]//2, len(bias))).copy()
    for y in range(2):
        for z in range(2):
            out += x[y::2, z::2] @ kernel[y, z]
    return out


def transpose2(x, parameters):
    kernel, bias = parameters
    out = np.broadcast_to(bias, (2*x.shape[0], 2*x.shape[1], len(bias))).copy()
    for y in range(2):
        for z in range(2):
            out[y::2, z::2] += x @ kernel[y, z]
    return out


def make_parameters(width=32, heads=4, depth=2, seed=19):
    if any(type(n) is not int or n < 1 for n in [width, heads, depth]) or width % 8 or (width//2) % heads:
        raise ValueError('width divisible by eight; heads must divide half-width')
    rng = np.random.default_rng(seed)
    def fc(a, b):
        return [rng.normal(0, 1/np.sqrt(a), (a, b)), rng.normal(0, .01, b)]
    def ln(c):
        return [np.ones(c), np.zeros(c)]
    def conv(a, b):
        return [rng.normal(0, 1/np.sqrt(4*a), (2, 2, a, b)), np.zeros(b)]
    def att(rate):
        inner = width//rate
        return {**{key: fc(width, inner) for key in ['q', 'k', 'v']}, 'out': fc(inner, width)}
    def layers(out):
        return [fc(width, width), fc(width, width), fc(width, out)]
    blocks = [{'self': att(1), 'to_image': att(2), 'to_tokens': att(2),
               'mlp': [fc(width, 2*width), fc(2*width, width)],
               'norms': [ln(width) for _ in range(4)]} for _ in range(depth)]
    return {'width': width, 'heads': heads,
            'frequencies': rng.normal(size=(2, width//2)),  # Frozen random Fourier buffer.
            'point_types': rng.normal(0, .1, (4, width)),
            'not_point': rng.normal(0, .1, width), 'no_mask': rng.normal(0, .1, width),
            'mask_down': [conv(1, 4), ln(4), conv(4, 16), ln(16), fc(16, width)],
            'output_tokens': rng.normal(0, .1, (5, width)),  # IoU then four mask tokens.
            'blocks': blocks, 'final_attention': att(2), 'final_norm': ln(width),
            'up': [conv(width, width//4), ln(width//4), conv(width//4, width//8)],
            'hyper': [layers(width//8) for _ in range(4)], 'quality': layers(4)}


def position(coords, frequencies):
    coords = array(coords, 2)
    if coords.shape[1] != 2:
        raise ValueError('XY coordinate pairs required')
    phase = 2*np.pi*((2*coords-1)@frequencies)
    return np.concatenate([np.sin(phase), np.cos(phase)], axis=-1)


def grid_position(grid_shape, frequencies):
    h, w = shape2(grid_shape)
    y, x = np.indices((h, w))
    coords = np.stack([(x+.5)/w, (y+.5)/h], axis=-1)
    return position(coords.reshape(-1, 2), frequencies).reshape(h, w, -1)


def encode_prompts(p, grid_shape, image_shape, points=None, labels=None, box=None, mask=None):
    h, w = shape2(grid_shape)
    ih, iw = shape2(image_shape)
    sparse = []
    if points is None and labels is not None:
        raise ValueError('labels require points')
    if points is not None:
        points = array(points, 2)
        labels = np.asarray(labels)
        if points.shape[1] != 2 or labels.shape != (len(points),) or labels.dtype.kind not in 'iu' or not np.isin(labels, [-1, 0, 1]).all():
            raise ValueError('XY points with integer labels -1,0,1 required')
        emb = position((points+.5)/[iw, ih], p['frequencies'])
        for i, label in enumerate(labels):
            emb[i] = p['not_point'] if label == -1 else emb[i]+p['point_types'][int(label)]
        sparse.extend(emb)
        if box is None:
            sparse.append(p['not_point'].copy())
    if box is not None:
        box = array(box, 1)
        if box.shape != (4,) or np.any(box[2:] <= box[:2]):
            raise ValueError('one strictly positive XYXY box required')
        corners = position((box.reshape(2, 2)+.5)/[iw, ih], p['frequencies'])
        sparse.extend(corners+p['point_types'][2:4])
    sparse = np.asarray(sparse, float).reshape(-1, p['width'])
    if mask is None:
        dense = np.broadcast_to(p['no_mask'], (h, w, p['width'])).copy()
    else:
        mask = array(mask, 2)
        if mask.shape != (4*h, 4*w):
            raise ValueError('mask logits must have four times the embedding height/width')
        a, n1, b, n2, c = p['mask_down']
        dense = gelu(norm(conv_stride2(mask[..., None], a), n1, 1e-6))
        dense = gelu(norm(conv_stride2(dense, b), n2, 1e-6))
        dense = linear(dense, c)
    return sparse, dense


def two_way(p, image, pe, tokens):
    initial = tokens.copy()
    q = tokens.copy()
    k = image.reshape(-1, p['width']).copy()
    pe = pe.reshape(k.shape)
    trace = []
    for i, block in enumerate(p['blocks']):
        # Fixed public inference graph: first self-attention has neither
        # re-added prompt encoding nor residual addition; later blocks do.
        if i == 0:
            q = attention(q, q, q, block['self'], p['heads'])
        else:
            q = q+attention(q+initial, q+initial, q, block['self'], p['heads'])
        q = norm(q, block['norms'][0])
        q = norm(q+attention(q+initial, k+pe, k, block['to_image'], p['heads']), block['norms'][1])
        q = norm(q+mlp(q, block['mlp']), block['norms'][2])
        k = norm(k+attention(k+pe, q+initial, q, block['to_tokens'], p['heads']), block['norms'][3])
        trace.append({'tokens': list(q.shape), 'imageSequence': list(k.shape)})
    q = norm(q+attention(q+initial, k+pe, k, p['final_attention'], p['heads']), p['final_norm'])
    return q, k.reshape(image.shape), trace


def decode(p, image_embedding, sparse, dense, multimask=True):
    image = array(image_embedding, 3)
    sparse, dense = array(sparse, 2), array(dense, 3)
    if min(image.shape) < 1 or image.shape[-1] != p['width'] or sparse.shape[1] != p['width'] or dense.shape != image.shape or type(multimask) is not bool:
        raise ValueError('compatible image/prompt dimensions and boolean mode required')
    pe = grid_position(image.shape[:2], p['frequencies'])
    tokens = np.concatenate([p['output_tokens'], sparse])
    updated, spatial, trace = two_way(p, image+dense, pe, tokens)
    first, normalization, second = p['up']
    enlarged = gelu(norm(transpose2(spatial, first), normalization, 1e-6))
    enlarged = gelu(transpose2(enlarged, second))
    dynamic = np.stack([mlp(updated[1+i], p['hyper'][i]) for i in range(4)])
    all_masks = np.einsum('kc,hwc->khw', dynamic, enlarged)
    all_scores = mlp(updated[0], p['quality'])  # No sigmoid: estimates are not bounded.
    selection = slice(1, 4) if multimask else slice(0, 1)
    return {'logits': all_masks[selection], 'quality': all_scores[selection],
            'allLogits': all_masks, 'allQuality': all_scores,
            'trace': trace, 'upscaledShape': list(enlarged.shape)}


def resize_shape(original, target):
    h, w = shape2(original)
    if type(target) is not int or target < 1:
        raise ValueError('positive target side required')
    ratio = target/max(h, w)
    size = (int(h*ratio+.5), int(w*ratio+.5))
    if min(size) == 0:
        raise ValueError('aspect ratio rounds a dimension to zero')
    return size


def transform_coords(coords, original, target):
    coords = array(coords, 2)
    if coords.shape[1] != 2:
        raise ValueError('XY coordinates required')
    h, w = shape2(original)
    nh, nw = resize_shape(original, target)
    return coords*[nw/w, nh/h]


def resize_logits(masks, size):
    """Bilinear align_corners=False coordinates with border clamping; no antialias.

    Used only for logit upsampling, not as a substitute for SAM's PIL image resize.
    """
    masks = array(masks, 3)
    if min(masks.shape) < 1:
        raise ValueError('nonempty K,H,W logits required')
    oh, ow = shape2(size)
    _, h, w = masks.shape
    out = np.empty((len(masks), oh, ow))
    for row in range(oh):
        y = np.clip((row+.5)*h/oh-.5, 0, h-1)
        y0, y1 = int(y), min(int(y)+1, h-1)
        dy = y-y0
        for col in range(ow):
            x = np.clip((col+.5)*w/ow-.5, 0, w-1)
            x0, x1 = int(x), min(int(x)+1, w-1)
            dx = x-x0
            out[:, row, col] = ((1-dy)*((1-dx)*masks[:, y0, x0]+dx*masks[:, y0, x1])
                                  +dy*((1-dx)*masks[:, y1, x0]+dx*masks[:, y1, x1]))
    return out


def postprocess(logits, resized_shape, original_shape, padded_side):
    rh, rw = shape2(resized_shape)
    shape2(original_shape)
    if type(padded_side) is not int or padded_side < max(rh, rw):
        raise ValueError('padded side must contain the resized image')
    square = resize_logits(logits, (padded_side, padded_side))
    return resize_logits(square[:, :rh, :rw], original_shape)


def stability(logits, threshold=0., offset=1.):
    logits = array(logits, 3)
    if min(logits.shape[1:]) < 1 or not np.isfinite([threshold, offset]).all() or offset < 0:
        raise ValueError('finite threshold/nonnegative offset and spatial dimensions required')
    small = (logits > threshold+offset).sum(axis=(1, 2))
    large = (logits > threshold-offset).sum(axis=(1, 2))
    # Zero union remains undefined (NaN), rather than inventing a stable mask.
    return np.divide(small, large, out=np.full(len(logits), np.nan), where=large != 0)


def demo():
    p = make_parameters()
    image = np.random.default_rng(5).normal(size=(2, 3, p['width']))
    sparse, dense = encode_prompts(p, (2, 3), (16, 24), [[4., 5.]], [1])
    result = decode(p, image, sparse, dense)
    single = decode(p, image, sparse, dense, False)
    neg, nd = encode_prompts(p, (2, 3), (16, 24), [[4., 5.]], [0])
    changed = decode(p, image, neg, nd)
    mask = result['logits'][int(np.argmax(result['quality']))]
    rs, rd = encode_prompts(p, (2, 3), (16, 24), [[4., 5.]], [1], mask=mask)
    refined = decode(p, image, rs, rd, False)
    return {'embeddingShape': list(image.shape), 'sparseShape': list(sparse.shape),
            'allMaskShape': list(result['allLogits'].shape), 'multimaskShape': list(result['logits'].shape),
            'singleMaskShape': list(single['logits'].shape), 'upscaledShape': result['upscaledShape'],
            'trace': result['trace'], 'quality': result['quality'].tolist(),
            'negativePointLogitDifference': float(np.max(np.abs(result['logits']-changed['logits']))),
            'denseFeedbackLogitDifference': float(np.max(np.abs(single['logits']-refined['logits']))),
            'inputEmbeddingUnchanged': bool(np.array_equal(image, np.random.default_rng(5).normal(size=image.shape))),
            'scope': 'random-parameter SAM1-style decoder forward on supplied features, not trained segmentation'}


if __name__ == '__main__':
    print(json.dumps(demo(), indent=2))

Actual output is:

{
  "embeddingShape": [
    2,
    3,
    32
  ],
  "sparseShape": [
    2,
    32
  ],
  "allMaskShape": [
    4,
    8,
    12
  ],
  "multimaskShape": [
    3,
    8,
    12
  ],
  "singleMaskShape": [
    1,
    8,
    12
  ],
  "upscaledShape": [
    8,
    12,
    4
  ],
  "trace": [
    {
      "tokens": [
        7,
        32
      ],
      "imageSequence": [
        6,
        32
      ]
    },
    {
      "tokens": [
        7,
        32
      ],
      "imageSequence": [
        6,
        32
      ]
    }
  ],
  "quality": [
    -0.14631879516977944,
    0.3483216384585388,
    0.23297616855968495
  ],
  "negativePointLogitDifference": 0.22885486783673314,
  "denseFeedbackLogitDifference": 0.4067314074086432,
  "inputEmbeddingUnchanged": true,
  "scope": "random-parameter SAM1-style decoder forward on supplied features, not trained segmentation"
}

Changing the positive point to a negative point changes logits by a maximum of about 0.228855; feeding a selected mask’s raw logits back as a dense prompt changes the dedicated single-mask logits by about 0.406731. The supplied image embedding stays unchanged and can be reused. A quality estimate of −0.146319 is a random regressor output, not a negative true IoU.

Twenty-one numerical checks cover known Fourier values, point types and placeholders, box corners, absent versus empty points, dense logits, explicit multi-head weighted sums, stable large scores, first-layer residual behavior, image updates, prompt-order invariance, dedicated single-mask selection, transpose-convolution phases, normalization/GELU, rounded coordinate scales, half-pixel interpolation, padding removal and stability edge cases. They do not constitute a comparison against pretrained PyTorch weights or a backward-pass test.

The name does not remove the need to specify a task

The default public SAM is not a text-prompt API

The original paper’s text-to-mask experiment modified training to use CLIP image embeddings as prompts, relying on CLIP’s image/text alignment to use text at inference. It was a separate proof of concept, not the unchanged model used in the earlier experiments. The fixed public predictor has no text argument. It is inaccurate both to promise default text prompting and to say the original paper never studied it. Text-to-mask experiment, §7.5, public API

The paper reports missing fine structures, occasional disconnected fragments and less crisp boundaries than more expensive specialized methods. A valid prompted mask is not automatically a complete semantic or panoptic segmentation, an amodal reconstruction, a video identity or a guarantee of domain accuracy. The first encoder pass also remains substantial even when cached prompt decoding is fast. Limitations

Separate model capability from the annotation process

The data engine moved through assisted-manual, semi-automatic and fully automatic stages. The paper describes 1.1 billion collected masks, 99.1% generated automatically, and a released SA-1B containing only automatically generated masks. These are not 1.1 billion masks independently drawn and verified by humans. Its reported quality study is the authors’ evidence, not a study repeated by this encyclopedia. Data engine and dataset discussion

The simulated training interaction has 11 steps: an initial point or box, eight error-region point additions and two steps without a new point. It passes unthresholded previous logits, and uses the candidate with highest predicted IoU for the next interaction when multiple masks are returned. This is the training procedure described in the paper; the example only computes one feedback pass and does not reproduce optimization or data collection. Training appendix

The family changed after 2023

Version / recordVerified dateChange supported by the cited source
SAM first preprint2023-04-05Promptable image segmentation; geometric prompts and ambiguity-aware masks
SAM 2 first preprint2024-08-01Image/video promptable segmentation with streaming memory; paper revision 2024-10-28
SAM 2.1 suite2024-09-30New checkpoints, released training code and web demo in the fixed README
SAM 3 official research entry2025-11-19Concept prompts for matching instances in images/video; first arXiv submission is 2025-11-20
SAM 3.1 release2026-03-27Object Multiplex groups objects into fixed-capacity buckets for joint processing; SAM 3 paper v2 is dated 2026-03-28

Sources for the table are the original history above, SAM 2 history, fixed SAM 2 updates, SAM 3 official entry, SAM 3 history and fixed 3.1 release notes. Announcement, suite release and preprint revision dates describe different events.

SAM 3’s overview describes Promptable Concept Segmentation: a short noun phrase, image exemplar or combination identifies a concept whose matching instances should receive masks and identities. It describes a shared-backbone detector and memory-based tracker, with a presence head separating recognition from localization. SAM 3.1 changes multi-object processing through shared buckets. These are overview-level comparisons here, not audited implementations of the later models or universal speed/accuracy guarantees. SAM 3 overview, 3.1 mechanism summary

Licenses must also be checked per artifact and version. The original model’s README points to Apache 2.0 while SA-1B has a separate Dataset Research License. The fixed SAM 3 license is titled “SAM License,” last updated 19 November 2025. This article does not interpret its full terms or assume the entire family shares one license. No upstream code, weights or images are copied into the teaching example. Original model/data notices, SAM 3 license heading

Ask what changed, then inspect the tensors

1. Three alternatives or three objects?

A click on a sleeve produces masks for the sleeve, shirt and person. Must two outputs be wrong?

Answer: Not necessarily. The prompt is ambiguous about part versus whole. Multiple plausible masks preserve that ambiguity. A further positive/negative point or box can clarify the intended region; the outputs are not automatically three independently detected instances.

2. Single-mask mode

Three multi-mask quality estimates are 0.1, 0.9 and 0.2. Does setting multimask=False necessarily return the second of these masks?

Answer: No. The fixed decoder returns a dedicated index-0 mask in single mode and indices 1–3 in multi mode. To choose the second candidate, explicitly select the maximum quality estimate among the three returned candidates. The mode switch changes which trained output token is used.

3. Rounding changes a coordinate

A 333×1000 image is resized to 341×1024. Where does point (500,166.5) go before the prompt encoder adds its pixel-center shift?

Answer: x becomes 500×1024/1000=512; y becomes 166.5×341/333=170.5. Use the actual rounded dimensions independently. The subsequent half-pixel shift and padded-image normalization belong to the prompt encoder and should not be applied twice.

4. Stable is not correct

For logits [2,0,-2,1], take central threshold 0 and offset 1. What is stability? Does it prove the object is segmented correctly?

Answer: Strictly above +1 there is one pixel; strictly above −1 there are three. Stability is 1/3. It compares two thresholded predictions and uses no GT, so it cannot prove correctness. If the low-threshold foreground is empty, the ratio is undefined; do not assign a perfect score.

Match each claim to the version actually inspected

The original-paper reading covers method and data-engine pages 4–6, model/training appendix pages 16–17, the text experiment on page 11, limitations on page 12 and automatic-generation appendix B on page 18. Method figures on pages 5 and 16 were visually checked. Other results, model cards and appendices were not fully audited.

The fixed original-code reading covers complete prompt/mask/two-way modules and selected predictor, builder, transformation and automatic-generation ranges. Later versions were checked through the stated official overview and release records. No official model was executed. This distinction lets a reader use the code to learn the original computation without mistaking it for an implementation or evaluation of every later SAM variant.

Make a prediction, then check

What does single-mask mode return in the fixed original decoder?

Choose one answer

Learning objectives

  • Trace sparse/dense prompts through the two-way decoder and dynamic mask heads.
  • Distinguish ambiguous alternatives, dedicated single output, quality estimates and stability.
  • Implement and check prompt coordinates, output selection and cached-feature inference.
  • Compare original SAM with documented SAM2/SAM3 changes without mixing APIs or dates.

Prerequisites & connections

Explore related knowledge →

References

  1. Segment Anything — v1 task, model and training
    Alexander Kirillov; Eric Mintun; Nikhila Ravi; Hanzi Mao; Chloe Rolland; Laura Gustafson; Tete Xiao; Spencer Whitehead; Alexander C. Berg; Wan-Yen Lo; Piotr Dollár; Ross Girshick · 2023
  2. SAM fixed prompt encoder and random Fourier positions
    Meta and repository contributors · 2024
  3. SAM fixed mask decoder and dedicated output tokens
    Meta and repository contributors · 2024
  4. SAM fixed two-way Transformer inference graph
    Meta and repository contributors · 2024
  5. SAM fixed channel normalization and MLP helpers
    Meta and repository contributors · 2024
  6. SAM fixed model preprocessing and mask postprocessing
    Meta and repository contributors · 2024
  7. SAM fixed geometric prompt API and image cache
    Meta and repository contributors · 2024
  8. SAM fixed longest-side image and coordinate transforms
    Meta and repository contributors · 2024
  9. SAM fixed original model configuration
    Meta and repository contributors · 2024
  10. SAM fixed automatic-mask defaults and filtering
    Meta and repository contributors · 2024
  11. SAM fixed mask stability score
    Meta and repository contributors · 2024
  12. SAM fixed model and dataset release notices
    Meta and repository contributors · 2024
  13. SAM 2 fixed overview and SAM 2.1 suite updates
    Meta and repository contributors · 2024
  14. SAM 3 fixed promptable concept segmentation overview
    Meta and repository contributors · 2026
  15. SAM 3.1 fixed Object Multiplex release notes
    Meta and repository contributors · 2026
  16. SAM 3 fixed license heading and version
    Meta and repository contributors · 2025
  17. Segment Anything arXiv first-submission record
    Alexander Kirillov; Eric Mintun; Nikhila Ravi; Hanzi Mao; Chloe Rolland; Laura Gustafson; Tete Xiao; Spencer Whitehead; Alexander C. Berg; Wan-Yen Lo; Piotr Dollár; Ross Girshick · 2023
  18. SAM 2 arXiv submission and revision history
    Meta research authors; arXiv or Meta publication record · 2024
  19. SAM 3 official research announcement entry
    Meta research authors; arXiv or Meta publication record · 2025
  20. SAM 3 arXiv first submission and revision
    Meta research authors; arXiv or Meta publication record · 2025

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: scoped original paper and fixed source reading, independent prompt/attention/geometry/output tests, complete bilingual comparison and measured diagram binding. Not human peer review, pretrained segmentation evaluation or training reproduction.

  • Twenty-one numerical checks plus complete bilingual/diagram binding. Verified Fourier/type/placeholder geometry, dense logits, explicit attention weighted sums, first-block residual distinction, sparse-order invariance, dedicated single output, transpose phases, norm/GELU, rounded coordinate transforms, postprocess order and stability edge cases.
  • Compared all bilingual arguments, eight display equations, complete code/stdout, four explained exercises and twenty scoped references. Separated random forward from learned performance, original text experiment from public API, data-engine recipe from defaults, and family announcements from preprint revisions.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.