Module contents
Lesson 10 of 25Core 100 min

Data augmentation: invariances, mixing and automated policies

Study augmentation as a task-dependent hypothesis, derive mixup and CutMix objectives, compare automated policies and evaluate accuracy and calibration under controlled budgets.

After this lesson you can

  • Explain vicinal risk and when transformations preserve labels.
  • Implement geometric, photometric and occlusion augmentations.
  • Derive mixup loss and compute CutMix weights using effective area.
  • Compare automated augmentation policies and training budgets.
  • Evaluate accuracy and calibration with independent data and uncertainty.

Before you start

More examples do not always mean more information

A slightly shifted photograph usually still shows the same object. That assumption allows new views of a labeled image to be generated. But not all transforms preserve the answer: flipping text, rotating a digit or erasing a small medical finding can change what should be predicted. Augmentation is a hypothesis about the problem, not a guarantee that the model will be invariant.

Convolution equivariance says how its output transforms when input shifts, under particular assumptions. It differs from requiring the final prediction to remain identical. Augmentation adds transformed examples to the training distribution, but finite budget and a particular network do not force that identity to hold exactly.

InteractiveWhat remains of the label

No transformation; the level does not change the image. The same 16 images allow comparison across levels. The classifier is a ResNet-18 trained for only 100 steps in the short run and selected by validation: its predictions can be weak.

Data: CIFAR-10 training set, revision 0b27149; seed 16101, step 100, selected by minimum validation loss. Each confidence comes from running the model on the same quantized pixels shown in the image, not from interpolating predictions across levels. A confident prediction does not guarantee that the label remains valid.

0
Original labelairplane
Model predictionairplane
Maximum confidence68.2 %
Compare images and predictions calculated for the same transforms and magnitudes.

Low confidence may indicate a difficult view but does not prove its label changed. High confidence also does not certify that the original label remains correct. The gallery classifier measures one model; it is not a semantic arbiter.

From empirical risk to vicinal risk

In empirical risk minimization, with examples (xi,yi)(x_i,y_i) and loss ℓ\ell, minimize R^(f)=n−1∑iℓ(f(xi),yi)\widehat R(f)=n^{-1}\sum_i\ell(f(x_i),y_i). Vicinal risk minimization replaces each example’s point mass with a neighborhood distribution νi\nu_i over transformed pairs:

R^vic(f)=1n∑i=1nE(x~,y~)∼νi[ℓ(f(x~),y~)].\widehat R_{\mathrm{vic}}(f)=\frac1n\sum_{i=1}^{n}\mathbb E_{(\tilde x,\tilde y)\sim\nu_i}\left[\ell(f(\tilde x),\tilde y)\right].

In practice approximate the expectation by sampling transforms on each visit. The formulation comes from Chapelle and colleagues. If TT preserves the label, you can take (x~,y~)=(T(xi),yi)(\tilde x,\tilde y)=(T(x_i),y_i). This equality is a task-dependent assumption: horizontal flipping may be reasonable for object classification, but a traffic arrow’s direction changes its class. For segmentation or detection, also transform the mask or boxes.

If an exact transform TT leaves the label unchanged, an ideal function might satisfy f(Tx)=f(x)f(Tx)=f(x). Minimizing augmented risk penalizes errors only on sampled views; it does not prove invariance outside that support or force exact equality even inside it. Policy, magnitudes and step count determine which constraints are observed.

Choosing νi\nu_i determines a tradeoff. If it generates only identical copies, empirical risk is recovered. If it generates plausible views of the same class, the model is asked to share information among them. If it assigns the original label to views that should have another, systematic noise is introduced. The formal expectation describes the objective to optimize; a training batch is a random gradient estimate, not an enumeration of every possible view. Its samples are not new independent world data: they start from the same original examples and can share their biases.

For a transform with random parameter θ\theta, write νi\nu_i as the distribution of (Tθ(xi),yi)(T_\theta(x_i),y_i) only when the label truly remains valid. In detection, translating the image requires translating the box and clipping it to the frame; if the object disappears, decide what to do with its annotation too. For X-rays, a transform can remove or reflect task-relevant markers; validity requires domain and intended-use knowledge.

Consider four domains before enabling a flip or rotation. A handwritten 6 rotated 180° can resemble a 9; reflecting a turn sign can change its direction. In satellite imagery, orientation may be irrelevant for classifying terrain type but not necessarily for a task using north as reference. In X-rays, laterality or markers can form part of the label. These are hypotheses to check against the specific problem, not a universal list of allowed operations.

Geometry, color and occlusion

Geometric and photometric transforms change different aspects. A crop with padding shifts the window, flipping reflects coordinates and scaling changes how much of the scene occupies the image. Brightness, contrast and saturation modify intensities. Their order matters: erasing before cropping generally differs from erasing afterward. Images must stay in the expected range before normalization, and color changes are not automatically appropriate when color is part of the diagnosis.

Random erasing hides a region to avoid the network always relying on the same cue. Cutout uses a spatial mask; Random Erasing explores regions of varying size and aspect and different fill rules. If occlusion removes the small object itself, retaining the complete label introduces potentially incorrect supervision. DeVries and Taylor report CIFAR-10 errors for WRN-28-10 under their crop-and-reflect recipe of 3.87 ± 0.08% without Cutout and 3.08 ± 0.16% with it; these results belong to that protocol and do not guarantee improvement for every task.

When implementing a batch crop, each example may receive a different position. With padding pp, height HH and width WW, one simple approach pads boundaries, samples integer shifts and gathers each example’s corresponding H×WH\times W window. Specify whether padding is zero, reflection or another rule: they generate different pixels near boundaries. A horizontal flip reverses the width axis; it does not permute channels. For jitter, define operation range and order before normalization; clipping intensities to the valid range also changes the distribution.

Vectorization avoids a Python loop per image but does not by itself prove the pipeline is faster. Transfer, memory access and synchronization have costs. Measure the complete pipeline on your hardware, with prepared data or loading included depending on the question, and compare the same work. A transform calculated after normalization needs its fill rule expressed in that space; normalized zero does not necessarily mean a black pixel.

The following jitter applies brightness, contrast and saturation per image in that fixed order. Calculation is vectorized; the final loop only compares results with torchvision operations. The color policy in the later ablation varies brightness only: do not confuse that comparison with this composite jitter.

[ ]Batch color jitterLocal GPU
"""Jitter vectorizado por imagen con orden fijo: brillo, contraste y saturación."""
import torch
from torchvision.transforms.v2 import functional as VF

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
g = torch.Generator(device=device).manual_seed(16110)
x = torch.rand((4, 3, 32, 32), generator=g, device=device)
factors = .6 + .8 * torch.rand((4, 3), generator=g, device=device)


def gray(x):
    return .2989*x[:, 0:1] + .587*x[:, 1:2] + .114*x[:, 2:3]


def color_jitter_batch(x, factors):
    """RGB flotante en [0,1], factores no negativos, uno de cada por imagen."""
    b, c, s = (factors[:, i, None, None, None] for i in range(3))
    x = (b*x).clamp(0, 1)
    mean = gray(x).mean((1, 2, 3), keepdim=True)
    x = (c*x + (1-c)*mean).clamp(0, 1)
    grayscale = gray(x)
    return (s*x + (1-s)*grayscale).clamp(0, 1)


out = color_jitter_batch(x, factors)
# Este bucle solo verifica la implementación; el cálculo anterior es por lote.
reference = torch.stack([
    VF.adjust_saturation(VF.adjust_contrast(VF.adjust_brightness(x[i], float(factors[i, 0])),
                                            float(factors[i, 1])), float(factors[i, 2]))
    for i in range(len(x))
])
assert torch.allclose(out, reference, atol=1e-6, rtol=1e-6)
assert bool(((0 <= out) & (out <= 1)).all())
print('Diferencia máxima con torchvision:', float((out-reference).abs().max()))
print('Factores brillo, contraste y saturación por imagen:')
print(factors.cpu())
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Mixing examples and targets

In mixup, choose two examples and coefficient λ∼Beta⁡(α,α)\lambda\sim\operatorname{Beta}(\alpha,\alpha), with α>0\alpha>0:

x~=λxi+(1−λ)xj,y~=λyi+(1−λ)yj.\tilde x=\lambda x_i+(1-\lambda)x_j,\qquad \tilde y=\lambda y_i+(1-\lambda)y_j.

Labels yiy_i and yjy_j are class vectors, and cross-entropy loss with logits zz is linear in the target. Thus, with the same predictions p=softmax⁡(z)p=\operatorname{softmax}(z),

−∑cy~clog⁡pc=λCE⁡(z,yi)+(1−λ)CE⁡(z,yj).-\sum_c\tilde y_c\log p_c=\lambda\operatorname{CE}(z,y_i)+(1-\lambda)\operatorname{CE}(z,y_j).

This does not claim f(x~)f(\tilde x) is the mixture of f(xi)f(x_i) and f(xj)f(x_j) or that the decision boundary is linear. Symmetry of the beta distribution gives E[λ]=1/2\mathbb E[\lambda]=1/2 for any positive α\alpha. When α\alpha is small, coefficients near endpoints are frequent; swapping the two examples, max⁡(λ,1−λ)\max(\lambda,1-\lambda) measures how much the larger weight dominates.

Loss equivalence also preserves the gradient with respect to logits because both expressions are the same function of zz. For class cc, the derivative is pc−y~cp_c-\tilde y_c. Do not confuse this example-pair-dependent label with label smoothing, which assigns extra mass according to a fixed distribution. If both examples belong to the same class, the mixed label remains that class even though the image changes.

A batch permutation may pair an image with itself. This does not break the formula, but reduces distinct mixtures appearing in that step. In a reproducible experiment, record how pairs are selected, whether λ\lambda is shared across the batch or sampled per example, and which operations are applied before and after mixing. These variants induce different training distributions.

[ ]Mixup coefficientsBrowser
import numpy as np

rng = np.random.default_rng(1610)
weights = rng.beta(0.2, 0.2, size=100_000)
print('media de λ:', weights.mean())
print('media del peso mayor:', np.maximum(weights, 1 - weights).mean())
print('proporción con peso mayor > 0.9:', (np.maximum(weights, 1 - weights) > 0.9).mean())

# Integración en [0, 1/2] de la densidad beta(a+1, a).
import math
a = 0.2
grid = np.linspace(0, 0.5, 100_001)
f = grid**a * (1-grid)**(a-1)
integral = (f[:-1] + f[1:]).sum() * (grid[1] - grid[0]) / 2
beta = math.exp(math.lgamma(a+1) + math.lgamma(a) - math.lgamma(2*a+1))
print('media del peso mayor por integración:', 1 - integral / beta)

The original mixup paper reports CIFAR-10 errors of 5.6% versus 4.2% for PreAct ResNet-18 and 3.8% versus 2.7% for WRN-28-10 under its recipe and budget. These are empirical comparisons, not a guarantee for every model. Calibration improvement also depends on distribution and protocol; measure confidence on separate data, not from a boundary’s visual smoothness.

InteractiveTwo moons and mixup training

Each map comes from a separately trained network. Change the model and strength to compare; tap the plane to choose a point. Colors intensify further from probability 0.5.

-1012-101
  • Class 0
  • Class 1

The line marks neighboring cells that change class at a threshold of 0.5. The crosshair is at (0.50, 0.25). Each network has 24 tanh hidden neurons; it was trained for 2400 steps with the same initialization on 240 points and evaluated on another 80. Data, split and weights are stored alongside the interactive. This single-seed experiment does not guarantee that mixup improves accuracy or produces a linear ramp.

Displayed model
Visible points
0.50
0.25
Displayed model validation accuracy95.0 %
Class 1 probability at the crosshair72.3 %
Without / with mixup at the crosshair72.3 % / 47.7 %
Compare models trained for discrete α values; surfaces show their actual predictions.

The figure’s experiment is reproduced with this local cell. It generates the split before training and uses the same initialization for each α. It saves weights and points alongside output; you can check probabilities using the MLP forward pass. The final common step is selected without choosing the best validation result.

[ ]Two moons: MLP with and without mixupLocal GPU
"""Entrena cinco MLP pequeñas y exporta los pesos de la figura de dos lunas.

Ejecución reproducible: OPENBLAS_NUM_THREADS=1 python train_moons.py
Los ejemplos y la partición se fijan antes del entrenamiento. Se elige el
último paso para todas las políticas, no el mejor resultado de validación.
"""
import json
import os
from pathlib import Path

import numpy as np
from threadpoolctl import threadpool_limits
threadpool_limits(limits=1)
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split

data_seed, split_seed, model_seed = 16101, 16102, 16103
x, y = make_moons(n_samples=320, noise=0.18, random_state=data_seed)
train, valid = train_test_split(np.arange(len(y)), test_size=0.25,
                                random_state=split_seed, stratify=y)
train_x, train_y = x[train], y[train]
valid_x, valid_y = x[valid], y[valid]
onehot = np.eye(2)[train_y]


def forward(x, params):
    hidden = np.tanh(x @ params['w1'] + params['b1'])
    logits = hidden @ params['w2'] + params['b2']
    logits -= logits.max(axis=1, keepdims=True)
    exp = np.exp(logits)
    return hidden, exp / exp.sum(axis=1, keepdims=True)


def train_model(alpha):
    init = np.random.default_rng(model_seed)
    pairing = np.random.default_rng(model_seed + 1)
    beta = np.random.default_rng(model_seed + 2)
    params = {'w1': init.normal(0, np.sqrt(1 / 2), (2, 24)), 'b1': np.zeros(24),
              'w2': init.normal(0, np.sqrt(1 / 24), (24, 2)), 'b2': np.zeros(2)}
    steps, lr = 2400, 0.12
    for _ in range(steps):
        if alpha:
            perm = pairing.permutation(len(train_x))
            lam = beta.beta(alpha, alpha, (len(train_x), 1))
            inputs = lam * train_x + (1 - lam) * train_x[perm]
            targets = lam * onehot + (1 - lam) * onehot[perm]
        else:
            inputs, targets = train_x, onehot
        hidden, probs = forward(inputs, params)
        dz = (probs - targets) / len(inputs)
        dw2 = hidden.T @ dz
        db2 = dz.sum(axis=0)
        dh = (dz @ params['w2'].T) * (1 - hidden ** 2)
        dw1, db1 = inputs.T @ dh, dh.sum(axis=0)
        for key, gradient in (('w1', dw1), ('b1', db1), ('w2', dw2), ('b2', db2)):
            params[key] -= lr * gradient
    train_prob = forward(train_x, params)[1]
    valid_prob = forward(valid_x, params)[1]
    return {'alpha': alpha, 'weights': {k: v.tolist() for k, v in params.items()},
            'train_accuracy': float((train_prob.argmax(1) == train_y).mean()),
            'valid_accuracy': float((valid_prob.argmax(1) == valid_y).mean()),
            'valid_loss': float(-np.log(valid_prob[np.arange(len(valid_y)), valid_y]).mean()),
            'valid_probs_class1': valid_prob[:, 1].tolist()}


models = [train_model(alpha) for alpha in (0, .1, .2, .5, 1.)]
result = {'generator': 'sklearn.datasets.make_moons', 'data_seed': data_seed,
          'split_seed': split_seed, 'model_seed': model_seed, 'noise': 0.18,
          'steps': 2400, 'learning_rate': 0.12, 'hidden_units': 24,
          'method': 'descenso por gradiente a lote completo; muestra Beta y permutación nuevas por paso',
          'selection': 'último paso, común a todas las políticas',
          'train': [[float(a), float(b), int(label)] for (a, b), label in zip(train_x, train_y)],
          'valid': [[float(a), float(b), int(label)] for (a, b), label in zip(valid_x, valid_y)],
          'models': models}
target = Path(os.environ.get('ORYON_MOONS_OUTPUT', 'm16-l10-moons-models.json'))
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(json.dumps(result, ensure_ascii=False, separators=(',', ':')), encoding='utf-8')
for m in models:
    print(f"alpha={m['alpha']}: entrenamiento={m['train_accuracy']:.4f}, "
          f"validación={m['valid_accuracy']:.4f}, pérdida_val={m['valid_loss']:.6f}")
print('Pesos y particiones:', target)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Pasting regions and correcting area

CutMix copies a region of one image into another. If the base image supplies spatial fraction λreal\lambda_{\mathrm{real}}, the target assigns that weight to its class and the rest to the patch class. The area rule is an approximation: a small region may contain the whole object, and a large one only background. It is not a direct measure of semantic proportion.

InteractiveThe area actually pasted

Two real CIFAR-10 training images: cat as the base and frog as the donor. The crop uses the same coordinates in both images. Drag the box to move it and its bottom circle to resize it; the sliders provide the same keyboard control.

CutMix
Only the visible region comes from the frog.
Mixup with the same weight
Both complete images are interpolated.

Blue: cat, 75.00 %. Orange: frog, 25.00 %. In both methods the soft label uses these weights; the area is a mixing rule, not a measure of how much of the object appears in the crop.

Nominal rectangle: 16×16 = 256 pixels. Inside the image: 16×16 = 256. If it crosses the edge, the actually pasted area is used, not the nominal one. The mixed image shows channel interpolation with display rounding.

Source: CIFAR-10, training split, revision 0b27149, rows 13 (cat) and 1 (frog), zero-based indices.

8
8
16
16
Visible pasted area256 / 1024 pixels
Cat weight75.00 % (768/1024)
Frog weight25.00 % (256/1024)
Move and resize the rectangle and compare adjusted weight with uniform mixing.

For an H×WH\times W image and a half-open integer rectangle [x0,x1)×[y0,y1)[x_0,x_1)\times[y_0,y_1), clip its endpoints to image bounds. If effective area is AA, then λreal=1−A/(HW)\lambda_{\mathrm{real}}=1-A/(HW). Using proposed area before clipping gives an incorrect target when the window extends outside. This cell checks boundary and empty-rectangle cases.

For example, if a proposed 16×16 patch has half its width outside a 32×32 image, only 8×16 pixels are copied. The base image label weighs 1−128/1024=0.8751-128/1024=0.875, not 1−256/10241-256/1024. If each batch item has a different mask, calculate a weight per item; one shared mask allows a single scalar. In both cases check the applied mask area, not a beta sample before rounding and clipping.

[ ]Actual CutMix areaBrowser
def cutmix_weight(h, w, x0, y0, x1, y1):
    x0, x1 = max(0, min(w, x0)), max(0, min(w, x1))
    y0, y1 = max(0, min(h, y0)), max(0, min(h, y1))
    area = max(0, x1 - x0) * max(0, y1 - y0)
    return 1 - area / (h * w)

for rect in [(0, 0, 32, 32), (-8, 8, 8, 24), (3, 3, 3, 10)]:
    print(rect, 'peso de la base:', cutmix_weight(32, 32, *rect))

In table 3 of Yun and colleagues, ResNet-50 on ImageNet obtains top-1 errors of 23.68% with the baseline recipe, 22.58% with mixup and 21.40% with CutMix. Their localization evaluation also favors CutMix under the described protocol. This does not imply CutMix always beats mixup: architecture, duration, data and metric matter.

Policies and budget

Automated augmentation policies organize operations, probabilities and magnitudes. AutoAugment searches subpolicies using validation evaluation; this search has a cost and can adapt to the chosen set. RandAugment reduces the search to parameters such as operation count NN and global magnitude MM. TrivialAugment randomly chooses one operation and magnitude from a fixed space, avoiding tuning a specific policy, although choosing the space and ranges remains a decision.

Strong augmentation can initially slow fitting and improve generalization with more steps, but can also remain harmful if it violates semantics. To distinguish these possibilities, compare curves under the same budget and also longer budgets. In validation use a deterministic transform unless explicitly studying test-time augmentation; then state how many views are combined and apply the same protocol to alternatives.

Uncertainty in a comparison

Accuracy does not describe all probability quality. For a partition of maximum confidence into bins BbB_b, binned expected calibration error, ECE, is calculated as

ECE⁡=∑b=1B∣Bb∣n∣acc⁡(Bb)−conf⁡(Bb)∣.\operatorname{ECE}=\sum_{b=1}^{B}\frac{|B_b|}{n}\left|\operatorname{acc}(B_b)-\operatorname{conf}(B_b)\right|.

Here acc⁡(Bb)\operatorname{acc}(B_b) is the fraction of correct predictions in the bin and conf⁡(Bb)\operatorname{conf}(B_b) the mean of their maximum probabilities. Empty bins contribute nothing; confidence exactly equal to one must enter the last bin. ECE depends on bin count and bounds and can hide per-class calibration errors. A small sample value does not prove perfect calibration or replace a reliability diagram.

For example, if a bin has 20 predictions with mean confidence 0.8 and 15 correct, its contribution before weighting by bin size is ∣15/20−0.8∣=0.05|15/20-0.8|=0.05. Then multiply by 20/n20/n. Do not average bin differences equally if sizes differ, or calculate confidence using a prediction from another image view. For unaugmented test use deterministic-view probabilities and unmixed labels; training loss with soft targets answers another question.

The experiment records all three individual seeds and paired differences. An interval from resampling examples quantifies variation associated with the evaluated sample conditional on the trained model; it does not turn one training run into multiple independent runs. With only three seeds, conclusions about between-training variability are fragile. Do not select the best policy by repeatedly consulting test: use validation for those decisions and reserve an independent test for the end.

Lab: batch operations and ablation

The lab implements batch operations on GPU and checks properties against torchvision. For a fair comparison, fix splits and separate randomness sources for initialization, example order, geometry and mixing: a policy then cannot change batches by consuming extra random numbers. The short experiment checks the full flow; it should not be interpreted as a converged benchmark. Select the checkpoint by validation and reserve an independent evaluation set for final decisions.

The short test uses 1000 fitting, 200 validation and 200 exploratory test images, with 100 steps per run. Short test is separate from m16-l07 and m16-l08 short subsets; full test shares images with earlier experiments. The gallery figure uses the geometry checkpoint from seed 16101, saved after selecting minimum validation loss. Its 100-step result does not represent a converged model.

The table printed by this cell includes accuracy, 15-bin ECE and bootstrap intervals stratified by class and conditional on each model. In the short run, the no-augmentation policy obtained 20%, 12% and 14% test accuracy across three seeds; geometry obtained 16%, 25% and 13%. These brief trials do not justify declaring a winning policy. Full mode is left to you.

[ ]Augmentation ablation on CIFAR-10Local GPU
"""CIFAR-10: ablación de aumentaciones y galería de predicciones reales.

Requiere torch, torchvision, numpy, pillow, pyarrow y huggingface_hub.
ORYON_VERIFY_SHORT=1 comprueba el programa con menos datos y pasos.
Las pruebas cortas son exploratorias y no reproducen un resultado publicado.
"""
import base64
import copy
import io
import json
import os
from pathlib import Path

os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG', ':4096:8')
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.transforms import v2
from torchvision.transforms.v2 import functional as VF

torch.set_num_threads(1)
torch.use_deterministic_algorithms(True)
torch.backends.cudnn.benchmark = False
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if device.type != 'cuda':
    raise RuntimeError('Este laboratorio requiere CUDA')
short = os.environ.get('ORYON_VERIFY_SHORT') == '1'
steps = 100 if short else 64000
batch_size = 64 if short else 128
train_n, valid_n, test_n = (100, 20, 20) if short else (4500, 500, 1000)
seeds = [16101, 16102, 16103]
policies = ['ninguna', 'geometria', 'color', 'borrado', 'mixup', 'cutmix']
revision = '0b27149'
amp = torch.cuda.is_bf16_supported()


def groups(split, seed):
    path = hf_hub_download(repo_id='uoft-cs/cifar10', repo_type='dataset',
                           filename=f'plain_text/{split}-00000-of-00001.parquet', revision=revision)
    parquet = pq.ParquetFile(path)
    labels = np.concatenate([b.column(0).to_numpy() for b in parquet.iter_batches(batch_size=1024, columns=['label'])]).astype(np.int64)
    rng = np.random.default_rng(seed)
    return path, labels, [rng.permutation(np.flatnonzero(labels == k)) for k in range(10)]


def read_images(path, labels, ids):
    positions = {int(source): i for i, source in enumerate(ids)}
    images = np.empty((len(ids), 3, 32, 32), dtype=np.uint8)
    seen = np.zeros(len(ids), dtype=bool)
    offset = 0
    for batch in pq.ParquetFile(path).iter_batches(batch_size=256, columns=['img']):
        for local in range(batch.num_rows):
            target = positions.get(offset + local)
            if target is not None:
                with Image.open(io.BytesIO(batch.column(0)[local].as_py()['bytes'])) as im:
                    images[target] = np.asarray(im.convert('RGB'), dtype=np.uint8).transpose(2, 0, 1)
                seen[target] = True
        offset += batch.num_rows
    if not seen.all():
        raise RuntimeError('Faltan imágenes')
    return torch.from_numpy(images).to(device), torch.from_numpy(labels[ids].copy()).to(device)


def datasets():
    train_path, train_labels, g = groups('train', 16070)
    train_ids = np.concatenate([x[:train_n] for x in g])
    valid_ids = np.concatenate([x[train_n:train_n + valid_n] for x in g])
    test_path, test_labels, tg = groups('test', 16074)
    start = 40 if short else 0
    test_ids = np.concatenate([x[start:start + test_n] for x in tg])
    assert not set(train_ids) & set(valid_ids)
    if short:
        assert not set(test_ids) & set(np.concatenate([x[:40] for x in tg]))
    return (read_images(train_path, train_labels, train_ids),
            read_images(train_path, train_labels, valid_ids),
            read_images(test_path, test_labels, test_ids), train_ids, valid_ids, test_ids)


def stats(images):
    total = torch.zeros(3, device=device, dtype=torch.float64)
    squares = torch.zeros_like(total)
    count = 0
    for batch in images.split(256):
        x = batch.to(torch.float64) / 255
        total += x.sum((0, 2, 3))
        squares += x.square().sum((0, 2, 3))
        count += len(batch) * 32 * 32
    mean = total / count
    std = (squares / count - mean.square()).clamp_min(0).sqrt()
    assert bool((std > 0).all())
    return mean.float()[None, :, None, None], std.float()[None, :, None, None]


def geometry(x, generator):
    n = len(x)
    padded = F.pad(x, (4, 4, 4, 4), mode='reflect')
    dy = torch.randint(0, 9, (n,), generator=generator, device=device)
    dx = torch.randint(0, 9, (n,), generator=generator, device=device)
    rows = dy[:, None] + torch.arange(32, device=device)[None, :]
    cols = dx[:, None] + torch.arange(32, device=device)[None, :]
    x = padded[torch.arange(n, device=device)[:, None, None, None],
               torch.arange(3, device=device)[None, :, None, None],
               rows[:, None, :, None], cols[:, None, None, :]]
    flip = torch.rand(n, generator=generator, device=device) < .5
    return torch.where(flip[:, None, None, None], x.flip(-1), x)


def brightness(x, factors):
    return (x * factors[:, None, None, None]).clamp(0, 1)


def erase_boxes(x, boxes):
    h, w = x.shape[-2:]
    rows = torch.arange(h, device=x.device)[None, :, None]
    cols = torch.arange(w, device=x.device)[None, None, :]
    x1, y1, x2, y2 = [boxes[:, k, None, None] for k in range(4)]
    mask = (cols >= x1) & (cols < x2) & (rows >= y1) & (rows < y2)
    return torch.where(mask[:, None], torch.zeros_like(x), x), mask


def random_erase(x, generator):
    n = len(x)
    # Cuadrados de lado uniforme entre 0 y 12; no pretende imitar la ley de v2.
    side = torch.randint(0, 13, (n,), generator=generator, device=device)
    cx = torch.randint(0, 32, (n,), generator=generator, device=device)
    cy = torch.randint(0, 32, (n,), generator=generator, device=device)
    x1 = (cx - side // 2).clamp(0, 32)
    y1 = (cy - side // 2).clamp(0, 32)
    boxes = torch.stack((x1, y1, (cx - side // 2 + side).clamp(0, 32),
                         (cy - side // 2 + side).clamp(0, 32)), dim=1)
    return erase_boxes(x, boxes)[0]


def cutmix_box(x, perm, boxes):
    _, mask = erase_boxes(x, boxes)
    mixed = torch.where(mask[:, None], x[perm], x)
    lam = 1 - mask.float().mean((1, 2))
    return mixed, lam


def random_cutmix(x, generator, beta_rng):
    n = len(x)
    nominal = beta_rng.beta(1., 1.)
    side = int(32 * np.sqrt(1 - nominal))
    cx = torch.randint(0, 32, (n,), generator=generator, device=device)
    cy = torch.randint(0, 32, (n,), generator=generator, device=device)
    x1 = (cx - side // 2).clamp(0, 32)
    y1 = (cy - side // 2).clamp(0, 32)
    boxes = torch.stack((x1, y1, (cx - side // 2 + side).clamp(0, 32),
                         (cy - side // 2 + side).clamp(0, 32)), dim=1)
    perm = torch.randperm(n, generator=generator, device=device)
    mixed, lam = cutmix_box(x, perm, boxes)
    return mixed, perm, lam


def property_tests():
    x = torch.linspace(0, 1, 4 * 3 * 32 * 32, device=device).reshape(4, 3, 32, 32)
    y = torch.tensor([0, 1, 2, 3], device=device)
    assert torch.allclose(brightness(x, torch.full((4,), .7, device=device)), VF.adjust_brightness(x, .7))
    boxes = torch.tensor([[0, 0, 1, 1], [28, 29, 32, 32], [0, 0, 0, 0], [4, 5, 12, 15]], device=device)
    erased, mask = erase_boxes(x, boxes)
    for i, (x1, y1, x2, y2) in enumerate(boxes.tolist()):
        expected = VF.erase(x[i], y1, x1, y2-y1, x2-x1, 0)
        assert torch.equal(erased[i], expected)
        assert int(mask[i].sum()) == (x2-x1)*(y2-y1)
    perm = torch.arange(4, device=device).roll(1)
    lam = .35
    mix = v2.MixUp(num_classes=10)
    mix.make_params = lambda flat: {'lam': lam}
    mx, my = mix(x, y)
    assert torch.allclose(mx, lam*x+(1-lam)*x[perm])
    assert torch.allclose(my, lam*F.one_hot(y, 10)+(1-lam)*F.one_hot(y[perm], 10))
    box = (0, 0, 5, 7)
    correct = 1 - 35/1024
    cut = v2.CutMix(num_classes=10)
    cut.make_params = lambda flat: {'box': box, 'lam_adjusted': correct}
    cx, cy = cut(x, y)
    own, weights = cutmix_box(x, perm, torch.tensor([box]*4, device=device))
    assert torch.equal(cx, own) and torch.allclose(weights, torch.full_like(weights, correct))
    assert torch.allclose(cy, correct*F.one_hot(y, 10)+(1-correct)*F.one_hot(y[perm], 10))
    print('Propiedades v2: brillo, borrado, MixUp y CutMix coinciden; área recortada 35/1024.', flush=True)


class Block(nn.Module):
    def __init__(self, cin, cout, stride=1):
        super().__init__()
        self.conv1 = nn.Conv2d(cin, cout, 3, stride=stride, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(cout)
        self.conv2 = nn.Conv2d(cout, cout, 3, padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(cout)
        self.shortcut = (nn.Sequential(nn.Conv2d(cin, cout, 1, stride=stride, bias=False), nn.BatchNorm2d(cout))
                         if stride != 1 or cin != cout else nn.Identity())

    def forward(self, x):
        return F.relu(self.bn2(self.conv2(F.relu(self.bn1(self.conv1(x))))) + self.shortcut(x))


class ResNet18(nn.Module):
    def __init__(self):
        super().__init__()
        self.stem = nn.Sequential(nn.Conv2d(3, 64, 3, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU())
        self.blocks = nn.ModuleList()
        channels = 64
        for stage, width in enumerate((64, 128, 256, 512)):
            for i in range(2):
                stride = 2 if stage > 0 and i == 0 else 1
                self.blocks.append(Block(channels, width, stride))
                channels = width
        self.fc = nn.Linear(512, 10)
        for module in self.modules():
            if isinstance(module, nn.Conv2d):
                nn.init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(module, nn.BatchNorm2d):
                nn.init.ones_(module.weight)
                nn.init.zeros_(module.bias)

    def forward(self, x):
        x = self.stem(x)
        for block in self.blocks:
            x = block(x)
        return self.fc(x.mean((2, 3)))


def predict(model, data, mean, std):
    model.eval()
    values = []
    with torch.no_grad():
        for x in data.split(128):
            x = ((x.float()/255 - mean) / std).contiguous(memory_format=torch.channels_last)
            with torch.autocast(device_type='cuda', dtype=torch.bfloat16, enabled=amp):
                values.append(model(x).float().cpu())
    return torch.cat(values)


def metrics(logits, labels):
    probs = logits.softmax(1).numpy()
    confidence = probs.max(1)
    correct = (probs.argmax(1) == labels).astype(float)
    bins = np.minimum((confidence * 15).astype(int), 14)
    def calc(idx):
        c, a, b = confidence[idx], correct[idx], bins[idx]
        ece = sum(abs(c[b == k].sum() - a[b == k].sum()) for k in range(15)) / len(idx)
        return a.mean(), ece
    point = calc(np.arange(len(labels)))
    rng = np.random.default_rng(16109)
    groups = [np.flatnonzero(labels == k) for k in range(10)]
    bootstrap = np.array([calc(np.concatenate([rng.choice(g, size=len(g), replace=True) for g in groups]))
                          for _ in range(500)])
    return {'accuracy': point[0], 'ece_15_bins': point[1],
            'accuracy_ci95_stratified': np.quantile(bootstrap[:, 0], [.025, .975]).tolist(),
            'ece_ci95_stratified': np.quantile(bootstrap[:, 1], [.025, .975]).tolist()}


def gallery(model, train_x, train_y, train_ids, mean, std, seed, best_step):
    positions = np.linspace(0, len(train_x)-1, 16, dtype=int)
    x0 = train_x[positions].float() / 255
    result = {'source': 'uoft-cs/cifar10 train', 'revision': revision, 'seed': seed,
              'selection': 'mínima pérdida de validación', 'best_step': best_step,
              'class_names': ['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck'],
              'transformations': {}}
    stacks = {'original': (), 'geometria': ('geometria',), 'color': ('color',),
              'borrado': ('borrado',), 'geometria_color': ('geometria', 'color'),
              'geometria_borrado': ('geometria', 'borrado'),
              'color_borrado': ('color', 'borrado'),
              'combinacion': ('geometria', 'color', 'borrado')}
    for mode, operations in stacks.items():
        result['transformations'][mode] = []
        for level in range(4):
            x = x0.clone()
            if 'geometria' in operations and level:
                padded = F.pad(x, (4, 4, 4, 4), mode='reflect')
                x = padded[:, :, 4-level:36-level, 4+level:36+level]
                if level >= 2:
                    x = x.flip(-1)
            if 'color' in operations:
                x = (x * (1 + .2 * level)).clamp(0, 1)
            if 'borrado' in operations:
                side = 4 * level
                x[:, :, 10:10+side, 10:10+side] = 0
            q = (x * 255).round().clamp(0, 255).to(torch.uint8)
            logits = predict(model, q, mean, std)
            probs = logits.softmax(1).numpy()
            items = []
            for i in range(16):
                image = q[i].permute(1, 2, 0).cpu().numpy()
                buffer = io.BytesIO()
                Image.fromarray(image, mode='RGB').save(buffer, format='PNG')
                items.append({'source_index': int(train_ids[positions[i]]), 'label': int(train_y[positions[i]]),
                              'png_base64': base64.b64encode(buffer.getvalue()).decode('ascii'),
                              'probabilities': probs[i].tolist(), 'prediction': int(probs[i].argmax())})
            result['transformations'][mode].append({'level': level, 'images': items})
    path = Path(os.environ.get('ORYON_GALLERY_OUTPUT', 'm16-l10-gallery.json'))
    path.write_text(json.dumps(result, ensure_ascii=False), encoding='utf-8')
    torch.save({'state_dict': {k: v.detach().cpu() for k, v in model.state_dict().items()},
                'mean': mean.cpu(), 'std': std.cpu(), 'seed': seed, 'best_step': best_step},
               os.environ.get('ORYON_GALLERY_CHECKPOINT', 'm16-l10-gallery.pt'))


def main():
    property_tests()
    (train_x, train_y), (valid_x, valid_y), (test_x, test_y), train_ids, valid_ids, test_ids = datasets()
    mean, std = stats(train_x)
    output = {'protocol': {'short': short, 'steps': steps, 'batch_size': batch_size, 'seeds': seeds,
        'train_per_class': train_n, 'valid_per_class': valid_n, 'test_per_class': test_n,
        'test_slice_per_class': [40, 60] if short else [0, 1000],
        'test_note': 'exploratorio; el conjunto completo comparte imágenes con lecciones anteriores',
        'selection': 'mínima pérdida de validación', 'ece': '15 intervalos iguales; bootstrap estratificado por clase, 500 réplicas, condicionado al modelo',
        'rng': 'inicialización, lotes, geometría, brillo, borrado y mezclas independientes',
        'mean': mean.flatten().cpu().tolist(), 'std': std.flatten().cpu().tolist()}, 'runs': []}
    outpath = Path(os.environ.get('ORYON_AUGMENT_OUTPUT', 'm16-l10-ablation.json'))
    for policy in policies:
        for seed in seeds:
            torch.manual_seed(seed)
            torch.cuda.manual_seed_all(seed)
            model = ResNet18().to(device=device, memory_format=torch.channels_last)
            opt = torch.optim.SGD(model.parameters(), lr=.1, momentum=.9, weight_decay=.0001)
            scheduler = torch.optim.lr_scheduler.MultiStepLR(opt, milestones=[steps//2, 3*steps//4], gamma=.1)
            generators = [torch.Generator(device=device).manual_seed(seed*100 + k) for k in range(1, 6)]
            batches, spatial, color, erasing, mixing = generators
            beta = np.random.default_rng(seed*100+6)
            best_loss = float('inf')
            best_state = None
            history = []
            checkpoints = set([1, steps//4, steps//2, 3*steps//4, steps])
            failure = None
            for step in range(1, steps+1):
                model.train()
                idx = torch.randint(len(train_x), (batch_size,), generator=batches, device=device)
                x, y = train_x[idx].float()/255, train_y[idx]
                if policy != 'ninguna':
                    x = geometry(x, spatial)
                if policy == 'color':
                    x = brightness(x, .6 + .8*torch.rand(len(x), generator=color, device=device))
                if policy == 'borrado':
                    x = random_erase(x, erasing)
                perm, lam = None, None
                if policy == 'mixup':
                    perm = torch.randperm(len(x), generator=mixing, device=device)
                    lam = float(beta.beta(.2, .2))
                    x = lam*x + (1-lam)*x[perm]
                elif policy == 'cutmix':
                    x, perm, lam = random_cutmix(x, mixing, beta)
                x = ((x - mean) / std).contiguous(memory_format=torch.channels_last)
                opt.zero_grad(set_to_none=True)
                with torch.autocast(device_type='cuda', dtype=torch.bfloat16, enabled=amp):
                    logits = model(x)
                    loss1 = F.cross_entropy(logits, y, reduction='none')
                    loss = loss1.mean() if perm is None else (lam*loss1 + (1-lam)*F.cross_entropy(logits, y[perm], reduction='none')).mean()
                if not bool(torch.isfinite(loss)):
                    failure = {'step': step, 'reason': 'pérdida no finita'}
                    break
                loss.backward()
                if not all(p.grad is None or bool(torch.isfinite(p.grad).all()) for p in model.parameters()):
                    failure = {'step': step, 'reason': 'gradiente no finito'}
                    break
                opt.step()
                scheduler.step()
                if step in checkpoints:
                    vl = predict(model, valid_x, mean, std)
                    vloss = float(F.cross_entropy(vl, valid_y.cpu()))
                    if not np.isfinite(vloss):
                        failure = {'step': step, 'reason': 'validación no finita'}
                        break
                    row = {'step': step, 'train_batch_loss': float(loss), 'valid_loss': vloss,
                           'valid_accuracy': float((vl.argmax(1) == valid_y.cpu()).float().mean())}
                    history.append(row)
                    if vloss < best_loss:
                        best_loss, best_step = vloss, step
                        best_state = copy.deepcopy({k: v.detach().cpu() for k, v in model.state_dict().items()})
            run = {'policy': policy, 'seed': seed, 'history': history, 'failure': failure}
            if best_state is not None:
                model.load_state_dict(best_state)
                logits = predict(model, test_x, mean, std)
                run.update({'best_step': best_step, 'best_valid_loss': best_loss,
                            'test': metrics(logits, test_y.cpu().numpy()) if torch.isfinite(logits).all() else None})
                if policy == 'geometria' and seed == seeds[0]:
                    gallery(model, train_x, train_y, train_ids, mean, std, seed, best_step)
            output['runs'].append(run)
            outpath.write_text(json.dumps(output, ensure_ascii=False, indent=2), encoding='utf-8')
            print(json.dumps({'policy': policy, 'seed': seed, 'best_step': run.get('best_step'),
                              'test': run.get('test'), 'failure': failure}, ensure_ascii=False), flush=True)
            del model, opt, scheduler, best_state
            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

NumericSymmetry of mixtures
If λ follows Beta(0.2, 0.2), what is its expectation?
NumericThe larger weight
For λ from Beta(0.2, 0.2), use the cell to estimate the expectation of max(λ, 1−λ). Enter an approximation to two decimal places.
NumericA patch at the boundary
A 32×32 image receives a requested rectangle from x=−8 to x=8 and y=8 to y=24, with upper endpoints excluded. What weight belongs to the base image after clipping to the boundary?
ProofThe loss of two labels
Prove: For a probability vector p with positive components, one-hot labels y_i, y_j and λ between 0 and 1, prove equivalence of mixed-target loss and mixed losses.
0
The same prediction p is used in both terms.

Step 1 of 3. Which expression defines cross-entropy with the mixed target?

QuizWhich transform preserves the label?
What is the best-justified choice when building an augmentation policy?
QuizStrong augmentation initially worsens results
An intense policy has worse validation after a few steps. Which experiment best distinguishes slower convergence from a harmful policy?
CodeCutMix with boundary-corrected area
Implement cutmix(x, y, alpha) for a B×C×H×W image batch and length-B integer labels on the same device. Sample λ with torch.distributions.Beta(alpha,alpha).sample(), choose a permutation with torch.randperm and center x and y coordinates with two torch.randint calls, in that order. The shared rectangle has integer sides int(W·sqrt(1−λ)) and int(H·sqrt(1−λ)); for odd sides put the extra pixel to the right or bottom. Clip endpoints to the image, copy that patch from permuted examples without modifying x and return (mixture, y_a, y_b, base_weight), where the scalar weight is 1 minus effective area divided by H·W. Reject nonpositive alpha. Respect x's device.
import torch

def cutmix(x, y, alpha):
  pass
Shift+Enter to run
Key idea

An augmentation encodes a hypothesis about which changes should preserve or modify the label. Check transform, target and evaluation protocol; a particular improvement or confidence belongs to an experiment, not a universal rule.

References