Lecture 26: Self-Supervised Learning (CS 189, Fall 2026)
In [ ]:
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision as tv
import torchvision.transforms as transforms
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
import seaborn as sns
import time
style.use('fivethirtyeight')
sns.set(style='whitegrid', color_codes=True)
torch.manual_seed(189)
np.random.seed(189)
# Check if GPU is available
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f'Using device: {device}')
In [ ]:
cifar_tf = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.247, 0.243, 0.261))
])
In [ ]:
# Load CIFAR-10 dataset
train_set = tv.datasets.CIFAR10(root='./data', train=True, download=True, transform=cifar_tf)
test_set = tv.datasets.CIFAR10(root='./data', train=False, download=True, transform=cifar_tf)
classes = train_set.classes
# Keep everything in memory as tensors (small enough for a demo)
X_train = torch.stack([x for x, _ in train_set])
y_train = torch.tensor(train_set.targets)
X_test = torch.stack([x for x, _ in test_set])
y_test = torch.tensor(test_set.targets)
print(f'Train: {tuple(X_train.shape)}, Test: {tuple(X_test.shape)}')
In [ ]:
def show(imgs, titles=None, n_cols=8):
mean = torch.tensor([0.4914, 0.4822, 0.4465]).view(3, 1, 1)
std = torch.tensor([0.247, 0.243, 0.261]).view(3, 1, 1)
n_rows = (len(imgs) + n_cols - 1) // n_cols
fig, axes = plt.subplots(n_rows, n_cols, figsize=(1.6 * n_cols, 1.8 * n_rows))
for i, ax in enumerate(np.array(axes).flatten()):
ax.axis('off')
if i < len(imgs):
ax.imshow((imgs[i].cpu() * std + mean).clamp(0, 1).permute(1, 2, 0))
if titles is not None:
ax.set_title(titles[i], fontsize=10)
plt.tight_layout()
plt.show()
show(X_train[:16], [classes[y] for y in y_train[:16]])
The Setup: Lots of Images, Few Labels¶
We keep 100 labels per class (1,000 total) and treat the rest of the training set as unlabeled.
In [ ]:
g = torch.Generator().manual_seed(0)
labeled_idx = torch.cat([torch.where(y_train == c)[0][torch.randperm(5000, generator=g)[:100]]
for c in range(10)])
X_unlabeled = X_train[torch.randperm(50000, generator=g)[:20000]] # unlabeled pool: labels never used
print(f'Labeled: {len(labeled_idx)}, Unlabeled pool: {len(X_unlabeled)}')
Encoder and Linear Probe¶
The encoder turns an image into a 512-d feature vector. To measure feature quality, we freeze the encoder and train only a linear classifier on the 1,000 labeled images.
In [ ]:
class Encoder(nn.Module):
def __init__(self):
super().__init__()
block = lambda c_in, c_out: [nn.Conv2d(c_in, c_out, 3, padding=1),
nn.BatchNorm2d(c_out), nn.ReLU(), nn.MaxPool2d(2)]
self.conv = nn.Sequential(*block(3, 32), *block(32, 64), *block(64, 128),
nn.AdaptiveAvgPool2d(2))
def forward(self, x):
return self.conv(x).flatten(1) # 128 x 2 x 2 = 512 features
In [ ]:
@torch.no_grad()
def features(encoder, X):
encoder.eval()
return torch.cat([encoder(X[i:i + 1000].to(device)).cpu() for i in range(0, len(X), 1000)])
def linear_probe(encoder):
"""Freeze the encoder, fit a linear classifier on the labeled images, report test accuracy."""
F_tr, F_te = features(encoder, X_train[labeled_idx]), features(encoder, X_test)
mu, sd = F_tr.mean(0), F_tr.std(0) + 1e-6
F_tr, F_te = (F_tr - mu) / sd, (F_te - mu) / sd
torch.manual_seed(0)
clf = nn.Linear(512, 10)
opt = optim.Adam(clf.parameters(), lr=1e-2, weight_decay=1e-2)
for _ in range(300):
loss = nn.functional.cross_entropy(clf(F_tr), y_train[labeled_idx])
opt.zero_grad(); loss.backward(); opt.step()
return (clf(F_te).argmax(1) == y_test).float().mean().item()
Baseline: A Random Encoder¶
In [ ]:
results = {}
torch.manual_seed(1)
random_encoder = Encoder().to(device)
results['Random encoder'] = linear_probe(random_encoder)
print(f"Random encoder: {results['Random encoder']:.1%}")
Pretext Task 1: Guess the Brightness¶
A free label: which brightness quartile is the image in? We never look at the class labels.
In [ ]:
def pretrain(make_batch, epochs=3, batch_size=256):
"""Train an encoder + 4-way head on a pretext task built from unlabeled images."""
torch.manual_seed(1)
encoder = Encoder().to(device)
model = nn.Sequential(encoder, nn.Linear(512, 4)).to(device)
opt = optim.Adam(model.parameters(), lr=1e-3)
start = time.time()
for epoch in range(epochs):
model.train()
perm = torch.randperm(len(X_unlabeled))
total, correct = 0.0, 0
for i in range(0, len(perm), batch_size):
x, y = make_batch(perm[i:i + batch_size])
logits = model(x.to(device))
loss = nn.functional.cross_entropy(logits, y.to(device))
opt.zero_grad(); loss.backward(); opt.step()
total += loss.item() * len(y)
correct += (logits.argmax(1).cpu() == y).sum().item()
print(f'Epoch {epoch + 1}: pretext loss {total / len(perm):.3f}, '
f'pretext accuracy {correct / len(perm):.0%} ({time.time() - start:.0f}s)')
return encoder, model
In [ ]:
brightness = X_unlabeled.mean(dim=(1, 2, 3))
cutoffs = torch.quantile(brightness, torch.tensor([0.25, 0.5, 0.75]))
def brightness_batch(idx):
return X_unlabeled[idx], torch.bucketize(brightness[idx], cutoffs)
bright_encoder, _ = pretrain(brightness_batch)
results['Brightness pretext'] = linear_probe(bright_encoder)
print(f"Brightness pretext: {results['Brightness pretext']:.1%}")
Pretext Task 2: Guess the Rotation¶
Rotate each image by 0°, 90°, 180°, or 270° and ask which one. To answer, the network has to know which way is up for a cat, a ship, a truck.
In [ ]:
def rotate_batch(idx):
x = X_unlabeled[idx]
k = torch.randint(0, 4, (len(x),))
out = x.clone()
for r in range(1, 4):
out[k == r] = torch.rot90(x[k == r], r, dims=(2, 3))
return out, k
x_rot, k_rot = rotate_batch(torch.arange(8))
show(x_rot, [f'{90 * int(k)}°' for k in k_rot])
In [ ]:
rot_encoder, rot_model = pretrain(rotate_batch)
results['Rotation pretext'] = linear_probe(rot_encoder)
print(f"Rotation pretext: {results['Rotation pretext']:.1%}")
Same Labels, Different Problems¶
In [ ]:
plt.figure(figsize=(8, 4))
names = list(results.keys())
bars = plt.bar(names, [100 * results[n] for n in names], color=['gray', 'C1', 'C0'])
plt.bar_label(bars, fmt='%.1f%%')
plt.ylabel('Test accuracy (%)')
plt.title('Linear probe with 100 labels per class')
plt.ylim(0, 60)
plt.show()
Where Is "Which Way Is Up" Hard to Tell?¶
Pretext accuracy on rotated test images, by class.
In [ ]:
@torch.no_grad()
def rotation_accuracy_by_class(model):
model.eval()
k = torch.randint(0, 4, (len(X_test),), generator=torch.Generator().manual_seed(0))
x = X_test.clone()
for r in range(1, 4):
x[k == r] = torch.rot90(X_test[k == r], r, dims=(2, 3))
pred = torch.cat([model(x[i:i + 1000].to(device)).argmax(1).cpu() for i in range(0, len(x), 1000)])
return [(pred[y_test == c] == k[y_test == c]).float().mean().item() for c in range(10)]
acc_by_class = rotation_accuracy_by_class(rot_model)
order = np.argsort(acc_by_class)
plt.figure(figsize=(10, 4))
plt.bar([classes[i] for i in order], [100 * acc_by_class[i] for i in order])
plt.ylabel('Rotation accuracy (%)')
plt.xticks(rotation=30)
plt.show()
print(', '.join(f'{classes[i]} {acc_by_class[i]:.0%}' for i in order))