Module contents
Lesson 19 of 25Core 110 min

Semantic segmentation: FCN, U-Net and DeepLab

Study semantic segmentation, FCNs, U-Net, DeepLab, segmentation losses and mIoU, with a controlled Oxford-IIIT Pet lab.

After this lesson you can

  • Explain fully convolutional networks and the relationship between output stride and resolution.
  • Implement U-Net skip connections and reason about spatial information.
  • Use dilated convolutions and ASPP to aggregate context at multiple scales.
  • Implement weighted cross-entropy, Dice loss and confusion-matrix mIoU.
  • Train and evaluate segmentation models under a declared protocol.

Before you start

A class for every pixel

A box can indicate where an animal is, but it does not separate its silhouette from the background or describe which parts are occluded. Semantic segmentation assigns a category to each valid pixel; two objects of the same class may receive the same label without distinguishing their identities. Annotation has its own granularity: an ambiguous region, a thin boundary and an exact mask are not necessarily the same thing.

In Oxford-IIIT Pet, the original README defines the trimap as 1 for foreground, 2 for background and 3 for the unclassified region. The lab treats 3 as an ambiguous band near the boundary, not as an exhaustive annotation of all contours. This three-class decision is not equivalent to ignoring the band and solving a binary task.

Count before averaging

Accumulate a matrix CC over all valid pixels: CijC_{ij} counts ground-truth label ii and prediction jj. The IoU of class kk is

IoU⁡k=Ckk∑jCkj+∑iCik−Ckk.\operatorname{IoU}_k=\frac{C_{kk}}{\sum_j C_{kj}+\sum_i C_{ik}-C_{kk}}.

mIoU averages classes according to a declared convention. If a class union is zero, exclude it or define another explicit rule; if there are no ground-truth pixels of that class but there are predictions, its union is positive and IoU is zero. Ignore a pixel based on its ground-truth label before accumulation, even if its prediction belongs to a valid class. Averaging IoU per image answers a different question and is generally not equivalent to calculating it from the aggregated matrix.

Pixel accuracy can hide rare classes: always predicting background gets most pixels right in an image with a small object but does not recover the object. Evaluating boundaries requires defining band width, units, exclusions and how images are aggregated: there is no single “boundary IoU” implicit in every implementation.

Fully convolutional networks and resolution

A dense layer on a fixed-size map can be represented as a convolution with the same spatial support and weights. When the converted model is applied to a larger image, weights are reused at compatible positions, accounting for padding and stride. A fully convolutional network thus produces a spatial logit map that can be rescaled to input size. Output stride describes the internal grid before upsampling, not necessarily the final mask size.

FCN combined predictions from different depths to recover detail. In its Table 2, on a subset of 736 VOC2011 validation images, FCN-32s, FCN-16s and FCN-8s achieved 59.4%, 62.4% and 62.7% mIoU respectively under its protocol. That comparison does not show that reducing stride always improves every boundary. If a layer operates at output stride 8 instead of 32, an image divisible by both has 16 times as many positions in that map; total network cost need not increase 16-fold.

InteractiveStride, interpolation and boundaries
Annotation
Prediction
  • Animal
  • Background
  • Ambiguous band

Sample train/0/965, resolution 128 × 128. Short verification run: 4 steps per model. Boundary IoU uses four-neighbor transitions without tolerance; FLOPs omit interpolation and normalization.

The three FCNs stop at different encoder stages and have different depths. Changing interpolation mode keeps the same logits; comparing models does not isolate stride alone. The sample is from validation and these masks do not prove convergence.

Output stride
Logit upsampling
1
Boundary IoU, this image0.1 %
mIoU, this image9.8 %
Nominal FLOPs, conv. and linear1.10 B
Actual predictions from a short check, still far from convergence. Compare annotation and FCNs before drawing conclusions about their quality.

U-Net and skip connections

A U-Net combines an encoder that aggregates context with a decoder that recovers resolution. Skips connect maps at the same scale to provide spatial information that downsampling may have lost. The original U-Net concatenates maps and uses valid convolutions, so it crops connections and produces output smaller than its input. A modern adaptation with padding or a ResNet encoder is not identical to that biomedical architecture.

Adding two tensors requires compatible shapes and channels and preserves the number of channels. Concatenation retains both sets of channels and increases the input of the next operation. With odd sizes, adjust the upsampled map to the actual skip size and state the interpolation method. Disabling a skip at inference changes the distribution received by a decoder trained with it; that intervention is not equivalent to retraining an architecture without the skip and does not prove a universal function for each scale.

InteractiveDisable a skip at inference
Annotation
Prediction
  • Animal
  • Background
  • Ambiguous band

Sample train/0/965. Short verification run: 4 steps. Skips are numbered from lowest to highest resolution.

The intervention replaces a feature map with zeros during inference on the same U-Net. The decoder was trained with every skip: this changes its input and is not equivalent to retraining an architecture without that connection. A single image does not establish the general role of a scale.

0
1
ConfigurationAll active
mIoU with all skips26.0 %
Configuration mIoU26.0 %
The masks come from this lesson's lab with only four training steps: they reveal what changes in this run, not the general effect of skips.

The conditioned U-Nets in many diffusion models reuse the idea of multiscale paths and skips, but incorporate different components and objectives; they are not exact copies of the original network.

Context without losing the entire grid

A dilated convolution with kernel kk and dilation dd has effective support 1+(k−1)d1+(k-1)d. If the jump between input centers is jj, the operation increases the theoretical receptive field by (k−1)dj(k-1)dj; stride ss changes the jump to jsjs. The theoretical field is a geometric bound, not proof that all its pixels influence the result equally, and some may fall in padding. Dilated convolution expands context without reducing the grid again.

The ASPP in DeepLabv3 combines 1×11\times1 branches, dilated 3×33\times3 convolutions and global pooling; it concatenates and projects their outputs. For output stride 16, the paper studies rates 6, 12 and 18, doubling them for stride 8. A large rate on a small map can cause many samples to fall in padding; it does not automatically yield useful context. DeepLabv3+ adds a decoder with features from an early stage. TorchVision’s deeplabv3_resnet50 constructor implements v3, not v3+.

Earlier versions of DeepLab used dense CRFs to refine predictions. Later architectures’ results without that post-processing show it is not mandatory in their configurations; they do not prove that no system can benefit from it.

Cross-entropy, Dice and ignored pixels

A segmentation loss can weight cross-entropy by class. If the sum is divided by the weights of valid pixels, changing all weights by the same factor does not change the loss; dividing by the number of pixels produces a different scale. Define the case with no valid pixels or no total weight to avoid division by zero.

For a class with probabilities pip_i, indicators gig_i and smoothing ε>0\varepsilon>0, one linear variant is

D=2∑ipigi+ε∑ipi+∑igi+ε,LD=1−D.D=\frac{2\sum_i p_ig_i+\varepsilon}{\sum_i p_i+\sum_i g_i+\varepsilon},\qquad L_D=1-D.

The sums cover only valid pixels. Its derivative with respect to pjp_j is

∂LD∂pj=(2∑ipigi+ε)−2gj(∑ipi+∑igi+ε)(∑ipi+∑igi+ε)2.\frac{\partial L_D}{\partial p_j}=\frac{(2\sum_i p_ig_i+\varepsilon)-2g_j(\sum_i p_i+\sum_i g_i+\varepsilon)}{(\sum_i p_i+\sum_i g_i+\varepsilon)^2}.

To differentiate with respect to logits, subsequently apply the derivative of sigmoid or softmax. The V-Net formulation uses a denominator with sums of squares; it agrees with the hard binary version, but not generally with this variant for probabilities. Class averaging, smoothing and absent classes are also part of the definition.

InteractiveDice versus cross-entropy

Synthetic model: each pixel has a feature x that can take two values. A σ(wx + b) classifier learns with full-batch gradient descent. CE and Dice start from the same parameters; IoU predicts object when probability is ≥ 0.5.

Object IoU during training0.000.51001.0200StepObject IoU
  • Cross-entropy
  • Soft Dice

The curve changes in jumps: training updates probabilities continuously, but binary IoU changes only when a probability crosses 0.5. Both methods rerun from the same start when prevalence or rate changes.

Step 200, Dice trajectory: w = 5.1968, b = −2.6134. For x = 1 probability is 92.98 %; for x = −0.2 it is 2.53 %.

Of object pixels, 60% have x = 1 and 40% x = −0.2; of background pixels, 20% have x = 1 and 80% x = −0.2. These are deterministic groups with both classes at each x value, not a convolutional network or measurements on real images. The composition corresponds to a batch of 1000 pixels at the control’s proportions.

CE averages −[y log p + (1 − y) log(1 − p)] with group frequencies. Soft Dice uses 1 − (2Σwᵢyᵢpᵢ + ε)/(Σwᵢpᵢ + Σwᵢyᵢ + ε), with Σwᵢ = 1 and ε = 10⁻⁶. Both start at w = 0, b = −2 and apply 200 simultaneous descent steps to both parameters.

Prevalence, threshold, feature and initialization affect the result. This simulation shows a possible mechanism; it does not prove that one loss is always better or replace evaluation on held-out masks.

10
1.0
200
Inspect trajectory
Object IoU, CE0.0 %
Object IoU, Dice21.4 %
Accuracy, selected trajectory78.0 %
Loss of selected trajectory0.6682
TP / FP / FN per 1000 pixels60 / 180 / 40
Probability with x = 192.98 %
Probability with x = −0.22.53 %
Explore the evolution of an explicit model with different object proportions; the curves do not represent a universal guarantee.

For binary masks with positive union, Dice⁡=2IoU⁡/(1+IoU⁡)\operatorname{Dice}=2\operatorname{IoU}/(1+\operatorname{IoU}). This is an increasing transformation, so both rank predictions for the same image and class equally. That conclusion does not automatically extend to averages over images or classes because the transformation is nonlinear. If both masks are empty, state how to handle the zero denominator.

Labs

Metrics and losses from scratch

This cell accumulates the confusion matrix, excludes empty unions from mIoU and calculates weighted cross-entropy and linear Dice. It exposes their reductions and differentiates with respect to logits, ignoring the specified positions. It checks gradients by finite differences and tests empty denominators and absent classes.

[ ]Segmentation metrics and lossesBrowser
"""Métricas y pérdidas multicategoría para segmentación, solo NumPy.

Filas de la matriz: clase verdadera; columnas: clase predicha. El valor
``ignore`` pertenece exclusivamente a la etiqueta verdadera. Dice lineal
se promedia sobre todas las clases especificadas, incluso las ausentes;
el suavizado positivo hace que una clase vacía en ambos lados tenga Dice 1.
"""
import numpy as np


def confusion_matrix(target, prediction, classes, ignore=255):
    target, prediction = np.asarray(target), np.asarray(prediction)
    if target.shape != prediction.shape or classes < 1:
        raise ValueError("Formas incompatibles o número de clases inválido")
    if not np.issubdtype(target.dtype, np.integer) or not np.issubdtype(prediction.dtype, np.integer):
        raise ValueError("Las etiquetas deben ser enteras")
    valid = target != ignore
    t, p = target[valid], prediction[valid]
    if np.any((t < 0) | (t >= classes) | (p < 0) | (p >= classes)):
        raise ValueError("Etiqueta válida fuera del rango")
    return np.bincount(classes * t.astype(np.int64) + p.astype(np.int64), minlength=classes * classes).reshape(classes, classes)


def iou_from_confusion(matrix):
    matrix = np.asarray(matrix)
    if matrix.ndim != 2 or matrix.shape[0] != matrix.shape[1] or np.any(matrix < 0):
        raise ValueError("Matriz cuadrada no negativa requerida")
    tp = np.diag(matrix).astype(float)
    union = matrix.sum(axis=0) + matrix.sum(axis=1) - tp
    iou = np.full(tp.shape, np.nan)
    np.divide(tp, union, out=iou, where=union > 0)
    present = union > 0
    return iou, float(iou[present].mean()) if np.any(present) else np.nan


def losses_and_gradients(logits, target, weights, ignore=255, eps=1e-6):
    """CE ponderada y Dice lineal, más gradientes respecto de logits.

    logits es (píxeles, clases). Para CE el denominador es la suma de
    pesos de las etiquetas válidas, no el número de píxeles. Para Dice,
    softmax precede a la pérdida: todas las clases contribuyen a la media.
    Si no hay etiquetas válidas o la suma de sus pesos es cero, no hay CE
    media definida y se rechaza la entrada. No se modifican los logits.
    """
    z = np.asarray(logits, dtype=float)
    y = np.asarray(target)
    w = np.asarray(weights, dtype=float)
    if z.ndim != 2 or z.shape[1] < 1 or y.shape != (len(z),) or w.shape != (z.shape[1],):
        raise ValueError("Formas incompatibles")
    if not np.issubdtype(y.dtype, np.integer) or not np.isfinite(z).all() or not np.isfinite(w).all():
        raise ValueError("Se requieren etiquetas enteras y valores finitos")
    if np.any(w < 0) or not np.isfinite(eps) or eps <= 0:
        raise ValueError("Pesos no negativos y eps positivo")
    valid = y != ignore
    indices = np.flatnonzero(valid)
    labels = y[valid]
    classes = z.shape[1]
    if np.any((labels < 0) | (labels >= classes)):
        raise ValueError("Etiqueta válida fuera del rango")
    denominator = w[labels].sum()
    if not len(indices) or denominator <= 0:
        raise ValueError("CE media indefinida: no hay peso válido")

    active = z[valid]
    shifted = active - active.max(axis=1, keepdims=True)
    log_prob = shifted - np.log(np.exp(shifted).sum(axis=1, keepdims=True))
    prob = np.exp(log_prob)
    onehot = np.eye(classes)[labels]
    ce = -(w[labels] * log_prob[np.arange(len(labels)), labels]).sum() / denominator
    grad_ce = np.zeros_like(z)
    grad_ce[valid] = (prob - onehot) * (w[labels] / denominator)[:, None]

    numerator = 2 * (prob * onehot).sum(axis=0) + eps
    divisor = prob.sum(axis=0) + onehot.sum(axis=0) + eps
    dice = numerator / divisor
    dice_loss = 1 - dice.mean()
    # Derivada respecto de las probabilidades, seguida del jacobiano softmax.
    grad_prob = (numerator[None, :] - 2 * onehot * divisor[None, :]) / divisor[None, :] ** 2 / classes
    grad_dice = np.zeros_like(z)
    grad_dice[valid] = prob * (grad_prob - (grad_prob * prob).sum(axis=1, keepdims=True))
    return float(ce), float(dice_loss), grad_ce, grad_dice


def _finite_difference(fn, x, delta=1e-5):
    numerical = np.empty_like(x)
    for i in np.ndindex(x.shape):
        plus, minus = x.copy(), x.copy()
        plus[i] += delta
        minus[i] -= delta
        numerical[i] = (fn(plus) - fn(minus)) / (2 * delta)
    return numerical


def main():
    target = np.array([0, 0, 1, 1, 2, 255])
    prediction = np.array([0, 1, 1, 0, 0, 999])
    matrix = confusion_matrix(target, prediction, 4)
    expected = np.array([[1, 1, 0, 0], [1, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]])
    assert np.array_equal(matrix, expected)
    iou, mean_iou = iou_from_confusion(matrix)
    assert np.allclose(iou[:3], [1 / 4, 1 / 3, 0]) and np.isnan(iou[3])
    assert np.isclose(mean_iou, 7 / 36)
    empty_iou, empty_mean = iou_from_confusion(np.zeros((3, 3), dtype=int))
    assert np.isnan(empty_iou).all() and np.isnan(empty_mean)
    assert confusion_matrix(np.array([255]), np.array([-5]), 3).sum() == 0
    missing_truth = confusion_matrix(np.array([0, 0]), np.array([0, 1]), 3)
    assert np.allclose(iou_from_confusion(missing_truth)[0][:2], [0.5, 0.0])
    assert np.isnan(iou_from_confusion(missing_truth)[0][2])

    z = np.array([[1.0, 0.1, -0.5], [-0.4, 0.7, 0.1], [0.2, -0.8, 0.4], [4.0, -3.0, 2.0]])
    labels = np.array([0, 1, 0, 255])
    weights = np.array([1.0, 2.0, 3.0])
    ce, dice_loss, grad_ce, grad_dice = losses_and_gradients(z, labels, weights)
    # Referencia escalar independiente, sin matriz one-hot ni vectorización.
    import math
    probabilities = [[math.exp(v) / sum(math.exp(u) for u in row) for v in row] for row in z[:3]]
    ce_reference = sum(-weights[int(labels[i])] * math.log(probabilities[i][int(labels[i])]) for i in range(3)) / 4
    dice_reference = 0.0
    for cls in range(3):
        intersection = sum(probabilities[i][cls] * (int(labels[i]) == cls) for i in range(3))
        cardinality = sum(probabilities[i][cls] + (int(labels[i]) == cls) for i in range(3))
        dice_reference += (2 * intersection + 1e-6) / (cardinality + 1e-6) / 3
    assert np.isclose(ce, ce_reference) and np.isclose(dice_loss, 1 - dice_reference)
    error_ce = np.max(np.abs(grad_ce - _finite_difference(lambda x: losses_and_gradients(x, labels, weights)[0], z)))
    error_dice = np.max(np.abs(grad_dice - _finite_difference(lambda x: losses_and_gradients(x, labels, weights)[1], z)))
    assert error_ce < 1e-8 and error_dice < 1e-8
    assert np.all(grad_ce[-1] == 0) and np.all(grad_dice[-1] == 0)
    assert np.allclose(grad_ce.sum(axis=1), 0, atol=1e-14)
    assert np.allclose(grad_dice.sum(axis=1), 0, atol=1e-14)
    # Cálculo escalar independiente y de alta magnitud para log-sum-exp.
    extreme = np.array([[1000.0, -1000.0], [-1000.0, 1000.0]])
    value = losses_and_gradients(extreme, np.array([1, 1]), np.ones(2))[0]
    assert np.isfinite(value) and np.isclose(value, 1000.0)
    for bad_labels, bad_weights in [(np.array([255]), np.ones(3)), (np.array([0]), np.zeros(3))]:
        try:
            losses_and_gradients(np.zeros((1, 3)), bad_labels, bad_weights)
        except ValueError:
            pass
        else:
            raise AssertionError("Se esperaba rechazar un denominador nulo")
    print("Matriz de confusión:\n", matrix)
    print("IoU por clase:", iou, "mIoU:", mean_iou)
    print("CE ponderada:", ce, "Dice lineal pérdida:", dice_loss)
    print("Error máximo gradiente CE:", error_ce, "Dice:", error_dice)
    print("CE estable para logits extremos:", value)


if __name__ == "__main__":
    main()

U-Net on Oxford-IIIT Pet

The local lab uses images and trimaps from a mirror at a pinned revision and checks their hashes. It separates training and validation within the training set and reserves test; it transforms image and mask together, using nearest-neighbor interpolation for labels. Value 3 is treated as an ambiguous band and pixels with 255 are ignored. A U-Net with ResNet-34 encoder, FCNs with declared strides and DeepLabv3 are compared under the protocol in the code. Training loss adds cross-entropy and half of a soft Dice loss, averaged only over classes present in the batch. Stride-8, 16 and 32 FCNs stop at different encoder stages: the comparison also changes depth and does not isolate grid size alone.

Images in the interactive figures come from Oxford-IIIT Pet, by Parkhi, Vedaldi, Zisserman and Jawahar. The official page declares the CC BY-SA 4.0 license and states that image rights belong to their authors. Versions reduced to 128 × 128 pixels are shown with masks from the short run overlaid; each row’s identification appears in the interactive.

Full mode trains for the reader; ORYON_VERIFY_SHORT=1 reduces data and steps to check the pipeline. The experiment exports the resulting masks, an inference-time skip ablation and, for FCNs, predictions using bilinear and nearest-neighbor interpolation of the same logits. A short run does not demonstrate convergence or architectural superiority. Assessing stability requires more seeds and evaluation on separate splits.

[ ]U-Net and baselines on Oxford-IIIT PetLocal GPU
"""U-Net, FCN y DeepLab sobre trimaps de Oxford-IIIT Pet.

Requiere torch, torchvision, numpy, pyarrow, Pillow y huggingface_hub.
El espejo se fija por revisión: sus particiones train/test se preservan y
validación se extrae solo de train. El trimap original 1/2/3 se convierte
en 0/1/2: animal, fondo y banda ambigua; 3 no es un contorno exacto.
ORYON_VERIFY_SHORT=1 solo verifica el circuito, no mide convergencia.
Los modelos consultan el mismo test: esas comparaciones son exploratorias.
ORYON_SEG_CHECKPOINT_DIR guarda checkpoints solo cuando se especifica.
"""
import base64
import hashlib
import io
import json
import os
from pathlib import Path

import numpy as np
import pyarrow.parquet as pq
from huggingface_hub import hf_hub_download
from PIL import Image
import torch
from torch import nn
from torch.nn import functional as F
from torchvision.models import ResNet34_Weights, ResNet50_Weights, resnet34
from torchvision.models.segmentation import deeplabv3_resnet50

torch.set_num_threads(1)
torch.backends.cudnn.benchmark=False
short=os.environ.get('ORYON_VERIFY_SHORT')=='1'
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
side=128 if short else 256
steps=4 if short else 1000
batch_size=2 if short else 8
seeds=[16191] if short else [16191,16192,16193]
repo='dpdl-benchmark/oxford_iiit_pet'
revision='18515194612b584bf54692372ac035ef773a5b41'
shard_sha256={
    'data/test-00000-of-00003.parquet':'cc4a6ca162c95b297116a4462ff7accf8a7f8ae3ce123d9be56d4c91c00380fa',
    'data/test-00001-of-00003.parquet':'c5fb1c1cff8c27809d11f827819088464311a17bf325703a39334031b28af280',
    'data/test-00002-of-00003.parquet':'65d370e76ca49a131ed874053ac372828303ef771ba4c961878faf4870217fda',
    'data/train-00000-of-00003.parquet':'473606455eb66b1ee9b2a8675e41bf8c7494370fc27eccc5eae5890f882b7442',
    'data/train-00001-of-00003.parquet':'3bc7e8a62a1756044d1ecc4750a246afda63d0e8ac8042f43789e661c87036a8',
    'data/train-00002-of-00003.parquet':'c75713efefddd8e7d692e666eb76072e58db9649c7c2fdccfbae05fba2acd7a3',
}
mean=torch.tensor([.485,.456,.406]).view(3,1,1)
std=torch.tensor([.229,.224,.225]).view(3,1,1)
names=('unet','fcn8','fcn16','fcn32','deeplab')


def read_data():
    """Leer bytes seleccionados por bloques, fijando revisión y particiones."""
    groups={'train':[],'validation':[],'test':[]}
    seen={}
    excluded={'duplicate':0}
    source_splits=('train','test')
    for split in source_splits:
        for shard in range(1 if short else 3):
            filename=f'data/{split}-{shard:05d}-of-00003.parquet'
            path=hf_hub_download(repo_id=repo,repo_type='dataset',revision=revision,filename=filename)
            digest=hashlib.sha256()
            with open(path,'rb') as stream:
                for part in iter(lambda:stream.read(1024*1024),b''): digest.update(part)
            if digest.hexdigest()!=shard_sha256[filename]: raise ValueError('Hash inesperado: '+filename)
            table=pq.ParquetFile(path)
            count=table.metadata.num_rows
            order=np.random.default_rng(16190+shard+(100 if split=='test' else 0)).permutation(count)
            if split=='train':
                if short:
                    subsets={'train':order[:32],'validation':order[32:40]}
                else:
                    cut=int(count*.8)
                    subsets={'train':order[:cut],'validation':order[cut:]}
            else:
                subsets={'test':order[:8] if short else order}
            positions={int(index):(kind,j) for kind,indices in subsets.items() for j,index in enumerate(indices)}
            local={kind:[None]*len(indices) for kind,indices in subsets.items()}
            offset=0
            for batch in table.iter_batches(batch_size=16,columns=['image','segmentation_mask','label']):
                rows=batch.to_pylist()
                for j,row in enumerate(rows):
                    choice=positions.get(offset+j)
                    if choice is not None:
                        kind,pos=choice
                        local[kind][pos]={'image':row['image']['bytes'],'mask':row['segmentation_mask']['bytes'],
                                          'label':int(row['label']),'source':f'{split}/{shard}/{offset+j}'}
                offset+=len(rows)
            for kind,rows in local.items():
                if any(row is None for row in rows): raise RuntimeError('Faltan filas de '+kind)
                for row in rows:
                    digest=hashlib.sha256(row['image']).hexdigest()
                    if digest in seen:
                        excluded['duplicate']+=1
                        continue
                    seen[digest]=kind
                    row['sha256']=digest
                    groups[kind].append(row)
    if any(not values for values in groups.values()): raise ValueError('Partición vacía')
    hashes={k:{r['sha256'] for r in rows} for k,rows in groups.items()}
    assert not hashes['train']&hashes['validation'] and not hashes['train']&hashes['test'] and not hashes['validation']&hashes['test']
    return groups,excluded


def get_item(row,flip=False):
    with Image.open(io.BytesIO(row['image'])) as image:
        image=image.convert('RGB').resize((side,side),Image.Resampling.BILINEAR)
        x=torch.from_numpy(np.asarray(image,dtype=np.uint8).copy()).permute(2,0,1).float()/255
    with Image.open(io.BytesIO(row['mask'])) as image:
        mask=np.asarray(image.resize((side,side),Image.Resampling.NEAREST),dtype=np.int64).copy()
    values=set(np.unique(mask).tolist())
    if not values.issubset({1,2,3,255}): raise ValueError(f'Trimap inesperado {values} en {row["source"]}')
    mask=np.where(mask==255,255,mask-1)
    y=torch.from_numpy(mask).long()
    if flip: x=x.flip(-1); y=y.flip(-1)
    return ((x-mean)/std).to(device),y.to(device)


class Encoder(nn.Module):
    def __init__(self):
        super().__init__()
        self.base=resnet34(weights=ResNet34_Weights.IMAGENET1K_V1)
        self.base.fc=nn.Identity()
        for p in self.base.parameters(): p.requires_grad_(False)
        for block in (self.base.layer2,self.base.layer3,self.base.layer4):
            for p in block.parameters(): p.requires_grad_(True)

    def forward(self,x,stop=32):
        b=self.base
        s=b.relu(b.bn1(b.conv1(x)))
        x=b.layer1(b.maxpool(s))
        c3=b.layer2(x)
        if stop==8: return s,x,c3,None,None
        c4=b.layer3(c3)
        if stop==16: return s,x,c3,c4,None
        return s,x,c3,c4,b.layer4(c4)


class Block(nn.Module):
    def __init__(self,cin,cout):
        super().__init__()
        self.net=nn.Sequential(nn.Conv2d(cin,cout,3,padding=1),nn.GroupNorm(8,cout),nn.ReLU(),
                               nn.Conv2d(cout,cout,3,padding=1),nn.GroupNorm(8,cout),nn.ReLU())
    def forward(self,x): return self.net(x)


class UNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.encoder=Encoder()
        self.blocks=nn.ModuleList([Block(512+256,256),Block(256+128,128),Block(128+64,64),Block(64+64,32)])
        self.head=nn.Conv2d(32,3,1)

    def forward(self,x,drop_skip=None):
        stem,c2,c3,c4,c5=self.encoder(x)
        z=c5
        for i,(skip,block) in enumerate(zip((c4,c3,c2,stem),self.blocks)):
            z=F.interpolate(z,size=skip.shape[-2:],mode='bilinear',align_corners=False)
            if drop_skip==i: skip=torch.zeros_like(skip)
            z=block(torch.cat((z,skip),dim=1))
        return F.interpolate(self.head(z),size=x.shape[-2:],mode='bilinear',align_corners=False)


class FCN(nn.Module):
    def __init__(self,stride):
        super().__init__()
        self.encoder=Encoder()
        self.stride=stride
        self.head=nn.Conv2d({8:128,16:256,32:512}[stride],3,1)

    def forward(self,x,upsample_mode='bilinear'):
        _,_,c3,c4,c5=self.encoder(x,stop=self.stride)
        feature={8:c3,16:c4,32:c5}[self.stride]
        if upsample_mode not in ('nearest','bilinear'): raise ValueError('Interpolación desconocida')
        options={'align_corners':False} if upsample_mode=='bilinear' else {}
        return F.interpolate(self.head(feature),size=x.shape[-2:],mode=upsample_mode,**options)


class DeepLab(nn.Module):
    def __init__(self):
        super().__init__()
        self.net=deeplabv3_resnet50(weights=None,weights_backbone=ResNet50_Weights.IMAGENET1K_V2,
                                    num_classes=3,aux_loss=False)
    def forward(self,x): return self.net(x)['out']


def build(name):
    if name=='unet': return UNet()
    if name.startswith('fcn'): return FCN(int(name[3:]))
    if name=='deeplab': return DeepLab()
    raise ValueError(name)


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


def loss_fn(logits,y):
    valid=y!=255
    if not bool(valid.any()): raise ValueError('Lote sin píxeles válidos')
    ce=F.cross_entropy(logits,y,ignore_index=255)
    safe=y.masked_fill(~valid,0)
    truth=F.one_hot(safe,3).permute(0,3,1,2).float()*valid[:,None]
    probs=logits.softmax(1)*valid[:,None]
    intersection=(probs*truth).sum((0,2,3))
    denominator=probs.sum((0,2,3))+truth.sum((0,2,3))
    present=truth.sum((0,2,3))>0
    dice=(2*intersection+1e-6)/(denominator+1e-6)
    dice_loss=1-dice[present].mean()
    return ce+.5*dice_loss


def confusion(logits,y):
    pred=logits.argmax(1)
    valid=(y!=255)&(y>=0)&(y<3)
    return torch.bincount((3*y[valid]+pred[valid]).flatten(),minlength=9).reshape(3,3)


def metrics(matrix):
    matrix=matrix.double()
    denom=matrix.sum(0)+matrix.sum(1)-matrix.diag()
    ious=[float(matrix[i,i]/denom[i]) if denom[i]>0 else None for i in range(3)]
    valid=[x for x in ious if x is not None]
    return {'miou':sum(valid)/len(valid) if valid else None,'iou':ious,'confusion':matrix.long().tolist()}


def boundary_counts(logits,y):
    """IoU de bordes de cuatro vecinos, sin tolerancia espacial ni ignorados."""
    prediction=logits.argmax(1)
    valid=(y!=255)&(y>=0)&(y<3)
    def edge(mask):
        result=torch.zeros_like(valid)
        horizontal=(mask[:,:,1:]!=mask[:,:,:-1])&valid[:,:,1:]&valid[:,:,:-1]
        vertical=(mask[:,1:,:]!=mask[:,:-1,:])&valid[:,1:,:]&valid[:,:-1,:]
        result[:,:,1:]|=horizontal; result[:,:,:-1]|=horizontal
        result[:,1:,:]|=vertical; result[:,:-1,:]|=vertical
        return result
    p,g=edge(prediction),edge(y)
    return int((p&g).sum()),int((p|g).sum())


def evaluate(model,rows,drop_skip=None):
    model.eval()
    total=torch.zeros((3,3),dtype=torch.int64,device=device)
    boundary_intersection=0; boundary_union=0
    with torch.no_grad():
        for row in rows:
            x,y=get_item(row)
            out=model(x[None],drop_skip=drop_skip) if drop_skip is not None else model(x[None])
            if not bool(torch.isfinite(out).all()): raise FloatingPointError('Logits no finitos')
            total+=confusion(out,y[None])
            intersection,union=boundary_counts(out,y[None])
            boundary_intersection+=intersection; boundary_union+=union
    result=metrics(total)
    result['boundary_iou']=boundary_intersection/boundary_union if boundary_union else None
    result['boundary_intersection']=boundary_intersection
    result['boundary_union']=boundary_union
    return result


def conv_flops(model):
    """Dos FLOPs por MAC nominal; solo conv/lineal, sin BN ni interpolación."""
    total=0
    def hook(layer,inputs,output):
        nonlocal total
        if isinstance(layer,nn.Conv2d):
            total+=2*output.numel()*(layer.in_channels//layer.groups)*layer.kernel_size[0]*layer.kernel_size[1]
        elif isinstance(layer,nn.Linear): total+=2*output.numel()*layer.in_features
    hooks=[m.register_forward_hook(hook) for m in model.modules() if isinstance(m,(nn.Conv2d,nn.Linear))]
    try:
        model.eval()
        with torch.no_grad(): model(torch.zeros((1,3,side,side),device=device))
    finally:
        for hook in hooks: hook.remove()
    return total


def png(array):
    buffer=io.BytesIO()
    Image.fromarray(array).save(buffer,format='PNG')
    return 'data:image/png;base64,'+base64.b64encode(buffer.getvalue()).decode('ascii')


def sample_outputs(model,rows,name):
    model.eval(); output=[]
    with torch.no_grad():
        for row in rows[:min(4,len(rows))]:
            x,y=get_item(row)
            logits=model(x[None])
            predicted=logits.argmax(1)[0].byte().cpu().numpy()
            original=((x.cpu()*std+mean).clamp(0,1).permute(1,2,0).numpy()*255).astype(np.uint8)
            item={'source':row['source'],'sha256':row['sha256'],'image':png(original),
                  'truth':png(y.byte().cpu().numpy()),'prediction':png(predicted),
                  'metrics':metrics(confusion(logits,y[None]))}
            if name.startswith('fcn'):
                item['upsampling']={}
                for mode in ('bilinear','nearest'):
                    changed=model(x[None],upsample_mode=mode)
                    intersection,union=boundary_counts(changed,y[None])
                    item['upsampling'][mode]={'prediction':png(changed.argmax(1)[0].byte().cpu().numpy()),
                        'metrics':metrics(confusion(changed,y[None])),
                        'boundary_intersection':intersection,'boundary_union':union,
                        'boundary_iou':intersection/union if union else None}
            if name=='unet':
                item['ablations']=[]
                for skip in range(4):
                    changed=model(x[None],drop_skip=skip)
                    item['ablations'].append({'skip':skip,'prediction':png(changed.argmax(1)[0].byte().cpu().numpy()),
                                              'metrics':metrics(confusion(changed,y[None]))})
            output.append(item)
    return output


def train_one(name,seed,groups):
    torch.manual_seed(seed)
    rng=np.random.default_rng(seed+1)
    flip_rng=torch.Generator().manual_seed(seed+2)
    model=build(name).to(device)
    opt=torch.optim.AdamW([p for p in model.parameters() if p.requires_grad],lr=.0001,weight_decay=.0001)
    counts=conv_flops(model)
    points=sorted(set((1,steps//2,steps)))
    history=[]; best=None; state=None
    for step in range(1,steps+1):
        model.train(); freeze_bn(model)
        ids=rng.integers(0,len(groups['train']),size=batch_size)
        batch=[get_item(groups['train'][int(i)],bool(torch.rand((),generator=flip_rng)<.5)) for i in ids]
        x=torch.stack([z[0] for z in batch]); y=torch.stack([z[1] for z in batch])
        opt.zero_grad(set_to_none=True)
        logits=model(x); loss=loss_fn(logits,y)
        if not bool(torch.isfinite(loss)): raise FloatingPointError(f'{name} 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'{name} gradiente no finito paso {step}')
        opt.step()
        if step in points:
            valid=evaluate(model,groups['validation'])
            row={'step':step,'batch_loss':float(loss.detach()),'validation':valid}
            history.append(row)
            if valid['miou'] is not None and (best is None or valid['miou']>best['validation']['miou']):
                best=row; state={k:v.detach().cpu().clone() for k,v in model.state_dict().items()}
            print(name,seed,'paso',step,'validación',valid['miou'],flush=True)
    if state is None: raise RuntimeError('Sin checkpoint de validación')
    model.load_state_dict(state)
    test=evaluate(model,groups['test'])
    samples=sample_outputs(model,groups['validation'],name) if seed==seeds[0] else []
    skip_metrics=[]
    if name=='unet':
        skip_metrics=[{'skip':i,'validation':evaluate(model,groups['validation'],drop_skip=i)} for i in range(4)]
    run={'model':name,'seed':seed,'best_step':best['step'],'history':history,'test_exploratory':test,
         'conv_linear_flops':counts,'skip_ablation':skip_metrics,'samples':samples}
    target_dir=os.environ.get('ORYON_SEG_CHECKPOINT_DIR')
    if target_dir:
        destination=Path(target_dir)/f'{name}-{seed}.pt'
        destination.parent.mkdir(parents=True,exist_ok=True)
        with destination.open('xb') as stream:
            torch.save({'model':model.state_dict(),'name':name,'seed':seed,'step':best['step']},stream)
        run['checkpoint']=str(destination)
    del model,opt,state
    torch.cuda.empty_cache()
    return run


def main():
    if device.type!='cuda': raise RuntimeError('Este laboratorio requiere CUDA')
    groups,excluded=read_data()
    output={'protocol':{'repo':repo,'revision':revision,'short':short,'seed_split':16190,
        'steps_per_model':steps,'seeds':seeds,'batch_size':batch_size,'resolution':side,
        'counts':{k:len(v) for k,v in groups.items()},'sources':{k:[r['source'] for r in v] for k,v in groups.items()},
        'deduplicated':excluded,'classes':['animal','fondo','banda ambigua'],
        'selection':'mIoU de validación; primer empate','test':'exploratorio al comparar modelos',
        'boundary':'IoU global de bordes de 4 vecinos, sin tolerancia; se excluyen pares de píxeles con ignorados',
        'flops':'2 por MAC nominal solo convoluciones y lineales; no incluye interpolación ni normalizaciones',
        'warning':'Split del espejo; las máscaras se verifican como 1/2/3/255. Hashes no detectan casi duplicados ni solapamiento ImageNet. Las ablaciones anulan skips sin reentrenar.',
        'gpu':torch.cuda.get_device_name(device),'torch':str(torch.__version__)},'runs':[]}
    path=Path(os.environ.get('ORYON_SEG_OUTPUT','pet-segmentation.json'))
    for name in names:
        for seed in seeds:
            output['runs'].append(train_one(name,seed,groups))
            path.write_text(json.dumps(output,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8')
    print('Resultados guardados:',path,flush=True)


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

ProofTwo ratios, one ranking
Prove: For two binary masks with positive union, prove the relationship between Dice and IoU and explain which ranking it preserves.
0
Let TP be the intersection area, and FP and FN the exclusive areas. No smoothing is used.

Step 1 of 3. How is Dice expressed in terms of TP, FP and FN?

NumericDilated receptive field
In TorchVision ResNet-50 v1.5 use a 7×7 stride-2 stem, 3×3 stride-2 maxpool, blocks [3,4,6,3] and replace_stride_with_dilation=[False,True,True]. Each dilated stage uses the previous dilation in its first 3×3 and the new one in subsequent convolutions. For a 512×512 image, what is the maximum theoretical receptive field at the end of layer4?
QuizHigh accuracy, low mIoU
For 1000 pixels in three classes, the matrix with ground-truth rows is [[940,0,0],[30,10,0],[20,0,0]]. What is the correct interpretation?
QuizConcatenate or add
An encoder map has 64 channels and a spatially aligned decoder map has 32. What happens when they are fused?
CodeAccumulate before averaging
Implement confusion_matrix(pred, target, num_classes, ignore_index) and miou(conf) with NumPy, without loops over pixels or classes. Matrix rows are ground-truth labels and columns are predictions. Skip pixels whose target is ignore_index; for the rest labels are between 0 and num_classes−1. miou averages classes with positive union and returns NaN if none have positive union.
import numpy as np

def confusion_matrix(pred, target, num_classes, ignore_index):
  pass

def miou(conf):
  pass
Shift+Enter to run
Key idea
Segmentation requires preserving both semantics and position. Internal map size, skip alignment, valid labels and the metric definition determine what an improvement means.