Module contents
Lesson 21 of 25Core 115 min

Vision Transformers: an image is worth 16×16 words

Study vision transformers, patch embeddings, positional interpolation, attention costs and data regimes with controlled experiments.

After this lesson you can

  • Derive patch projection and its convolutional equivalent.
  • Analyze token counts, attention costs and positional interpolation.
  • Compare ViT and CNN inductive biases under explicit data and training protocols.
  • Interpret attention distance and experimentally compare model outputs.

Before you start

A sequence built from the image

A language transformer receives discrete tokens; an image arrives as a grid of values. The Vision Transformer divides that grid into patches, projects each to a vector and applies an encoder to the sequence. It does not eliminate all spatial structure: each patch preserves pixel order and the same projection is shared across positions. It does change the locality and compositional biases of a CNN.

For a C×H×WC\times H\times W image and non-overlapping P×PP\times P patches, if HH and WW are divisible by PP there are N=(H/P)(W/P)N=(H/P)(W/P) patches. The patch projection flattens each block in a declared order and applies the same matrix E∈RD×CP2E\in\mathbb R^{D\times CP^2}. A convolution without padding, with kernel_size=stride=P, groups one and dilation one, computes exactly the same thing if its weights and bias are rearranged consistently. PyTorch convolution is correlation: the kernel need not be reversed.

If patch order is CHW, Ed,(cP+u)P+v=Wd,c,u,vE_{d,(cP+u)P+v}=W_{d,c,u,v}. If flattened HWC, weights must be permuted; matching shapes do not guarantee matching values. Without padding and with indivisible dimensions, the incomplete edge is discarded. In CIFAR-10, a 32×3232\times32 image with patch 16 produces four patches; with a CLS token there are five tokens, not four. Patch 4 produces 64 patches and 65 tokens with CLS.

InteractiveFrom image to sequence

The image is artificial and single-channel. Select a patch: the highlighted rectangle becomes a sequence position, scanning rows from left to right.

Patch (2, 2): rows 32 to 47, columns 32 to 47. Patch index 30; sequence position 31, zero-based.

0: CLS30: (2, 1)31: (2, 2)32: (2, 3)

Patch vector: 256 values. Beginning: [0.145, 0.147, 0.148, 0.150, 0.151, 0.153, …].

Flattening and linear product: [−0.14605, 0.28508]. Both paths calculate the same output with the same weights and biases.

Image of size H × H: the value at (x, y), zero-based, is ((x + 0.5)/H + 2(y + 0.5)/H)/3. The preview shows 16 × 16 samples of that image. For the demonstration the patch is projected to two channels with weight w(x, y, k) = (((x + 2y + 3k) mod 7) − 3)/7 and bias k/8, with k = 0, 1. The output is not from a trained ViT.

The cost counter uses D = 768, 12 heads and batch 1. There are 196 patches and 197 tokens including CLS. QKᵀ and AV cost 2N²D = 59,610,624 MAC total, or 119,221,248 FLOP counting one MAC as two operations. QKV and output projections, MLP, softmax and normalization are excluded.

The 12 N × N matrices, one per head, materialized for one batch element occupy 465,708 values and 1,862,832 bytes in FP32. This is not peak model or training memory; block-processing attention implementations can avoid materializing them.

Image side in pixels
Patch side P
Patch projection
Attention storage type
2
2
Patches196
Total tokens197
QKᵀ y AV119 M FLOP
Attention matrices1.78 MiB
Select a patch and compare its two projections; the counter separates attention products and materialized memory.

Encoder, position and readout

The original Vision Transformer adds a class token and learned positional vectors, then applies attention and MLP blocks with pre-normalization and residual connections. A head reads the CLS output; another option is averaging patch tokens. The encoder block is studied in detail in the transformers module. While its lesson is not yet written, this lesson’s lab defines the necessary block self-containedly.

In ViT, B uses 12 blocks, width 768, MLP width 3072 and 12 heads; L uses 24, 1024, 4096 and 16; H uses 32, 1280, 5120 and 16. In Table 1 of Steiner and colleagues, Ti and S use widths 192 and 384 respectively, with 12 blocks. The /16 suffix indicates patch side length, not the number of layers.

Without positions, an index-dependent mask or another symmetry-breaking operation, shared attention and MLPs are equivariant to token permutation. If CLS stays fixed while patches are permuted, its output is invariant to that permutation; the same holds for global averaging. This does not mean invariance to arbitrary pixel permutations within a patch. With dropout, the exact statement per realization requires permuting its mask too or working in deterministic inference.

Quadratic does not mean the whole cost

With total length SS including prefixes, width DD, MLP expansion rr and one image per batch, Q, K, V and output projections cost 4SD24SD^2 MACs; products QKTQK^T and AVAV cost 2S2D2S^2D MACs, and the MLP 2rSD22rSD^2. If one MAC counts as two FLOPs, multiply by two. These figures omit normalization, softmax, biases and activations. The quadratic part is not the full block cost.

For ViT-B/16, D=768D=768, r=4r=4 and one CLS: at 224×224224\times224 there are 197 tokens; at 384×384384\times384, 577. Products QKTQK^T and AVAV cost 119,221,248 and 1,022,757,888 FLOPs per block respectively, an approximate factor of 8.579. Including the four attention projections lowers the factor to 3.571; with the block MLP it is 3.161. These ratios depend on dimensions and operation-count convention.

Materializing an FP32 attention matrix per head requires 4hS24hS^2 bytes per image and layer, excluding other activations and backward. Blockwise implementations can avoid materializing the whole matrix without eliminating the quadratic arithmetic products. Attention cost must be measured alongside projections, memory and batch size.

Positions at another resolution

Positional interpolation separates special tokens, rearranges patch positions into their original 2D grid, interpolates each channel to the new grid and flattens again. Preserve CLS and any other prefix; record original height and width so you do not assume a square grid. Interpolating vectors and then calculating cosine similarity is generally not equivalent to directly interpolating a similarity map.

The specific recipe matters: the TorchVision helper uses bicubic interpolation with align_corners=True, while timm uses its own interpolation and antialiasing convention. Do not assume identical implementations or preserved accuracy without measuring. If patch count changes and the table is not adapted, a dimension mismatch is typical rather than necessarily obtaining random predictions. Two-dimensional sinusoidal and rotary positions also exist, with their own axis conventions.

InteractiveWhat positions learned

Each cell represents cosine similarity to the selected position. Brightness indicates similarity: background for zero and color for one; negative values use a second color. The outline marks the reference.

  • Positive cosine
  • Negative cosine
  • Zero norm: undefined

Weights: timm/vit_small_patch16_224.augreg_in21k_ft_in1k, revision 5bbc78bad2961a2cee98d6e4a03fa92969175f24, short export. CLS is excluded. Bicubic interpolation without antialiasing and with align_corners=false matches the accompanying lab; other libraries may use another convention. If a vector has zero norm, its cosine is undefined. Selection is also possible using the sliders.

14
7
7
Grid14 × 14
Reference (row, column)7, 7
Minimum cosine−0.597
Maximum cosine1.000
Select a position and compare its cosine similarities before and after interpolating the learned vectors.

The map comes from the actual weights of the ViT-S pinned in the lab. Changing the grid alters the queried vectors; it does not retrain their positions. The similarities shown also do not guarantee the model retains accuracy at the new resolution.

Data, architecture and recipe

The data regime and inductive bias cannot be reduced to saying ViT always needs more data. In Table 5 of the ViT paper, after fine-tuning at resolution 384, ViT-B/16 achieves 77.91%, 83.97% and 84.15% ImageNet top-1 under the ImageNet-1k, ImageNet-21k and JFT pretraining regimes described there; ViT-L/16 achieves 76.53%, 85.15% and 87.12%. Data and training details change: those figures alone do not isolate a single cause.

The same paper studies the crossover between families using random JFT subsets of 9, 30 and 90 million images and the full dataset. Its Figure 4 uses few-shot linear evaluation on ImageNet and validation selection, not the same full fine-tuning that produces Table 5. The authors observe ViT-B/32 is far behind ResNet-50 with 9 million but surpasses it with 90 million or more under that protocol; they also describe a ranking reversal for ViT-L/16 and ResNet-152×2. This is one comparison, not a universal data threshold or proof that architecture is the only cause.

InteractiveData and recipes under different protocols

Points are published ImageNet top-1 accuracies. Each view comes from a defined experiment; the axis starts at 70% and curves are not drawn between experiments.

7075808590ViT-B/1677.91ViT-L/1676.53

ViT-B/16: Fine-tuning at 384 · ViT-L/16: Fine-tuning at 384.

Pretraining: ImageNet-1k, approximately 1.3 million. ViT table 5 reports accuracy after fine-tuning each model on ImageNet at resolution 384. Data origin and composition and training details also change; the points do not isolate the causal effect of adding images.

The “CNN and ViT crossover on JFT” option explores four study sizes using approximate values digitized from the published figure.

Sources: ViT, tables 5 and 6; DeiT, tables 3 and 8. Results are specific to their models and protocols; they are not measurements made in this lesson.

ViT-B/1677.91 %
ViT-L/1676.53 %
Explore published tables and digitized ViT and ResNet curves, with each experiment's protocol.

The DeiT recipe showed competitive ImageNet-1k training through careful augmentation, regularization and optimization. In Table 3 of DeiT, DeiT-B without distillation reaches 81.8% at resolution 224 and the hard-distillation variant with both heads reaches 83.4%, under the published protocol. The additional token learns from the teacher; not all DeiT models use distillation. In Table 8, removing RandAugment reduces the central result from 81.8% to 79.6%, and removing Mixup reduces it to 78.7%. These are independent ablations without retuning other hyperparameters, so they do not prove stronger augmentation is always better.

The published recipe combines AdamW, augmentations and regularization, including stochastic depth. In hard distillation, the distillation head fits the class predicted by the CNN teacher, while the class head fits the supervised label. When evaluating the variant with both heads, their predictions are combined according to the protocol; see knowledge distillation to distinguish objectives and temperature.

Global pooling, convolutional stems and budget-aware regularization are alternatives to test. A small-data test with a CNN recipe can be a baseline, but does not prove all ViTs are inferior. Conversely, pretraining and its data must be accounted for when comparing with a ResNet trained from scratch.

Weight decay is also a recipe choice: many training runs explicitly exclude biases, normalization parameters, CLS and positions from decay. Check optimizer groups rather than assuming a library separates them for you. Changing this decision alters the experiment and may interact with the rest of regularization.

Local or global?

An attention head can mix nearby or distant patches. Attention-weighted mean distance describes that pattern for particular images and layers; it does not by itself identify a causal explanation. Raghu and colleagues found local and global heads in their experiments, with differences across sizes and pretraining regimes. It does not follow that locality never appears with little data or few steps: the compared model and protocol must be measured.

InteractiveAttention distance by layer and head

Each point is a head. The chosen layer is highlighted. Distance measures separation on the patch grid, weighted by attention and averaged over queries and images.

8.40Distance (parches)123456789101112Layer

Source: short run with timm/vit_small_patch16_224.augreg_in21k_ft_in1k, revision 5bbc78bad2961a2cee98d6e4a03fa92969175f24, on 2 CIFAR test images enlarged to 224 × 224. CLS is excluded from queries and keys and the remainder is divided by the remaining mass, with a floor of 10⁻¹². The control uses this implementation’s PyTorch initialization with seed 16211; it is not a training trajectory. Horizontal point offsets within a layer improve readability and do not represent another variable. This summary does not establish causality or segmentation.

Weights
1
1
Heads6
Selected head4.00 parches
Mean over heads4.35 parches
Minimum and maximum0.84 / 6.65
Compare distances from a pretrained ViT-S and an untrained initialization on two CIFAR images from the short run.

This tiny sample shows heads with different distances. It measures only two images and one initialization, so it serves to inspect the calculation, not establish a general trend or attribute it solely to training.

In the lab, parity with timm is checked at 224 pixels. At other resolutions the custom implementation interpolates without antialiasing and the timm recipe may use it, so that check does not guarantee parity there. The untrained control uses PyTorch layer initialization in the custom implementation; a difference from the pretrained model does not isolate the effect of training alone.

Local labs

Both cells are self-contained and require PyTorch, torchvision, timm, safetensors, pyarrow, Pillow and huggingface_hub. The first run obtains CIFAR-10 and pinned official weights in their caches. To verify the pipeline, set ORYON_VERIFY_SHORT=1: the second cell uses four steps per branch, one seed and only 20 validation and 20 test images. Its results are exploratory and do not support accuracy comparisons or declaring a winner. The position and distance figures come from an actual short run of the first cell with two images.

The first cell builds a custom encoder while the m18 lesson is unavailable, checks projection equivalence and compares its logits with timm at 224×224. It saves positions and attention distances to vit-analysis.json, or the ORYON_VIT_OUTPUT path. The random control is one initialization of this implementation’s PyTorch layers, not necessarily timm’s initialization recipe; the observed difference does not isolate training alone. The custom interpolation preserves CLS and does not use antialiasing, so parity checked at 224 does not automatically extend to other resolutions or guarantee retained accuracy.

[ ]Custom ViT and timm weightsLocal GPU
"""ViT propio, proyección por parches y paridad con pesos oficiales de timm.

Requiere torch, torchvision, timm, safetensors, huggingface_hub, pyarrow y Pillow.
Descarga el checkpoint fijado y CIFAR-10 en la caché común al ejecutarse. La prueba
ORYON_VERIFY_SHORT=1 usa menos imágenes, sin modificar las matemáticas del modelo.
La atención se mide explícitamente y no interpreta sus pesos como explicaciones.
La paridad con timm solo se comprueba a 224; la interpolación propia a otra
resolución no usa antialias. El control aleatorio usa la inicialización de
capas PyTorch de esta implementación, no necesariamente la de timm.
"""
import io
import json
import os
from pathlib import Path

import numpy as np
import pyarrow.parquet as pq
from PIL import Image
from huggingface_hub import hf_hub_download
from safetensors.torch import load_file
import timm
import torch
from torch import nn
from torch.nn import functional as F

DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
OUT = Path(os.environ.get('ORYON_VIT_OUTPUT', 'vit-analysis.json'))
REPO = 'timm/vit_small_patch16_224.augreg_in21k_ft_in1k'
REVISION = '5bbc78bad2961a2cee98d6e4a03fa92969175f24'


class PatchEmbed(nn.Module):
    def __init__(self, p, d):
        super().__init__()
        self.proj = nn.Conv2d(3, d, kernel_size=p, stride=p)

    def forward(self, x):
        return self.proj(x).flatten(2).transpose(1, 2)


class Attention(nn.Module):
    def __init__(self, dim, heads):
        super().__init__()
        if dim % heads:
            raise ValueError('La dimensión debe ser divisible por el número de cabezas')
        self.heads, self.head_dim = heads, dim // heads
        self.qkv = nn.Linear(dim, 3 * dim, bias=True)
        self.proj = nn.Linear(dim, dim)
        self.last_attention = None
        self.capture = False

    def forward(self, x):
        b, n, d = x.shape
        qkv = self.qkv(x).reshape(b, n, 3, self.heads, self.head_dim).permute(2, 0, 3, 1, 4)
        q, k, v = qkv.unbind(0)
        attention = (q @ k.transpose(-2, -1) * self.head_dim ** -.5).softmax(dim=-1)
        if self.capture:
            self.last_attention = attention.detach()
        return self.proj((attention @ v).transpose(1, 2).reshape(b, n, d))


class MLP(nn.Module):
    def __init__(self, dim, hidden):
        super().__init__()
        self.fc1, self.fc2 = nn.Linear(dim, hidden), nn.Linear(hidden, dim)

    def forward(self, x):
        return self.fc2(F.gelu(self.fc1(x)))


class Block(nn.Module):
    def __init__(self, dim, heads):
        super().__init__()
        self.norm1 = nn.LayerNorm(dim, eps=1e-6)
        self.attn = Attention(dim, heads)
        self.norm2 = nn.LayerNorm(dim, eps=1e-6)
        self.mlp = MLP(dim, 4 * dim)

    def forward(self, x):
        x = x + self.attn(self.norm1(x))
        return x + self.mlp(self.norm2(x))


def interpolate_positions(pos, old_grid, new_grid):
    if pos.ndim != 3 or pos.shape[0] != 1 or pos.shape[1] != 1 + old_grid[0] * old_grid[1]:
        raise ValueError('La rejilla antigua no coincide con las posiciones')
    cls, grid = pos[:, :1], pos[:, 1:]
    if old_grid == new_grid:
        return pos
    grid = grid.transpose(1, 2).reshape(1, pos.shape[-1], *old_grid)
    grid = F.interpolate(grid, size=new_grid, mode='bicubic', align_corners=False)
    return torch.cat((cls, grid.flatten(2).transpose(1, 2)), dim=1)


class ViT(nn.Module):
    def __init__(self, image_size=224, patch_size=16, dim=384, depth=12, heads=6, classes=1000, pooling='cls'):
        super().__init__()
        if image_size % patch_size or pooling not in ('cls', 'mean'):
            raise ValueError('Tamaño de imagen o pooling no válido')
        self.patch_size, self.pooling = patch_size, pooling
        self.grid = (image_size // patch_size, image_size // patch_size)
        self.patch_embed = PatchEmbed(patch_size, dim)
        self.cls_token = nn.Parameter(torch.zeros(1, 1, dim))
        self.pos_embed = nn.Parameter(torch.zeros(1, 1 + self.grid[0] * self.grid[1], dim))
        self.blocks = nn.Sequential(*(Block(dim, heads) for _ in range(depth)))
        self.norm = nn.LayerNorm(dim, eps=1e-6)
        self.head = nn.Linear(dim, classes)
        nn.init.trunc_normal_(self.cls_token, std=.02)
        nn.init.trunc_normal_(self.pos_embed, std=.02)

    def forward(self, x):
        b, _, h, w = x.shape
        if h % self.patch_size or w % self.patch_size:
            raise ValueError('La imagen debe ser divisible por el tamaño de parche')
        tokens = self.patch_embed(x)
        tokens = torch.cat((self.cls_token.expand(b, -1, -1), tokens), dim=1)
        tokens = tokens + interpolate_positions(self.pos_embed, self.grid, (h // self.patch_size, w // self.patch_size))
        tokens = self.norm(self.blocks(tokens))
        features = tokens[:, 0] if self.pooling == 'cls' else tokens[:, 1:].mean(dim=1)
        return self.head(features)


def verify_patch_projection():
    for h, w, p in [(12, 20, 4), (16, 16, 8)]:
        torch.manual_seed(h + w)
        x1 = torch.randn(2, 3, h, w, requires_grad=True)
        x2 = x1.detach().clone().requires_grad_(True)
        conv = nn.Conv2d(3, 7, p, stride=p)
        patches = F.unfold(x1, kernel_size=p, stride=p).transpose(1, 2)
        y1 = F.linear(patches, conv.weight.flatten(1), conv.bias)
        y2 = conv(x2).flatten(2).transpose(1, 2)
        torch.testing.assert_close(y1, y2, rtol=1e-5, atol=1e-6)
        y1.square().sum().backward(); y2.square().sum().backward()
        torch.testing.assert_close(x1.grad, x2.grad, rtol=1e-5, atol=1e-6)
    pos = torch.randn(1, 1 + 3 * 4, 8)
    assert torch.equal(interpolate_positions(pos, (3, 4), (3, 4)), pos)
    resized = interpolate_positions(pos, (3, 4), (5, 7))
    assert resized.shape == (1, 36, 8) and torch.equal(pos[:, :1], resized[:, :1])
    print('Patchify/Conv2d, gradientes y posiciones: pruebas correctas.')


def fixed_images(count):
    path = hf_hub_download(repo_id='uoft-cs/cifar10', repo_type='dataset', revision='0b27149',
                           filename='plain_text/test-00000-of-00001.parquet')
    records = []
    for batch in pq.ParquetFile(path).iter_batches(batch_size=32, columns=['img', 'label']):
        rows = batch.to_pylist()
        for row in rows:
            image = Image.open(io.BytesIO(row['img']['bytes'])).convert('RGB')
            # La ficha del checkpoint usa bicúbica y normalización a [-1,1].
            image = image.resize((224, 224), Image.Resampling.BICUBIC)
            pixels = torch.from_numpy(np.asarray(image).copy()).permute(2, 0, 1).float() / 127.5 - 1
            records.append((pixels, int(row['label'])))
            if len(records) == count:
                return records
    raise RuntimeError('No se han encontrado suficientes imágenes CIFAR')


def attention_distance(model, images):
    for block in model.blocks:
        block.attn.capture = True
    grid = model.grid
    coords = torch.stack(torch.meshgrid(torch.arange(grid[0], device=DEVICE),
                                        torch.arange(grid[1], device=DEVICE), indexing='ij'), dim=-1).reshape(-1, 2).float()
    distances = torch.cdist(coords, coords)
    layer_sums = None
    for image in images:
        with torch.no_grad():
            model(image.unsqueeze(0).to(DEVICE))
        heads = []
        for block in model.blocks:
            # Excluye CLS tanto en consultas como en claves y renormaliza por fila.
            a = block.attn.last_attention[0, :, 1:, 1:]
            denom = a.sum(-1).clamp_min(1e-12)
            heads.append(((a * distances).sum(-1) / denom).mean(-1).cpu().numpy())
            block.attn.last_attention = None
        values = np.stack(heads)
        layer_sums = values if layer_sums is None else layer_sums + values
    for block in model.blocks:
        block.attn.capture = False
    return (layer_sums / len(images)).tolist()


def main():
    verify_patch_projection()
    torch.manual_seed(16210)
    path = hf_hub_download(repo_id=REPO, revision=REVISION, filename='model.safetensors')
    weights = load_file(path, device='cpu')
    reference = timm.create_model('vit_small_patch16_224', pretrained=False).eval()
    reference.load_state_dict(weights, strict=True)
    model = ViT().eval()
    model.load_state_dict(weights, strict=True)
    del weights
    reference = reference.to(DEVICE)
    images = fixed_images(2 if SHORT else 8)
    batch = torch.stack([im for im, _ in images[:2]]).to(DEVICE)
    with torch.no_grad():
        expected = reference(batch).cpu()
    del reference
    if DEVICE.type == 'cuda':
        torch.cuda.empty_cache()
    model = model.to(DEVICE)
    with torch.no_grad():
        own = model(batch).cpu()
    diff = float((own - expected).abs().max())
    torch.testing.assert_close(own, expected, rtol=1e-4, atol=1e-4)
    print('Máxima diferencia absoluta de logits:', diff)
    del batch, expected, own
    torch.manual_seed(16211)
    random_model = ViT().eval().to(DEVICE)
    learned = attention_distance(model, [im for im, _ in images])
    untrained = attention_distance(random_model, [im for im, _ in images])
    result = {'source': REPO, 'revision': REVISION, 'timm_version': timm.__version__,
              'short': SHORT, 'cifar_revision': '0b27149', 'split': 'test',
              'image_indices': list(range(len(images))), 'cifar_labels': [label for _, label in images],
              'preprocess': 'CIFAR RGB a 224×224 bicúbico; dividir por 127.5 y restar 1',
              'grid': list(model.grid), 'positions': model.pos_embed.detach().cpu().tolist(),
              'logits_max_abs_diff': diff, 'distance_unit': 'parches',
              'distance': {'pretrained': learned, 'random_seed_16211': untrained},
              'note': 'El control aleatorio usa la inicialización PyTorch de este modelo; las distancias no implican causalidad. La paridad con timm se mide solo a 224.'}
    OUT.parent.mkdir(parents=True, exist_ok=True)
    OUT.write_text(json.dumps(result, ensure_ascii=False), encoding='utf-8')
    print('Guardado:', OUT.resolve())
    if DEVICE.type == 'cuda':
        torch.cuda.empty_cache()


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

The second cell retains lesson 11’s ResNet-18 and compares the basic recipe and CutMix for a small ViT with an adaptation of pretrained ViT-S. Its training subsets are nested; validation remains separate and selects the checkpoint. Test is exploratory because it has been consulted in other lessons. Inference measurement uses declared warm-up, synchronization and batches; it excludes preprocessing and shared load affects timings. Incremental output is saved in vit-cifar.json, or ORYON_CIFAR_VIT_OUTPUT.

For each ViT-S it selects the checkpoint by validation at 224×224. It then evaluates the same checkpoint on the same test at 224×224 and 256×256, interpolating positions from 14×14 to 16×16 and retaining CLS. Both accuracies are exploratory: interpolation allows another resolution but does not guarantee maintaining or improving accuracy.

[ ]ViT and ResNet on CIFAR-10Local GPU
"""ResNet18 de l11 frente a ViT CIFAR y ViT-S preentrenado.

Requiere torch, torchvision, timm, safetensors, pyarrow, Pillow y huggingface_hub.
La primera ejecución usa la caché común para CIFAR-10 y los pesos preentrenados.
ORYON_VERIFY_SHORT=1 recorre todas las ramas con pocos datos y pasos, sin converger.
Los resultados en test son exploratorios: este test ya aparece en otras lecciones.
"""
import io
import json
import os
from pathlib import Path
import time

import numpy as np
import pyarrow.parquet as pq
from PIL import Image
from huggingface_hub import hf_hub_download
from safetensors.torch import load_file
import timm
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.data import DataLoader, TensorDataset

DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
OUT = Path(os.environ.get('ORYON_CIFAR_VIT_OUTPUT', 'vit-cifar.json'))
REPO = 'timm/vit_small_patch16_224.augreg_in21k_ft_in1k'
REVISION = '5bbc78bad2961a2cee98d6e4a03fa92969175f24'


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):
    """Misma arquitectura e inicialización que la celda de m16-l11."""
    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 CifarViT(nn.Module):
    def __init__(self, dim=192, heads=3, depth=6, patch=4):
        super().__init__()
        self.projection = nn.Conv2d(3, dim, patch, stride=patch)
        self.cls = nn.Parameter(torch.zeros(1, 1, dim))
        self.pos = nn.Parameter(torch.zeros(1, (32 // patch) ** 2 + 1, dim))
        layer = nn.TransformerEncoderLayer(dim, heads, dim_feedforward=4 * dim,
                    dropout=0., activation='gelu', batch_first=True, norm_first=True, layer_norm_eps=1e-6)
        self.blocks = nn.TransformerEncoder(layer, depth, enable_nested_tensor=False)
        self.norm = nn.LayerNorm(dim, eps=1e-6)
        self.head = nn.Linear(dim, 10)
        nn.init.trunc_normal_(self.cls, std=.02)
        nn.init.trunc_normal_(self.pos, std=.02)
        # TransformerEncoder clona la capa inicial: inicializar cada copia por separado.
        for block in self.blocks.layers:
            for name, parameter in block.named_parameters():
                if parameter.ndim > 1:
                    nn.init.xavier_uniform_(parameter)

    def forward(self, x):
        x = self.projection(x).flatten(2).transpose(1, 2)
        x = torch.cat((self.cls.expand(x.shape[0], -1, -1), x), dim=1) + self.pos
        return self.head(self.norm(self.blocks(x))[:, 0])


def groups(split, seed):
    path = hf_hub_download(repo_id='uoft-cs/cifar10', repo_type='dataset', revision='0b27149',
                           filename=f'plain_text/{split}-00000-of-00001.parquet')
    labels = np.concatenate([b.column(0).to_numpy() for b in
                             pq.ParquetFile(path).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 image:
                    images[pos] = np.asarray(image.convert('RGB'), dtype=np.uint8).transpose(2, 0, 1)
                seen[pos] = True
        offset += batch.num_rows
    if not seen.all():
        raise ValueError('No se pudieron leer todos los ejemplos')
    return torch.from_numpy(images), torch.from_numpy(labels[indices].copy())


def prepare_data():
    path, labels, group = groups('train', 16070)
    # En corto usa un subconjunto de la validación de l11: solo dos por clase.
    train_n, valid_n = (100, 2) if SHORT else (4500, 500)
    counts = [20] if SHORT else [450, 2250, 4500]
    # La validación es un bloque del de l11 y no se mueve al reducir train.
    train_indices = np.concatenate([x[:counts[-1]] for x in group])
    val_indices = np.concatenate([x[train_n:train_n + valid_n] for x in group])
    test_path, test_labels, test_groups = groups('test', 16074)
    test_indices = np.concatenate([x[60:62] if SHORT else x[:1000] for x in test_groups])
    assert not set(train_indices) & set(val_indices)
    x, y = read_selected(path, labels, train_indices)
    valid = read_selected(path, labels, val_indices)
    test = read_selected(test_path, test_labels, test_indices)
    return (x, y), valid, test, counts, train_indices.tolist(), val_indices.tolist(), test_indices.tolist()


def augment(x, generator):
    # Recorte tras padding de 4 y volteo por imagen, sin tocar las etiquetas.
    b = len(x)
    padded = F.pad(x, (4, 4, 4, 4), mode='reflect')
    dy = torch.randint(0, 9, (b,), generator=generator, device=DEVICE)
    dx = torch.randint(0, 9, (b,), generator=generator, device=DEVICE)
    grids = padded.unfold(2, 32, 1).unfold(3, 32, 1)
    x = grids[torch.arange(b, device=DEVICE), :, dy, dx]
    flip = torch.rand(b, device=DEVICE, generator=generator) < .5
    return torch.where(flip[:, None, None, None], x.flip(-1), x)


def cutmix(x, y, generator):
    b, _, h, w = x.shape
    order = torch.randperm(b, generator=generator, device=DEVICE)
    # Rectángulo de tamaño uniforme, una política explícita y no copia de DeiT.
    cut_h = int(torch.randint(1, h + 1, (), generator=generator, device=DEVICE))
    cut_w = int(torch.randint(1, w + 1, (), generator=generator, device=DEVICE))
    y0 = int(torch.randint(0, h - cut_h + 1, (), generator=generator, device=DEVICE))
    x0 = int(torch.randint(0, w - cut_w + 1, (), generator=generator, device=DEVICE))
    result = x.clone()
    result[:, :, y0:y0 + cut_h, x0:x0 + cut_w] = x[order, :, y0:y0 + cut_h, x0:x0 + cut_w]
    weight = 1 - cut_h * cut_w / (h * w)
    return result, y[order], weight


def create_model(kind):
    if kind == 'resnet':
        return ResNet18()
    if kind in ('vit_basico', 'vit_cutmix'):
        return CifarViT()
    if kind == 'vit_preentrenado':
        checkpoint = hf_hub_download(repo_id=REPO, revision=REVISION, filename='model.safetensors')
        model = timm.create_model('vit_small_patch16_224', pretrained=False)
        model.load_state_dict(load_file(checkpoint, device='cpu'), strict=True)
        model.reset_classifier(10)
        return model
    raise ValueError(kind)


def preprocess(x, pretrained, mean, std, resolution=224):
    x = x.float().to(DEVICE) / 255.
    if pretrained:
        x = F.interpolate(x, size=(resolution, resolution), mode='bicubic', align_corners=False, antialias=True)
        return (x - .5) / .5
    return (x - mean) / std


@torch.no_grad()
def accuracy(model, data, pretrained, mean, std, batch_size, resolution=224):
    model.eval()
    correct, total = 0, 0
    for x, y in DataLoader(TensorDataset(*data), batch_size=batch_size, shuffle=False):
        logits = model(preprocess(x, pretrained, mean, std, resolution))
        if not torch.isfinite(logits).all():
            raise FloatingPointError('Logits de evaluación no finitos')
        correct += int((logits.argmax(-1).cpu() == y).sum())
        total += len(y)
    return correct / total


def sync():
    if DEVICE.type == 'cuda':
        torch.cuda.synchronize()


def rescale_vit_checkpoint(state, old_grid=(14, 14), new_grid=(16, 16)):
    """Interpola posiciones espaciales y conserva exactamente el token CLS.

    Usa bicúbica, align_corners=False y antialias=True, como el remuestreo
    de posiciones de timm; el resto de tensores se deja sin modificar.
    """
    result = dict(state)
    pos = state['pos_embed']
    if pos.shape[0] != 1 or pos.shape[1] != 1 + old_grid[0] * old_grid[1]:
        raise ValueError('El checkpoint no contiene la rejilla espacial esperada')
    cls = pos[:, :1]
    grid = pos[:, 1:].transpose(1, 2).reshape(1, pos.shape[-1], *old_grid)
    grid = F.interpolate(grid.float(), size=new_grid, mode='bicubic', align_corners=False, antialias=True)
    result['pos_embed'] = torch.cat((cls, grid.to(pos.dtype).flatten(2).transpose(1, 2)), dim=1)
    if not torch.equal(result['pos_embed'][:, :1], cls):
        raise AssertionError('La interpolación ha modificado CLS')
    return result


def train_statistics(images):
    # Acumula por tandas: convertir los 45 000 ejemplos a float de una vez
    # puede ocupar más de medio GB y std puede crear otro temporal igual.
    total = torch.zeros(3, dtype=torch.float64)
    squares = torch.zeros(3, dtype=torch.float64)
    count = 0
    for chunk in images.split(256):
        value = chunk.to(torch.float64) / 255.
        total += value.sum(dim=(0, 2, 3))
        squares += value.square().sum(dim=(0, 2, 3))
        count += len(chunk) * chunk.shape[2] * chunk.shape[3]
    mean = total / count
    std = (squares / count - mean.square()).clamp_min(0).sqrt().clamp_min(1e-6)
    return mean.float().to(DEVICE)[None, :, None, None], std.float().to(DEVICE)[None, :, None, None]


@torch.no_grad()
def inference_throughput(model, data, pretrained, mean, std, batch_size):
    model.eval()
    x = preprocess(data[0][:batch_size], pretrained, mean, std)
    for _ in range(2):
        model(x)
    sync(); start = time.perf_counter()
    repeats = 3 if SHORT else 20
    for _ in range(repeats):
        model(x)
    sync()
    return {'images_per_second': len(x) * repeats / (time.perf_counter() - start),
            'batch_size': len(x), 'warmup_batches': 2, 'timed_batches': repeats,
            'includes_preprocessing': False}


def run_one(kind, seed, n_per_class, data, valid, test):
    torch.manual_seed(seed)
    if DEVICE.type == 'cuda':
        torch.cuda.manual_seed_all(seed)
    train_x, train_y = data
    selection = torch.cat([torch.where(train_y == label)[0][:n_per_class] for label in range(10)])
    x, y = train_x[selection], train_y[selection]
    mean, std = train_statistics(x)
    model = create_model(kind).to(DEVICE)
    pretrained = kind == 'vit_preentrenado'
    strong = kind == 'vit_cutmix'
    # Decay solo para matrices y convoluciones, no bias, normas ni posiciones.
    with_decay, without_decay = [], []
    for name, param in model.named_parameters():
        (without_decay if param.ndim <= 1 or 'pos' in name or 'cls' in name else with_decay).append(param)
    optimizer = torch.optim.AdamW([{'params': with_decay, 'weight_decay': .05},
                                   {'params': without_decay, 'weight_decay': 0.}],
                                  lr=1e-4 if pretrained else 3e-4)
    batch_size = 2 if SHORT and pretrained else 16 if SHORT else 32 if pretrained else 128
    order_rng = torch.Generator().manual_seed(seed + 1)
    augment_rng = torch.Generator(device=DEVICE.type).manual_seed(seed + 2)
    mix_rng = torch.Generator(device=DEVICE.type).manual_seed(seed + 3)
    loader = DataLoader(TensorDataset(x, y), batch_size=batch_size, shuffle=True, generator=order_rng)
    best, best_state, curves, total_steps = -1., None, [], 0
    epochs = 1 if SHORT else 50
    for epoch in range(epochs):
        model.train()
        total_loss, seen = 0., 0
        sync(); start = time.perf_counter()
        for images, labels in loader:
            images, labels = images.to(DEVICE), labels.to(DEVICE)
            # Misma augmentación geométrica para todas las ramas.
            images = augment(images.float() / 255., augment_rng)
            target2, weight = labels, 1.
            if strong:
                images, target2, weight = cutmix(images, labels, mix_rng)
            if pretrained:
                images = F.interpolate(images, size=(224, 224), mode='bicubic', align_corners=False, antialias=True)
                images = (images - .5) / .5
            else:
                images = (images - mean) / std
            optimizer.zero_grad(set_to_none=True)
            logits = model(images)
            loss = weight * F.cross_entropy(logits, labels) + (1 - weight) * F.cross_entropy(logits, target2)
            if not torch.isfinite(loss):
                raise FloatingPointError(f'Pérdida no finita en {kind}')
            loss.backward()
            if any(p.grad is not None and not torch.isfinite(p.grad).all() for p in model.parameters()):
                raise FloatingPointError(f'Gradiente no finito en {kind}')
            optimizer.step()
            total_loss += float(loss.detach()) * len(labels)
            seen += len(labels)
            total_steps += 1
            if SHORT and total_steps >= 4:
                break
        sync(); seconds = time.perf_counter() - start
        val = accuracy(model, valid, pretrained, mean, std, batch_size)
        curves.append({'epoch': epoch + 1, 'steps': total_steps, 'examples': seen,
                       'loss': total_loss / seen, 'validation_accuracy': val,
                       'training_images_per_second': seen / seconds})
        print(kind, 'semilla', seed, 'por clase', n_per_class, curves[-1])
        if val > best:
            best = val
            best_state = {key: value.detach().cpu().clone() for key, value in model.state_dict().items()}
    model.load_state_dict(best_state)
    test_accuracy = accuracy(model, test, pretrained, mean, std, batch_size)
    inference = inference_throughput(model, valid, pretrained, mean, std, batch_size)
    parameters = sum(p.numel() for p in model.parameters())
    by_resolution = None
    if pretrained:
        # La selección anterior se hizo solo con validación a 224. Las dos
        # evaluaciones siguientes usan exactamente el mismo test exploratorio.
        del optimizer, model, with_decay, without_decay, param, logits, loss
        if DEVICE.type == 'cuda':
            torch.cuda.empty_cache()
        larger = timm.create_model('vit_small_patch16_224', pretrained=False, img_size=256, num_classes=10)
        larger.load_state_dict(rescale_vit_checkpoint(best_state), strict=True)
        larger = larger.to(DEVICE)
        test_256 = accuracy(larger, test, True, mean, std, batch_size, resolution=256)
        by_resolution = {'224': test_accuracy, '256': test_256,
                         'selection': 'validación a 224',
                         'position_interpolation': 'bicúbica 14×14 a 16×16; align_corners=False; antialias=True; CLS conservado',
                         'note': 'Mismo test exploratorio; no garantiza mantener exactitud.'}
        del larger
    actual_mean = [.5, .5, .5] if pretrained else mean.flatten().cpu().tolist()
    actual_std = [.5, .5, .5] if pretrained else std.flatten().cpu().tolist()
    return {'model': kind, 'seed': seed, 'train_per_class': n_per_class,
            'parameters': parameters, 'curves': curves,
            'best_validation': best, 'test_exploratory': test_accuracy,
            'normalization': {'mean': actual_mean, 'std': actual_std},
            'pretrained': pretrained, 'inference_throughput': inference,
            'test_by_resolution': by_resolution}


def main():
    data, valid, test, counts, train_ids, valid_ids, test_ids = prepare_data()
    seeds = [16210] if SHORT else [16210, 16211, 16212]
    result = {'short': SHORT, 'dataset': 'uoft-cs/cifar10', 'revision': '0b27149',
              'training_indices': train_ids, 'validation_indices': valid_ids, 'test_indices': test_ids,
              'split_seeds': [16070, 16074], 'seeds': seeds, 'timm_version': timm.__version__,
              'pretrained_source': REPO + '@' + REVISION,
              'protocol': 'AdamW en todas las ramas, lr 3e-4 desde cero y 1e-4 preentrenado; '
                          'recorte/volteo común; CutMix solo vit_cutmix. '
                          'Throughput incluye augmentación y entrenamiento, sin calentamiento separado; '
                          'en inferencia calentamiento explícito sin preprocesado; tamaños de lote '
                          'y resolución distintos para el modelo preentrenado; '
                          'carga compartida y primera época pueden alterar el resultado.',
              'note': 'Test exploratorio, compartido con otras lecciones. En corto se evalúan '
                      '20 ejemplos en validación y 20 en test; no compara precisión.',
              'runs': []}
    OUT.parent.mkdir(parents=True, exist_ok=True)
    for n in counts:
        for seed in seeds:
            for kind in ('resnet', 'vit_basico', 'vit_cutmix', 'vit_preentrenado'):
                result['runs'].append(run_one(kind, seed, n, data, valid, test))
                OUT.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
                if DEVICE.type == 'cuda':
                    torch.cuda.empty_cache()
    print('Salida:', OUT.resolve())


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

ProofOne operation in two forms
Prove: Show that projecting each non-overlapping CHW patch with the same linear layer is equivalent to a Conv2d with kernel and stride P.
0
Assume zero padding, groups one, dilation one, H and W divisible by P and equal biases.

Step 1 of 2. Which coordinate of the flattened vector corresponds to pixel (c,u,v) of the patch?

NumericPatches at 224
For ViT-B/16 with a 224×224 image and one CLS, how many tokens enter each block?
NumericPatches at 384
For the same architecture with a 384×384 image and one CLS, how many tokens are there?
NumericAttention products at 224
In a ViT-B/16 block with a 224×224 image, one CLS and D=768, how many FLOPs do QKᵀ and AV total? Count 1 MAC as 2 FLOPs; exclude projections, softmax and other operations.
NumericAttention products at 384
With the same convention and architecture but a 384×384 image, how many FLOPs do QKᵀ and AV total in one block?
NumericHow much do quadratic products grow?
For D=768, one CLS and patch size 16, compare QKᵀ and AV between 384×384 and 224×224. Count 1 MAC as 2 FLOPs; omit projections, softmax and other operations. What is the 384/224 FLOP ratio?
CodeChange the positional grid
Implement interpolate_pos_embed(pos, old_grid, new_grid) with PyTorch. pos has shape 1×(1+H×W)×D and contains a CLS followed by positions in row order. Preserve CLS exactly, rearrange the old_grid=(H,W), interpolate channels to new_grid with bicubic interpolation and align_corners=False and return the sequence. Do not assume a square grid.
import torch

def interpolate_pos_embed(pos, old_grid, new_grid):
  pass
Shift+Enter to run
QuizWithout positions
A deterministic ViT without positions or a position-dependent mask keeps CLS fixed. What happens when only patches are permuted?
QuizA ViT with little data
A ViT trained from scratch with the same short recipe as a CNN fits training but validates poorly. Which comparison is more informative?
Key idea
ViT turns patches into tokens and shares a projection, but its costs, positions and data needs depend on concrete details. Compare architectures with documented recipes and budgets.