Module contents
Lesson 17 of 25Advanced 115 min

Object detection II: the R-CNN family, anchors and feature pyramids

Trace two-stage object detection through anchors, region proposals, RoIAlign and feature pyramids, then evaluate a controlled Faster R-CNN adaptation.

After this lesson you can

  • Explain two-stage detection and measure proposal recall.
  • Assign anchors and calculate RPN classification and regression targets.
  • Implement RoIAlign and distinguish it from quantized RoIPool.
  • Construct a feature pyramid and assign RoIs to levels.
  • Diagnose proposal, classification, regression and suppression failures.

Before you start

From all windows to a few proposals

An image can contain objects of very different sizes, positions and aspect ratios. Evaluating an independent CNN on every possible window would repeat almost all work. Two-stage detection separates candidate-region search from classification and refinement. The first stage must recall objects with few proposals; the second can spend more compute per region. A missed proposal cannot be recovered in the second stage if no other proposal covers it adequately.

R-CNN used external selective-search proposals, one CNN per region and separately trained SVM classifiers and regressors. Fast R-CNN shared the whole image’s convolutional map, extracted region features with RoIPool and trained classification and regression with joint loss. It still depended on external proposals. Fast R-CNN table 4, with VGG16 on an Nvidia K40 and VOC2007, reports 47.0 seconds per image for R-CNN and 0.32 for Fast R-CNN excluding proposals; their mAPs are 66.0% and 66.9%. The published time ratio is not a measurement of this machine, and a complete system must also count proposal generation cost.

Faster R-CNN replaced external proposals with a proposal network sharing features with the detector. The paper studies several sharing approaches and describes four-step alternating training; sharing parameters does not mean discrete selection and NMS decisions have ordinary gradients throughout the pipeline.

Anchors: geometric hypotheses

A grid of anchors places reference boxes of several scales and aspect ratios around feature-map positions. The head predicts objectness and offsets relative to each box using reference-box encoding. Objectness distinguishes object from background to propose regions; semantic class is decided later. Three scales and three ratios give nine anchors per position, but coverage and total count also depend on stride, image size and boundary filtering.

For training, calculate IoU between anchors and annotated objects. One common rule marks positive if best IoU exceeds 0.7 or the anchor attains maximum IoU for an object; mark negative if not positive and best IoU is below 0.3; ignore the intermediate interval. State equality, tie and no-object cases. The original paper discards anchors crossing image boundaries during training; other implementations may use different rules.

Marking maxima per object does not ensure one-to-one correspondence. If two objects share one maximum anchor, one positive label cannot simultaneously contain two different regression targets. Subsampling can also discard forced positives. Guaranteeing coverage after sampling requires capacity assumptions and a specific assignment; an unconditional promise would be false.

InteractiveAnchors, positives and negatives

Explicit geometric scene on a 100 × 100 unit canvas. A is small and B is elongated. The 25 points are anchor centers; the selected anchor’s full box is drawn. The two annotations are the dashed boxes.

AB0100
  • Positive
  • Negative
  • Ignored
  • Object A
  • Object B

Anchor 12: center (50, 50), size 32.0 × 32.0; IoU with A 0.063, with B 0.523. Status: Positive; target B. It is a best anchor for B.

Centers are at (10 + 20j, 10 + 20i), with i and j from 0 to 4; scale s and ratio r produce width s√r and height s/√r. Objects are A = (24, 28, 39, 50) and B = (36, 34, 84, 60), in xyxy. The selected box is clipped only in the drawing: IoU uses the whole anchor, including outside the canvas.

Without forcing, an anchor is positive if its maximum IoU is ≥ the positive threshold, negative if it is < the negative threshold, and ignored in between. With forcing enabled, each object proposes all its anchors tied at the greatest IoU, provided it is greater than zero; maximum ties use absolute tolerance 10⁻¹². These anchors become positive even below the threshold.

Each positive anchor is assigned to the object with which it has highest IoU; ties choose A. If the same anchor is best for several objects, it counts as a collision and receives only one target. Thus forcing does not guarantee a positive assigned to every object. This model illustrates one policy; real implementations may resolve ties and collisions differently.

32
Width / height ratio
0.70
0.30
Force best anchors
12
Positives3
Negatives22
Ignored0
Positives assigned to A1
Positives assigned to B2
Positive only by forcing3
Best-anchor collisions0
Explore explicit geometry and observe how thresholds and ratios change coverage; ties and collisions are stated in the figure.

The proposal network

The RPN applies a shared 3×33\times3 convolution to the map and two 1×11\times1 heads: for kk anchors per position, it predicts 2k2k two-class logits and 4k4k offsets. An equivalent formulation uses one binary logit per anchor with binary cross-entropy. Predictions are decoded, clipped, filtered and sorted; then NMS and top-K limits produce proposals for the second stage.

Objectness classification uses sampled positives and negatives; Smooth L1 regression uses positives only. The original work samples up to 256 anchors per image, with positive proportion at most one half, and fills with negatives if positives are insufficient. Its formulation normalizes classification and regression differently and uses λ=10\lambda=10; an implementation averaging both losses by sample count and choosing another weight is valid but not numerically identical to that recipe. With no positives, define regression loss as zero without dividing by zero.

Proposal quality must be measured before classification: for each object check whether any proposal reaches a given IoU and calculate recall at different budgets. Low small-object mAP does not by itself identify whether resolution, proposals, classification or regression failed.

RoIPool and RoIAlign

An RoI occupies a continuous image region; to extract a fixed-size tensor it must be converted to the map using its spatial scale. RoIPool quantizes edges and subdivisions into discrete cells and usually applies a maximum per bin. A small region movement may change no cell until a boundary is crossed, at which point selection changes abruptly.

RoIAlign avoids quantizing boundaries and sampling points. At each point (x,y)(x,y) it combines four neighbors with bilinear interpolation and aggregates bin samples. Map displacement translates to image units through stride, but quantizing boundaries and bins can accumulate effects: there is no universal half-stride bound on final output error. With torchvision.ops.roi_align, aligned=True subtracts half a pixel in map coordinates; legacy aligned=False follows another convention and forces a minimum size of one pixel on the map. Do not apply the offset twice.

InteractiveRoIPool's hidden shift

A synthetic 6 × 6 map feeds two operators with 2 × 2 output. The same bin is highlighted in both. RoIAlign averages four bilinear samples; RoIPool takes the maximum of the highlighted cells.

RoIAlign, aligned=True357681076810911810911131291113121416131214161517141615171918
  • RoI shifted −0.5
  • Bin
  • Bilinear samples

Four samples (x, y): (0.95, 1.02); (1.55, 1.02); (0.95, 1.67); (1.55, 1.67). Their values are interpolated and averaged.

RoIPool357681076810911810911131291113121416131214161517141615171918
  • Bin cells

Cells (x, y): (1, 1); (2, 1); (1, 2); (2, 2). The value is their maximum.

Outputs in row-major order: RoIAlign [7.660, 9.250, 10.861, 11.622]; RoIPool [10.000, 13.000, 14.000, 16.000]. Original RoI in the image: (18.40, 19.20, 56.80, 60.80) pixels, xyxy format.

The value at column x and row y of the map is (x + 1) + 2(y + 1) + ((x + 2y) mod 3), with x and y from 0 to 5. The RoI in map coordinates is (1.15, 1.20, 3.55, 3.80); to place it in the image, coordinates are multiplied by stride. This example does not measure a network or a real image.

RoIAlign subtracts 0.5 from all four map coordinates, as in torchvision aligned=True, and uses two samples per axis in each bin. RoIPool rounds both ends to the nearest integer, treats them as inclusive and uses floor/ceil for each bin; bins may share cells. Displayed shifts are (rounded endpoint − original endpoint) × stride, only for RoIPool’s initial corner; they do not measure error across the whole operator.

Outputs also differ because here RoIPool uses a maximum and RoIAlign averages. Do not attribute the entire numerical difference to rounding. The half-pixel adjustment defines a coordinate convention and does not by itself imply a fault in every implementation.

1.15
1.20
Stride, pixels per map unit
0
Bin, zero-based row and column0, 0
RoIAlign, bilinear average7.660
RoIPool, maximum10.000
Initial corner x rounding−2.40 px
Initial corner y rounding−3.20 px
Compare fractional regions, bins and interpolated samples under the stated conventions.

Mask R-CNN studied this misalignment for masks. In section 4.2, with ResNet-50-C4 and stride 16, RoIAlign improves mask AP by approximately 3 points over RoIPool; with FPN the reported improvement is 1.5 mask AP points and 0.5 box AP points. These are results of those configurations, not a universal guarantee or comparison of interchangeable metrics.

A pyramid with shared semantics

An image pyramid runs the extractor at different resolutions. SSD already predicted from several maps at different resolutions; that does not mean it builds FPN’s same top-down path with lateral connections. A feature pyramid network builds multiscale maps within one network. The bottom-up hierarchy reduces resolution and increases abstraction; the top-down path upsamples the semantic map and adds it to a lateral connection at the corresponding scale. In original FPN, lateral 1×11\times1 convolutions equalize channels, upsampling uses nearest neighbor and a 3×33\times3 produces each P2–P5 map. P6 is obtained by subsampling P5 for the RPN. The relationship with scale space is conceptual: learned maps are not simply Gaussian images.

InteractiveThe feature pyramid

Schematic model: C2–C5 are bottom-up outputs; lateral arrows transform channels and the top-down path adds an upsampled version. The final convolution produces each P map. Blocks do not represent measured activations.

Bottom-up path: C2 to C5. Top-down path: M5 to M2 and their P maps.

C2M2P2C3M3P3C4M4P4C5M5P5

P6 is obtained from P5 for the RPN; the RoI head uses P2–P5. M2–M5 represent internal sums before smoothing. Top-down arrows connect those maps; a 3×3 convolution produces each P output separately. Level P3: stride 8; on a transformed 800 × 1216 image, assuming exact division, the map has 100 × 152 positions. Lateral convolutions are 1×1; the figure omits channels.

● Small: 32 × 32 → P2
● Medium: 112 × 112 → P3
● Large: 448 × 448 → P5

For the chosen RoI: raw level 3; after clamping to P2–P5, P3. This rule applies to size in the transformed image and does not determine the anchors’ IoU labels.

3
Output level
112
Selected levelP3
Level stride8
Chosen RoI112 × 112
RoI assignmentP3
Follow bottom-up, lateral and top-down connections and assign regions by size to head levels.

The FPN paper assigns an RoI of width ww and height hh in the transformed image via k=⌊4+log⁡2(wh/224)⌋k=\lfloor4+\log_2(\sqrt{wh}/224)\rfloor, clipped to available P2–P5 levels. This rule assigns RoIs to second-stage levels; RPN anchor-label assignment is based on IoU. In the particular published comparison, FPN improved mean proposal recall by 8.0 points and COCO-style AP by 2.3 points over its baseline; changing architecture, data or budget can change the result.

Training with limited memory

A pretrained detector is a starting point, not a from-scratch evaluation. Document source classes, image and box transforms and frozen stages. With small batches, BatchNorm statistics can be unstable; freezing them is an option to measure. GroupNorm does not depend on batch size, but replacing pretrained BatchNorm changes the function and needs an adaptation protocol. Mixed precision reduces some memory costs, but some operations retain higher precision and benefit depends on hardware and implementation.

Separate training and validation by image identifier. Select checkpoint on validation and reserve an independent set for confirmatory evaluation. Record objects by size range and proposal recall alongside AP; avoid attributing an observed difference to one component without an experiment isolating it.

Labs

Anchors and proposal loss

The first cell builds a minimal RPN. It uses continuous xyxy anchors, height/width ratio and centers shifted by half a stride. Assignment forces all tied maxima per object, including zero maxima; each anchor receives only one GT target. Thus forced labeling does not itself resolve collisions or guarantee coverage after sampling. This example does not implement boundary filtering, top-K or proposal NMS.

[ ]RPN and assignment from scratchLocal GPU
"""Anchors y RPN didáctica en CPU o GPU con PyTorch.

Convenciones: xyxy continuo, proporciones h/w, centros en (índice+0,5)*stride.
Se conservan anchors fuera de la imagen para asignación; no se realiza aquí
el filtrado, la NMS ni el top-K de propuestas. Etiquetas: 1 positivo, 0
negativo y -1 ignorado. Umbrales estrictos: IoU > pos y IoU < neg.
Todos los máximos empatados de cada GT se fuerzan positivos, incluso si el
máximo es 0. Cada anchor se asigna para regresión al GT de mayor IoU; si hay
empate de GT, gana el de menor índice. La colisión no garantiza que cada GT
tenga una regresión propia y el muestreo puede quitar positivos forzados.

La pérdida didáctica es BCEWithLogits promediada sobre anchors muestreados
más Smooth L1 con beta=1/9 para positivos, dividida por el mismo total de
anchors muestreados. No reproduce la normalización original del artículo.
"""
import math
import torch
from torch import nn
from torch.nn import functional as F


def check_boxes(boxes):
    if boxes.ndim != 2 or boxes.shape[1] != 4 or not boxes.is_floating_point():
        raise ValueError('Cajas flotantes de forma (N, 4)')
    if not torch.isfinite(boxes).all() or (boxes[:, 2:] <= boxes[:, :2]).any():
        raise ValueError('Cajas finitas con área positiva')
    return boxes


def make_anchors(height, width, stride, size, ratios, *, dtype=torch.float32, device='cpu'):
    """Una escala y varias relaciones h/w; salida en orden y, x, ratio."""
    if height < 0 or width < 0 or stride <= 0 or size <= 0 or not ratios or any(r <= 0 for r in ratios):
        raise ValueError('Dimensiones, stride, escala o proporciones inválidas')
    r = torch.as_tensor(ratios, dtype=dtype, device=device)
    wh = torch.stack((size / torch.sqrt(r), size * torch.sqrt(r)), dim=1)
    ys = (torch.arange(height, dtype=dtype, device=device) + .5) * stride
    xs = (torch.arange(width, dtype=dtype, device=device) + .5) * stride
    yy, xx = torch.meshgrid(ys, xs, indexing='ij')
    centers = torch.stack((xx, yy), dim=-1)[:, :, None, :]
    return torch.cat((centers - wh / 2, centers + wh / 2), dim=-1).reshape(-1, 4)


def pairwise_iou(a, b):
    check_boxes(a)
    check_boxes(b)
    low = torch.maximum(a[:, None, :2], b[None, :, :2])
    high = torch.minimum(a[:, None, 2:], b[None, :, 2:])
    intersection = (high - low).clamp(min=0).prod(dim=-1)
    aa = (a[:, 2:] - a[:, :2]).prod(dim=-1)[:, None]
    bb = (b[:, 2:] - b[:, :2]).prod(dim=-1)[None, :]
    return intersection / (aa + bb - intersection)


def assign_anchors(anchors, gt, pos_thr=.7, neg_thr=.3):
    """Devuelve etiquetas, índice de GT por anchor y máximos por GT."""
    check_boxes(anchors)
    check_boxes(gt)
    if not 0 <= neg_thr < pos_thr <= 1:
        raise ValueError('Se exige 0 <= neg_thr < pos_thr <= 1')
    n, g = len(anchors), len(gt)
    labels = torch.full((n,), -1, dtype=torch.int64, device=anchors.device)
    matched = torch.full((n,), -1, dtype=torch.int64, device=anchors.device)
    if not g:
        labels.fill_(0)
        return labels, matched, torch.empty((0,), dtype=anchors.dtype, device=anchors.device)
    if not n:
        return labels, matched, torch.zeros((g,), dtype=anchors.dtype, device=anchors.device)
    iou = pairwise_iou(anchors, gt)
    best_per_anchor, matched = iou.max(dim=1)  # torch.max resuelve empate por el primer índice
    best_per_gt = iou.max(dim=0).values
    labels[best_per_anchor < neg_thr] = 0
    labels[best_per_anchor > pos_thr] = 1
    labels[(iou == best_per_gt[None, :]).any(dim=1)] = 1
    return labels, matched, best_per_gt


def sample_labels(labels, batch_size, positive_fraction, generator):
    """Elige sin reemplazo índices de positivos y negativos; omite ignorados."""
    if batch_size < 0 or not 0 <= positive_fraction <= 1:
        raise ValueError('Tamaño o fracción de muestreo inválidos')
    pos = torch.where(labels == 1)[0]
    neg = torch.where(labels == 0)[0]
    count_pos = min(len(pos), int(batch_size * positive_fraction))
    count_neg = min(len(neg), batch_size - count_pos)
    # El generador se crea en el mismo dispositivo que las etiquetas.
    pos = pos[torch.randperm(len(pos), generator=generator, device=labels.device)[:count_pos]]
    neg = neg[torch.randperm(len(neg), generator=generator, device=labels.device)[:count_neg]]
    return torch.cat((pos, neg))


def encode_boxes(anchors, gt):
    check_boxes(anchors)
    check_boxes(gt)
    if anchors.shape != gt.shape:
        raise ValueError('Una caja objetivo por anchor')
    a_wh, g_wh = anchors[:, 2:] - anchors[:, :2], gt[:, 2:] - gt[:, :2]
    a_center, g_center = anchors[:, :2] + a_wh / 2, gt[:, :2] + g_wh / 2
    return torch.cat(((g_center - a_center) / a_wh, torch.log(g_wh / a_wh)), dim=1)


def decode_boxes(anchors, deltas):
    check_boxes(anchors)
    if anchors.shape != deltas.shape or not torch.isfinite(deltas).all():
        raise ValueError('Desplazamientos finitos de forma (N, 4)')
    a_wh = anchors[:, 2:] - anchors[:, :2]
    center = anchors[:, :2] + a_wh / 2 + deltas[:, :2] * a_wh
    wh = a_wh * torch.exp(deltas[:, 2:])
    decoded = torch.cat((center - wh / 2, center + wh / 2), dim=1)
    return check_boxes(decoded)


class RPNHead(nn.Module):
    def __init__(self, channels, anchors_per_position):
        super().__init__()
        self.count = anchors_per_position
        self.conv = nn.Conv2d(channels, channels, 3, padding=1)
        self.objectness = nn.Conv2d(channels, anchors_per_position, 1)
        self.box_deltas = nn.Conv2d(channels, 4 * anchors_per_position, 1)

    def forward(self, features):
        # Aplana primero y, x, anchor; las cuatro coordenadas permanecen juntas.
        logits, deltas = [], []
        for feature in features:
            hidden = F.relu(self.conv(feature))
            batch, _, height, width = hidden.shape
            logits.append(self.objectness(hidden).permute(0, 2, 3, 1).reshape(batch, -1))
            raw = self.box_deltas(hidden).reshape(batch, self.count, 4, height, width)
            deltas.append(raw.permute(0, 3, 4, 1, 2).reshape(batch, -1, 4))
        return torch.cat(logits, dim=1), torch.cat(deltas, dim=1)


def rpn_loss(logits, deltas, anchors, targets, *, batch_size=256, positive_fraction=.5, seed=17):
    if logits.ndim != 2 or deltas.shape != (*logits.shape, 4) or logits.shape[1] != len(anchors):
        raise ValueError('Formas incompatibles entre RPN y anchors')
    if len(targets) != len(logits):
        raise ValueError('Se espera un conjunto de GT por imagen')
    generator = torch.Generator(device=logits.device).manual_seed(seed)
    cls_sum = logits.sum() * 0
    box_sum = deltas.sum() * 0
    total = positives = 0
    per_image = []
    for i, gt in enumerate(targets):
        labels, matched, best = assign_anchors(anchors, gt)
        chosen = sample_labels(labels, batch_size, positive_fraction, generator)
        pos = chosen[labels[chosen] == 1]
        if len(chosen):
            cls_sum = cls_sum + F.binary_cross_entropy_with_logits(logits[i, chosen], labels[chosen].to(logits.dtype), reduction='sum')
        if len(pos):
            encoded = encode_boxes(anchors[pos], gt[matched[pos]])
            box_sum = box_sum + F.smooth_l1_loss(deltas[i, pos], encoded, beta=1/9, reduction='sum')
        positives += len(pos)
        total += len(chosen)
        coverage = [int(((labels == 1) & (matched == j)).sum()) for j in range(len(gt))]
        per_image.append({'positive_before_sampling': int((labels == 1).sum()),
                          'negative_before_sampling': int((labels == 0).sum()),
                          'ignored': int((labels == -1).sum()),
                          'sampled': len(chosen), 'sampled_positive': len(pos),
                          'regression_anchors_per_gt_before_sampling': coverage,
                          'best_iou_per_gt': best.tolist()})
    divisor = max(total, 1)
    return cls_sum / divisor, box_sum / divisor, per_image


def main():
    torch.manual_seed(1617)
    generator = torch.Generator().manual_seed(1617)
    features = [torch.randn(2, 8, 4, 5, generator=generator), torch.randn(2, 8, 2, 3, generator=generator)]
    specs = [(4, 5, 8, 16), (2, 3, 16, 32)]
    anchors = torch.cat([make_anchors(h, w, stride, size, [.5, 1., 2.]) for h, w, stride, size in specs])
    targets = [torch.tensor([[8., 8., 24., 24.], [20., 4., 36., 20.]]), torch.empty((0, 4))]
    head = RPNHead(8, 3)
    logits, deltas = head(features)
    cls, reg, info = rpn_loss(logits, deltas, anchors, targets, batch_size=64, positive_fraction=.5)
    loss = cls + reg
    loss.backward()
    assert all(p.grad is not None and torch.isfinite(p.grad).all() for p in head.parameters())
    print('Anchors por nivel:', [h*w*3 for h,w,_,_ in specs], 'total:', len(anchors))
    print('Formas logits y desplazamientos:', tuple(logits.shape), tuple(deltas.shape))
    print('Pérdidas objectness y regresión:', round(cls.item(), 6), round(reg.item(), 6))
    print('Asignación y muestreo por imagen:', info)
    print('Todos los gradientes de la cabeza son finitos.')


if __name__ == '__main__':
    main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

RoIAlign and FPN

The second cell implements aligned RoIAlign with fixed boxes and map gradients, and an FPN connected to ResNet-50. The looped operator is a teaching reference, not a fast replacement for TorchVision’s kernel. Check coordinates and options match before comparing results.

[ ]RoIAlign and FPN from scratchLocal GPU
"""RoIAlign alineado y FPN didácticos, más un backbone ResNet-50.

RoIAlign usa cajas (K,5): índice de imagen, x1, y1, x2, y2 en coordenadas
de imagen. Las cajas se tratan como datos fijos: no hay gradiente respecto
a sus coordenadas. Sí hay gradiente respecto al mapa de características.
Se aplica escala y después el desplazamiento -0,5 de aligned=True. Los
valores fuera de [-1,H] o [-1,W] son cero; los demás se limitan al borde.
Es una referencia con bucles, no una alternativa rápida al operador nativo.
"""
from collections import OrderedDict
import math
import torch
from torch import nn
from torch.nn import functional as F
from torchvision.models import resnet50


def roi_align_puro(feature, boxes, output_size, spatial_scale=1., sampling_ratio=-1):
    if feature.ndim != 4 or not feature.is_floating_point():
        raise ValueError('feature debe tener forma flotante (N,C,H,W)')
    n, channels, height, width = feature.shape
    if min(n, channels, height, width) <= 0 or boxes.ndim != 2 or boxes.shape[1] != 5:
        raise ValueError('Dimensiones de feature o cajas inválidas')
    if not torch.isfinite(boxes).all() or boxes.requires_grad:
        raise ValueError('Las cajas deben ser finitas y fijas')
    if isinstance(output_size, int):
        out_h = out_w = output_size
    else:
        out_h, out_w = output_size
    if out_h <= 0 or out_w <= 0 or not math.isfinite(spatial_scale) or spatial_scale <= 0:
        raise ValueError('Tamaño de salida y escala deben ser positivos')
    if not len(boxes):
        return feature.new_zeros((0, channels, out_h, out_w)) + feature[..., :0].sum()

    def sample(image, y, x):
        # Convención del kernel nativo: fuera de este intervalo es cero.
        if y < -1 or y > height or x < -1 or x > width:
            return feature[image, :, 0, 0].nan_to_num(nan=0., posinf=0., neginf=0.) * 0
        y, x = max(0., y), max(0., x)
        y0, x0 = min(int(y), height-1), min(int(x), width-1)
        y1, x1 = min(y0+1, height-1), min(x0+1, width-1)
        if y0 == height-1:
            y = float(y0)
        if x0 == width-1:
            x = float(x0)
        ly, lx = y-y0, x-x0
        return ((1-ly)*(1-lx)*feature[image,:,y0,x0] + (1-ly)*lx*feature[image,:,y0,x1]
                + ly*(1-lx)*feature[image,:,y1,x0] + ly*lx*feature[image,:,y1,x1])

    outputs = []
    for box in boxes:
        raw = box.detach().tolist()
        image = int(raw[0])
        if image != raw[0] or not 0 <= image < n or raw[3] <= raw[1] or raw[4] <= raw[2]:
            raise ValueError('Índice o coordenadas xyxy inválidas')
        x0, y0, x1, y1 = (v*spatial_scale-.5 for v in raw[1:])
        roi_w, roi_h = x1-x0, y1-y0
        step_w, step_h = roi_w/out_w, roi_h/out_h
        grid_w = sampling_ratio if sampling_ratio > 0 else max(1, math.ceil(roi_w/out_w))
        grid_h = sampling_ratio if sampling_ratio > 0 else max(1, math.ceil(roi_h/out_h))
        bins = []
        for ph in range(out_h):
            row = []
            for pw in range(out_w):
                samples = [sample(image, y0+(ph+(iy+.5)/grid_h)*step_h,
                                  x0+(pw+(ix+.5)/grid_w)*step_w)
                           for iy in range(grid_h) for ix in range(grid_w)]
                row.append(torch.stack(samples).mean(dim=0))
            bins.append(torch.stack(row, dim=-1))
        outputs.append(torch.stack(bins, dim=-2))
    return torch.stack(outputs)


class FPNDesdeCero(nn.Module):
    """P2 a P5 y P6 por submuestreo; entrada C2 a C5 en ese orden."""
    def __init__(self, in_channels=(256,512,1024,2048), out_channels=256):
        super().__init__()
        self.lateral = nn.ModuleList(nn.Conv2d(c, out_channels, 1) for c in in_channels)
        self.output = nn.ModuleList(nn.Conv2d(out_channels, out_channels, 3, padding=1) for _ in in_channels)

    def forward(self, features):
        if len(features) != len(self.lateral):
            raise ValueError('Un mapa por etapa de la FPN')
        inner = self.lateral[-1](features[-1])
        results = [self.output[-1](inner)]
        for i in range(len(features)-2, -1, -1):
            lateral = self.lateral[i](features[i])
            inner = lateral + F.interpolate(inner, size=lateral.shape[-2:], mode='nearest')
            results.insert(0, self.output[i](inner))
        results.append(F.max_pool2d(results[-1], kernel_size=1, stride=2))
        return OrderedDict((f'P{i+2}', value) for i, value in enumerate(results))


def resnet50_stages(backbone, images):
    x = backbone.maxpool(backbone.relu(backbone.bn1(backbone.conv1(images))))
    c2 = backbone.layer1(x)
    c3 = backbone.layer2(c2)
    c4 = backbone.layer3(c3)
    c5 = backbone.layer4(c4)
    return [c2, c3, c4, c5]


def main():
    torch.manual_seed(1617)
    # Sin pesos preentrenados ni afirmación de precisión: demostración de formas.
    backbone = resnet50(weights=None).eval()
    fpn = FPNDesdeCero().eval()
    with torch.no_grad():
        stages = resnet50_stages(backbone, torch.randn(1, 3, 65, 79))
        pyramid = fpn(stages)
    print('C2 a C5:', [tuple(c.shape) for c in stages])
    print('P2 a P6:', {key:tuple(value.shape) for key,value in pyramid.items()})
    feature = torch.arange(16, dtype=torch.float64).reshape(1,1,4,4).requires_grad_()
    box = torch.tensor([[0., .5, .5, 3.5, 3.5]], dtype=torch.float64)
    pooled = roi_align_puro(feature, box, (2,2), sampling_ratio=2)
    pooled.sum().backward()
    print('RoIAlign:', pooled.detach().flatten().tolist())
    print('Gradiente finito:', bool(torch.isfinite(feature.grad).all()))
    # Referencia nativa: dos imágenes, región fraccionaria y región que cruza el borde.
    from torchvision.ops import roi_align as native_roi_align
    feature = torch.arange(2*7*8, dtype=torch.float64).reshape(2,1,7,8).requires_grad_()
    boxes = torch.tensor([[0., .2,.4,6.3,5.8], [1., -1.,-1.,7.,6.]], dtype=torch.float64)
    ours = roi_align_puro(feature, boxes, (2,3), spatial_scale=1., sampling_ratio=2)
    our_grad = torch.autograd.grad(ours.square().sum(), feature)[0]
    ref_feature = feature.detach().clone().requires_grad_()
    reference = native_roi_align(ref_feature, boxes, (2,3), spatial_scale=1., sampling_ratio=2, aligned=True)
    ref_grad = torch.autograd.grad(reference.square().sum(), ref_feature)[0]
    torch.testing.assert_close(ours, reference, rtol=1e-8, atol=1e-8)
    torch.testing.assert_close(our_grad, ref_grad, rtol=1e-8, atol=1e-8)
    print('RoIAlign frente a TorchVision: salida y gradiente coinciden')


if __name__ == '__main__':
    main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Fine-tuning on VOC

The local cell starts with Faster R-CNN using COCO weights and retains its head’s 91 outputs. It uses disjoint VOC2007 train and val identifiers, removes images with difficult annotations, checks hashes and maps VOC’s 20 classes to COCO indices by name. Because VOC does not annotate all COCO classes, objects of unlabeled classes can be treated as background during tuning. Validation compares initial and final states; the final state is saved if requested, rather than selecting the best checkpoint. This exploratory validation does not replace independent test.

Layer4, FPN, RPN and the region head are trained, with earlier stages frozen and BatchNorm in evaluation. The custom evaluation comes from the current detection mAP cell and is checked against TorchMetrics. Sizes and object recall are broken down without attributing causality to one stage. Readers can save the checkpoint by setting ORYON_CHECKPOINT_DIR; the cell refuses to overwrite it. Full mode runs 2000 steps, while ORYON_VERIFY_SHORT=1 limits images and steps to verify the flow.

In a short run of the cell itself, with 12 training images, 8 validation images and 4 steps, own AP changed from 0.61697 to 0.61849; TorchMetrics gave 0.61697 and 0.61849 rounded to five decimal places. Validation contained 2 medium objects, 15 large and no small ones under the cell’s size ranges. These are exploratory measurements from a tiny sample, not evidence of general improvement or evaluation of small objects; COCO-pretrained weights may share images with VOC.

[ ]Fine-tune and evaluate Faster R-CNNLocal GPU
"""Ajuste breve o completo de Faster R-CNN FPN en VOC2007.

Requiere torch, torchvision, torchmetrics, pycocotools, numpy, Pillow y
huggingface_hub. Usa el espejo y los pesos de m16-l16 en las cachés comunes.
ORYON_VERIFY_SHORT=1 limita muestras y pasos; solo verifica el circuito.
Los resultados de validación son exploratorios, no son el protocolo oficial
VOC ni un test independiente. No se prueba ausencia de solapamiento con COCO.
La cabeza conserva las clases COCO, pero VOC solo anota sus 20 clases: otros
objetos COCO no anotados en las imágenes pueden tratarse como fondo al ajustar.
Solo si se define ORYON_CHECKPOINT_DIR se guarda el estado final en ese
directorio. No se sobrescribe un checkpoint existente.
"""
import hashlib
import io
import json
import os
import tarfile
import xml.etree.ElementTree as ET
from pathlib import Path

import numpy as np
from PIL import Image
from huggingface_hub import hf_hub_download
import torch
from torch import nn
from torchmetrics.detection.mean_ap import MeanAveragePrecision
from torchvision.models.detection import fasterrcnn_resnet50_fpn, FasterRCNN_ResNet50_FPN_Weights

os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG', ':4096:8')
torch.set_num_threads(1)
torch.backends.cudnn.benchmark = False
short = os.environ.get('ORYON_VERIFY_SHORT') == '1'
steps = 4 if short else 2000
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
seed = 16171
repo = 'davin11/VOC2007'
revision = 'fa6fc00e5e617859ce9b7aa7abd581c7bd8ffa15'
filename = 'VOCtrainval_06-Nov-2007.tar'
checksum = '7d8cd951101b0957ddfd7a530bdc8a94f06121cfc1e511bb5937e973020c7508'
weights = FasterRCNN_ResNet50_FPN_Weights.COCO_V1
names = weights.meta['categories']
voc_names = ['aeroplane','bicycle','bird','boat','bottle','bus','car','cat','chair','cow',
             'diningtable','dog','horse','motorbike','person','pottedplant','sheep','sofa','train','tvmonitor']
aliases = {'aeroplane':'airplane', 'diningtable':'dining table', 'motorbike':'motorcycle',
           'pottedplant':'potted plant', 'sofa':'couch', 'tvmonitor':'tv'}
mapping = {name:names.index(aliases.get(name,name)) for name in voc_names}
allowed = set(mapping.values())
transform = weights.transforms()


def sha256_file(path):
    digest = hashlib.sha256()
    with open(path,'rb') as stream:
        for part in iter(lambda:stream.read(1024*1024),b''):
            digest.update(part)
    return digest.hexdigest()


def iou_matrix(box, boxes):
    if not len(boxes):
        return np.empty(0, dtype=np.float64)
    lo = np.maximum(box[:2], boxes[:, :2])
    hi = np.minimum(box[2:], boxes[:, 2:])
    intersection = np.maximum(hi-lo, 0).prod(axis=1)
    area_a = np.maximum(box[2:]-box[:2], 0).prod()
    area_b = np.maximum(boxes[:, 2:]-boxes[:, :2], 0).prod(axis=1)
    return np.divide(intersection, area_a+area_b-intersection,
                     out=np.zeros_like(intersection), where=(area_a+area_b-intersection)>0)
def own_ap(predictions, targets, thresholds=np.linspace(.5,.95,10), max_det=100):
    """Área all, sin ignore/crowd: matching por imagen y clase; 101 recalls."""
    classes = sorted({int(c) for target in targets for c in target['labels'].tolist()})
    table = []
    for threshold in thresholds:
        scores_by_class = []
        for category in classes:
            events, num_gt = [], 0
            for prediction, target in zip(predictions, targets):
                gt = target['boxes'][target['labels']==category].numpy().astype(np.float64)
                num_gt += len(gt)
                mask = prediction['labels']==category
                boxes = prediction['boxes'][mask].numpy().astype(np.float64)
                scores = prediction['scores'][mask].numpy().astype(np.float64)
                order = np.argsort(-scores, kind='stable')[:max_det]
                used = np.zeros(len(gt), dtype=bool)
                for idx in order:
                    overlaps = iou_matrix(boxes[idx], gt)
                    best, current = -1, min(float(threshold), 1-1e-10)
                    for j, overlap in enumerate(overlaps):
                        if used[j] or overlap < current:
                            continue
                        best, current = j, overlap
                    if best >= 0:
                        used[best] = True
                    events.append((float(scores[idx]), int(best >= 0)))
            events.sort(key=lambda event: -event[0])  # estable entre imágenes y empates
            if not events:
                scores_by_class.append(0.)
                continue
            tp = np.cumsum([event[1] for event in events])
            fp = np.cumsum([1-event[1] for event in events])
            recall = tp/num_gt
            precision = tp/np.maximum(tp+fp, 1)
            precision = np.maximum.accumulate(precision[::-1])[::-1]
            ix = np.searchsorted(recall, np.linspace(0,1,101), side='left')
            interpolated = np.zeros(101)
            valid = ix < len(precision)
            interpolated[valid] = precision[ix[valid]]
            scores_by_class.append(float(interpolated.mean()))
        table.append(float(np.mean(scores_by_class)) if scores_by_class else None)
    return {'map': float(np.mean(table)), 'map_50': table[0], 'map_75': table[5],
            'per_iou': table, 'classes_with_ground_truth': classes}


def read_voc(path):
    """Conserva train/val, descarta difficult y copias exactas entre grupos."""
    prefix='VOCdevkit/VOC2007/'
    groups, seen = {'train':[], 'val':[]}, {}
    excluded={'difficult':{'train':0,'val':0}, 'duplicate':{'train':0,'val':0}}
    with tarfile.open(path,'r:') as archive:
        ids={s:archive.extractfile(prefix+f'ImageSets/Main/{s}.txt').read().decode('ascii').split() for s in groups}
        if not set(ids['train']).isdisjoint(ids['val']):
            raise ValueError('IDs presentes en train y validación')
        for split in ('train','val'):
            cap = (12 if split == 'train' else 8) if short else None
            for image_id in ids[split]:
                root=ET.fromstring(archive.extractfile(prefix+'Annotations/'+image_id+'.xml').read())
                objects=root.findall('object')
                if any(int(o.findtext('difficult',default='0')) for o in objects):
                    excluded['difficult'][split]+=1
                    continue
                if not objects:
                    continue
                boxes=[]
                labels=[]
                for obj in objects:
                    box=obj.find('bndbox')
                    xyxy=[int(box.findtext('xmin'))-1,int(box.findtext('ymin'))-1,
                          int(box.findtext('xmax')),int(box.findtext('ymax'))]
                    if xyxy[2]<=xyxy[0] or xyxy[3]<=xyxy[1]:
                        raise ValueError('Caja degenerada en '+image_id)
                    boxes.append(xyxy)
                    labels.append(mapping[obj.findtext('name')])
                raw=archive.extractfile(prefix+'JPEGImages/'+image_id+'.jpg').read()
                digest=hashlib.sha256(raw).hexdigest()
                if digest in seen:
                    excluded['duplicate'][split]+=1
                    continue
                seen[digest]=split
                groups[split].append({'id':image_id,'bytes':raw,'sha256':digest,'boxes':boxes,'labels':labels})
                if cap is not None and len(groups[split])>=cap:
                    break
    if not groups['train'] or not groups['val']:
        raise ValueError('Falta train o validación tras filtrar')
    return groups, excluded


def input_target(row, flip=False):
    with Image.open(io.BytesIO(row['bytes'])) as image:
        x=transform(image.convert('RGB'))
    boxes=torch.tensor(row['boxes'],dtype=torch.float32).reshape(-1,4)
    if flip:
        x=x.flip(-1)
        width=x.shape[-1]
        boxes=boxes.clone()
        boxes[:,0],boxes[:,2]=width-boxes[:,2].clone(),width-boxes[:,0].clone()
    y={'boxes':boxes.to(device),'labels':torch.tensor(row['labels'],dtype=torch.int64,device=device)}
    return x.to(device),y


def freeze_bn(model):
    for module in model.modules():
        if isinstance(module,nn.modules.batchnorm._BatchNorm):
            module.eval()


def configure(model):
    for param in model.parameters(): param.requires_grad_(False)
    # Mantiene tallo y layer1-3 congelados. FPN, layer4, RPN y ROI se ajustan.
    for module in (model.backbone.body.layer4,model.backbone.fpn,model.rpn,model.roi_heads):
        for param in module.parameters(): param.requires_grad_(True)
    trainable=[p for p in model.parameters() if p.requires_grad]
    return torch.optim.SGD(trainable,lr=.001,momentum=.9,weight_decay=.0001)


def size_recall(predictions,targets,score_threshold=.5):
    """Recall diagnóstico IoU .5 por área GT; no es AP por tamaño."""
    counts={k:{'matched':0,'total':0} for k in ('small','medium','large')}
    for pred,target in zip(predictions,targets):
        boxes=target['boxes'].numpy()
        labels=target['labels'].numpy()
        used=set()
        for i in np.argsort(-pred['scores'].numpy(),kind='stable'):
            if float(pred['scores'][i])<score_threshold: continue
            ious=iou_matrix(pred['boxes'][i].numpy(),boxes)
            valid=[j for j in range(len(boxes)) if j not in used and labels[j]==int(pred['labels'][i]) and ious[j]>=.5]
            if valid: used.add(max(valid,key=lambda j:(ious[j],-j)))
        for j,b in enumerate(boxes):
            area=float((b[2]-b[0])*(b[3]-b[1]))
            group='small' if area<32**2 else ('medium' if area<96**2 else 'large')
            counts[group]['total']+=1
            counts[group]['matched']+=int(j in used)
    return counts


def evaluate(model,rows):
    model.eval()
    predictions=[]
    targets=[]
    with torch.no_grad():
        for row in rows:
            x,target=input_target(row)
            result=model([x])[0]
            mask=torch.tensor([int(label) in allowed for label in result['labels']],device=device)
            predictions.append({k:result[k][mask].float().cpu() if k!='labels' else result[k][mask].cpu() for k in ('boxes','scores','labels')})
            targets.append({k:v.cpu() for k,v in target.items()})
    own=own_ap(predictions,targets)
    metric=MeanAveragePrecision(box_format='xyxy',iou_type='bbox',backend='pycocotools')
    metric.update(predictions,targets)
    ref=metric.compute()
    for key in ('map','map_50','map_75'):
        if not np.isclose(own[key],float(ref[key]),atol=1e-6,rtol=0):
            raise AssertionError(f'{key}: propia {own[key]}, referencia {float(ref[key])}')
    sizes={k:(None if float(ref[k])<0 else float(ref[k])) for k in ('map_small','map_medium','map_large')}
    return {'own':own,'reference':{k:float(ref[k]) for k in ('map','map_50','map_75')},
            'ap_by_size':sizes,'recall_by_size_at_iou50_score50':size_recall(predictions,targets)}


def main():
    if device.type!='cuda': raise RuntimeError('Se requiere CUDA para este laboratorio')
    checkpoint_dir=os.environ.get('ORYON_CHECKPOINT_DIR')
    checkpoint_path=Path(checkpoint_dir)/'voc-finetune-final.pt' if checkpoint_dir else None
    if checkpoint_path is not None and checkpoint_path.exists():
        raise FileExistsError(f'El checkpoint ya existe: {checkpoint_path}')
    torch.manual_seed(seed)
    np_rng=np.random.default_rng(seed+1)
    flip_rng=torch.Generator().manual_seed(seed+2)
    path=hf_hub_download(repo_id=repo,repo_type='dataset',revision=revision,filename=filename)
    if sha256_file(path)!=checksum: raise ValueError('Tar VOC con hash inesperado')
    groups,excluded=read_voc(path)
    model=fasterrcnn_resnet50_fpn(weights=weights,box_score_thresh=0.,box_detections_per_img=100).to(device)
    optimizer=configure(model)
    bf16=torch.cuda.is_bf16_supported()
    dtype=torch.bfloat16 if bf16 else torch.float16
    scaler=torch.amp.GradScaler('cuda',enabled=not bf16)
    before=evaluate(model,groups['val'])
    history=[]
    for step in range(1,steps+1):
        model.train()
        freeze_bn(model)
        index=int(np_rng.integers(0,len(groups['train'])))
        flip=bool(torch.rand((),generator=flip_rng)<.5)
        x,target=input_target(groups['train'][index],flip)
        optimizer.zero_grad(set_to_none=True)
        with torch.autocast('cuda',dtype=dtype):
            pieces=model([x],[target])
            loss=sum(pieces.values())
        if not bool(torch.isfinite(loss)):
            raise FloatingPointError(f'Pérdida no finita en paso {step}')
        scaler.scale(loss).backward()
        scaler.unscale_(optimizer)
        grads=[p.grad for group in optimizer.param_groups for p in group['params'] if p.grad is not None]
        if not grads or any(not bool(torch.isfinite(g).all()) for g in grads):
            raise FloatingPointError(f'Gradiente no finito en paso {step}')
        scaler.step(optimizer)
        scaler.update()
        history.append({'step':step,'image_id':groups['train'][index]['id'],'flip':flip,
                        'loss':float(loss.detach()),'losses':{k:float(v.detach()) for k,v in pieces.items()}})
        if step in (1,steps): print('paso',step,'pérdida',history[-1]['loss'],flush=True)
    after=evaluate(model,groups['val'])
    output={'protocol':{'short':short,'steps':steps,'seed':seed,'dataset':repo,'revision':revision,
        'split':'VOC2007 train y val; no se usa test', 'exclude':excluded,
        'train_ids':[r['id'] for r in groups['train']],'validation_ids':[r['id'] for r in groups['val']],
        'weights':'FasterRCNN_ResNet50_FPN_Weights.COCO_V1','labels':mapping,
        'bn':'estadísticas congeladas','amp':str(dtype),'batch_size':1,
        'optimization':'SGD lr=0,001 momentum=0,9 wd=0,0001; entrenables FPN, layer4, RPN y ROI',
        'note':'AP propia de m16-l16: área all sin crowd; no es VOC oficial. AP por tamaño de TorchMetrics. La validación se consulta dos veces y es exploratoria; posible solapamiento con COCO no descartado. VOC no anota las demás clases COCO, que podrían tratarse como fondo al ajustar.'},
        'baseline_validation':before,'final_validation':after,'training':history}
    if checkpoint_path is not None:
        checkpoint_path.parent.mkdir(parents=True,exist_ok=True)
        with checkpoint_path.open('xb') as stream:
            torch.save({'model':model.state_dict(),'optimizer':optimizer.state_dict(),
                        'steps':steps,'class_mapping':mapping,'seed':seed},stream)
        output['checkpoint']=str(checkpoint_path)
    out=Path(os.environ.get('ORYON_FASTER_OUTPUT','voc-finetune.json'))
    out.write_text(json.dumps(output,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8')
    print('validación antes:',before,'después:',after,'archivo:',out,flush=True)
    del model,optimizer
    torch.cuda.empty_cache()


if __name__=='__main__':
    main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

CodeInterpolate an RoI
Implement roi_align(feature, boxes, output_size, spatial_scale, sampling_ratio) in pure PyTorch without calling torchvision.ops.roi_align. feature has shape N×C×H×W and boxes shape K×5 with image index and image xyxy coordinates. Use aligned=True: scale and subtract 0.5, bilinearly interpolate each point and average sampling_ratio×sampling_ratio samples per bin. Scale must be positive and finite. Samples completely outside the map are zero even when the map contains nonfinite values; empty output retains a gradient connection to the map. Tests use positive sampling_ratio, fixed boxes and check gradients with respect to the map.
import torch

def roi_align(feature, boxes, output_size, spatial_scale, sampling_ratio):
  pass
Shift+Enter to run
NumericCount the anchors
An 800×1216 image produces P2–P6 maps with strides 4, 8, 16, 32 and 64. For each dimension use ceiling of size/stride; there is one scale and three ratios per position. How many anchors are there before boundary filtering?
NumericA small region
The FPN rule uses k=floor(4+log₂(√(wh)/224)) and clips to P2–P5. Which level number receives a 32×32 RoI?
NumericA medium region
With the same rule and P2–P5, which level number receives a 112×112 RoI?
NumericA large region
With the same rule and P2–P5, which level number receives a 448×448 RoI?
CodeForce coverage when possible
Implement assign_anchors(anchors, gt_boxes, pos_thr, neg_thr) with NumPy for continuous positive-area xyxy boxes. Return (labels, assigned): initially labels is 1 if the anchor’s best IoU is at least pos_thr, 0 if below neg_thr and −1 otherwise; assigned contains the highest-IoU GT for positives and −1 for others. Then for each GT force its maximum-IoU anchor positive, breaking ties by smaller index, and assign it to that GT even if another had higher IoU with the anchor. If two GTs force the same anchor, raise ValueError: this policy cannot cover both with one target. With no GT all are negative and assigned is −1; with GT but no anchors raise ValueError. Coverage is before subsampling.
import numpy as np

def assign_anchors(anchors, gt_boxes, pos_thr, neg_thr):
  pass
Shift+Enter to run
QuizWhere to investigate?
At IoU 0.5, proposal recall for small objects is low even before classification; for covered objects classification is usually correct. Which experiment is most direct?
QuizGood regions, wrong classes
Proposals cover objects and final boxes align well, but are often assigned the wrong class. Which component deserves investigation first?
QuizCorrect class, shifted box
Proposals cover objects and classes are correct, but many refined boxes are shifted and miss required IoU. Where would you start?
QuizCovered objects that disappear
Before NMS there are two correct boxes for two overlapping objects of the same class; afterward only one remains. Which component would you investigate?
Key idea
A good second stage cannot compensate for missing proposals. Anchors, spatial alignment and pyramids are coupled decisions that must be checked with the same coordinates and evaluation protocol.