AI Wiki中文/EN

Mask R-CNN: give each detected object its own pixel grid

Mask R-CNN

Derive class-specific mask loss, follow RoIAlign coordinates and boundary cases, and train a complete small mask branch with verified gradients.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A good box does not tell you where the fingers are

Suppose a detector places a rectangle around a person’s hand. The box can be correct while including large background gaps between the fingers. A mask predictor must recover that finer shape. If its region extraction rounds every boundary to a coarse feature-grid location, a small rounding error can move an entire thin finger.

Mask R-CNN extends the two-stage detection structure with a spatial mask branch. It also uses RoIAlign to avoid quantizing region coordinates and bin boundaries. These solve different parts of the problem: the branch predicts object membership; alignment preserves the coordinate relationship needed to supervise it. Original method, §3

Kaiming He, Georgia Gkioxari, Piotr Dollár and Ross Girshick first submitted the preprint on 20 March 2017. The method text used here is revision v3, dated 24 January 2018; the revision date is not the method’s first appearance. Submission record

Read R-CNN for proposals and box heads, and instance segmentation for the identity and evaluation problem. Here we follow the mask branch all the way from sampled features to parameter gradients. The runnable model is deliberately small, with supplied features and positive boxes; it does not train an entire detector.

Keep geometry and class supervision separate

Which branch answers which question?

The detection path predicts a category and refines a box. The mask path predicts foreground membership within each region on a two-dimensional grid. During training, a positive RoI receives the mask of its matched GT object, even if another object of the same class overlaps the region. The relevant membership question is “does this pixel belong to this instance?”, not “does this pixel belong to any object of this class?”

The original objective adds classification, box and mask terms:

L=Lcls+Lbox+Lmask.L=L_{\mathrm{cls}}+L_{\mathrm{box}}+L_{\mathrm{mask}}.

The mask term applies only to positive RoIs. In the fixed Torchvision implementation, the training branch selects regions whose labels are greater than zero, projects their matched masks, and computes a class-indexed binary loss. Inference selects the mask channel corresponding to each predicted class. Fixed RoI training, loss and inference

Let each of N positive RoIs produce an m×m grid for K class channels. Region n has class k(n), target pixel y and selected logit z. With sigmoid probability p, the mean mask loss is:

Lmask=−1Nm2∑n,u,v[ynuvlog⁡pnuv+(1−ynuv)log⁡(1−pnuv)],pnuv=σ(znuv,k(n)).L_{\mathrm{mask}}=-\frac1{Nm^2}\sum_{n,u,v}\left[y_{nuv}\log p_{nuv}+(1-y_{nuv})\log(1-p_{nuv})\right],\quad p_{nuv}=\sigma(z_{nuv,k(n)}).

Only the selected channel participates for that region. The other K−1 channels do not compete through a pixelwise softmax and get no gradient from its mask term. A pixel outside the instance has binary target 0; it is not a separate background mask class competing with the object classes. Our local channels start at zero for foreground classes. Do not use those indices as COCO category IDs or assume they equal the indices of a pretrained detector.

For stable computation, express binary cross-entropy directly using the selected logit. This avoids taking the log of a probability rounded to zero:

ℓ(z,y)=max⁡(z,0)−zy+log⁡(1+e−∣z∣).\ell(z,y)=\max(z,0)-zy+\log(1+e^{-|z|}).

Differentiate the sigmoid log-likelihood; the factors from the logarithms and sigmoid cancel to p−y. Including the averaging factor and class selection gives:

∂Lmask∂znuvk=1[k=k(n)]Nm2(σ(znuvk)−ynuv).\frac{\partial L_{\mathrm{mask}}}{\partial z_{nuvk}}=\frac{\mathbf1[k=k(n)]}{Nm^2}\left(\sigma(z_{nuvk})-y_{nuv}\right).

The target may be fractional. Fixed Torchvision projects a binary GT mask with RoIAlign, producing interpolated values rather than thresholding it back to a binary image. This is a sampling-based soft target, not an exact polygon/pixel area integral. If there are no positive regions, the implementation returns a differentiable zero loss; the local program returns zero loss and zero gradients. Target projection and BCE

RoIAlign samples coordinates, not rounded bins

Use an H×W feature map with pixel centers indexed by integer y,x. Scale an image-space XYXY box into feature coordinates. In the fixed implementation, aligned=True then subtracts 0.5 from each box coordinate; legacy mode leaves them unchanged and clamps the resulting width and height to at least 1. These are explicit coordinate conventions, not interchangeable flags. Fixed Python RoIAlign

For a sample between neighboring centers, let a=x−floor(x) and b=y−floor(y). Bilinear interpolation uses the four local values:

F~(y,x)=(1−b)(1−a)F00+(1−b)aF01+b(1−a)F10+baF11.\widetilde F(y,x)=(1-b)(1-a)F_{00}+(1-b)aF_{01}+b(1-a)F_{10}+baF_{11}.

This interpolates the feature field. It does not reconstruct ground-truth image detail that the backbone has already lost. For output bin (r,c), output size (h,w), region width WRW_R and height HRH_R, sample grid (ny,nx)(n_y,n_x) and within-bin indices (i,j), use:

y=y0+(r+i+1/2ny)HRh,x=x0+(c+j+1/2nx)WRw.y=y_0+\left(r+\frac{i+1/2}{n_y}\right)\frac{H_R}{h},\qquad x=x_0+\left(c+\frac{j+1/2}{n_x}\right)\frac{W_R}{w}.

The local implementation averages all samples in each bin. A positive sampling argument gives a fixed number per axis; its -1 option uses ceilings of region size divided by output size. The paper discusses max or average aggregation, so average pooling is a chosen profile rather than the definition of all RoIAlign variants. Paper RoIAlign description, fixed CPU forward

On the affine feature field F(y,x)=x+2y, box [1,1,3,3], output 2×2 and two samples per axis, legacy mode gives [[4.5,5.5],[6.5,7.5]]. With the half-pixel offset, it gives [[3,4],[5,6]]. Both are reproducible results under different coordinate contracts.

Boundaries are part of the operator

The fixed native CPU helper assigns zero to samples with y<−1y < -1, y>Hy > H, x<−1x < -1 or x>Wx > W. Within the remaining border interval it clamps to available pixel centers. The Python reference path does not contain the same far-outside zero branch. Public dispatch depends on available ops and deterministic-algorithm/device conditions. These are source observations from a particular version, not a runtime comparison performed on this project. Native boundary helper, Python helper and dispatch

For a constant 2×2 feature map of value 7, box [1.9,0,2,1], one output bin and two samples per axis, legacy width clamping expands width 0.1 to 1. The x samples become 2.15 and 2.65, beyond W=2. The native-source profile returns 0; a border-clamp-only calculation returns 7. A test using only interior boxes would miss this difference. The program below implements the stated native boundary profile and does not claim bitwise equality with every Torchvision backend.

A spatial head and its backward path

The fixed default FPN mask head receives 14×14 features and uses four same-size 3×3 convolutions with 256 channels, a 2×2 stride-two transpose convolution, and a 1×1 class projection. Spatial output is 28×28. The transpose operation changes resolution before the class projection. Fixed head construction

Our example keeps these operator roles but uses two channels and 3×3 region features. With no padding, dilation one and zero output padding, the selected transpose convolution doubles a side:

nout=(nin−1)⋅2+2=2nin.n_{\mathrm{out}}=(n_{\mathrm{in}}-1)\cdot2+2=2n_{\mathrm{in}}.
OperationPer-region outputTrainable parameters
RoIAlign3×3×20
Four same 3×3/ReLU layers3×3×24×(3×3×2×2+2)=152
2×2 transpose convolution/ReLU6×6×22×2×2×2+2=18
1×1 class logits6×6×21×1×2×2+2=6
TotalTwo foreground channels176

With box coordinates fixed, RoIAlign is a linear map A from feature values to sampled outputs. The gradient scatters each output derivative back to its contributing feature pixels using the same weights, accumulating where regions overlap:

R=AF,∂L∂F=AT∂L∂R.R=AF,\qquad \frac{\partial L}{\partial F}=A^{\mathsf T}\frac{\partial L}{\partial R}.

The program also reverses the class convolution, ReLU, transpose convolution and four ordinary convolutions. ReLU at zero uses derivative zero. It computes feature gradients but does not optimize a backbone or differentiate the supplied box coordinates.

For N regions and h×w outputs with nynxn_y n_x samples, alignment costs O(NhwnynxC)O(Nhw n_y n_x C); the explicit weight cache has O(Nhwnynx)O(Nhw n_y n_x) entries up to a factor of four. A convolution costs O(Nhwk2CinCout)O(Nhw k^2 C_{\mathrm{in}} C_{\mathrm{out}}), and backward has the same order. Retaining activations adds memory, and this loop-based NumPy implementation is intended for small regions, not GPU-scale training.

Check that the gradient reaches the features

This complete program uses Python 3.12 and NumPy 1.26.4. It supplies two coordinate feature channels on a 12×12 grid, two positive boxes, two matched object masks and foreground classes 0/1. Projected targets contain 33 fractional pixels. There is no proposal generation or box classification hidden in the example.

"""Original NumPy mask branch; supplied features/positive boxes, not a detector.

HWC features; XYXY boxes in image coordinates. ROIAlign uses average sampling,
the v0.17 native CPU interpolation boundary profile and fixed box coordinates.
The four-convolution mask head, transpose convolution and selected-class BCE
have full parameter/feature gradients. No RPN, box head, FPN or COCO evaluation.
"""
import json
import numpy as np


def positive_int(value):
    if type(value) is not int or value < 1:
        raise ValueError('positive integer required')
    return value


def hwc(value):
    x = np.asarray(value, float)
    if x.ndim != 3 or min(x.shape) < 1 or not np.isfinite(x).all():
        raise ValueError('finite nonempty HWC feature map required')
    return x


def interpolation(h, w, y, x):
    """Native-source boundary profile; coordinates are pixel-center indices."""
    if y < -1 or y > h or x < -1 or x > w:
        return ()
    y, x = np.clip(y, 0, h - 1), np.clip(x, 0, w - 1)
    lo_y, lo_x = int(y), int(x)
    hi_y, hi_x = min(lo_y + 1, h - 1), min(lo_x + 1, w - 1)
    dy, dx = y - lo_y, x - lo_x
    return ((lo_y, lo_x, (1-dy)*(1-dx)), (lo_y, hi_x, (1-dy)*dx),
            (hi_y, lo_x, dy*(1-dx)), (hi_y, hi_x, dy*dx))


def roi_align(feature, boxes, size=(3, 3), samples=2, aligned=False, scale=1.):
    x = hwc(feature)
    boxes = np.asarray(boxes, float)
    if boxes.ndim != 2 or boxes.shape[1] != 4 or not np.isfinite(boxes).all():
        raise ValueError('finite N by 4 XYXY boxes required, including shape (0,4)')
    if np.any(boxes[:, 2:] <= boxes[:, :2]):
        raise ValueError('strictly positive box width and height required')
    if len(size) != 2:
        raise ValueError('two output dimensions required')
    oh, ow = [positive_int(n) for n in size]
    if type(samples) is not int or samples == 0 or samples < -1:
        raise ValueError('samples must be -1 (adaptive) or a positive integer')
    if type(aligned) is not bool or not np.isfinite(scale) or scale <= 0:
        raise ValueError('boolean aligned and positive finite scale required')
    result = np.zeros((len(boxes), oh, ow, x.shape[2]))
    cache = []
    for n, box in enumerate(boxes):
        x0, y0, x1, y1 = box*scale - (.5 if aligned else 0.)
        width, height = x1-x0, y1-y0
        if not aligned:
            width, height = max(width, 1.), max(height, 1.)
        ny = samples if samples > 0 else int(np.ceil(height/oh))
        nx = samples if samples > 0 else int(np.ceil(width/ow))
        for row in range(oh):
            for col in range(ow):
                for iy in range(ny):
                    for ix in range(nx):
                        sy = y0+(row+(iy+.5)/ny)*height/oh
                        sx = x0+(col+(ix+.5)/nx)*width/ow
                        for yy, xx, weight in interpolation(*x.shape[:2], sy, sx):
                            weight /= ny*nx
                            if weight:
                                result[n, row, col] += weight*x[yy, xx]
                                cache.append((n, row, col, yy, xx, weight))
    return result, (x.shape, result.shape, cache)


def roi_backward(gradient, cache):
    shape, output_shape, entries = cache
    g = np.asarray(gradient, float)
    if g.shape != output_shape or not np.isfinite(g).all():
        raise ValueError('finite ROI output gradient of the original shape required')
    dx = np.zeros(shape)
    for n, row, col, yy, xx, weight in entries:
        dx[yy, xx] += weight*g[n, row, col]
    return dx


def conv_same(x, kernel, bias):
    # Internal model operator: square odd kernels, stride one, zero padding.
    k = kernel.shape[0]
    pad = k//2
    xp = np.pad(x, ((pad, pad), (pad, pad), (0, 0)))
    h, w = x.shape[:2]
    out = np.broadcast_to(bias, (h, w, len(bias))).copy()
    for y in range(k):
        for z in range(k):
            out += xp[y:y+h, z:z+w] @ kernel[y, z]
    return out


def conv_backward(x, kernel, gradient):
    k = kernel.shape[0]
    pad = k//2
    xp = np.pad(x, ((pad, pad), (pad, pad), (0, 0)))
    dxp = np.zeros_like(xp)
    dk = np.zeros_like(kernel)
    h, w = x.shape[:2]
    for y in range(k):
        for z in range(k):
            dk[y, z] = np.einsum('hwc,hwf->cf', xp[y:y+h, z:z+w], gradient)
            dxp[y:y+h, z:z+w] += gradient @ kernel[y, z].T
    return dxp[pad:pad+h, pad:pad+w], (dk, gradient.sum(axis=(0, 1)))


def upconv(x, kernel, bias):
    h, w = x.shape[:2]
    out = np.broadcast_to(bias, (2*h, 2*w, 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 up_backward(x, kernel, gradient):
    dx, dk = np.zeros_like(x), np.zeros_like(kernel)
    for y in range(2):
        for z in range(2):
            part = gradient[y::2, z::2]
            dx += part @ kernel[y, z].T
            dk[y, z] = np.einsum('hwc,hwf->cf', x, part)
    return dx, (dk, gradient.sum(axis=(0, 1)))


def parameters(channels=2, hidden=2, classes=2, seed=7):
    for n in (channels, hidden, classes):
        positive_int(n)
    rng = np.random.default_rng(seed)
    def layer(k, a, b):
        return [rng.normal(0, np.sqrt(2/(k*k*a)), (k, k, a, b)), np.zeros(b)]
    return {'conv': [layer(3, channels if i == 0 else hidden, hidden) for i in range(4)],
            'up': layer(2, hidden, hidden), 'head': layer(1, hidden, classes)}


def arrays(tree, prefix=''):
    if isinstance(tree, np.ndarray):
        return {prefix: tree}
    result = {}
    for key, value in (tree.items() if isinstance(tree, dict) else enumerate(tree)):
        result.update(arrays(value, prefix+'/'+str(key)))
    return result


def mask_forward(features, boxes, p, size=(3, 3), samples=2, aligned=False, scale=1.):
    rois, rc = roi_align(features, boxes, size, samples, aligned, scale)
    classes = len(p['head'][1])
    logits = np.empty((len(rois), 2*size[0], 2*size[1], classes))
    caches = []
    for i, x in enumerate(rois):
        cc = []
        for kernel, bias in p['conv']:
            z = conv_same(x, kernel, bias)
            cc.append((x, z))
            x = np.maximum(z, 0)
        up_input = x
        up_z = upconv(x, *p['up'])
        head_input = np.maximum(up_z, 0)
        logits[i] = conv_same(head_input, *p['head'])
        caches.append((cc, up_input, up_z, head_input))
    return logits, (rc, caches)


def mask_backward(p, cache, gradient):
    rc, caches = cache
    g = np.asarray(gradient, float)
    shape = rc[1]
    if g.shape != (shape[0], 2*shape[1], 2*shape[2], len(p['head'][1])) or not np.isfinite(g).all():
        raise ValueError('finite mask logit gradient of the original shape required')
    grads = {key: np.zeros_like(value) for key, value in arrays(p).items()}
    dr = np.zeros(shape)
    for i, (cc, up_input, up_z, head_input) in enumerate(caches):
        dx, head = conv_backward(head_input, p['head'][0], g[i])
        dx, ug = up_backward(up_input, p['up'][0], dx*(up_z > 0))
        cg = [None]*len(p['conv'])
        for j in reversed(range(len(p['conv']))):
            x, z = cc[j]
            dx, cg[j] = conv_backward(x, p['conv'][j][0], dx*(z > 0))
        dr[i] = dx
        for key, value in arrays({'conv': cg, 'up': ug, 'head': head}).items():
            grads[key] += value
    return grads, roi_backward(dr, rc)


def selected_bce(logits, targets, labels):
    z, y, labels = np.asarray(logits, float), np.asarray(targets, float), np.asarray(labels)
    if z.ndim != 4 or min(z.shape[1:]) < 1 or not np.isfinite(z).all():
        raise ValueError('finite N,H,W,K logits required')
    if y.shape != z.shape[:3] or not np.isfinite(y).all() or np.any((y < 0) | (y > 1)):
        raise ValueError('finite N,H,W targets in [0,1] required')
    if labels.shape != (len(z),) or labels.dtype.kind not in 'iu' or np.any(labels < 0) or np.any(labels >= z.shape[3]):
        raise ValueError('one valid integer foreground channel per positive ROI required')
    dz = np.zeros_like(z)
    if len(z) == 0:
        return 0., dz
    selected = np.stack([z[i, :, :, int(k)] for i, k in enumerate(labels)])
    loss = np.mean(np.maximum(selected, 0)-selected*y+np.log1p(np.exp(-np.abs(selected))))
    # Stable sigmoid without evaluating an overflowing unused np.where branch.
    prob = np.exp(-np.logaddexp(0., -selected))
    ds = (prob-y)/y.size
    for i, k in enumerate(labels):
        dz[i, :, :, int(k)] = ds[i]
    return float(loss), dz


def project_targets(masks, boxes, matched, size=(6, 6)):
    """Soft targets: one matched binary image mask per supplied positive ROI.

    This local profile uses legacy ROIAlign, scale 1, adaptive sampling, without
    thresholding the projected targets. It does not assign boxes to objects.
    """
    masks, matched, boxes = np.asarray(masks), np.asarray(matched), np.asarray(boxes, float)
    if masks.ndim != 3 or min(masks.shape[1:]) < 1 or not np.isin(masks, [0, 1]).all():
        raise ValueError('binary G,H,W masks required')
    if boxes.ndim != 2 or boxes.shape[1] != 4:
        raise ValueError('N,4 boxes required')
    if matched.shape != (len(boxes),) or matched.dtype.kind not in 'iu' or np.any(matched < 0) or np.any(matched >= len(masks)):
        raise ValueError('valid matched ground-truth index for every ROI required')
    oh, ow = [positive_int(n) for n in size]
    out = np.empty((len(boxes), oh, ow))
    for i, j in enumerate(matched):
        out[i] = roi_align(masks[int(j), :, :, None], boxes[i:i+1], size, samples=-1)[0][0, :, :, 0]
    return out


def demo(seed=0):
    yy, xx = np.indices((12, 12))
    features = np.stack([xx/11., yy/11.], axis=-1)
    boxes = np.array([[1.2, 1.1, 8.2, 8.1], [4.4, 3.2, 10.4, 9.2]])
    masks = np.zeros((2, 12, 12), np.uint8)
    masks[0, 2:7, 2:6] = 1
    masks[1, 4:9, 6:10] = 1
    target = project_targets(masks, boxes, np.array([0, 1]))
    labels = np.array([0, 1])  # Local foreground-only channels, not COCO category IDs.
    p = parameters(seed=seed)
    logits, cache = mask_forward(features, boxes, p)
    before, dz = selected_bce(logits, target, labels)
    grads, df = mask_backward(p, cache, dz)
    for key, value in arrays(p).items():
        value -= .05*grads[key]
    after = selected_bce(mask_forward(features, boxes, p)[0], target, labels)[0]
    assert after < before
    return {'seed': seed, 'featureShape': list(features.shape), 'positiveBoxes': len(boxes),
            'roiShape': [2, 3, 3, 2], 'logitShape': list(logits.shape),
            'parameters': sum(v.size for v in arrays(p).values()),
            'lossBefore': before, 'lossAfterOneStep': after,
            'featureGradientNorm': float(np.linalg.norm(df)),
            'nonzeroParameterGradientArrays': sum(bool(np.any(g)) for g in grads.values()),
            'fractionalTargetPixels': int(((target > 0) & (target < 1)).sum()),
            'scope': 'mask branch only; supplied features, positive boxes, identities and classes'}


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

Actual output for seed 0 is:

{
  "seed": 0,
  "featureShape": [
    12,
    12,
    2
  ],
  "positiveBoxes": 2,
  "roiShape": [
    2,
    3,
    3,
    2
  ],
  "logitShape": [
    2,
    6,
    6,
    2
  ],
  "parameters": 176,
  "lossBefore": 0.6931682481724811,
  "lossAfterOneStep": 0.693036110601795,
  "featureGradientNorm": 0.00042876366365966756,
  "nonzeroParameterGradientArrays": 12,
  "fractionalTargetPixels": 33,
  "scope": "mask branch only; supplied features, positive boxes, identities and classes"
}

A step of size 0.05 changes loss from 0.693168248 to 0.693036111. All 12 parameter arrays have nonzero gradients, and the feature-gradient norm is about 0.000428764. This checks the local path, not segmentation accuracy.

Seventeen tests check affine sampling, boundaries, adaptive sampling, scale, rectangular outputs, a separately assembled interpolation matrix and its transpose, overlap accumulation, class isolation, soft-target derivatives, extreme logits, target projection, transpose phases and empty/invalid cases. A smaller 49-parameter configuration additionally checks every parameter and all 25 input feature values by central differences, using step 1e−5 and positive activations away from ReLU kinks.

There is also a real failure example. With seed 7, hidden ReLUs block the feature gradient and only the final bias array has a nonzero gradient, yet the loss still falls. The test suite retains this case. Seed 0 was selected to expose the complete gradient path, not to claim a better benchmark score. A falling loss alone cannot establish that all layers are learning.

The branch is only as useful as its regions

Mask quality depends on detections, class decisions, feature resolution and annotation alignment. A missed object has no region to segment. A wrong selected class can pick the wrong mask channel. Increasing mask resolution does not by itself correct either failure.

Training and inference also differ. In the paper, mask learning uses positive matched regions; during inference the box branch and NMS select detections before masks are computed for the retained boxes. The predicted-class mask is resized to its region and thresholded at 0.5. The original experiments separately trained the RPN by default for convenient ablations rather than always sharing jointly trained features. These details should not be replaced with a generic description of modern end-to-end training. Original training and inference, physical pages 4–5

The local example omits RPN, backbone, FPN, box losses, NMS, resizing/pasting masks back to the original image and full dataset evaluation. Its two-channel features are constructed, not learned. Extend the system only after specifying how coordinates pass through image resizing, feature scaling, target projection and final mask placement. Use the instance-level matching rules from the preceding article rather than treating pixel accuracy as detection quality.

Follow one region through the model

1. Which class receives the gradient?

A positive region belongs to class 1 and produces three mask channels. If another class channel changes from logit 0 to 1000, must this region’s mask loss change?

Answer: No. The mask loss selects class 1’s channel before applying binary cross-entropy. Other mask channels receive zero gradient from this region’s mask term. This differs from a pixelwise class softmax, whose normalization couples the channels.

2. Count the small head

The example has four 3×3 layers from two channels to two, a 2×2 transpose layer from two to two, and a 1×1 output from two to two. Include biases. How many parameters and what output size follow a 3×3 region?

Answer: The four ordinary layers use 4×(36+2)=152 parameters, the transpose layer 16+2=18, and the class projection 4+2=6, totaling 176. The same convolutions preserve 3×3, the transpose gives 6×6, and the output has two channels: 6×6×2.

3. A thin region at the border

Why does the constant-feature example [1.9,0,2,1] not necessarily return 7 under legacy native sampling?

Answer: Legacy mode clamps width 0.1 to 1. With one output bin and two x samples, the sample coordinates become 2.15 and 2.65. Both exceed W=2, so the specified native helper gives zero contributions. Assuming that every boundary implementation only clamps to the last pixel would predict the wrong result.

4. Loss decreased; did the backbone learn?

After one update, mask loss decreases. Is that sufficient evidence that gradients reached the input features or that the whole detector learned?

Answer: No. The retained seed-7 example lowers loss through the final bias while feature gradients are zero. Inspect gradient paths and compare analytic derivatives with independent checks. Even nonzero feature gradients in this program do not prove backbone learning: the features are supplied and no backbone parameters are trained.

Separate the method, revision and implementation

The original-paper reading covers method pages 2–4 and selected inference/setup text on page 5, with method figures visually inspected. The fixed Torchvision reading covers the documented mask head, positive-region loss/inference, ROIAlign sampling, shared CPU boundary helper and Python dispatch. It does not constitute an audit of the full detector or execution of pretrained weights.

The two ideas worth carrying into later systems are object-conditioned spatial prediction and explicit coordinate contracts. Instance segmentation supplies the matching and identity questions; U-Net supplies a contrasting whole-image spatial architecture. Better feature extraction, different proposal mechanisms or later mask predictors still need targets and evaluation that agree about which pixels belong to which object.

Make a prediction, then check

A positive region belongs to class 1. Which mask channels receive its BCE gradient?

Choose one answer

Learning objectives

  • Derive selected-class binary mask loss and soft-target gradients.
  • Trace RoIAlign scaling, half-pixel offsets, sampling and boundary contracts.
  • Train a complete small mask branch and verify every parameter and feature derivative.

Prerequisites & connections

Explore related knowledge →

References

  1. Mask R-CNN — v3 region masks and alignment
    Kaiming He; Georgia Gkioxari; Piotr Dollár; Ross Girshick · 2017
  2. Mask R-CNN arXiv submission history
    arXiv; Kaiming He and coauthors · 2017
  3. Torchvision v0.17.0 RoIAlign — sampling and dispatch
    Torchvision contributors
  4. Torchvision v0.17.0 CPU RoIAlign forward setup
    Torchvision contributors
  5. Torchvision v0.17.0 native RoIAlign interpolation boundary
    Torchvision contributors
  6. Torchvision v0.17.0 Mask R-CNN head construction
    Torchvision contributors
  7. Torchvision v0.17.0 mask targets, class loss and inference
    Torchvision contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: scoped primary/source reading, explicit identity and coordinate counterexamples, independent arithmetic/gradient tests and complete bilingual comparison. Not independent human review or official benchmark reproduction.

  • Compared both complete languages, displayed equations, executable code/stdout, four explained exercises and scoped references; separate toy profiles from official APIs and complete benchmark claims.
  • Seventeen numerical checks plus bilingual structure: interpolation matrix/transpose, native boundary profile, complete mask gradients, every49 parameter and25 input derivatives, selected soft-target BCE, empty batch and seed7 dead-ReLU counterexample. No upstream runtime comparison.

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.