Code
# on Google Colab, PyTorch comes preinstalled; timm may not
import sys
if "google.colab" in sys.modules:
!pip install -q timmColab link
In class 6 we saw how convolutions dominated computer vision: local filters, stacked in ever deeper networks (ResNet) and in encoder-decoders (U-Net). Today we’ll meet the mechanism behind almost all of today’s AI: attention.
Plan
As in class 6, each architecture has a fact sheet 🗂️ with the year, type of training, strengths and limitations.
import os
os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1") # cleaner output when downloading from Hugging Face
os.environ.setdefault("HF_HUB_VERBOSITY", "error")
import time
import zipfile
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.colors import ListedColormap
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import transforms
from skimage import data, io
from PIL import Image
import timm
from huggingface_hub import hf_hub_download
# chart colors and style (the same as in the Machine Learning classes)
AZUL, LARANJA, VERDE, CINZA, TINTA = "#2a78d6", "#eb6834", "#1baf7a", "#898781", "#52514e"
plt.rcParams.update({
"axes.spines.top": False, "axes.spines.right": False,
"axes.edgecolor": CINZA, "axes.labelcolor": TINTA,
"xtick.color": TINTA, "ytick.color": TINTA,
"axes.grid": True, "grid.color": "#e6e5e1", "figure.dpi": 110,
})
torch.manual_seed(42)
# images in the ImageNet standard (the same used in DINOv2's pre-training)
MEDIA = torch.tensor([0.485, 0.456, 0.406])[:, None, None]
DESVIO = torch.tensor([0.229, 0.224, 0.225])[:, None, None]
normaliza = lambda x: (x - MEDIA) / DESVIO
# the LandCover.ai dataset from class 6 (already in the Hugging Face cache if you ran that class)
PASTA_LC = "data/landcoverai"
if not os.path.exists(PASTA_LC):
caminho = hf_hub_download(repo_id="isaaccorley/landcoverai", filename="landcoverai100.zip", repo_type="dataset")
zipfile.ZipFile(caminho).extractall(PASTA_LC)
NOMES_LC = ["background", "building", "forest", "water", "road"]
CORES_LC = ["#d9d9d9", "#e34948", "#1baf7a", "#2a78d6", "#eda100"]
cmap_lc = ListedColormap(CORES_LC)
print(f"PyTorch {torch.__version__}, timm {timm.__version__}")PyTorch 2.14.1, timm 1.0.30
A convolution (class 6) only looks at each pixel’s neighborhood. To relate distant parts of the image (the left eye with the right one, a river with the bridge that crosses it), a CNN has to stack many layers.
Attention does this in one layer: each element (a word, a patch of the image) looks at all the others and decides how much each one matters to it. Each element produces three vectors:
| Vector | Question | Library analogy |
|---|---|---|
| Query \(Q\) | “what am I looking for?” | what you type in the search box |
| Key \(K\) | “what do I offer?” | the title of each book |
| Value \(V\) | “what is my content?” | the content of the book |
The similarity between one element’s query and every other element’s key becomes a weight, and the output is the average of the values weighted by those weights:
\[\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^\top}{\sqrt{d}}\right) V\]
def atencao(Q, K, V):
d = Q.shape[-1]
pontuacoes = Q @ K.transpose(-2, -1) / d ** 0.5 # similarity between each query and each key
pesos = pontuacoes.softmax(dim=-1) # each row sums to 1
return pesos @ V, pesos
torch.manual_seed(0)
tokens = ["river", "bridge", "rain", "flood", "road", "house"]
X_tok = torch.randn(len(tokens), 16) # 6 "tokens", each a vector of 16 numbers
W_q, W_k, W_v = (nn.Linear(16, 8, bias=False) for _ in range(3)) # learnable projections
with torch.no_grad():
Q, K, V = W_q(X_tok), W_k(X_tok), W_v(X_tok)
saida, pesos = atencao(Q, K, V)
saida_torch = F.scaled_dot_product_attention(Q[None], K[None], V[None])[0]
print(f"input {tuple(X_tok.shape)} → Q, K, V {tuple(Q.shape)} → output {tuple(saida.shape)}")
print(f"same as PyTorch's F.scaled_dot_product_attention? {torch.allclose(saida, saida_torch, atol=1e-6)}")
print(f"each row of the weights sums to 1: {pesos.sum(dim=1).round(decimals=4).tolist()}")
fig, ax = plt.subplots(figsize=(6.5, 5))
im = ax.imshow(pesos, cmap="Blues", vmin=0)
ax.set(xticks=range(6), xticklabels=tokens, yticks=range(6), yticklabels=tokens,
xlabel="key: who is looked at", ylabel="query: who looks", title="Attention matrix (random weights)")
for i in range(6):
for j in range(6):
ax.text(j, i, f"{pesos[i, j]:.2f}", ha="center", va="center", fontsize=9, color="white" if pesos[i, j] > 0.3 else TINTA)
ax.grid(False)
plt.colorbar(im, ax=ax, shrink=0.8)
plt.show()entrada (6, 16) → Q, K, V (6, 8) → saída (6, 8)
igual ao F.scaled_dot_product_attention do PyTorch? True
cada linha dos pesos soma 1: [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]

With random projections the weights mean nothing; training is precisely adjusting \(W_q\), \(W_k\) and \(W_v\) so that each element pays attention to the relevant other elements.
In practice we use several heads (multi-head attention): several attentions in parallel, each with its own projections, which learn to look for different things. PyTorch already has the ready-made layer:
mha = nn.MultiheadAttention(embed_dim=16, num_heads=4, batch_first=True)
saida, pesos_mha = mha(X_tok[None], X_tok[None], X_tok[None]) # self-attention: Q, K and V come from the same sequence
print(f"input (1, 6, 16) → output {tuple(saida.shape)}, weights {tuple(pesos_mha.shape)} (mean of the 4 heads)")entrada (1, 6, 16) → saída (1, 6, 16), pesos (1, 6, 6) (média das 4 cabeças)
Attention alone isn’t a Transformer. A Transformer block combines four pieces, three of which we already know:
x ──────────────┐ x ─────────────┐
│ │ │ │
LayerNorm │ LayerNorm │
│ │ residual │ │ residual
Multi-Head │ connection MLP │ connection
Attention │ (ResNet!) (Linear → │
│ │ GELU → │
+ ◄─────────────┘ Linear) │
│ │ │
└──────────── ► ───────────────────► + ◄────────────┘
| Piece | Role | Where we’ve seen it |
|---|---|---|
| Multi-Head Attention | each token exchanges information with all the others | Part 1 |
| MLP (two linear layers) | each token processes the information it received, on its own | classes 1 to 4 |
Residual connection (x + ...) |
the gradient flows through dozens of blocks | ResNet, class 6 |
| LayerNorm | normalizes each token (mean 0, std 1), stabilizes training | a relative of ResNet’s BatchNorm |
A model like ViT or an LLM is basically dozens of these blocks stacked.
class BlocoTransformer(nn.Module):
def __init__(self, dim=16, cabecas=4, expansao=4):
super().__init__()
self.norm1 = nn.LayerNorm(dim)
self.atencao = nn.MultiheadAttention(dim, cabecas, batch_first=True)
self.norm2 = nn.LayerNorm(dim)
self.mlp = nn.Sequential(nn.Linear(dim, expansao * dim), nn.GELU(), nn.Linear(expansao * dim, dim))
def forward(self, x):
h = self.norm1(x)
x = x + self.atencao(h, h, h)[0] # 1. the tokens talk to each other (+ residual)
x = x + self.mlp(self.norm2(x)) # 2. each token processes what it received (+ residual)
return x
bloco = BlocoTransformer()
x = X_tok[None] # (1 sequence, 6 tokens, 16 numbers)
print(f"input {tuple(x.shape)} → output {tuple(bloco(x).shape)}: the shape doesn't change, so blocks can be stacked")
pronto = nn.TransformerEncoderLayer(d_model=16, nhead=4, dim_feedforward=64, batch_first=True, norm_first=True)
print(f"parameters: our block = {sum(p.numel() for p in bloco.parameters())}, "
f"nn.TransformerEncoderLayer from PyTorch = {sum(p.numel() for p in pronto.parameters())}")
encoder = nn.Sequential(*[BlocoTransformer() for _ in range(6)]) # 6 stacked blocks = a Transformer encoder
print(f"6 stacked blocks: {tuple(encoder(x).shape)}, {sum(p.numel() for p in encoder.parameters()):,} parameters")entrada (1, 6, 16) → saída (1, 6, 16): o formato não muda, então dá para empilhar
parâmetros: nosso bloco = 3280, nn.TransformerEncoderLayer do PyTorch = 3280
6 blocos empilhados: (1, 6, 16), 19,680 parâmetros
An important detail: attention compares everything with everything, without looking at position. If we shuffle the input tokens, the output comes out shuffled in the same way, with the same values. For the block, “the river overflowed after the rain” and “the rain overflowed after the river” would be the same thing!
torch.manual_seed(0)
ordem = torch.randperm(6)
with torch.no_grad():
saida_normal = bloco(X_tok[None])[0]
saida_embaralhada = bloco(X_tok[ordem][None])[0]
print(f"new token order: {ordem.tolist()}")
print(f"is the shuffled output the normal output in the new order? {torch.allclose(saida_embaralhada, saida_normal[ordem], atol=1e-5)}")nova ordem dos tokens: [2, 5, 3, 0, 1, 4]
a saída embaralhada é a saída normal na nova ordem? True
That’s why every Transformer adds position information to each token before the first block: a different vector for position 1, 2, 3… (positional embedding), which can be fixed (sines and cosines, in the original paper) or learned (in ViT). With this, the same token at different positions gets different representations.
🗂️ Fact sheet: Transformer
Year 2017 (Vaswani et al., Google, paper Attention Is All You Need) Old or new? Recent historically, and the basis of today’s AI (GPT, Claude, Gemini, BERT, ViT) Type of training originally supervised (text translation with sentence pairs); today almost always self-supervised on large volumes of text (predicting the next word or masked words) Why it matters replaced recurrent networks (LSTM) and convolution with attention: each element relates to all the others in a single layer, and the computation is parallel, ideal for GPUs Strengths global context; scales very well with data and model size; the same architecture works for text, images, audio and time series. Each block uses residual connections (the ResNet idea!) and LayerNorm Limitations the cost of attention grows with the square of the number of elements (large images get expensive); needs a lot of data because it has little built-in knowledge about the structure of the problem Still used? it’s the dominant architecture today
How do we apply attention to an image? Attention between all pixels would be far too expensive (a 224 × 224 image has 50 thousand pixels, so 2.5 billion pairs). ViT cuts the image into patches, for example of 16 × 16 pixels, and treats each patch as a “word”:
gato = transforms.functional.to_tensor(Image.fromarray(data.chelsea()).resize((224, 224)))
P = 16
patches = gato.unfold(1, P, P).unfold(2, P, P) # (3, 14, 14, 16, 16)
patches = patches.permute(1, 2, 0, 3, 4).reshape(-1, 3, P, P) # (196, 3, 16, 16): a sequence of 196 patches
print(f"image {tuple(gato.shape)} → {patches.shape[0]} patches of {tuple(patches.shape[1:])} → tokens of {3 * P * P} numbers")
fig = plt.figure(figsize=(16, 4.8))
ax = fig.add_axes([0.0, 0.05, 0.3, 0.9])
ax.imshow(gato.permute(1, 2, 0))
for k in range(1, 14):
ax.axhline(k * P - 0.5, color="white", lw=0.8)
ax.axvline(k * P - 0.5, color="white", lw=0.8)
ax.set_title("224 × 224 image cut into 14 × 14 patches")
ax.axis("off")
for k in range(24):
ax = fig.add_axes([0.33 + k * 0.0275, 0.42, 0.025, 0.16])
ax.imshow(patches[k + 84].permute(1, 2, 0))
ax.axis("off")
fig.text(0.33, 0.66, "… which become a SEQUENCE of tokens (patches 85 to 108 shown), like words in a sentence",
color=TINTA, fontsize=11)
plt.show()imagem (3, 224, 224) → 196 patches de (3, 16, 16) → tokens de 768 números

🗂️ Fact sheet: Vision Transformer (ViT)
Year 2020 (Dosovitskiy et al., Google) Old or new? Recent Type of training in the original paper, supervised on giant datasets (JFT-300M, 300 million images); today the best ViTs are trained in a self-supervised way (Part 4) Why it matters showed that convolution isn’t needed for vision: a pure Transformer on patches matches or beats CNNs, and it unified vision and language in the same architecture (the basis of multimodal models) Strengths global attention from the first layer; scales very well with data; it’s the basis of vision and Earth observation foundation models Limitations with little data it usually loses to CNNs (it lacks convolution’s built-in neighborhood bias); quadratic cost in the number of patches; resolution limited by the patch size Still used? yes, it’s the basis of DINOv2, SAM, CLIP, Prithvi and many others
Let’s open up a trained ViT: DINOv2 (ViT-S/14, the version with registers), downloaded from the Hub. We intercept the input of the last attention layer and compute the weights \(\text{softmax}(QK^\top/\sqrt{d})\), as in section 1.2.
Two questions:
About registers: large ViTs tend to “hide” global information in a few background patches, which makes the attention maps noisy. The version with registers (Darcet et al., 2023) adds 4 extra tokens for that role, and the maps come out clean.
inicio = time.time()
dino = timm.create_model("hf-hub:timm/vit_small_patch14_reg4_dinov2.lvd142m", pretrained=True, img_size=448).eval()
N_PREFIXO = dino.num_prefix_tokens # 1 [CLS] + 4 registers
LADO = 448 // 14 # 32 × 32 patches
print(f"DINOv2 ViT-S/14 loaded in {time.time() - inicio:.0f} s: {sum(p.numel() for p in dino.parameters()) / 1e6:.0f} M parameters, "
f"{len(dino.blocks)} blocks, {dino.blocks[-1].attn.num_heads} heads, {N_PREFIXO} special tokens")
def prepara(img, lado=448):
x = transforms.functional.to_tensor(Image.fromarray(img).resize((lado, lado), Image.BICUBIC))
return normaliza(x)[None]
capturado = {}
dino.blocks[-1].attn.register_forward_hook(lambda modulo, entrada, saida: capturado.__setitem__("x", entrada[0]))
@torch.no_grad()
def atencao_ultima_camada(img):
"""Returns the patch features and the last layer's attention weights: (heads, tokens, tokens)."""
feats = dino.forward_features(prepara(img))
a, x = dino.blocks[-1].attn, capturado["x"]
B, N, C = x.shape
qkv = a.qkv(x).reshape(B, N, 3, a.num_heads, C // a.num_heads).permute(2, 0, 3, 1, 4)
q, k = a.q_norm(qkv[0]), a.k_norm(qkv[1])
pesos = (q @ k.transpose(-2, -1) * a.scale).softmax(dim=-1)
return feats[0, N_PREFIXO:], pesos[0]
img_gato = data.chelsea()
feats_gato, att_gato = atencao_ultima_camada(img_gato)
print(f"patch features: {tuple(feats_gato.shape)} attention weights: {tuple(att_gato.shape)}")DINOv2 ViT-S/14 carregado em 1 s: 22 M parâmetros, 12 blocos, 6 cabeças, 5 tokens especiais
features dos patches: (1024, 384) pesos de atenção: (6, 1029, 1029)
gato_448 = np.array(Image.fromarray(img_gato).resize((448, 448)))
linha_olho, coluna_olho = 11, 11 # patch over the left eye
indice_olho = N_PREFIXO + linha_olho * LADO + coluna_olho
mapa_olho = att_gato[:, indice_olho, N_PREFIXO:].mean(0).reshape(LADO, LADO)
mapas_cls = att_gato[:, 0, N_PREFIXO:].reshape(-1, LADO, LADO) # [CLS] attention in each head
fig, axes = plt.subplots(2, 4, figsize=(16, 9))
axes[0, 0].imshow(gato_448)
axes[0, 0].add_patch(Rectangle((coluna_olho * 14, linha_olho * 14), 14, 14, fill=False, edgecolor=LARANJA, lw=3))
axes[0, 0].set_title("chosen patch (orange)")
axes[0, 1].imshow(gato_448)
axes[0, 1].imshow(np.array(Image.fromarray(mapa_olho.numpy()).resize((448, 448), Image.BILINEAR)), cmap="inferno", alpha=0.65)
axes[0, 1].set_title("where this patch looks")
for h in range(6):
ax = axes.flat[2 + h]
ax.imshow(mapas_cls[h], cmap="viridis")
ax.set_title(f"[CLS], head {h + 1}")
for ax in axes.flat:
ax.axis("off")
plt.suptitle("Attention in DINOv2's last layer", y=0.99)
plt.tight_layout()
plt.show()
Reading the plot: the patch on one eye pays attention mainly to the other eye, on the other side of the image. A 3 × 3 convolution would need many layers to relate two such distant regions; attention does it in one operation. Each [CLS] head has specialized in something different: outlines, eyes, ears, background regions.
Nobody told the model what an eye is: DINOv2 has never seen a label. It was trained in a self-supervised way, the subject of the last part.
| CNN (ResNet) | Transformer (ViT) | |
|---|---|---|
| Basic operation | convolution (local filter) | attention (everything with everything) |
| Context | local, grows with depth | global from the 1st layer |
| Built-in knowledge | neighborhood and translation (good with little data) | almost none (needs lots of data) |
| Cost | linear in the number of pixels | quadratic in the number of patches |
| Best when | little data, large images, real time | lots of data, large-scale pre-training |
Everything we’ve trained so far was supervised: someone labeled each image (or each pixel). Labels are expensive, slow and, in Earth observation, scarce: there are petabytes of satellite images, but very few land use masks.
Self-supervised learning (SSL) creates supervision from the data itself, with a “pretext” task:
| Family | Pretext task | Examples |
|---|---|---|
| Masked modeling | hide ~75% of the patches and reconstruct them | MAE (2021), SatMAE (2022), Prithvi (2023) |
| Contrastive | two augmented versions of the same image should have similar representations, and different images distant ones | SimCLR, MoCo (2020), SSL4EO-S12 (2022) |
| Self-distillation | a “student” learns to imitate a “teacher” that sees another version of the image | DINO (2021), DINOv2 (2023), DINOv3 (2025) |
After this pre-training on millions of unlabeled images, the model becomes a foundation model: with a few labeled images, it is adapted (fine-tuning) to specific tasks, exactly as we did with ResNet-50 in class 6’s U-Net.
🗂️ Fact sheet: Self-supervised models (MAE, DINO, DINOv2)
Year 2020–2021 (SimCLR, MoCo, MAE, DINO) and 2023 (DINOv2); still evolving fast (DINOv3 in 2025) Old or new? New generation: the current frontier of the field Type of training self-supervised: millions or billions of images without labels (DINOv2 used 142 million curated images); then supervised adaptation with few labels Why it matters breaks the dependence on labels; the learned representations are so general that they work for classification, segmentation, depth estimation and search without retraining the backbone Strengths takes advantage of abundant unlabeled data (perfect for satellites); rich, transferable representations; few labels needed to adapt to new tasks Limitations pre-training requires a lot of compute (hundreds of GPUs); large models; data and pretext tasks must be chosen carefully; the domain matters (a model trained on photos isn’t ideal for radar) Still used? it’s the path of today’s foundation models, including in Earth observation
We take the features DINOv2 produces for each patch (vectors of 384 numbers) and compress them into 3 numbers with PCA, used as RGB colors. Patches with similar features get similar colors. We also cluster the features with K-means (the technique from the unsupervised learning class) into 5 groups.
Nobody told the model what an eye, a forest or a roof is.
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
def pca_rgb(feats):
rgb = PCA(n_components=3).fit_transform(feats.numpy())
rgb = (rgb - rgb.min(0)) / (rgb.max(0) - rgb.min(0))
return rgb.reshape(LADO, LADO, 3)
ID_AEREO = "M-33-20-D-d-3-3_247" # tile with all 5 classes
img_aerea = io.imread(f"{PASTA_LC}/output/{ID_AEREO}.jpg")
mascara_aerea = io.imread(f"{PASTA_LC}/output/{ID_AEREO}_m.png")[..., 0]
feats_aereo, _ = atencao_ultima_camada(img_aerea)
fig, axes = plt.subplots(2, 4, figsize=(16, 8.3))
for linha, (img, feats, ref, titulo_ref) in enumerate([
(img_gato, feats_gato, None, None),
(img_aerea, feats_aereo, mascara_aerea, "true label (for comparison only)")]):
grupos = KMeans(n_clusters=5, n_init=10, random_state=0).fit_predict(feats.numpy()).reshape(LADO, LADO)
axes[linha, 0].imshow(img); axes[linha, 0].set_title("image")
axes[linha, 1].imshow(pca_rgb(feats)); axes[linha, 1].set_title("DINOv2 features (PCA → RGB)")
axes[linha, 2].imshow(grupos, cmap="tab10", vmin=0, vmax=9, interpolation="nearest"); axes[linha, 2].set_title("K-means, 5 groups (no labels)")
if ref is not None:
axes[linha, 3].imshow(ref, cmap=cmap_lc, vmin=0, vmax=4, interpolation="nearest"); axes[linha, 3].set_title(titulo_ref)
else:
axes[linha, 3].axis("off")
for ax in axes[linha, :3]:
ax.axis("off")
axes[1, 3].axis("off")
plt.suptitle("What DINOv2 learned without any labels", y=0.99)
plt.tight_layout()
plt.show()
Reading the plot: on the cat, the features separate eyes, nose and mouth, fur and background. In the aerial image, forest, water and the area with houses and yards form different groups, with boundaries very close to those of the true label, and the road shows up as a strip between them. DINOv2 wasn’t even trained on aerial images, and K-means doesn’t know the class names (the group colors don’t match the label colors). Even so, it’s almost a segmentation without a single label.
The same idea is being applied to satellite imagery, with models available on Hugging Face:
| Model | Who | Year | Pre-training | On the Hub |
|---|---|---|---|---|
| Prithvi-EO | NASA and IBM | 2023 / 2024 | masked autoencoder (MAE) on Harmonized Landsat Sentinel-2 time series | ibm-nasa-geospatial/Prithvi-EO-2.0-300M |
| SSL4EO-S12 | TU Munich / DLR | 2022 | contrastive and MAE on Sentinel-1 and Sentinel-2 | wangyi111/SSL4EO-S12 |
| Clay | Clay (non-profit) | 2024 | MAE on multiple sensors and resolutions | made-with-clay/Clay |
| DOFA | TU Munich and partners | 2024 | a single model for sensors with different numbers of bands | earthflow/DOFA |
| DINOv3 (satellite) | Meta | 2025 | self-distillation on ~493 million satellite images | facebook/dinov3-vitl16-pretrain-sat493m |
In the next class we’ll see how these models are trained (pretext tasks, masking, self-distillation) and how to adapt them to a real problem with few labels.
| Concept | Key idea |
|---|---|
| Attention | each element looks at all the others, with weights \(\text{softmax}(QK^\top/\sqrt{d})\) |
| Multi-head | several attentions in parallel, each looking for different relationships |
| Transformer block | attention + MLP, each with a residual connection and LayerNorm; dozens of blocks stacked |
| Position | attention ignores order; that’s why we add positional embeddings to the tokens |
| ViT | the image becomes a sequence of patches; global attention from the first layer |
| Self-supervised | learning representations without labels (MAE, DINO) and then adapting with few labels |
| Architecture | Year | Era | Type of training | Strength | Weakness |
|---|---|---|---|---|---|
| Transformer | 2017 | current | supervised → self-supervised | global context, scales with data | quadratic cost, needs lots of data |
| ViT | 2020 | current | supervised → self-supervised | global attention on images | weak with little data |
| DINOv2, MAE, Prithvi | 2021–2025 | new generation | self-supervised | general representations without labels | very expensive pre-training |
BlocoTransformer, remove both residual connections and stack 12 blocks. Does the output still have reasonable values?torch.randn(6, 16)) to X_tok and repeat the token shuffling test. Is the shuffled output still equal to the reordered normal output? Why?