AI Wiki中文/EN

Segment Anything:用提示说明这张掩码代表什么

Segment Anything

跟踪点、框和掩码提示怎样经过SAM双向解码器,理解输出歧义与坐标变换,并区分SAM、SAM 2和SAM 3。

本页目录直觉理解数学与方法代码实现局限与误解实验与练习研究脉络

点中袖子,还没有说清要谁

设想在照片里点中一个人的袖子。你想要袖子、整件衣服,还是整个人?点击给出了位置,却没有完整定义目标。如果把其他解释都当作错误,就会把一个含糊请求伪装成精确要求。

原始Segment Anything Model,简称SAM,把分割看成以提示为条件的任务。点、框或前一张掩码说明想要的区域,模型预测合理的成员掩码。多个输出可以保留歧义,等待进一步输入消除。掩码不会自动成为语义类别标签,同一个提示的三个备选也不是独立发现的三个物体。任务与模型说明

Alexander Kirillov等作者于2023年4月5日提交《Segment Anything》。这里的“原始SAM”指该图像模型和固定版本的公开推理实现。后续SAM 2、SAM 3在任务和系统上有具体变化,下文分别说明;本篇小程序实现原始风格的提示编码器与掩码解码器,不是整个家族。首版提交记录

有用的架构分工是:图像处理一次,多个提示复用特征。用户补一个负点或修改掩码,不必再次运行重型图像编码器。若图像编码耗时为TIT_I,一次提示编码/解码为TPT_P,交互n次,理想化串行成本为:

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

这里不包含图像加载、结果传输等开销。因此提示响应快,不代表第一次响应或端到端图像编码也快。公开预测器会保存图像嵌入,供后续调用复用。预测器与图像缓存

实际计算的小型SAM解码路径:缓存的2乘3乘32图像嵌入和两个稀疏提示token,经过双向注意力产生四张mask logit,再分别选择专用单掩码或三个候选。
来自可执行例子的原创图。尺寸描述随机参数下的真实计算,不代表预训练分割质量。

跟着提示、图像和输出token走

图像编码一次,每个请求分别编码

论文默认图像编码器使用MAE预训练的ViT-H/16,并加入窗口注意力与间隔设置的全局注意力。输入缩放并填充到1024×1024,得到64×64空间网格,再把特征投影到256通道。固定构造代码还指定两个解码块、八个注意力头。这些尺寸描述原系统;下方例子明确采用更小的给定特征。架构附录、固定构造代码

稀疏提示变成一个或多个向量,稠密提示保留空间网格。固定点编码器对归一化XY坐标使用随机Fourier特征。设归一化坐标为u、固定高斯频率矩阵为B,位置映射为:

ϕ(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是保存下来的随机缓冲,不是每点一次就重新采样。移动点的位置,会可复现地改变位置向量。坐标先移到像素中心,再分别把x除以填充后的图像宽度、y除以高度。前景点与背景点添加不同的可学习类型向量:

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\}.

框贡献两个向量,分别使用左上角和右下角类型。缺失点标签−1会丢弃坐标向量,改用可学习占位向量。如果提供点但没有框,固定实现还会追加一个占位。因此“不传点参数”和“传入空点数组”是不同代码路径。占位仍是一个token,不是把某个位置从注意力中删除的屏蔽矩阵。完整提示编码器

前一张低分辨率掩码以未阈值化logit传入,不只是二值前景图。两次带通道归一化和GELU的步长2卷积,把宽高缩小四倍;1×1投影把通道数变为图像特征通道数,随后逐位置相加。没有mask提示时,每个位置加一个可学习no-mask向量。传入全零mask不等于省略mask。提示编码器、归一化与MLP辅助算子

信息向两个方向流动

把可学习输出token与稀疏提示token拼接。两个解码块各执行四步:token自注意力、token到图像的交叉注意力、token MLP、图像到token的交叉注意力。最后一步很关键:图像特征也会按当前请求更新,不是在整个解码过程中始终作为被动的键和值。

一个宽度为dhd_h的注意力头内,投影后的查询、键和值采用熟悉的缩放加权和:

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

token到图像注意力中,Q的行对应token,K、V的行对应图像位置。图像到token时,角色反过来。原始交叉注意力投影先把256维减半到128维,再分头;它减少计算量,没有改变空间位置数。原始提示向量与图像位置会在指定查询/键路径重新加入。固定双向Transformer

有个实现细节值得实际检查,不能假设每层相同:第一个token自注意力既没有额外加入原始提示编码,也没有残差相加;后续自注意力块才相加。两个块结束后,再运行一次token到图像注意力和归一化,然后解码器才上采样图像特征。程序遵循这个公开推理执行图,不把论文概述的文字顺序照搬成另一份执行顺序,也不宣称复现训练时的dropout配方。固定块执行顺序

每个输出token生成不同的像素分类器

更新后的图像网格经过两次2×2、步长2的转置卷积放大。原配置通道数从256经64变为32,空间每条边放大四倍。每个mask token经过自己的三层MLP,产生与放大特征通道数相同的向量;在每个位置点乘,就得到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).

wjw_j会通过token解码随提示变化。这是动态像素分类器,不是Mask R-CNN那种按类别索引的固定掩码通道。另一个输出token经过MLP预测掩码质量,训练目标是估计IoU。公开实现的最后没有sigmoid,所以原始估计在数学上不被限制在[0,1]。掩码解码器与输出MLP

内部有四个mask token,加一个质量token。多掩码模式返回mask索引1–3,单掩码模式返回索引0。关闭多掩码,不是从其他三张里挑分数最高的一张。如果要选那三个候选中最好的一张,应明确根据其质量分数选择。API把这个决定交给调用者,不会在点击数量改变时自动切模式。输出切片、公开预测选项

对有歧义的训练提示,论文计算候选掩码损失,只从最低损失候选反传。掩码监督按20:1组合focal损失和Dice损失:

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损失加强困难像素决策的影响;Dice损失比较软前景重叠。具体平滑与归约约定属于具体训练实现。上式记录论文的权重与候选选择规则,不补造未指定的实现细节。质量头用真实掩码IoU作为MSE监督,权重为1。下方小程序只有推理前向,没有实现这些训练损失,也不声称训练梯度已通过检查。训练附录

缩放时,取整后的尺寸也要进入坐标计算

原图尺寸为H×W。长边缩放后,对尺寸取整,得到H′、W′。点坐标必须使用这些实际尺寸:

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

333×1000图像把长边变为1024后,尺寸为341×1024。x比例是1.024,y比例却是341/333。两轴都用1.024,会引入小的坐标偏差。这些坐标之后才进入提示编码器的像素中心与归一化约定。长边变换

最终掩码的固定处理顺序是:先把低分辨率logit双线性放大到填充方形,裁掉右/下填充,再缩放到原图;最后才应用严格的零logit阈值。例子实现这个logit插值顺序,不替代所有PIL或带抗锯齿的图像缩放路径。掩码后处理、图像与张量变换的区别

“自动”生成也在提供提示

自动掩码生成会采样点网格、预测候选,再做过滤。预测IoU是学习得到的估计;稳定性询问同一掩码在相近logit阈值下是否变化。设中心阈值t、偏移δ,高阈值前景集合为A,低阈值集合为B。当δ非负时,A包含在B中:

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

它比较两个预测,不是与真值掩码的IoU。固定辅助函数没有为空并集定义分数,本例返回NaN,不赋予稳定满分。默认t=0、δ=1时,恰好等于阈值的像素不计入,因为比较是严格大于。稳定性辅助函数

公开生成器默认包括32×32点网格、预测IoU阈值0.88、稳定性阈值0.95和框NMS阈值0.7。前一项过滤使用大于0.88,后一项则是大于等于0.95。默认不启用额外裁剪层和小区域清理。论文制作SA-1B的数据生成配方使用了额外裁剪、后处理和专门训练的模型;不能把公开默认设置当成数据集生产流程的复现。生成器默认值与过滤、数据生成附录

一次完整的小型提示到掩码计算

原创程序使用Python 3.12、NumPy 1.26.4,给定一张2×3×32图像嵌入和一组提示。这个矩形网格是允许的教学配置,不是原始方形ViT管线的输出。程序包含稀疏/稠密提示编码、两个双向块、最终注意力、上采样、全部四个动态掩码头、质量预测与输出选择。权重随机;点改变后输出变化,展示的是提示依赖,不是学会了物体理解。

量原始默认配置本例
图像嵌入64×64×256给定2×3×32
解码块数/头数2 / 82 / 4
token MLP宽度204864
单点无框时的稀疏向量数22
加上输出后的token数77
放大的掩码特征256×256×328×12×4
内部/多掩码/单掩码数量4 / 3 / 14 / 3 / 1

设图像位置数P、token数T、投影后的总通道数d,交叉注意力分数计算为O(TPd),token自注意力为O(T²d)。投影和MLP还有与通道宽度有关的开销。解码器避免每次点击都做稠密P×P图像自注意力,但图像编码器仍有自己的成本。本例NumPy循环和保存的激活面向小规模算例,不代表浏览器或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))

实际输出为:

{
  "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"
}

把正点改成负点,logit最大变化约0.228855;把选中掩码的原始logit作为稠密提示反馈,专用单掩码logit最大变化约0.406731。给定图像嵌入不被修改,可以复用。质量估计−0.146319是随机回归器的输出,不是负的真实IoU。

21项计算检查覆盖已知Fourier值、点类型与占位、框角、无点与空点、dense logits、显式多头加权和、大分数稳定性、首层残差行为、图像更新、提示顺序不变性、专用单掩码选择、转置卷积相位、归一化/GELU、取整后坐标比例、半像素插值、去填充及稳定性边界。它们不是预训练PyTorch权重对照,也不是反向传播测试。

名字没有省掉定义任务这一步

默认公开SAM不是文本提示API

原论文的文本到掩码实验修改了训练,用CLIP图像嵌入作为提示,再借助图文对齐在推理时输入文本。它是独立的概念实验,不是前面其他实验里未经改动的模型。固定公开预测器没有text参数。承诺默认支持文本提示不准确,说原论文从未研究文本也不准确。第7.5节文本实验、公开API

论文指出会漏掉细结构,偶尔生成不连通碎片,边界也可能不如计算量更高的专门方法清晰。一个合理的提示掩码,不自动等于完整语义/全景分割、遮挡重建、视频身份或领域准确率保证。即使缓存后的提示解码很快,首次编码成本仍在。局限部分

模型能力与标注流程分别说明

数据引擎经历人工辅助、半自动和全自动阶段。论文说明共收集11亿掩码,其中99.1%全自动生成,发布的SA-1B只含自动生成掩码。它们不是11亿张由人工逐一绘制并核验的掩码。论文的质量研究是作者提供的证据,不是本百科重复执行的实验。数据引擎与数据集讨论

模拟训练交互共11步:初始点或框、八次从错误区域加点、两次不加新点。过程传递上一轮未阈值化logit,多掩码输出时选预测IoU最高的候选进入下一次交互。这是论文训练流程;本例只计算一次反馈,没有复现优化或数据收集。训练附录

2023年之后,家族发生了变化

版本/记录核定日期来源支持的变化
SAM首个预印本2023-04-05可提示图像分割;几何提示与保留歧义的掩码
SAM 2首个预印本2024-08-01带流式记忆的图像/视频提示分割;论文修订为2024-10-28
SAM 2.1套件2024-09-30固定README记录新权重、训练代码与web demo
SAM 3官方研究条目2025-11-19用概念提示匹配图像/视频实例;首个arXiv提交为2025-11-20
SAM 3.1发布2026-03-27Object Multiplex按固定容量桶分组、联合处理多个对象;SAM 3论文v2为2026-03-28

表中来源包括上文原始提交记录、SAM 2历史、固定SAM 2更新、SAM 3官方条目、SAM 3历史与固定3.1发布说明。公告、套件发布和预印本修订日期描述不同事件。

SAM 3概述的Promptable Concept Segmentation用短名词短语、图像例子或组合来指定概念,为匹配的实例返回掩码和身份。概述描述共享骨干的检测器与基于记忆的跟踪器,并用presence head区分识别与定位。SAM 3.1则通过共享桶改变多对象处理。这些是本篇的概览层比较,不是后续模型的完整实现审计,也不是适用于所有条件的速度/准确率保证。SAM 3概览、3.1机制说明

许可也要按材料与版本核对。原模型README指向Apache 2.0,SA-1B另有Dataset Research License;固定SAM 3许可标题为“SAM License”,最后更新日期是2025年11月19日。本篇不解读其全部条款,也不假设整个家族共用一种许可。教学例子没有复制上游代码、权重或图片。原模型与数据许可说明、SAM 3许可标题

先问改变了什么,再查看张量

1. 三个备选,还是三个物体?

点中袖子后,模型给出袖子、衣服和人的掩码。是否一定有两个输出错误?

答案:不一定。提示没有明确部件还是整体,多个合理掩码保留了歧义。再加正/负点或框可以说明意图;这些输出不自动成为三个独立检测到的实例。

2. 单掩码模式

三个多掩码候选的质量估计为0.1、0.9、0.2。设置multimask=False,一定会返回其中第二张吗?

答案:不会。固定解码器单模式返回专用索引0,多模式返回索引1–3。要选择第二个候选,应对已经返回的三张候选明确按质量估计取最大值。切模式改变的是使用哪个训练输出token。

3. 取整改变坐标

333×1000图像缩放为341×1024。提示编码器增加像素中心偏移前,点(500,166.5)变成什么位置?

答案:x为500×1024/1000=512,y为166.5×341/333=170.5。分别使用取整后的实际尺寸。后续半像素偏移和填充图归一化属于提示编码器,不应做两遍。

4. 稳定不等于正确

logit为[2,0,-2,1],中心阈值0、偏移1。稳定性是多少?能证明物体被正确分割吗?

答案:严格大于+1的有一个像素,严格大于−1的有三个,所以稳定性为1/3。它只比较两个阈值化预测,没有使用真值,不能证明正确。如果低阈值前景为空,比值没有定义,不要赋予满分。

每个主张都对应实际核查过的版本

原论文核读覆盖第4–6页方法/数据引擎、第16–17页模型与训练附录、第11页文本实验、第12页局限,以及第18页自动生成附录B。第5和16页方法图经过目视检查,其他结果、模型卡和附录未做完整审计。

原始固定代码核读覆盖完整提示/掩码/双向模块,以及指定预测器、构造器、变换和自动生成代码范围。后续版本通过所列官方概览及发布记录核查。没有执行官方模型。这样读者可以用代码理解原始计算,而不会误以为它实现并评测了后续每一种SAM变体。

先判断,再看解释

固定原始解码器的单掩码模式返回什么?

选择一个答案

学习目标

  • 追踪稀疏/稠密提示如何经过双向解码器与动态掩码头。
  • 区分歧义候选、专用单输出、质量估计与稳定性。
  • 实现并核对提示坐标、输出选择与复用图像特征的推理。
  • 依据记录比较原SAM与SAM2/SAM3变化,不混用接口或日期。

先修与延伸

查看知识关联图 →

参考文献

  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

版本1 · 编写状态: 已完成记录中的技术复核

查看技术检查记录(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.

  • 二十一项计算加完整双语/图示绑定:Fourier/类型/占位几何、dense logits、显式注意力加权和、首层残差区别、稀疏顺序不变性、专用单输出、转置相位、归一化/GELU、取整坐标、后处理顺序和稳定性边界。
  • 逐节核对双语论点、八组展示公式、完整代码/输出、四组解释习题与二十项限定来源;区分随机前向与学习性能、原文本实验与公开接口、数据生产配方与默认值、家族公告与预印本修订。

核对的来源位置:

相关主题

没有匹配结果,试试英文名或缩写。

已显示 0 条结果

将整个查询放入双引号,可按短语匹配。