Module contents
Lesson 18 of 25Advanced 120 min

Object detection III: one-stage, focal loss, anchor-free and DETR

Study one-stage detection, focal loss, FCOS assignment and DETR set prediction, and compare short controlled detector experiments.

After this lesson you can

  • Explain dense one-stage detection and the role of postprocessing.
  • Derive a numerically stable focal loss and its complete gradient.
  • Assign FCOS point targets and centerness.
  • Distinguish DETR matching costs from losses after matching.
  • Interpret detector accuracy, convergence and latency under their full protocols.

Before you start

A dense prediction at each position

In video or robotics, both box quality and time until a response can matter. A two-stage detector generates proposals and then classifies and refines them. A one-stage detector densely predicts classes and boxes from feature maps without a separate proposal stage. It can still use filtering, candidate selection and NMS at the end. One stage does not by definition imply lower latency on every hardware or implementation.

YOLO v1 formulated detection as regression over a grid: it assigns each object to its center cell and selects a responsible predictor among that cell’s predictors. It used squared-error loss and not later versions’ anchors. SSD predicts reference boxes and classes from maps at several resolutions and selects hard negatives. For SSD300, the paper reports 74.3% mAP on VOC2007 and 59 images per second on a Titan X at batch 8; at batch 1 it reports 46 images per second. These belong to its protocol, not COCO AP or measurements on this machine.

The YOLO genealogy includes different branches and teams. v2 added anchors and multiscale training; v3 predicted at three scales; v4 combined architecture and augmentation techniques; v5 developed a PyTorch implementation with size variants; v6 targeted efficient industrial detection; v7 studied architecture and training; v8 added an anchor-free head in the Ultralytics family; v9 proposed programmable gradient information; v10 explored dual assignment for NMS-free inference; YOLO11 revised backbone and neck; and v12 studied attention-centered architectures. These choices do not equally describe all variants.

Many easy negatives

A dense detector can evaluate around 100,000 anchors per image, only a small fraction corresponding to objects. Even if each easy negative has little individual loss, their sum and gradients can dominate. RetinaNet proposed focal loss to reduce that contribution without necessarily discarding examples.

For y∈{0,1}y\in\{0,1\}, q=2y−1q=2y-1, logit zz, pt=σ(qz)p_t=\sigma(qz) and weight αt=α\alpha_t=\alpha if y=1y=1 or 1−α1-\alpha if y=0y=0:

LFL=−αt(1−pt)γlog⁡pt.L_{FL}=-\alpha_t(1-p_t)^\gamma\log p_t.

Differentiating the modulator too gives

∂LFL∂z=αtq(1−pt)γ[γptlog⁡pt−(1−pt)].\frac{\partial L_{FL}}{\partial z}=\alpha_tq(1-p_t)^\gamma\left[\gamma p_t\log p_t-(1-p_t)\right].

With γ=0\gamma=0 this becomes binary cross-entropy weighted by αt\alpha_t; it is ordinary BCE only if the applicable weight is one. Loss factor (1−pt)γ(1-p_t)^\gamma is not generally the gradient ratio: the modulator also depends on the logit. For stability calculate log⁡pt=−softplus⁡(−qz)\log p_t=-\operatorname{softplus}(-qz) and 1−pt=σ(−qz)1-p_t=\sigma(-qz) rather than taking the logarithm of a probability rounded to zero.

InteractiveFocal loss downweights easy examples

For an object logit z and label y ∈ {0, 1}, pₜ is the probability assigned to the correct class. αₜ = α for object and 1 − α for background. The dashed curve fixes γ = 0 with the same α.

Loss per example0.000.01.730.53.451.0pₜ
  • Focal with chosen γ
  • γ = 0
  • Chosen example
Contribution by pₜ interval0.00.0247.40.5494.81.0pₜ
  • Background, y = 0
  • Object, y = 1

Bars sum contributions; they do not count anchors. The vertical axis rescales with the controls. For the selected quantity, 591.123 comes from background and 52.498 from objects.

Hypothetical batch of 100,000 anchors, not measured results. Background: 70,000 with pₜ = 0.995; 20,000 with 0.95; 7,000 with 0.75; 2,000 with 0.40. Object: 300 with 0.30; 400 with 0.60; 300 with 0.90. Each interval is [a, b), except the last which includes 1.

FL = −αₜ(1 − pₜ)γ log(pₜ). With t = 2y − 1, pₜ = sigmoid(tz), ∂FL/∂z = αₜt(1 − pₜ)γ[γpₜ log(pₜ) − (1 − pₜ)]. The sum of gradient magnitudes is not the total gradient: each anchor’s signs and Jacobians can cancel or alter the result.

For γ = 0, weighted cross-entropy is recovered. The factor (1 − pₜ)γ multiplies the loss, but not the entire gradient: differentiation introduces another term. The greater relative contribution of difficult examples depends on the batch and α, and is not a universal guarantee. Model inspired by Lin and colleagues.

2.0
0.25
0.95
Curve example class
Displayed contribution
Example focal loss0.000096
Same example with γ = 00.038470
Ratio to γ = 00.002500
Batch sum643.621
Sum with γ = 04066.607
Fraction contributed by background91.8 %
Compare loss and contributions from an explicit example population; changing γ does not change how many examples exist.

Initial bias b=log⁡(π/(1−π))b=\log(\pi/(1-\pi)) produces initial probability π\pi if the rest of the logit is zero. With π=0,01\pi=0,01 (0.01), b≈−4,59512b\approx-4,59512 (−4.59512): this is an initialization prior, not a guarantee about later predictions. A common reduction divides summed loss by assigned positive count with an explicit convention when zero; dividing by all anchors changes gradient scale. In RetinaNet table 1b, the published comparison obtains 31.1 AP with cross-entropy and 34.0 with focal γ=2\gamma=2, using different tuned α\alpha values. Not all hyperparameters are held fixed in that comparison.

Points and distances: FCOS

In anchor-free detection, a map position can directly predict distances to a box’s four sides. For point (x,y)(x,y) inside (x1,y1,x2,y2)(x_1,y_1,x_2,y_2), FCOS uses l=x−x1l=x-x_1, t=y−y1t=y-y_1, r=x2−xr=x_2-x and b=y2−yb=y_2-y. For a strictly interior point and valid box, all four distances are positive. An implementation must state treatment of boundary points, degenerate boxes and ties.

Label assignment also depends on pyramid level. FCOS compares max⁡(l,t,r,b)\max(l,t,r,b) with per-level size ranges and, if several boxes are eligible, chooses the smallest area. The centerness target is

c∗=min⁡(l,r)max⁡(l,r)min⁡(t,b)max⁡(t,b).c^*=\sqrt{\frac{\min(l,r)}{\max(l,r)}\frac{\min(t,b)}{\max(t,b)}}.

It lies between zero and one for interior points and equals one at the geometric center. The network learns a centerness prediction and combines it with class score; neither that target nor prediction guarantees high final IoU. FCOS applies NMS at the end.

InteractiveWhich point predicts which box

Synthetic 128 × 96 pixel scene with two overlapping boxes. Each point is the center of a cell at the chosen level; the double circle marks the active point.

AB
  • Assigned to A
  • Assigned to B
  • Background

Active range for max(l, t, r, b): [0, 48] pixels. For B: (l, t, r, b) = (12, 9, 33, 16) pixels; centerness = 0.4523.

Candidate A
Distances (l, t, r, b): (42, 24, 8, 26).
Inside: yes · Maximum distance: 42.0 px · Range: yes.
Area: 2500 px² · Eligible: yes.
Candidate B
Distances (l, t, r, b): (12, 9, 33, 16).
Inside: yes · Maximum distance: 33.0 px · Range: yes.
Area: 1125 px² · Eligible: yes.

A = (10, 20, 60, 70) and B = (40, 35, 85, 60), in xyxy. Centers at stride s are ((j + 0.5)s, (i + 0.5)s). For each box, l = x − x₁, t = y − y₁, r = x₂ − x and b = y₂ − y; an interior point requires all four distances to be strictly positive.

Among boxes containing the point and whose maximum distance falls within the level range, the one with the smallest area is chosen; ties select A. P3 uses [0, 48], P4 (48, 80] and P5 (80, ∞), in pixels. This convention resolves boundaries explicitly. The example omits center sampling and does not train a network.

For an assigned point, centerness = √[(min(l, r)/max(l, r)) · (min(t, b)/max(t, b))]. It is 1 at the geometric center and decreases toward the edges. Changing the range can exclude a box without changing its geometry: assignment and regression are distinct decisions.

Level and stride
48
80
86
Positive points at this level48
Background points at this level144
Points assigned to A30
Points assigned to B18
Points with two candidates6
Selected point(52, 44)
Selected targetB
Centerness0.4523
Explore explicit geometric points and objects with visible distances, centerness and assignment rules.

CenterNet predicts centers through a heatmap as well as size and subpixel offset. It avoids IoU-based box NMS but selects local heatmap maxima: that is still postprocessing. ATSS shows the importance of sample selection: per object it takes candidates near its center at each level, calculates an adaptive threshold from their mean and standard deviation of IoUs and requires the center to lie inside the object. It does not prove all anchor-based and anchor-free architectures equivalent.

Detection as a set: DETR

DETR formulates set prediction with learned object queries in a transformer encoder-decoder producing a fixed set of predictions in parallel. During training it matches each ground-truth object with a distinct query by minimizing global cost; remaining queries receive the “no object” class. With MM objects and QQ queries, Q≥MQ\ge M is needed to match all. If Q<MQ<M, rectangular assignment can match only QQ objects; that limitation must not be hidden.

DETR matching cost combines −p(c)-p(c), box L1 distance and a GIoU term. After matching, classification loss uses −log⁡p(c)-\log p(c) and geometric losses apply to assigned pairs. Although both class terms favor high probabilities, substituting one for the other can change global assignment. Matching indices are discrete: differentiation does not pass through index choice, but losses of selected pairs are differentiated.

DETR also adds auxiliary losses to intermediate decoder outputs during training. Its protocol calculates matching for each supervised output; removing those losses or reusing a fixed assignment are different experimental choices, not a necessary consequence of the transformer.

InteractiveDETR matching

Three objects, ten queries and normalized boxes form an explicit geometric model, not DETR output. Each cell shows the cost of assigning a query to an object: −class weight × probability + L1 weight × distance + GIoU weight × (1 − GIoU).

ABC

Blue: ground-truth objects. Dashed gray: queries. Dashed orange: displayed matched queries.

Scroll the table horizontally to see all ten queries.

Object / queryQ0Q1Q2Q3Q4Q5Q6Q7Q8Q9
A1.062.784.615.824.274.906.297.806.206.56
B7.175.874.136.084.973.280.933.656.985.97
C10.108.417.596.428.207.155.784.266.564.80

A → Q0 · B → Q6 · C → Q7

Reproducible model: query i has center (0.13 + 0.22·(i mod 4), 0.20 + 0.28·floor(i/4)) and size 0.22 × 0.18. Its four logits are sin((i+1)(k+2)), k=0,1,2,3, converted to probabilities with softmax; the last is “no object”. Objects A, B and C use classes 0, 1 and 2 and xyxy boxes (0.08; 0.12; 0.30; 0.32), (0.42; 0.37; 0.70; 0.59) and (0.62; 0.66; 0.91; 0.87).

All 10×9×8 assignments are enumerated and the minimum-cost one selected, breaking ties lexicographically. The control reveals pairs from that solution; it does not simulate internal steps of the Hungarian algorithm. One-to-one assignment during training does not guarantee absence of duplicates at inference.

1.0
5.0
2.0
3
Minimum total cost6.2552
Pairs3
Unmatched queries7
Calculate the cost matrix of explicit predictions and observe its optimal assignment; unmatched queries receive the no-object class.

One-to-one matching encourages nonredundant predictions and the original DETR procedure omits NMS, but this does not prove a particular inference cannot produce duplicates. SciPy’s implementation solves linear assignment using modified Jonker-Volgenant; obtaining an optimal solution does not mean its internal steps match a Hungarian algorithm animation.

DETR table 1 reports 42.0 COCO AP for both Faster R-CNN FPN+ and DETR with ResNet-50; for small objects it reports 26.6 and 20.5 respectively. Training budgets differ, so that table does not identify one cause. Deformable DETR attends to a few reference points and multiple levels; its table 1 reports 43.8 AP and 26.4 small AP after 50 epochs versus DETR’s 42.0 and 20.5 after 500 in that comparison. Mechanisms and configuration also change, not just epochs.

RT-DETR combines a multiscale hybrid encoder with query selection and allows decoder layer count to vary at inference. Its authors report RT-DETR-R50 at 53.1 COCO AP and 108 images per second on a T4 GPU with TensorRT FP16 and 640 × 640 input under their protocol. To choose among families, measure resolution, backbone, batch, numerical precision and preprocessing on the target system: AP and throughput published under different configurations do not determine your application’s latency.

Labs

Focal loss and matching from scratch

The first cell calculates focal loss and its gradient with stable operations and checks it against finite differences. The second separates DETR’s assignment cost from the subsequent loss and handles sets with no objects and more objects than queries.

[ ]Focal loss and gradientBrowser
"""Focal binaria desde logits, con derivada analítica y ejemplo explícito.

Devuelve pérdida y derivada por elemento, sin reducción. El peso α_t vale
α para y=1 y 1−α para y=0. γ=0 da BCE ponderada, no BCE sin pesos.
"""
import numpy as np


def focal_logits(logits, targets, alpha=.25, gamma=2.):
    z, y = np.broadcast_arrays(np.asarray(logits, dtype=np.float64),
                               np.asarray(targets, dtype=np.float64))
    if not np.isfinite(z).all() or not np.isin(y, [0., 1.]).all():
        raise ValueError('Logits finitos y etiquetas binarias')
    if not np.isfinite(alpha) or not 0 <= alpha <= 1 or not np.isfinite(gamma) or gamma < 0:
        raise ValueError('α entre 0 y 1; γ finito y no negativo')
    sign = 2*y-1
    signed = sign*z
    log_pt = -np.logaddexp(0., -signed)
    pt = np.exp(log_pt)
    one_minus_pt = np.exp(-np.logaddexp(0., signed))
    weight = np.where(y == 1, alpha, 1-alpha)
    factor = one_minus_pt ** gamma
    loss = -weight * factor * log_pt
    gradient = weight * sign * factor * (gamma*pt*log_pt - one_minus_pt)
    return loss, gradient


# Derivada analítica frente a diferencias finitas, para ambas clases y γ.
z = np.array([-8., -3., -.4, .5, 3., 8.])
y = np.array([0., 1., 0., 1., 0., 1.])
max_error = 0.
for gamma in (0., .5, 1., 2., 5.):
    loss, analytic = focal_logits(z, y, gamma=gamma)
    h = 1e-5
    numerical = (focal_logits(z+h, y, gamma=gamma)[0] - focal_logits(z-h, y, gamma=gamma)[0])/(2*h)
    max_error = max(max_error, float(np.max(np.abs(analytic-numerical))))
assert max_error < 1e-9
loss0, grad0 = focal_logits(z, y, alpha=.25, gamma=0)
weight = np.where(y == 1, .25, .75)
reference_bce = np.logaddexp(0., -(2*y-1)*z)
prob = np.exp(-np.logaddexp(0., -z))
np.testing.assert_allclose(loss0, weight*reference_bce, atol=1e-14)
np.testing.assert_allclose(grad0, weight*(prob-y), atol=1e-14)
extreme_loss, extreme_grad = focal_logits(np.array([-1000., 1000., -1000., 1000.]), [1,0,0,1])
assert np.isfinite(extreme_loss).all() and np.isfinite(extreme_grad).all()
np.testing.assert_allclose(extreme_grad[:2], [-.25, .75], atol=1e-14)

# Modelo sintético explícito: 95.000 negativos fáciles, 4.000 intermedios,
# 1.000 difíciles; p_t es fijo en cada grupo y no procede de un entrenamiento.
pt = np.repeat([.99, .6, .2], [95000, 4000, 1000])
negative_logits = np.log((1-pt)/pt)
group = np.repeat([0,1,2], [95000,4000,1000])
for gamma in (0., 1., 2., 5.):
    values, _ = focal_logits(negative_logits, np.zeros(len(pt)), gamma=gamma)
    totals = np.bincount(group, weights=values, minlength=3)
    print('γ =', gamma, 'pérdida por grupo:', np.round(totals, 6).tolist(),
          'fracción:', np.round(totals/totals.sum(), 6).tolist())
print('Error máximo de la derivada:', max_error)
print('γ=0: BCE ponderada; logits ±1000: resultados finitos')
print('Prior π=0,01: sesgo', float(np.log(.01/.99)))
[ ]DETR cost and lossBrowser
"""Asignación de DETR y pérdida de conjuntos para una imagen.

Las cajas son cxcywh normalizadas y las clases 0..C-1; no objeto es C.
El matching usa -p(clase), L1 y 1-GIoU. Su selección es discreta; aquí solo
se calculan valores, no derivadas a través de scipy ni de los índices.
La pérdida posterior usa -log p, peso 0,1 para no objeto y caja por GT.
"""
from itertools import permutations
import numpy as np
from scipy.optimize import linear_sum_assignment


def cxcywh_to_xyxy(boxes):
    boxes = np.asarray(boxes, dtype=np.float64).reshape(-1, 4)
    if not np.isfinite(boxes).all() or np.any(boxes[:, 2:] <= 0):
        raise ValueError('Cajas finitas con tamaño positivo')
    return np.concatenate((boxes[:, :2]-boxes[:, 2:]/2, boxes[:, :2]+boxes[:, 2:]/2), axis=1)


def giou_matrix(a, b):
    a, b = cxcywh_to_xyxy(a), cxcywh_to_xyxy(b)
    lo = np.maximum(a[:, None, :2], b[None, :, :2])
    hi = np.minimum(a[:, None, 2:], b[None, :, 2:])
    intersection = np.maximum(hi-lo, 0).prod(axis=-1)
    area_a = (a[:, 2:]-a[:, :2]).prod(axis=-1)[:, None]
    area_b = (b[:, 2:]-b[:, :2]).prod(axis=-1)[None, :]
    union = area_a + area_b - intersection
    enclosure = (np.maximum(a[:, None, 2:], b[None, :, 2:])
                 - np.minimum(a[:, None, :2], b[None, :, :2])).prod(axis=-1)
    return intersection/union - (enclosure-union)/enclosure


def matching_cost(logits, boxes, gt_labels, gt_boxes, class_weight=1., l1_weight=5., giou_weight=2.):
    logits = np.asarray(logits, dtype=np.float64)
    boxes, gt_boxes = np.asarray(boxes, dtype=np.float64), np.asarray(gt_boxes, dtype=np.float64)
    gt_labels = np.asarray(gt_labels)
    if gt_labels.dtype.kind not in 'iu' or gt_labels.ndim != 1:
        raise ValueError('Las etiquetas deben ser un vector de índices enteros')
    if logits.ndim != 2 or logits.shape[1] < 2 or boxes.shape != (len(logits), 4):
        raise ValueError('Logits (Q,C+1) y cajas (Q,4)')
    if gt_boxes.shape != (len(gt_labels), 4) or not np.isfinite(logits).all():
        raise ValueError('GT o logits inválidos')
    if np.any(gt_labels < 0) or np.any(gt_labels >= logits.shape[1]-1):
        raise ValueError('Las etiquetas GT deben ser clases con objeto')
    if not all(np.isfinite(v) and v >= 0 for v in (class_weight, l1_weight, giou_weight)):
        raise ValueError('Los pesos deben ser finitos y no negativos')
    cxcywh_to_xyxy(boxes)
    cxcywh_to_xyxy(gt_boxes)
    shifted = logits - logits.max(axis=1, keepdims=True) if len(logits) else logits
    log_probs = shifted - np.log(np.exp(shifted).sum(axis=1, keepdims=True)) if len(logits) else shifted
    probabilities = np.exp(log_probs)
    class_cost = -probabilities[:, gt_labels]
    l1 = np.abs(boxes[:, None, :] - gt_boxes[None, :, :]).sum(axis=2)
    giou = giou_matrix(boxes, gt_boxes)
    cost = class_weight*class_cost + l1_weight*l1 + giou_weight*(1-giou)
    return cost, log_probs, l1, giou


def match_queries(cost):
    cost = np.asarray(cost, dtype=np.float64)
    if cost.ndim != 2 or not np.isfinite(cost).all():
        raise ValueError('Matriz de costes finita Q por M')
    query, target = linear_sum_assignment(cost)
    unmatched_targets = np.setdiff1d(np.arange(cost.shape[1]), target)
    return query, target, unmatched_targets


def detr_set_loss(logits, boxes, gt_labels, gt_boxes, no_object_weight=.1,
                  class_weight=1., l1_weight=5., giou_weight=2.):
    logits = np.asarray(logits, dtype=np.float64)
    labels = np.asarray(gt_labels)
    if not np.isfinite(no_object_weight) or no_object_weight <= 0:
        raise ValueError('Peso de no objeto positivo y finito')
    cost, log_probs, l1, giou = matching_cost(logits, boxes, labels, gt_boxes,
                                               class_weight, l1_weight, giou_weight)
    query, target, missing = match_queries(cost)
    if len(missing):
        raise ValueError('Hay más GT que consultas: no se pueden asignar todos')
    background = logits.shape[1]-1
    class_targets = np.full(len(logits), background, dtype=np.int64)
    class_targets[query] = labels[target]
    weights = np.where(class_targets == background, no_object_weight, 1.)
    classification = (-log_probs[np.arange(len(logits)), class_targets] * weights).sum() / max(weights.sum(), 1e-15)
    denominator = max(len(labels), 1)
    box_l1 = float(l1[query, target].sum()/denominator)
    box_giou = float((1-giou[query, target]).sum()/denominator)
    return {'pairs': list(zip(query.tolist(), target.tolist())), 'classification': float(classification),
            'l1': box_l1, 'giou': box_giou,
            'total': float(class_weight*classification+l1_weight*box_l1+giou_weight*box_giou)}


# Un caso rectangular de tres consultas, dos clases y dos objetos.
logits = np.log([[.6,.3,.1], [.3,.05,.65], [.05,.7,.25]])
boxes = np.array([[.2,.3,.2,.2], [.7,.7,.2,.2], [.8,.7,.2,.2]])
gt_labels = np.array([0, 1])
gt_boxes = np.array([[.2,.3,.2,.2], [.8,.7,.2,.2]])
cost, _, _, _ = matching_cost(logits, boxes, gt_labels, gt_boxes)
q, t, missing = match_queries(cost)
assert not len(missing) and len(q) == 2
brute = min(sum(cost[p[j],j] for j in range(2)) for p in permutations(range(3),2))
np.testing.assert_allclose(cost[q,t].sum(), brute, atol=1e-12)
result = detr_set_loss(logits, boxes, gt_labels, gt_boxes)
assert result['pairs'] == [(0,0),(2,1)]
assert result['l1'] == 0 and abs(result['giou']) < 1e-14

# Gradiente analítico de la clasificación con las parejas actuales fijas.
prob = np.exp(logits) / np.exp(logits).sum(axis=1, keepdims=True)
class_targets = np.array([0, 2, 1])  # consulta 1 es no objeto
weights = np.where(class_targets == 2, .1, 1.)
classification_gradient = prob.copy()
classification_gradient[np.arange(len(logits)), class_targets] -= 1
classification_gradient *= weights[:, None] / weights.sum()
numeric = np.zeros_like(logits)
for i in range(len(logits)):
    for j in range(logits.shape[1]):
        plus, minus = logits.copy(), logits.copy()
        plus[i,j] += 1e-5
        minus[i,j] -= 1e-5
        lp = detr_set_loss(plus, boxes, gt_labels, gt_boxes)
        lm = detr_set_loss(minus, boxes, gt_labels, gt_boxes)
        assert lp['pairs'] == lm['pairs'] == result['pairs']
        numeric[i,j] = (lp['classification']-lm['classification'])/(2e-5)
gradient_error = float(np.max(np.abs(classification_gradient-numeric)))
assert gradient_error < 1e-9

# El coste de clase es -p, no -log p: este ejemplo cambia la asignación.
p = np.array([[.6,.3,.1],[.3,.05,.65]])
same_box = np.tile(np.array([.5,.5,.2,.2]), (2,1))
class_only, log_p, _, _ = matching_cost(np.log(p), same_box, [0,1], same_box,
                                         l1_weight=0, giou_weight=0)
q1, t1, _ = match_queries(class_only)
q2, t2, _ = match_queries(-log_p[:, [0,1]])
assert list(zip(q1,t1)) == [(0,0),(1,1)] and list(zip(q2,t2)) == [(0,1),(1,0)]

# Empates: cualquier óptimo es válido. Cero GT y Q<M no se esconden.
q, t, missing = match_queries(np.zeros((3,2)))
assert len(q) == len(t) == 2 and not len(missing) and len(set(q)) == len(set(t)) == 2
empty = detr_set_loss(logits, boxes, np.array([], dtype=int), np.empty((0,4)))
assert not empty['pairs'] and empty['l1'] == empty['giou'] == 0 and empty['classification'] > 0
q, t, missing = match_queries(np.zeros((1,2)))
assert len(q) == len(t) == 1 and len(missing) == 1
try:
    detr_set_loss(logits[:1], boxes[:1], gt_labels, gt_boxes)
    raise AssertionError('Se omitió silenciosamente un objeto')
except ValueError as error:
    assert 'más GT que consultas' in str(error)
print('Coste por consulta y objeto:\n', np.round(cost, 6))
print('Pares óptimos:', result['pairs'], 'coste:', round(float(brute), 6))
print('Pérdidas clasificación/L1/GIoU/total:', [round(result[k], 8) for k in ('classification','l1','giou','total')])
print('Error máximo del gradiente de clasificación:', gradient_error)
print('Empate y cero GT comprobados; con Q<M se informa y se rechaza la pérdida parcial')
print('Asignación −p y −log p distintas:', list(zip(q1,t1)), list(zip(q2,t2)))

A small FCOS on VOC

The next cell trains a teaching FCOS on ResNet-18 and three FPN levels, using focal loss, distances to sides, GIoU and centerness. It uses separate VOC training and validation sets and the evaluator from the previous lesson. If you provide ORYON_FASTER_CHECKPOINT, it loads the final checkpoint from the previous lesson’s two-stage lab and compares both under the specified transforms; otherwise it reports that the comparison was not performed. Faster R-CNN starts from COCO weights, and overlap with VOC has not been ruled out; the observed validation is not a confirmatory test. Its limit of 100 detections is also applied before removing COCO classes outside VOC: these can displace predictions for evaluated classes. Faster latency includes its full output, while FCOS uses its 20 classes, so post-processing is not identical either. Architecture, backbone, pretraining and number of steps can differ, so no mAP or latency difference is attributed to a single component.

In a short check with one seed, 12 training images, 8 validation images and four steps, FCOS’s measured AP was 0 and the short Faster checkpoint’s was approximately 0.541. This tests the pipeline rather than comparing converged models: pretraining, architecture and the rest of the protocol differ. The cell prints the values from your run.

[ ]Small FCOS on VOCLocal GPU
"""FCOS reducido de tres niveles en VOC; comparación con m16-l17.

Requiere torch, torchvision, numpy, Pillow y huggingface_hub. La AP propia
se copia de la celda actual m16-l17. ORYON_VERIFY_SHORT=1 usa pocas imágenes
y pasos solo para verificar el circuito. ORYON_FASTER_CHECKPOINT señala
opcionalmente el archivo voc-finetune-final.pt creado por la celda de l17.
Si falta, el resultado dice que la comparación no se ejecutó. El ajuste y
la validación usan VOC train/val y no equivalen a la evaluación VOC oficial.
FCOS y Faster difieren en arquitectura, backbone, pesos y entrenamiento;
las mediciones no atribuyen causalidad a una sola diferencia.
"""
import hashlib
import io
import json
import math
import os
import statistics
import tarfile
import time
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 torch.nn import functional as F
from torchvision import transforms
from torchvision.models import ResNet18_Weights, resnet18
from torchvision.models.detection import fasterrcnn_resnet50_fpn, FasterRCNN_ResNet50_FPN_Weights
from torchvision.ops import FeaturePyramidNetwork, batched_nms

torch.set_num_threads(1)
torch.backends.cudnn.benchmark=False
short=os.environ.get('ORYON_VERIFY_SHORT')=='1'
steps=4 if short else 2000
seed=16181
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
repo='davin11/VOC2007'
revision='fa6fc00e5e617859ce9b7aa7abd581c7bd8ffa15'
filename='VOCtrainval_06-Nov-2007.tar'
checksum='7d8cd951101b0957ddfd7a530bdc8a94f06121cfc1e511bb5937e973020c7508'
weights=FasterRCNN_ResNet50_FPN_Weights.COCO_V1
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:weights.meta['categories'].index(aliases.get(name,name)) for name in voc_names}
allowed=set(mapping.values())
classes=sorted(allowed)
index_of={label:i for i,label in enumerate(classes)}
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 freeze_bn(model):
    for module in model.modules():
        if isinstance(module,nn.modules.batchnorm._BatchNorm):
            module.eval()


def prepare(row, flip=False):
    """Escala la arista mayor a 320 y rellena abajo/derecha: ambas redes comparten entrada."""
    with Image.open(io.BytesIO(row['bytes'])) as image:
        image=image.convert('RGB')
        w,h=image.size
        factor=320/max(w,h)
        nw,nh=max(1,round(w*factor)),max(1,round(h*factor))
        x=transforms.functional.to_tensor(image.resize((nw,nh),Image.Resampling.BILINEAR))
    boxes=torch.tensor(row['boxes'],dtype=torch.float32).reshape(-1,4)
    boxes[:,[0,2]]*=nw/w
    boxes[:,[1,3]]*=nh/h
    if flip:
        x=x.flip(-1)
        boxes[:,0],boxes[:,2]=nw-boxes[:,2].clone(),nw-boxes[:,0].clone()
    x=F.pad(x,(0,320-nw,0,320-nh))
    target={'boxes':boxes.to(device),'labels':torch.tensor(row['labels'],dtype=torch.long,device=device)}
    return x.to(device),target,(nw,nh)


class FCOSSmall(nn.Module):
    def __init__(self):
        super().__init__()
        self.backbone=resnet18(weights=ResNet18_Weights.IMAGENET1K_V1)
        self.backbone.fc=nn.Identity()
        self.fpn=FeaturePyramidNetwork([128,256,512],64)
        def tower():
            return nn.Sequential(nn.Conv2d(64,64,3,padding=1),nn.GroupNorm(8,64),nn.ReLU(),
                                 nn.Conv2d(64,64,3,padding=1),nn.GroupNorm(8,64),nn.ReLU())
        self.cls_tower,self.box_tower=tower(),tower()
        self.cls=nn.Conv2d(64,len(classes),3,padding=1)
        self.box=nn.Conv2d(64,4,3,padding=1)
        self.centerness=nn.Conv2d(64,1,3,padding=1)
        nn.init.constant_(self.cls.bias,-math.log(99.))
        for param in self.backbone.parameters(): param.requires_grad_(False)
        for param in self.backbone.layer4.parameters(): param.requires_grad_(True)
        self.register_buffer('mean',torch.tensor([.485,.456,.406]).view(1,3,1,1))
        self.register_buffer('std',torch.tensor([.229,.224,.225]).view(1,3,1,1))

    def forward(self,x):
        z=(x-self.mean)/self.std
        b=self.backbone
        z=b.maxpool(b.relu(b.bn1(b.conv1(z))))
        c2=b.layer1(z)
        c3=b.layer2(c2)
        c4=b.layer3(c3)
        c5=b.layer4(c4)
        pyramid=self.fpn({'p3':c3,'p4':c4,'p5':c5})
        outputs=[]
        for feature,stride in zip(pyramid.values(),(8,16,32)):
            cls=self.cls_tower(feature)
            box=self.box_tower(feature)
            outputs.append((self.cls(cls),F.softplus(self.box(box))*stride,self.centerness(box),stride))
        return outputs


def points_for(h,w,stride):
    yy,xx=torch.meshgrid(torch.arange(h,device=device),torch.arange(w,device=device),indexing='ij')
    return torch.stack(((xx.flatten()+.5)*stride,(yy.flatten()+.5)*stride),dim=1)


def assign(points,boxes,labels,size_range,valid_size):
    """Interior estricto, rango sobre max(l,t,r,b), desempate por primera caja."""
    n=len(points)
    out_labels=torch.full((n,),-1,dtype=torch.long,device=device)
    out_dist=torch.zeros((n,4),device=device)
    valid=(points[:,0]<valid_size[0]) & (points[:,1]<valid_size[1])
    out_labels[valid]=0
    if not len(boxes): return out_labels,out_dist,torch.zeros(n,device=device),valid
    x,y=points[:,0,None],points[:,1,None]
    d=torch.stack((x-boxes[None,:,0],y-boxes[None,:,1],boxes[None,:,2]-x,boxes[None,:,3]-y),dim=2)
    maximum=d.max(dim=2).values
    inside=(d.min(dim=2).values>0) & (maximum>size_range[0]) & (maximum<=size_range[1]) & valid[:,None]
    area=(boxes[:,2]-boxes[:,0])*(boxes[:,3]-boxes[:,1])
    area=area[None,:].expand(n,-1).masked_fill(~inside,float('inf'))
    best,idx=area.min(dim=1)
    pos=torch.isfinite(best)
    out_labels[pos]=torch.tensor([index_of[int(x)] + 1 for x in labels[idx[pos]]],device=device,dtype=torch.long)
    out_dist[pos]=d[torch.arange(n,device=device)[pos],idx[pos]]
    cent=torch.zeros(n,device=device)
    v=out_dist[pos]
    if len(v): cent[pos]=torch.sqrt((torch.minimum(v[:,0],v[:,2])/torch.maximum(v[:,0],v[:,2]))*(torch.minimum(v[:,1],v[:,3])/torch.maximum(v[:,1],v[:,3])))
    return out_labels,out_dist,cent,valid


def focal(logits,target,alpha=.25,gamma=2.):
    bce=F.binary_cross_entropy_with_logits(logits,target,reduction='none')
    p=torch.sigmoid(logits)
    pt=p*target+(1-p)*(1-target)
    return ((alpha*target+(1-alpha)*(1-target))*(1-pt).pow(gamma)*bce).sum()


def giou_aligned(a,b):
    lo=torch.maximum(a[:,:2],b[:,:2]); hi=torch.minimum(a[:,2:],b[:,2:])
    inter=(hi-lo).clamp(min=0).prod(dim=1)
    aa=(a[:,2:]-a[:,:2]).clamp(min=0).prod(dim=1)
    ab=(b[:,2:]-b[:,:2]).clamp(min=0).prod(dim=1)
    union=aa+ab-inter
    enc=(torch.maximum(a[:,2:],b[:,2:])-torch.minimum(a[:,:2],b[:,:2])).clamp(min=0).prod(dim=1)
    return inter/union.clamp_min(1e-7)-(enc-union)/enc.clamp_min(1e-7)


def decode(points,dist):
    return torch.stack((points[:,0]-dist[:,0],points[:,1]-dist[:,1],
                        points[:,0]+dist[:,2],points[:,1]+dist[:,3]),dim=1)


def losses(outputs,target,valid_size):
    classification=torch.zeros((),device=device); regression=torch.zeros((),device=device); center_loss=torch.zeros((),device=device)
    positives=0
    for (cls,dist,cent,stride),size_range in zip(outputs,((0,64),(64,128),(128,float('inf')))):
        pts=points_for(cls.shape[-2],cls.shape[-1],stride)
        lab,truth,ct,valid=assign(pts,target['boxes'],target['labels'],size_range,valid_size)
        c=cls[0].permute(1,2,0).reshape(-1,len(classes))
        d=dist[0].permute(1,2,0).reshape(-1,4)
        z=cent[0,0].reshape(-1)
        onehot=torch.zeros_like(c)
        pos=lab>0
        if bool(pos.any()): onehot[pos,lab[pos]-1]=1
        classification=classification+focal(c[valid],onehot[valid])
        if bool(pos.any()):
            regression=regression+(1-giou_aligned(decode(pts[pos],d[pos]),decode(pts[pos],truth[pos]))).sum()
            center_loss=center_loss+F.binary_cross_entropy_with_logits(z[pos],ct[pos],reduction='sum')
        positives+=int(pos.sum())
    denom=max(1,positives)
    return (classification+regression+center_loss)/denom,{'positive_points':positives,
        'classification':float((classification/denom).detach()),'giou':float((regression/denom).detach()),
        'centerness':float((center_loss/denom).detach())}


def predict(model,x,valid_size):
    all_boxes=[]; all_scores=[]; all_labels=[]
    for cls,dist,cent,stride in model(x[None]):
        pts=points_for(cls.shape[-2],cls.shape[-1],stride)
        ds=dist[0].permute(1,2,0).reshape(-1,4)
        probs=(torch.sigmoid(cls[0]).permute(1,2,0).reshape(-1,len(classes))*torch.sigmoid(cent[0,0].reshape(-1,1))).sqrt()
        valid=(pts[:,0]<valid_size[0])&(pts[:,1]<valid_size[1])
        probs[~valid]=0
        values,flat=probs.flatten().topk(min(1000,probs.numel()))
        keep=values>=.01; values,flat=values[keep],flat[keep]
        pointidx=torch.div(flat,len(classes),rounding_mode='floor'); classidx=flat%len(classes)
        boxes=decode(pts[pointidx],ds[pointidx])
        boxes[:,[0,2]]=boxes[:,[0,2]].clamp(0,valid_size[0])
        boxes[:,[1,3]]=boxes[:,[1,3]].clamp(0,valid_size[1])
        keep=(boxes[:,2]>boxes[:,0])&(boxes[:,3]>boxes[:,1])
        all_boxes.append(boxes[keep]); all_scores.append(values[keep]); all_labels.append(classidx[keep])
    boxes,scores,labs=torch.cat(all_boxes),torch.cat(all_scores),torch.cat(all_labels)
    keep=batched_nms(boxes,scores,labs,.5)[:100]
    coco=torch.tensor(classes,device=device,dtype=torch.long)
    return {'boxes':boxes[keep],'scores':scores[keep],'labels':coco[labs[keep]]}


def evaluate(model,rows,kind):
    model.eval(); preds=[]; targets=[]
    with torch.no_grad():
        for row in rows:
            x,target,valid=prepare(row)
            out=predict(model,x,valid) if kind=='fcos' else model([x])[0]
            if kind=='faster':
                mask=torch.tensor([int(label) in allowed for label in out['labels']],device=device)
                out={k:out[k][mask] for k in ('boxes','scores','labels')}
            preds.append({k:v.cpu() for k,v in out.items()})
            targets.append({k:v.cpu() for k,v in target.items()})
    return own_ap(preds,targets)


def latency(model,row,kind):
    model.eval(); x,_,valid=prepare(row)
    def forward(): return predict(model,x,valid) if kind=='fcos' else model([x])[0]
    with torch.no_grad():
        for _ in range(3): forward()
        torch.cuda.synchronize(); times=[]
        for _ in range(10):
            start=time.perf_counter(); forward(); torch.cuda.synchronize(); times.append(time.perf_counter()-start)
    return {'median_seconds':statistics.median(times),'samples_seconds':times,
            'note':'entrada ya preparada y copiada; incluye decodificación de cajas y NMS, sincroniza cada petición'}


def main():
    if device.type!='cuda': raise RuntimeError('Este laboratorio requiere CUDA')
    path=hf_hub_download(repo_id=repo,repo_type='dataset',revision=revision,filename=filename)
    if sha256_file(path)!=checksum: raise ValueError('Hash VOC incorrecto')
    groups,excluded=read_voc(path)
    torch.manual_seed(seed); generator=np.random.default_rng(seed+1); flip_rng=torch.Generator().manual_seed(seed+2)
    model=FCOSSmall().to(device)
    opt=torch.optim.SGD([p for p in model.parameters() if p.requires_grad],lr=.001,momentum=.9,weight_decay=.0001)
    history=[]
    for step in range(1,steps+1):
        model.train(); freeze_bn(model)
        row=groups['train'][int(generator.integers(len(groups['train'])))]
        flip=bool(torch.rand((),generator=flip_rng)<.5)
        x,target,valid=prepare(row,flip)
        opt.zero_grad(set_to_none=True)
        loss,parts=losses(model(x[None]),target,valid)
        if not bool(torch.isfinite(loss)): raise FloatingPointError(f'Pérdida no finita: paso {step}')
        loss.backward()
        grads=[p.grad for p in model.parameters() if p.requires_grad and 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: paso {step}')
        opt.step()
        history.append({'step':step,'image_id':row['id'],'flip':flip,'loss':float(loss.detach()),**parts})
        if step in (1,steps): print('paso',step,history[-1],flush=True)
    validation=evaluate(model,groups['val'],'fcos')
    timing=latency(model,groups['val'][0],'fcos')
    out={'protocol':{'short':short,'steps':steps,'seed':seed,'dataset':repo,'revision':revision,
        'train_ids':[r['id'] for r in groups['train']],'validation_ids':[r['id'] for r in groups['val']],
        'excluded':excluded,'preprocess':'lado mayor 320, relleno inferior y derecho a 320×320',
        'metric':'AP de l17 all/maxDet100 sobre cajas en imagen redimensionada; no evaluación VOC oficial',
        'warning':'Una semilla y prueba corta no implican convergencia. Arquitectura, backbone, pesos y duración difieren.',
        'gpu':torch.cuda.get_device_name(device),'torch':str(torch.__version__)},
        'training':history,'fcos_validation':validation,'fcos_latency':timing}
    checkpoint=os.environ.get('ORYON_FASTER_CHECKPOINT')
    if checkpoint and Path(checkpoint).is_file():
        payload=torch.load(checkpoint,map_location='cpu',weights_only=True)
        if payload['class_mapping']!=mapping: raise ValueError('El checkpoint usa otro mapeo de clases')
        # La celda l17 construyó con pesos COCO y FrozenBatchNorm; reutilizar
        # ese constructor conserva la estructura antes de cargar el checkpoint.
        faster=fasterrcnn_resnet50_fpn(weights=weights,box_score_thresh=0.,box_detections_per_img=100)
        faster.load_state_dict(payload['model']); faster.transform.min_size=(320,); faster.transform.max_size=320
        faster=faster.to(device)
        out['faster']={'checkpoint':checkpoint,'steps':payload['steps'],
                       'validation':evaluate(faster,groups['val'],'faster'),'latency':latency(faster,groups['val'][0],'faster')}
        del faster
    else:
        out['faster']={'status':'checkpoint no indicado o inexistente; comparación omitida'}
    target=Path(os.environ.get('ORYON_FCOS_OUTPUT','fcos-voc.json'))
    target.write_text(json.dumps(out,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8')
    print('FCOS',validation,'Faster',out['faster'],'archivo',target,flush=True)
    del model,opt
    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.

Inspect DETR queries

This cell loads a pretrained DETR at a pinned revision and a VOC image. It inspects the actual dimensions of last-layer cross-attention, the padding mask and the query with the highest object score. The overlay interpolates an attention grid over the image: it is an approximate visualization of weights, not a causal explanation. The experiment also reports model detections without adding NMS, without assuming that duplicates are impossible.

In the check with VOC image 000009, query 92 had the highest class score, for “person”; the attention map had 8 heads and an 11 × 15 grid. At a score threshold of 0.3 there were 34 queries and 13 same-class pairs with IoU at least 0.5. That overlap does not prove duplicates: two different objects can overlap, and a single image does not establish a general rate.

[ ]Inspect DETR queriesLocal GPU
"""Inspección local de DETR preentrenado, sin NMS ni afirmaciones causales.

Dependencias: torch, torchvision, transformers, huggingface_hub, Pillow,
numpy y matplotlib. Descarga/caché compartida de VOC2007 y DETR. La imagen
000009 y el hash del dataset son los de la celda actual m16-l16; se lee el
tar sin extraer. Se fija la revisión del modelo y se imprime la versión de
Transformers para que el resultado pueda reproducirse. Usa poca resolución
para reducir memoria; no es la configuración de evaluación del paper.

El mapa dibuja la media entre cabezas de la atención cruzada de la última
capa para la consulta con mayor puntuación de clase de objeto. Se recupera
la forma real y la máscara del último mapa del backbone mediante un hook;
no se deducen sus dimensiones con la raíz cuadrada de tokens. La atención
es sobre características del encoder, no una atribución causal a píxeles.
"""
import hashlib
import io
import json
import tarfile
from pathlib import Path
from importlib.metadata import version

import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import torch
from torch.nn import functional as F
from huggingface_hub import hf_hub_download
from transformers import AutoImageProcessor, DetrForObjectDetection


MODEL = 'facebook/detr-resnet-50'
MODEL_REVISION = '1d5f47bd3bdd2c4bbfa585418ffe6da5028b4c0b'
DATASET = 'davin11/VOC2007'
DATASET_REVISION = 'fa6fc00e5e617859ce9b7aa7abd581c7bd8ffa15'
ARCHIVE = 'VOCtrainval_06-Nov-2007.tar'
ARCHIVE_SHA256 = '7d8cd951101b0957ddfd7a530bdc8a94f06121cfc1e511bb5937e973020c7508'
IMAGE_ID = '000009'
SCORE_THRESHOLD = 0.30
PAIR_IOU_THRESHOLD = 0.50


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 unpack_backbone(output):
    """Soporta DetrConvModel de v4 y DetrConvEncoder de v5."""
    features = output[0] if isinstance(output, tuple) else output
    if not isinstance(features, (tuple, list)) or not features:
        raise RuntimeError('Salida de backbone desconocida; revisa la versión de Transformers')
    last = features[-1]
    if not isinstance(last, (tuple, list)) or len(last) != 2:
        raise RuntimeError('No se encontró el último mapa y su máscara')
    feature, mask = last
    if feature.ndim != 4 or mask is None or mask.ndim != 3 or feature.shape[-2:] != mask.shape[-2:]:
        raise RuntimeError('Forma inesperada del mapa o de la máscara')
    return feature.shape[-2:], mask.detach().bool().cpu()


def iou_xyxy(a, b):
    """IoU de dos cajas continuas, incluso si no solapan."""
    intersection = max(0., min(a[2], b[2])-max(a[0], b[0])) * max(0., min(a[3], b[3])-max(a[1], b[1]))
    area_a = max(0., a[2]-a[0]) * max(0., a[3]-a[1])
    area_b = max(0., b[2]-b[0]) * max(0., b[3]-b[1])
    union = area_a + area_b - intersection
    return intersection / union if union > 0 else 0.


def summarize_detections(probabilities, boxes, width, height, names, threshold):
    """Conserva consultas con puntuación de clase máxima >= threshold, sin NMS.

    Las cajas cxcywh se convierten a xyxy en píxeles sin recortarlas. Se
    calculan las IoU de cada par de la misma clase; el solapamiento por sí
    solo no determina si son duplicados o dos objetos distintos.
    """
    detections = []
    for q, (probs, box) in enumerate(zip(probabilities, boxes)):
        label = max(range(len(probs)-1), key=lambda c: probs[c])
        score = float(probs[label])
        if score < threshold:
            continue
        cx, cy, w, h = (float(v) for v in box)
        xyxy = [(cx-w/2)*width, (cy-h/2)*height,
                (cx+w/2)*width, (cy+h/2)*height]
        detections.append({'query':q, 'label':label, 'class':names.get(label, str(label)),
                           'score':score, 'no_object_score':float(probs[-1]), 'xyxy':xyxy})
    detections.sort(key=lambda item: (-item['score'], item['query']))
    pairs = []
    for i, first in enumerate(detections):
        for second in detections[i+1:]:
            if first['label'] == second['label']:
                pairs.append({'queries':[first['query'],second['query']], 'label':first['label'],
                              'class':first['class'], 'iou':iou_xyxy(first['xyxy'], second['xyxy'])})
    return detections, pairs


def main():
    torch.set_num_threads(1)
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    print('torch:', torch.__version__, 'transformers:', version('transformers'), 'dispositivo:', device)
    archive_path = hf_hub_download(repo_id=DATASET, repo_type='dataset', revision=DATASET_REVISION, filename=ARCHIVE)
    if sha256_file(archive_path) != ARCHIVE_SHA256:
        raise ValueError('El hash del archivo VOC no coincide')
    with tarfile.open(archive_path, 'r:') as archive:
        raw = archive.extractfile('VOCdevkit/VOC2007/JPEGImages/'+IMAGE_ID+'.jpg').read()
    with Image.open(io.BytesIO(raw)) as source:
        image = source.convert('RGB').copy()

    processor = AutoImageProcessor.from_pretrained(MODEL, revision=MODEL_REVISION)
    try:
        model = DetrForObjectDetection.from_pretrained(MODEL, revision=MODEL_REVISION,
                                                       attn_implementation='eager').to(device).eval()
    except (TypeError, ValueError) as error:
        raise RuntimeError('Esta versión no admite cargar DETR con atención eager; revisa Transformers y su documentación') from error
    inputs = processor(images=image, return_tensors='pt',
                       size={'shortest_edge':320, 'longest_edge':480})
    pixels = inputs['pixel_values']
    pixel_mask = inputs.get('pixel_mask', torch.ones(pixels.shape[0], *pixels.shape[-2:], dtype=torch.long))
    if pixels.shape[0] != 1 or not torch.all(pixel_mask == 1):
        raise RuntimeError('El ejemplo espera una sola imagen sin padding inicial')
    original_h, original_w = pixels.shape[-2:]
    # Añadimos padding derecho e inferior para comprobar la máscara de verdad.
    padding_h = (-original_h % 32) + 32
    padding_w = (-original_w % 32) + 32
    pixels = F.pad(pixels, (0,padding_w,0,padding_h), value=0).to(device)
    pixel_mask = F.pad(pixel_mask, (0,padding_w,0,padding_h), value=0).to(device)
    backbone_info = {}

    def record_backbone(module, args, output):
        shape, mask = unpack_backbone(output)
        backbone_info['shape'] = tuple(int(x) for x in shape)
        backbone_info['mask'] = mask

    hook = model.model.backbone.register_forward_hook(record_backbone)
    try:
        with torch.no_grad():
            output = model(pixel_values=pixels, pixel_mask=pixel_mask,
                           output_attentions=True, return_dict=True)
    finally:
        hook.remove()
    if not output.cross_attentions or output.cross_attentions[-1] is None:
        raise RuntimeError('No se devolvió atención cruzada; comprueba soporte eager y output_attentions')
    if 'mask' not in backbone_info:
        raise RuntimeError('El hook no observó la máscara del backbone')
    attention = output.cross_attentions[-1].detach().float().cpu()
    logits = output.logits[0].detach().float().cpu()
    probabilities = logits.softmax(-1)
    boxes = output.pred_boxes[0].detach().float().cpu()
    if attention.ndim != 4 or attention.shape[0] != 1 or attention.shape[2] != len(logits):
        raise RuntimeError('Dimensiones de atención inesperadas')
    height, width = backbone_info['shape']
    mask = backbone_info['mask'][0]
    if attention.shape[-1] != height*width or mask.shape != (height,width):
        raise RuntimeError('Tokens, mapa y máscara no coinciden')
    object_scores, labels = probabilities[:, :-1].max(dim=1)
    query = int(object_scores.argmax())
    label = int(labels[query])
    coarse = attention[0,:,query,:].mean(dim=0).reshape(height,width)
    if not torch.isfinite(coarse).all():
        raise ValueError('Atención no finita')
    pad_mass = float(coarse[~mask].sum())
    if pad_mass > 1e-5:
        raise AssertionError('La atención a tokens enmascarados no es despreciable')
    masked = coarse * mask
    padded_height, padded_width = pixels.shape[-2:]
    # Interpolación al lienzo con padding, recorte y escala a la imagen original.
    canvas = F.interpolate(masked[None,None], size=(padded_height,padded_width),
                           mode='bilinear', align_corners=False)[0,0]
    canvas = canvas[:original_h,:original_w]
    heat = F.interpolate(canvas[None,None], size=(image.height,image.width),
                         mode='bilinear', align_corners=False)[0,0].numpy()
    cx,cy,w,h = [float(v) for v in boxes[query]]
    corners = [(cx-w/2)*image.width, (cy-h/2)*image.height,
               (cx+w/2)*image.width, (cy+h/2)*image.height]
    predicted_class = model.config.id2label.get(label, str(label))
    print('Consulta:', query, 'clase:', predicted_class, 'p objeto:', float(object_scores[query]),
          'p no objeto:', float(probabilities[query,-1]))
    print('Entrada redimensionada:', (original_h,original_w), 'con padding:', (padded_height,padded_width),
          'mapa:', (height,width), 'cabezas:', attention.shape[1], 'masa padding:', pad_mass)
    detections, pairs = summarize_detections(probabilities.tolist(), boxes.tolist(), image.width, image.height,
                                              model.config.id2label, SCORE_THRESHOLD)
    print('Consultas con puntuación de clase >=', SCORE_THRESHOLD, 'sin NMS; cajas xyxy en píxeles sin recortar:')
    for detection in detections:
        print(detection)
    overlapping = [pair for pair in pairs if pair['iou'] >= PAIR_IOU_THRESHOLD]
    print('Pares de la misma clase:', len(pairs), 'con IoU >=', PAIR_IOU_THRESHOLD, ':', overlapping)
    print('La IoU alta señala solapamiento, no demuestra duplicados; solo se examina esta imagen y umbral.')

    fig, axes = plt.subplots(1,2,figsize=(11,4),constrained_layout=True)
    for axis in axes:
        axis.imshow(image)
        axis.axis('off')
    axes[0].set_title('Imagen y caja de la consulta')
    axes[0].add_patch(plt.Rectangle((corners[0],corners[1]),corners[2]-corners[0],corners[3]-corners[1],
                                    fill=False,color='lime',linewidth=2))
    axes[1].imshow(heat, cmap='magma', alpha=.55)
    axes[1].set_title('Atención cruzada interpolada')
    output_file = Path('detr-atencion.png')
    fig.savefig(output_file, dpi=120)
    plt.close(fig)
    np.savez_compressed('detr-atencion-datos.npz', attention=coarse.numpy(),
                        valid_mask=mask.numpy(), heat=heat, box=np.asarray(corners))
    metadata = {'model': MODEL, 'model_revision': MODEL_REVISION, 'dataset': DATASET,
                'dataset_revision': DATASET_REVISION, 'image_id': IMAGE_ID,
                'torch': str(torch.__version__), 'transformers': version('transformers'),
                'device': str(device), 'query': query, 'label': label, 'class': predicted_class,
                'object_score': float(object_scores[query]), 'no_object_score': float(probabilities[query,-1]),
                'original_image_wh': [image.width,image.height], 'input_hw': [original_h,original_w],
                'padded_hw': [padded_height,padded_width], 'feature_hw': [height,width],
                'attention_heads': int(attention.shape[1]), 'masked_attention_mass': pad_mass,
                'score_threshold':SCORE_THRESHOLD, 'pair_iou_report_threshold':PAIR_IOU_THRESHOLD,
                'detections':detections, 'same_class_pairs':pairs,
                'note': 'Promedio de cabezas, capa final; interpolación aproximada, no atribución causal ni NMS.'}
    Path('detr-atencion-metadata.json').write_text(json.dumps(metadata,ensure_ascii=False,indent=2),encoding='utf-8')
    print('Archivos:', output_file, 'detr-atencion-datos.npz', 'detr-atencion-metadata.json')
    del output, model
    if device.type == 'cuda':
        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

ProofDo not freeze the modulator
Prove: Differentiate focal loss with respect to binary logit z, with pₜ=sigmoid(qz), q=2y−1 and fixed weight αₜ.
0
Work with γ≥0 and 0<pₜ<1. Apply the product rule to both factors depending on pₜ.

Step 1 of 3. What is the derivative of pₜ with respect to z?

NumericTwo degrees of ease
With γ=2, how much smaller is the loss modulating factor for pₜ=0.99 than for pₜ=0.6? Enter the ratio easy factor / less easy factor.
NumericInitialize objectness
If the rest of the initial logit is zero, what bias gives a sigmoid object probability of 0.01? Round to three decimal places.
CodeAssign points to objects
Implement fcos_targets(points, boxes, classes, size_ranges) with NumPy. points is P×2, boxes is G×4 xyxy, classes contains positive integer labels and size_ranges is P×2. A point is eligible for a box if it is strictly inside and the maximum of l,t,r,b satisfies minimum ≤ maximum < upper limit. If several boxes are eligible, choose the smallest area and, on a tie, the lowest index. Return labels of length P, distances P×4 and centerness of length P; background has label 0, zero distances and zero centerness. Support zero objects.
import numpy as np

def fcos_targets(points, boxes, classes, size_ranges):
  pass
Shift+Enter to run
QuizCompare convergence
A comparison reports that Deformable DETR achieves higher AP in fewer epochs than DETR. Which explanation and conclusion are justified?
Key idea
Architecture, assignment and the evaluation protocol together determine what a detector learns. A loss or matching alone guarantees neither higher accuracy nor an absence of errors at inference.