Module contents
Lesson 11 of 25Advanced 120 min

Guided project: ResNet to 94% on CIFAR-10 in minutes on your GPU

Examine fast CIFAR training through controlled ablations, patch whitening, flip alternation, test-time augmentation and paired-seed comparisons.

After this lesson you can

  • Separate architecture, preparation, compilation, training and evaluation costs.
  • Derive regularized PCA and ZCA patch whitening and its limitations.
  • Explain flip alternation, weight averaging and test-time augmentation.
  • Design paired comparisons and calculate power under explicit assumptions.
  • Evaluate a short CIFAR training ablation without claiming full convergence.

Before you start

A fast recipe is a measuring instrument

Training a network faster allows a comparison to be repeated with more seeds and implementation errors explored before committing a large budget. But a fast stopwatch does not automatically turn a difference into evidence: define data, architecture, numerical precision, compilation, evaluation and what the timing includes.

This project starts from a ResNet for CIFAR. The airbench94 reference by Jordan makes another choice: its main architecture is a compact VGG-style CNN, not ResNet-9. The work reports 94.01% mean CIFAR-10 accuracy on an A100: 3.29 seconds for the compiled version and 3.83 for the uncompiled version under its protocol. Initial compilation costs extra. This is a published reference figure, not a promise for your RTX 4060, another split or a modified implementation.

The paper’s clock spans the first access to training data through test predictions; prior warmup with dummy data is allowed. To compare recipes also measure data preparation and compilation separately. A speedup appearing only when a cost is omitted from one row does not answer the same question.

InteractiveA ladder of choices

Real 100-step trial with five seeds per configuration. The horizontal axis shows the median training-time ratios against ResNet-18 with the same seed; it excludes preparation and inference. The vertical axis shows validation accuracy; bars show minima and maxima, not confidence intervals.

0 %25 %50 %75 %100 %Configuration RConfiguration AConfiguration BConfiguration CConfiguration DSelected: C01×Relative training time
  • ResNet-18 (R)
  • Compact CNN (A to D)

Only the selected point is labeled to avoid overlap. A: no PCA, random flip. B: no PCA, alternating flip. C: PCA, random. D: PCA, alternating. Architecture comparisons also change the recipe and batch; do not attribute their difference to a single cause. The measured loop includes augmentation, gradient checks and EMA, but excludes PCA filter calculation and inference. Times under shared load are indicative. The 100-step models have not converged.

Architecture
Evaluated weights
Evaluation views
Selected configurationC
Mean validation accuracy54.7 %
Minimum to maximum across seeds50.5 % to 57.0 %
Median training-time ratio0.46× ResNet-18
Compare configurations with their seeds and budgets; interactions require experiments that measure them.

Baseline and compute budget

A fast training recipe starts with a verifiable baseline: for example, the 32×32-adapted ResNet-18 built in ResNet. Keep a separate validation split and use the same example order and seeds to compare variants. Airbench’s compact network also changes architecture: fewer operations or different precision are part of the comparison, not an improvement automatically attributable to one optimization.

In the paper’s implementation, the cumulative step from baseline to whitening reduces epochs to reach the mean target from 45 to 21; partial identity initialization, different bias rates, Lookahead and multicrop evaluation are then added. These are sequential steps in the published experiment: subtracting two rows does not necessarily measure a technique’s isolated effect when it interacts with earlier ones. Use a factorial design or configuration pairs differing in one decision to estimate a particular interaction.

GPU-resident data, batch operations and channels_last can reduce certain overheads, while mixed precision and compilation change kernels used. Their effect depends on hardware and batch shape. Synchronize the GPU before and after the timed interval, separate preparation, warmup, compilation, training and evaluation, and state included stages. Times under shared load vary; interpret ratios and trends cautiously, as in CNN performance.

Whitening patches without hiding assumptions

Patch whitening uses training statistics to construct initial filters. Extract RGB patches pi∈Rdp_i\in\mathbb R^d, where d=Ck2d=Ck^2, calculate their mean μ\mu and centered covariance Σ=n−1∑i(pi−μ)(pi−μ)T\Sigma=n^{-1}\sum_i(p_i-\mu)(p_i-\mu)^T. If Σ=Udiag⁡(s1,…,sd)UT\Sigma=U\operatorname{diag}(s_1,\ldots,s_d)U^T and ε>0\varepsilon>0, define

WPCA=diag⁡ ⁣((si+ε)−1/2)UT,WZCA=UWPCA.W_{\mathrm{PCA}}=\operatorname{diag}\!\left((s_i+\varepsilon)^{-1/2}\right)U^T,\qquad W_{\mathrm{ZCA}}=U W_{\mathrm{PCA}}.

With centered patches, transformed covariance in PCA coordinates is diag⁡(si/(si+ε))\operatorname{diag}(s_i/(s_i+\varepsilon)). Thus with positive regularization it is not exactly identity. ZCA rotates the result back toward original coordinates. A small eigenvalue would greatly amplify noise without regularization; ε\varepsilon limits amplification. Keeping only some components loses information, and full-dimensional reconstruction is not invertible unless all necessary components are retained.

The conditioning intuition appears in least-squares linear regression: its Hessian with respect to coefficients is proportional to the feature second-moment matrix. If patches are centered and si>0s_i>0, the ratio between largest and smallest regularized eigenvalues changes from smax⁡/smin⁡s_{\max}/s_{\min} to

smax⁡/(smax⁡+ε)smin⁡/(smin⁡+ε).\frac{s_{\max}/(s_{\max}+\varepsilon)}{s_{\min}/(s_{\min}+\varepsilon)}.

It is less than or equal to the original ratio for ε>0\varepsilon>0. This calculation explains a possible local advantage in a linear problem; it does not prove the entire CNN Hessian becomes well conditioned or that a particular initialization always improves accuracy. If smin⁡=0s_{\min}=0, both matrices retain a direction with no variance and that ratio is undefined: adding ε\varepsilon avoids division by zero when constructing the filter but does not invent information in that direction.

InteractivePatch spectrum and filters

A centered covariance of 15376 2×2 RGB patches, extracted from 16 real CIFAR-10 training images. PCA expresses the output in the eigenvector basis; ZCA returns to the original RGB coordinates. The control selects a transformation coordinate, not a class.

Input covariance spectrum
Component 1: 0.60680647703074521Component 2: 0.0505308468270348962Component 3: 0.029657082060416563Component 4: 0.0179267232260515444Component 5: 0.0113878849134968335Component 6: 0.0033085906939879926Component 7: 0.00110885934113234987Component 8: 0.00086642854227052218Component 9: 0.000242849696898295159Component 10: 0.0001979019950239349710Component 11: 0.0000846003563363347711Component 12: 0.00002068521713157271412

Height represents the square root of the eigenvalue to make small directions visible. Gray bars are discarded. Condition is calculated only in the retained subspace; discarding directions makes the full transformation lose rank.

Selected filter in each RGB channel
Red
Weight 0.35874Weight 0.36066Weight 0.35713Weight 0.35490
Green
Weight 0.37098Weight 0.37334Weight 0.37196Weight 0.37020
Blue
Weight 0.38013Weight 0.38212Weight 0.38173Weight 0.37994
  • Negative weight
  • Positive weight
Input image
CIFAR-10 training image, row 22234
Coordinate output

Each patch coordinate mean is subtracted before applying the filter. The 31×31 map uses its own color scale: its absolute maximum is 2.413. Filter coefficients use another separate color scale. The sign of an eigenvector is arbitrary; here the signs stored in the data are retained.

For eigenvalue λ, the variance of each retained direction is λ/(λ+ε), not necessarily one; its mean across the 12 directions is 58.6 %. PCA returns only retained coordinates. ZCA projects back to 12 coordinates; with truncation they remain correlated and the covariance rank is at most 12.

Source: CIFAR-10, training split, revision 0b27149. This is a calculation with 16 images, not the full dataset spectrum or a classifier accuracy measurement. The airbench implementation uses its own statistics and PCA filters, not this small estimate.

Transformation
12
0
Displayed coordinatecomponent 1
Condition before, retained subspace29335.3
Condition after, retained subspace49.26
Discarded dimensions0
Explore regularization and distinguish the PCA basis change from ZCA reconstruction.

The figure uses 16 real training images and their centered 2×2 patches. This cell reproduces extraction, covariance, eigenvectors and the displayed image; it calculates statistics on those 16 examples, so the spectrum is not intended as an accurate representation of all CIFAR-10.

[ ]CIFAR patches and centered filtersLocal GPU
"""Covarianza centrada de 16 imágenes de CIFAR-10 y blanqueado de parches.

Ejecuta en Python local con numpy, pillow, pyarrow y huggingface_hub. El archivo
de salida contiene estadísticas y una imagen, no depende de esta carpeta.
"""
import base64
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

revision = '0b27149'
indices = [22234, 28381, 40466, 43131, 37392, 7584, 11326, 44297,
           26470, 23097, 14184, 2020, 23409, 34534, 26055, 11114]
path = hf_hub_download(repo_id='uoft-cs/cifar10', repo_type='dataset', revision=revision,
                       filename='plain_text/train-00000-of-00001.parquet')
found = {}
offset = 0
for batch in pq.ParquetFile(path).iter_batches(batch_size=128, columns=['img', 'label']):
    for pos in range(batch.num_rows):
        index = offset + pos
        if index in indices:
            raw = batch.column(0)[pos].as_py()['bytes']
            with Image.open(io.BytesIO(raw)) as im:
                pixels = np.asarray(im.convert('RGB'), dtype=np.uint8).copy()
            if pixels.shape != (32, 32, 3):
                raise ValueError('Forma inesperada')
            found[index] = (pixels, int(batch.column(1)[pos].as_py()))
    offset += batch.num_rows
    if len(found) == len(indices):
        break
if len(found) != len(indices):
    raise ValueError('No se han encontrado todas las imágenes')

images = np.stack([found[i][0] for i in indices]).astype(np.float64) / 255
# np mueve las dos dimensiones de ventana al final: RGB, fila y columna.
patches = np.lib.stride_tricks.sliding_window_view(images, (2, 2), axis=(1, 2)).reshape(-1, 12)
mean = patches.mean(axis=0)
centered = patches - mean
covariance = centered.T @ centered / len(centered)
eigenvalues, eigenvectors = np.linalg.eigh(covariance)
order = np.argsort(eigenvalues)[::-1]
eigenvalues, eigenvectors = eigenvalues[order], eigenvectors[:, order]
if eigenvalues.min() < -1e-12:
    raise ValueError('La covarianza no es semidefinida positiva')
eps = .001
scale = 1 / np.sqrt(eigenvalues + eps)
pca = scale[:, None] * eigenvectors.T
zca = eigenvectors @ pca
predicted = eigenvalues / (eigenvalues + eps)
np.testing.assert_allclose(pca @ covariance @ pca.T, np.diag(predicted), atol=1e-10)
np.testing.assert_allclose(zca @ covariance @ zca.T, eigenvectors @ np.diag(predicted) @ eigenvectors.T, atol=1e-10)
buffer = io.BytesIO()
Image.fromarray(found[indices[0]][0]).save(buffer, format='PNG')
result = {'dataset':'uoft-cs/cifar10', 'revision':revision, 'split':'train',
          'indices':indices, 'labels':[found[i][1] for i in indices], 'num_patches':len(patches),
          'patch_size':2, 'normalization':'RGB en [0,1], parches centrados por coordenada',
          'coordinate_order':'canal RGB, fila del parche, columna del parche',
          'mean':mean.tolist(), 'covariance':covariance.tolist(),
          'eigenvalues':eigenvalues.tolist(), 'eigenvectors':eigenvectors.tolist(),
          'sample_index':indices[0], 'sample_png_base64':base64.b64encode(buffer.getvalue()).decode('ascii'),
          'sample_rgb':found[indices[0]][0].tolist()}
target = Path(os.environ.get('ORYON_WHITEN_OUTPUT', 'm16-l11-whitening.json'))
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(json.dumps(result, ensure_ascii=False, separators=(',', ':')), encoding='utf-8')
print('Imágenes:', len(indices), 'parches 2×2:', len(patches), 'dimensión:', len(mean))
print('Autovalores de la covarianza:', np.array2string(eigenvalues, precision=8))
print('Error máximo PCA:', np.max(np.abs(pca @ covariance @ pca.T - np.diag(predicted))))
print('Error máximo ZCA:', np.max(np.abs(zca @ covariance @ zca.T - eigenvectors @ np.diag(predicted) @ eigenvectors.T)))
print('Resultado:', target)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The legacy airbench implementation builds a second moment of 2×2 patches from normalized inputs without explicitly subtracting patch mean. That matches centered covariance only if the mean is zero. It uses 12 PCA directions and their 12 negatives as frozen filters, not centered ZCA. The 24 stacked channels cannot have rank-24 identity covariance: negatives depend linearly on positives. Their biases are initially trained. This lesson’s exercise implements the centered regularized variant for understanding; it is not presented as an exact copy of published code.

The next cell checks the derivation on a small explicitly constructed set. Its numbers are properties of this example, not CIFAR statistics.

[ ]Covariance after whiteningBrowser
import numpy as np

x = np.array([[-2., -1.], [-1., 1.], [1., -1.], [2., 1.]])
x = x - x.mean(axis=0)
cov = x.T @ x / len(x)
values, vectors = np.linalg.eigh(cov)
eps = .1
w = np.diag(1 / np.sqrt(values + eps)) @ vectors.T
print('autovalores originales:', values)
print('covarianza PCA regularizada:', w @ cov @ w.T)
print('diagonal esperada:', values / (values + eps))

Calculate mean and statistics using training only. Using test to fit filters introduces information from the evaluation set. In a large implementation, accumulate sums and products in batches to avoid materializing all patches at once; check dimensions and channel order before copying vectors into a convolution.

Optimizer, views and weights

The paper’s specific recipe combines SGD with Nesterov, an aggressive schedule and choices about gradient and bias scaling. Numerical learning-rate magnitude depends on whether loss is summed or averaged over the batch: do not copy a number without also carrying over that convention. Label smoothing, weight decay and BatchNorm statistics updates are part of the recipe. The reference’s Lookahead updates slow weights and copies them back into the network during training; an EMA used only for evaluation is a different operation and must be identified as such.

Flip alternation requires identifying each image across epochs. You can fix an initial orientation per image and alternate it at each epoch visit. If each image appears once per epoch, after two epochs each has been seen in both orientations. Sampling batches with replacement and alternating the batch does not guarantee this property. A symmetric reflection may match the original image, so two orientations do not necessarily imply two different images.

In the published experiment with per-epoch shuffling, the mean changes from 93.92% with random flipping to 94.01% with alternation; without that shuffling means are 93.40% and 93.48%. This comparison belongs to its protocol, not a guarantee for every domain. The flip must also preserve the task label, as discussed in augmentation.

Test-time augmentation, TTA, evaluates several views of one example and aggregates predictions. The paper uses six unequally weighted views: original and mirror weigh 0.25 each; four shifted and reflected views weigh 0.125 each. Averaging logits and averaging probabilities are different rules. If a model is exactly flip-invariant, the reflected view gives the same output and its average adds no information. TTA can generally improve or worsen a prediction and adds compute; measure it at evaluation time too.

To understand diminishing returns from correlated views, consider a scalar model in which mm estimates have variance σ2\sigma^2 and common correlation ρ\rho. Their mean has variance σ2[1+(m−1)ρ]/m\sigma^2[1+(m-1)\rho]/m, provided that correlation matrix is valid. At correlation one, averaging identical copies does not reduce variance; at zero correlation it falls as 1/m1/m. This is an error model, not a classification accuracy promise. The mean may also retain bias shared by every view.

InteractivePredictions from multiple views

Real predictions from a network trained in a short run. Adding views can change the prediction, but does not guarantee improvement or a monotonic increase in correct predictions.

Original image: airplane
True label: airplane
Each view: true-label probability
1. Original
34.2 %Predicts: ship
2. Mirror
36.5 %Predicts: ship (not included)
3. Bottom right
29.3 %Predicts: ship (not included)
4. Bottom right, then mirror
27.8 %Predicts: ship (not included)
5. Top left
41.0 %Predicts: airplane (not included)
6. Top left, then mirror
43.6 %Predicts: airplane (not included)
Correct predictions in this sample as views are added

Blue: mean logits. Orange: mean probabilities. The maximum is 16.

1 view7 / 7
2 views8 / 7
3 views8 / 8
4 views7 / 7
5 views8 / 8
6 views7 / 7
Aggregated distribution: softmax of mean logits
airplane *
34.2 %
automobile
1.2 %
bird
6.8 %
cat
1.6 %
deer
2.5 %
dog
2.0 %
frog
1.1 %
horse
1.1 %
ship
46.0 %
truck
3.5 %

* True label. With 1 view, the probability of that label is 34.2 % when averaging logits and 34.2 % when averaging probabilities. Among the 16 images: 7 and 7 correct predictions respectively. These are exploratory results for this sample, not a reliable estimate of overall performance.

Views are prefixes in the indicated order, equally weighted. This differs from the weighted rule used by the lab for its six views. Directions name the one-pixel content shift with reflected padding; for mirrored views, the flip is applied after shifting. Source: CIFAR-10 test, revision 0b27149, seed 16111, 100 steps; shown are 16 images selected at evenly spaced positions among the 200 exported, without selection by outcome.

1
Averaging method
Aggregated predictionship
True-label probability34.2 %
Correct predictions on these images7 / 16
Aggregate measured views and check when averaging changes the prediction.

Measure an idea without turning test into training

The lab compares configurations with paired seeds. For pairs with the same architecture and batch size, split and batch order are retained, and shared parameters start from the same initialization except the deliberately modified filter. ResNet-18 and the compact CNN are different architectures and use different batch sizes in full mode, so sharing a seed does not mean sharing weights or batch sequence. Final evaluation on a test already consulted to design or select alternatives is exploratory. Retain an independent set if a final estimate is needed after decisions. Repeating seeds does not replace additional test examples, and resampling examples of a fixed model is not equivalent to retraining.

Power calculation requires specifying the design. With a 0.1-point improvement target, paired-difference standard deviation of 0.15 points, two-sided t-test at 5% and normally distributed differences, the power calculation requires 20 pairs to exceed 80%. Individual standard deviations of each method do not determine that of their differences without their correlation. The number is planning under assumptions, not a guarantee that a particular run detects the effect.

[ ]Power of a paired comparisonLocal GPU
from scipy.stats import nct, t
from math import sqrt

delta, sigma, alpha = 0.1, 0.15, 0.05
def power(n):
    critical = t.ppf(1-alpha/2, n-1)
    noncentrality = sqrt(n) * delta / sigma
    return nct.sf(critical, n-1, noncentrality) + nct.cdf(-critical, n-1, noncentrality)

n = next(n for n in range(2, 1000) if power(n) >= .8)
print('parejas necesarias:', n, 'potencia:', power(n))
print('potencia con una pareja menos:', power(n-1))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Local lab

The experiment provides both a full recipe to run and a short verification. Verification uses fewer examples and steps, records actual results and does not certify reaching the 94% target. Full training and any hyperparameter search are for you to run. To test an idea, retain the baseline and separately record each seed, split, budget and TTA cost.

The short test compares ResNet-18 with four PCA and flip combinations in the compact CNN, with five seeds and 100 steps per run. The no-PCA control retains partial identity initialization in three filters and random initialization in the rest; it is not a purely random-filter control. Weight averaging is an evaluation EMA, not the paper’s Lookahead. It includes the final partial batch so every complete epoch visits all examples; this is another difference from legacy code. Loop times include augmentation, gradient checks and EMA, but exclude preparation, filter calculation and inference. Whitening statistics use training only.

In this short check, validation accuracy of the CNN with PCA and alternating flip is 54.5%, 55%, 49.5%, 56.5% and 54% for the five seeds. It does not represent full training or prove one technique wins by itself. The short test subset is used for figure views; it is exploratory.

[ ]CIFAR: fast-training ablationLocal GPU
"""Ablación CIFAR-10 inspirada en airbench94 legacy, no reproducción del récord.

Requiere torch, numpy, pillow, pyarrow y huggingface_hub, y CUDA.
ORYON_VERIFY_SHORT=1 usa 1000/200/200 imágenes y 100 pasos por corrida.
El modo normal usa 45000/5000 de train/valid y todo el test, 9.9 épocas y
lote 1024. El 94 % publicado pertenece a otra partición y a otra receta.

Cambios frente a legacy/airbench94.py: validación separada del entrenamiento;
estadísticas calculadas solo sobre train y muestra de 5000 imágenes estratificada
por clase; AMP bfloat16 si está disponible;
EMA convencional de evaluación en lugar de Lookahead; se incluye el lote final
incompleto; selección de variantes
en validación; PCA opcional o filtros con identidad parcial y resto aleatorio,
congelados en ambos casos, para aislar su inicialización. No se usa torch.compile.
Se mide un tiempo de entrenamiento
sin preparación y se mide la inferencia por separado, con sincronización CUDA.
"""
import base64
import io
import json
import math
import os
import time
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

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')
amp = torch.cuda.is_bf16_supported()
short = os.environ.get('ORYON_VERIFY_SHORT') == '1'
train_n, valid_n, test_n = (100, 20, 20) if short else (4500, 500, 1000)
batch_size = 64 if short else 1024
seed_count = int(os.environ.get('ORYON_STUDY_SEEDS', '5'))
if seed_count < 1 or seed_count > 1000:
    raise ValueError('ORYON_STUDY_SEEDS debe estar entre 1 y 1000')
seeds = [16111 + i for i in range(seed_count)]
revision = '0b27149'
outpath = Path(os.environ.get('ORYON_FAST_CIFAR_OUTPUT', 'm16-l11-fast-cifar.json'))


def clock():
    torch.cuda.synchronize()
    return time.perf_counter()


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_selected(path, labels, indices):
    positions = {int(idx): i for i, idx in enumerate(indices)}
    images = np.empty((len(indices), 3, 32, 32), dtype=np.uint8)
    seen = np.zeros(len(indices), dtype=bool)
    offset = 0
    for batch in pq.ParquetFile(path).iter_batches(batch_size=256, columns=['img']):
        for local in range(batch.num_rows):
            pos = positions.get(offset + local)
            if pos is not None:
                with Image.open(io.BytesIO(batch.column(0)[local].as_py()['bytes'])) as im:
                    images[pos] = np.asarray(im.convert('RGB'), dtype=np.uint8).transpose(2, 0, 1)
                seen[pos] = 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[indices].copy()).to(device)


def dataset():
    path, 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])
    path_test, labels_test, tg = groups('test', 16074)
    start = 60 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[:60] for x in tg]))
    return (read_selected(path, labels, train_ids), read_selected(path, labels, valid_ids),
            read_selected(path_test, labels_test, test_ids), train_ids, valid_ids, test_ids)


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


def patch_moments(images, mean, std):
    # Hasta 5000 imágenes de ajuste, muestreadas equitativamente por clase.
    s = torch.zeros(12, device=device, dtype=torch.float64)
    gram = torch.zeros((12, 12), device=device, dtype=torch.float64)
    count = 0
    # Las imágenes vienen agrupadas por clase; los primeros 5000 no serían representativos.
    subset = torch.linspace(0, len(images)-1, min(5000, len(images)), device=device).long()
    for selection in subset.split(64):
        part = images[selection]
        x = (part.float()/255 - mean) / std
        patches = F.unfold(x, kernel_size=2).transpose(1, 2).reshape(-1, 12).double()
        s += patches.sum(0)
        gram += patches.T @ patches
        count += len(patches)
    mu = s / count
    moment = gram / count
    covariance = moment - mu[:, None]*mu[None, :]
    values, vectors = torch.linalg.eigh(moment)
    vals_c, vecs_c = torch.linalg.eigh(covariance)
    values, vectors = values.flip(0), vectors.flip(1)
    vals_c, vecs_c = vals_c.flip(0), vecs_c.flip(1)
    assert bool((values >= -1e-8).all() and (vals_c >= -1e-8).all())
    return {'patch_count': count, 'mean': mu, 'moment': moment, 'covariance': covariance,
            'eigenvalues': values.clamp_min(0), 'eigenvectors': vectors,
            'centered_eigenvalues': vals_c.clamp_min(0), 'centered_eigenvectors': vecs_c}


def pca_filters(moments, eps=5e-4):
    eigenvalues, vectors = moments['eigenvalues'], moments['eigenvectors']
    pca = (vectors / (eigenvalues + eps).sqrt()[None, :]).T.reshape(12, 3, 2, 2)
    return torch.cat((pca, -pca), dim=0).float()


def crop_batch(x, generator):
    padded = F.pad(x, (2, 2, 2, 2), mode='reflect')
    n = len(x)
    dy = torch.randint(0, 5, (n,), generator=generator, device=device)
    dx = torch.randint(0, 5, (n,), generator=generator, device=device)
    rows = dy[:, None] + torch.arange(32, device=device)[None, :]
    cols = dx[:, None] + torch.arange(32, device=device)[None, :]
    return padded[torch.arange(n, device=device)[:, None, None, None],
                  torch.arange(3, device=device)[None, :, None, None],
                  rows[:, None, :, None], cols[:, None, None, :]]


class FastBN(nn.BatchNorm2d):
    def __init__(self, channels):
        super().__init__(channels, eps=1e-12, momentum=.4)
        self.weight.requires_grad = False


class FastConv(nn.Conv2d):
    def __init__(self, cin, cout, kernel_size=3, padding='same', bias=False):
        super().__init__(cin, cout, kernel_size, padding=padding, bias=bias)
        with torch.no_grad():
            if self.bias is not None:
                self.bias.zero_()
            nn.init.dirac_(self.weight[:cin])


class ConvGroup(nn.Module):
    def __init__(self, cin, cout):
        super().__init__()
        self.conv1, self.pool, self.norm1 = FastConv(cin, cout), nn.MaxPool2d(2), FastBN(cout)
        self.conv2, self.norm2, self.activ = FastConv(cout, cout), FastBN(cout), nn.GELU()

    def forward(self, x):
        x = self.activ(self.norm1(self.pool(self.conv1(x))))
        return self.activ(self.norm2(self.conv2(x)))


class FastNet(nn.Module):
    """Red convolucional tipo VGG, no residual, correspondiente a airbench94."""
    def __init__(self, filters):
        super().__init__()
        self.whiten = FastConv(3, 24, 2, padding=0, bias=True)
        if filters is not None:
            with torch.no_grad():
                self.whiten.weight.copy_(filters)
        self.whiten.weight.requires_grad = False
        self.activ = nn.GELU()
        self.blocks = nn.Sequential(ConvGroup(24, 64), ConvGroup(64, 256), ConvGroup(256, 256))
        self.pool = nn.MaxPool2d(3)
        self.fc = nn.Linear(256, 10, bias=False)

    def forward(self, x):
        x = self.blocks(self.activ(self.whiten(x)))
        return self.fc(self.pool(x).flatten(1)) / 9


class Block18(nn.Module):
    def __init__(self, cin, cout, stride):
        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 and not i else 1
                self.blocks.append(Block18(channels, width, stride))
                channels = width
        self.fc = nn.Linear(512, 10)
        for mod in self.modules():
            if isinstance(mod, nn.Conv2d):
                nn.init.kaiming_normal_(mod.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(mod, nn.BatchNorm2d):
                nn.init.ones_(mod.weight)
                nn.init.zeros_(mod.bias)

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


class EMA:
    """Media exponencial de evaluación; no modifica la trayectoria de entrenamiento."""
    def __init__(self, model):
        self.state = {k: v.detach().clone() for k, v in model.state_dict().items()}

    def update(self, model, decay=.95):
        with torch.no_grad():
            for key, value in model.state_dict().items():
                if value.is_floating_point():
                    self.state[key].lerp_(value.detach(), 1-decay)
                else:
                    self.state[key].copy_(value)


def six_views(model, images, mean, std):
    model.eval()
    outputs = []
    with torch.no_grad():
        for data in images.split(128):
            x = (data.float()/255 - mean) / std
            p = F.pad(x, (1, 1, 1, 1), mode='reflect')
            inputs = [x, x.flip(-1), p[:, :, :32, :32], p[:, :, :32, :32].flip(-1),
                      p[:, :, 2:34, 2:34], p[:, :, 2:34, 2:34].flip(-1)]
            with torch.autocast(device_type='cuda', dtype=torch.bfloat16, enabled=amp):
                logits = torch.stack([model(v.contiguous(memory_format=torch.channels_last)).float() for v in inputs], 1)
            outputs.append(logits.cpu())
    return torch.cat(outputs)


def summarize(logits, labels):
    weights = torch.tensor([.25, .25, .125, .125, .125, .125])
    all_logits = (logits * weights[None, :, None]).sum(1)
    mirror = logits[:, :2].mean(1)
    return {'one': float((logits[:, 0].argmax(1) == labels).float().mean()),
            'flip': float((mirror.argmax(1) == labels).float().mean()),
            'six_weighted': float((all_logits.argmax(1) == labels).float().mean()),
            'loss_one': float(F.cross_entropy(logits[:, 0], labels))}


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


def train_one(arch, white, flip_mode, seed, train_x, train_y, valid_x, valid_y, moments, mean, std):
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    filters = pca_filters(moments) if white else None
    model = (FastNet(filters) if arch == 'fast' else ResNet18()).to(device=device, memory_format=torch.channels_last)
    ema = EMA(model)
    bs = batch_size if arch == 'fast' else (64 if short else 128)
    per_epoch = math.ceil(len(train_x) / bs)
    steps = 100 if short else (math.ceil(per_epoch*9.9) if arch == 'fast' else 64000)
    if arch == 'fast':
        m = .85
        kilostep = 1024*(1 + 1/(1-m))
        lr = 11.5/kilostep
        wd = .0153*bs/kilostep
        norm_biases = [v for k, v in model.named_parameters() if 'norm' in k and v.requires_grad]
        others = [v for k, v in model.named_parameters() if 'norm' not in k and v.requires_grad]
        opt = torch.optim.SGD([{'params': norm_biases, 'lr': lr*64, 'weight_decay': wd/(lr*64)},
                               {'params': others, 'lr': lr, 'weight_decay': wd/lr}], momentum=m, nesterov=True)
        def schedule(step):
            warm = max(1, int(steps*.23))
            return .2 + .8*step/warm if step < warm else 1 - .93*(step-warm)/(steps-warm)
        scheduler = torch.optim.lr_scheduler.LambdaLR(opt, schedule)
    else:
        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)
    order_g = torch.Generator(device=device).manual_seed(seed*100+1)
    crop_g = torch.Generator(device=device).manual_seed(seed*100+2)
    flip_g = torch.Generator(device=device).manual_seed(seed*100+3)
    flip_init_g = torch.Generator(device=device).manual_seed(seed*100+4)
    initial_flip = torch.rand(len(train_x), generator=flip_init_g, device=device) < .5
    history, step, epoch, failure = [], 0, 0, None
    start = clock()
    while step < steps:
        order = torch.randperm(len(train_x), generator=order_g, device=device)
        for pos in range(0, len(order), bs):
            idx = order[pos:pos+bs]
            x = train_x[idx].float()/255
            flip = (initial_flip[idx] ^ bool(epoch % 2)) if flip_mode == 'alternante' else (torch.rand(len(idx), generator=flip_g, device=device) < .5)
            x = torch.where(flip[:, None, None, None], x.flip(-1), x)
            x = crop_batch(x, crop_g)
            x = ((x-mean)/std).contiguous(memory_format=torch.channels_last)
            if arch == 'fast':
                model.whiten.bias.requires_grad_(epoch < 3)
            model.train()
            opt.zero_grad(set_to_none=True)
            with torch.autocast(device_type='cuda', dtype=torch.bfloat16, enabled=amp):
                logits = model(x)
                # También el lote final se ajusta al lote de referencia de 1024.
                loss = (F.cross_entropy(logits, train_y[idx], label_smoothing=.2, reduction='sum') * (1024/len(idx))
                        if arch == 'fast' else F.cross_entropy(logits, train_y[idx]))
            if not bool(torch.isfinite(loss)):
                failure = {'step': step+1, '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+1, 'reason': 'gradiente no finito'}
                break
            opt.step()
            scheduler.step()
            step += 1
            if step % 5 == 0:
                ema.update(model)
            if step in {1, steps//4, steps//2, 3*steps//4, steps}:
                history.append({'step': step, 'batch_loss': float(loss.detach())/(1024 if arch == 'fast' else 1)})
            if step >= steps:
                break
        epoch += 1
        if failure:
            break
    train_seconds = clock()-start
    raw = {k: v.detach().clone() for k, v in model.state_dict().items()}
    pred_start = clock()
    raw_logits = single_view(model, valid_x, mean, std)
    one_seconds = clock()-pred_start
    pred_start = clock()
    raw_views = six_views(model, valid_x, mean, std)
    six_seconds = clock()-pred_start
    model.load_state_dict(ema.state)
    ema_views = six_views(model, valid_x, mean, std)
    model.load_state_dict(raw)
    if not bool(torch.isfinite(raw_views).all() and torch.isfinite(ema_views).all()):
        failure = {'step': step, 'reason': 'predicción no finita'}
        raw_metric = ema_metric = None
    else:
        assert torch.allclose(raw_logits, raw_views[:, 0], atol=1e-5, rtol=1e-5)
        raw_metric = summarize(raw_views, valid_y.cpu())
        ema_metric = summarize(ema_views, valid_y.cpu())
    result = {'arch': arch, 'whitening': white, 'flip': flip_mode, 'seed': seed,
              'steps': step, 'epochs_started': epoch, 'history': history, 'failure': failure,
              'valid_raw': raw_metric, 'valid_ema': ema_metric,
              'time': {'train_seconds': train_seconds, 'one_view_seconds': one_seconds, 'six_views_seconds': six_seconds}}
    return model, result


def save_figure_data(moments, train_x, train_y, train_ids, test_x, test_y, test_ids, views):
    sample = train_x[0].permute(1, 2, 0).cpu().numpy()
    buffer = io.BytesIO()
    Image.fromarray(sample, mode='RGB').save(buffer, format='PNG')
    result = {'source': 'uoft-cs/cifar10 revision '+revision, 'train_image_source_index': int(train_ids[0]),
              'train_image_label': int(train_y[0]), 'train_image_png': base64.b64encode(buffer.getvalue()).decode('ascii'),
              'patch_count': moments['patch_count'], 'sample_images': min(5000, len(train_x)),
              'pca_eigenvalues': moments['eigenvalues'].cpu().tolist(), 'pca_eigenvectors': moments['eigenvectors'].cpu().tolist(),
              'centered_mean': moments['mean'].cpu().tolist(),
              'centered_eigenvalues': moments['centered_eigenvalues'].cpu().tolist(),
              'centered_eigenvectors': moments['centered_eigenvectors'].cpu().tolist(),
              'tta': {'seed': seeds[0], 'white': True, 'flip': 'alternante',
                      'view_order': ['original', 'espejo', 'abajo_derecha', 'espejo_abajo_derecha', 'arriba_izquierda', 'espejo_arriba_izquierda'],
                      'weights': [.25, .25, .125, .125, .125, .125], 'items': []}}
    for i in range(len(test_ids)):
        image = test_x[i].permute(1, 2, 0).cpu().numpy()
        buf = io.BytesIO()
        Image.fromarray(image, mode='RGB').save(buf, format='PNG')
        result['tta']['items'].append({'source_index': int(test_ids[i]), 'label': int(test_y[i]),
                                       'png_base64': base64.b64encode(buf.getvalue()).decode('ascii'),
                                       'logits': views[i].tolist()})
    path = Path(os.environ.get('ORYON_FAST_FIGURES_OUTPUT', 'm16-l11-figures.json'))
    path.write_text(json.dumps(result, ensure_ascii=False), encoding='utf-8')


def warmup(train_size, valid_size):
    """Calienta kernels con datos ficticios; su coste no entra en los tiempos."""
    for arch in ('resnet18', 'fast'):
        model = (FastNet(None) if arch == 'fast' else ResNet18()).to(device=device, memory_format=torch.channels_last)
        n = batch_size if arch == 'fast' else (64 if short else 128)
        x = torch.zeros((n, 3, 32, 32), device=device).contiguous(memory_format=torch.channels_last)
        y = torch.zeros(n, dtype=torch.long, device=device)
        for _ in range(2):
            model.zero_grad(set_to_none=True)
            with torch.autocast(device_type='cuda', dtype=torch.bfloat16, enabled=amp):
                loss = F.cross_entropy(model(x), y)
            loss.backward()
        remainder = train_size % n
        if remainder:
            model.zero_grad(set_to_none=True)
            with torch.autocast(device_type='cuda', dtype=torch.bfloat16, enabled=amp):
                partial_loss = F.cross_entropy(model(x[:remainder]), y[:remainder])
            partial_loss.backward()
        dummy = torch.zeros((min(valid_size, 256), 3, 32, 32), dtype=torch.uint8, device=device)
        dummy_mean = torch.zeros((1, 3, 1, 1), device=device)
        dummy_std = torch.ones_like(dummy_mean)
        single_view(model, dummy, dummy_mean, dummy_std)
        six_views(model, dummy, dummy_mean, dummy_std)
        torch.cuda.synchronize()
        del model, x, y, loss, dummy, dummy_mean, dummy_std
        torch.cuda.empty_cache()


def main():
    (train_x, train_y), (valid_x, valid_y), (test_x, test_y), train_ids, valid_ids, test_ids = dataset()
    mean, std = image_stats(train_x)
    start = clock()
    moments = patch_moments(train_x, mean, std)
    whitening_seconds = clock()-start
    filters = pca_filters(moments).double().reshape(24, 12)[:12]
    whitened = filters @ moments['moment'] @ filters.T
    theoretical = moments['eigenvalues']/(moments['eigenvalues']+5e-4)
    assert torch.allclose(whitened.diagonal(), theoretical, atol=1e-5, rtol=1e-5)
    assert torch.allclose(whitened, torch.diag(whitened.diagonal()), atol=1e-5, rtol=1e-5)
    print('PCA: segundo momento transformado coincide con lambda/(lambda+eps)', flush=True)
    warmup_start = clock()
    warmup(len(train_x), len(valid_x))
    warmup_seconds = clock()-warmup_start
    result = {'protocol': {'short': short, 'train_per_class': train_n, 'valid_per_class': valid_n,
        'test_per_class': test_n, 'test_slice_per_class': [60, 80] if short else [0, 1000],
        'test_note': 'exploratorio; el test completo comparte imágenes con lecciones previas',
        'batch_size_fast': batch_size, 'seeds': seeds, 'mean': mean.flatten().cpu().tolist(),
        'std': std.flatten().cpu().tolist(), 'amp_bfloat16': amp,
        'whitening_seconds': whitening_seconds, 'warmup_seconds': warmup_seconds,
        'warmup': 'dos forward y backward de lote completo, uno del lote parcial y evaluaciones de 1 y 6 vistas con datos ficticios',
        'timing': 'sincronización CUDA; entrenamiento sin preparación; inferencia de validación por separado',
        'source': 'https://github.com/KellerJordan/cifar10-airbench/blob/master/legacy/airbench94.py',
        'differences': 'train/valid separados, normalización train y muestra de whitening estratificada, bfloat16, EMA de evaluación en vez de Lookahead, lote final incluido, sin compile; 100 pasos y lote 64 solo en corto'}, 'runs': []}
    pair_only = os.environ.get('ORYON_ONLY_PAIR') == '1'
    configs = ([('fast', True, f) for f in ('aleatorio', 'alternante')] if pair_only else
               [('resnet18', False, 'aleatorio')] + [('fast', w, f) for w in (False, True) for f in ('aleatorio', 'alternante')])
    for arch, white, flip in configs:
        for seed in seeds:
            model, run = train_one(arch, white, flip, seed, train_x, train_y, valid_x, valid_y, moments, mean, std)
            if arch == 'fast' and white and flip == 'alternante' and seed == seeds[0] and run['failure'] is None:
                views = six_views(model, test_x, mean, std)
                run['test_raw_exploratory'] = summarize(views, test_y.cpu())
                save_figure_data(moments, train_x, train_y, train_ids, test_x, test_y, test_ids, views)
            result['runs'].append(run)
            outpath.write_text(json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False), encoding='utf-8')
            print(json.dumps(run, ensure_ascii=False), flush=True)
            del model
            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.

One idea and twenty seeds

As a contrast example, run the previous cell with ORYON_ONLY_PAIR=1 and ORYON_STUDY_SEEDS=20: it compares two flip policies with PCA, pairing seeds. To test your own idea, first formulate the hypothesis and replace the alternative branch with your modification in a documented way; retain split, budget and initialization, and adapt analysis labels. Do not choose the modification by consulting test. The next cell analyzes JSON indicated by ORYON_FAST_CIFAR_OUTPUT; by default it uses pairs already produced by the preceding cell. The five-short-seed comparison verifies analysis; it is not equivalent to the full twenty-seed study.

[ ]Paired differences by seedLocal GPU
"""Contraste emparejado de una hipótesis fijada antes de ver la validación.

Primero ejecuta el laboratorio con ORYON_STUDY_SEEDS=20, ORYON_ONLY_PAIR=1 y
ORYON_FAST_CIFAR_OUTPUT=m16-l11-study.json. Este programa lee ese JSON.
"""
import json
import os
from pathlib import Path
import numpy as np
from scipy import stats

path = Path(os.environ.get('ORYON_FAST_CIFAR_OUTPUT', 'm16-l11-study.json'))
result = json.loads(path.read_text(encoding='utf-8'))
grouped = {'aleatorio': {}, 'alternante': {}}
for run in result['runs']:
    if run['arch'] == 'fast' and run['whitening'] and run['flip'] in grouped and run['failure'] is None:
        grouped[run['flip']][run['seed']] = run['valid_raw']['one']
left, right = grouped['aleatorio'], grouped['alternante']
if set(left) != set(right) or len(left) < 2:
    raise ValueError('Se requieren al menos dos semillas emparejadas completas')
seeds = sorted(left)
delta = np.array([right[s]-left[s] for s in seeds])
n = len(delta)
mean, sd = float(delta.mean()), float(delta.std(ddof=1))
print('Semilla  alternante - aleatorio (exactitud de validación)')
for seed, value in zip(seeds, delta):
    print(seed, float(value))
print('n =', n, 'media =', mean, 'desviación muestral =', sd)
if sd > 0:
    margin = stats.t.ppf(.975, n-1)*sd/np.sqrt(n)
    test = stats.ttest_1samp(delta, 0.)
    print('IC bilateral del 95 %:', (mean-margin, mean+margin), 'p bilateral:', float(test.pvalue))
else:
    print('Diferencias constantes: el contraste t habitual tiene error estándar cero.')
print('Condicionado a esta partición de validación; no sustituye una evaluación final independiente.')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

NumericHow many pairs
With paired-difference deviation of 0.15 points, 0.1-point improvement, two-sided t-test at 5% and minimum 80% power, how many pairs are needed according to the cell?
QuizA redundant view
If a model is exactly invariant to a horizontal flip for an image and TTA averages its original and reflected logits, what happens?
QuizA seemingly conclusive table
One configuration beats another by 0.1 points on one seed. What conclusion is justified?
CodeRegularized PCA filters
Implement patch_whitening_weights(images, patch_size, eps). Receive an N×C×H×W NumPy array and return (filters, mean): filters has shape (C·k²)×C×k×k and mean shape C·k². Extract all valid patches of side k, flatten in C,k,k order, center each component, calculate covariance with patch count as denominator and return PCA filters W=diag((s+eps)^−1/2)Uᵀ. Require positive eps. Eigenvector order and sign are not fixed.
import numpy as np

def patch_whitening_weights(images, patch_size, eps):
  pass
Shift+Enter to run
CodeTwo rules for aggregating views
Implement tta_predict(model, x, shifts, flip, average). For each integer pair (dy,dx) in shifts, generate a view with torch.roll on the final two axes and, if flip is True, add its horizontal reflection. Evaluate model on each view. If average is 'logits', average logits; if it is 'probabilidades', apply softmax by class before averaging. Reject empty shifts or an unsupported average value. Circular translation is an explicit convention of this exercise.
import torch

def tta_predict(model, x, shifts, flip, average):
  pass
Shift+Enter to run
Key idea

Fast training is useful when you know what was measured. Architecture, initialization and multicrop evaluation form a complete protocol; evidence of improvement requires appropriate comparisons and seeds.

References