Lesson 14 of 186 min
Self-supervised learning
Hide part of the data and train the network to fill it in: the answer comes from the data itself, so no one has to write a label.
After this lesson you can explain how a model learns from data with no labels.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Pick what to hide
Each image has eight rows and eight columns. A right-half mask selects the last four columns of every row. The original pixels in those columns supply the answers. Make the split before training so you can score the network on pictures it hasn't seen.
import torch
from torch import nn
from torch.nn import functional as F
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
digits = load_digits()
x = torch.tensor(digits.data, dtype=torch.float32) / 16
train, test, labels, answers = train_test_split(x, torch.tensor(digits.target), test_size=.2, random_state=0, stratify=digits.target)
right = torch.arange(64) % 8 >= 4
print(train.masked_fill(right, 0)[:1].shape, train[:1, right].shape)torch.Size([1, 64]) torch.Size([1, 32])
Check what transfers
Give two classifiers the same five labeled pictures per digit. Freeze the reconstruction encoder for the first and train the second from scratch. In this run, the frozen encoder gave 71.9% accuracy, and the network trained on the labels reached 84.2%. Filling in pixels and telling digits apart reward different features.
torch.manual_seed(0)
torch.set_num_threads(4)
encoder = nn.Sequential(nn.Linear(64, 32), nn.ReLU())
rebuild = nn.Sequential(encoder, nn.Linear(32, 64))
opt = torch.optim.Adam(rebuild.parameters(), lr=.001)
for _ in range(30):
for ids in torch.randperm(len(train)).split(32):
opt.zero_grad()
F.mse_loss(rebuild(train[ids].masked_fill(right, 0))[:, right], train[ids][:, right]).backward()
opt.step()few = torch.cat([torch.where(labels == digit)[0][:5] for digit in range(10)])
encoder.requires_grad_(False)for body in (encoder, nn.Sequential(nn.Linear(64, 32), nn.ReLU())):
torch.manual_seed(0)
model = nn.Sequential(body, nn.Linear(32, 10))
opt = torch.optim.Adam(model.parameters(), lr=.001)
for _ in range(200):
opt.zero_grad()
F.cross_entropy(model(train[few]), labels[few]).backward()
opt.step()
print(f"{(model(test).argmax(1) == answers).float().mean():.1%}")71.9% 84.2%
Check for collapse
A loss that only pulls same-image crops together can score identical descriptions perfectly. Check whether their values vary across images. DINOv2 uses a slowly updated teacher, balances its scores, and adds a loss that spreads image features out. This small check catches the all-identical case.
descriptions = encoder(test).detach()
constant = descriptions[:1].expand_as(descriptions)
print("Learned spread:", round(descriptions.std(dim=0, unbiased=False).mean().item(), 3))
print("Collapsed spread:", round(constant.std(dim=0, unbiased=False).mean().item(), 3))Learned spread: 0.163 Collapsed spread: 0.0
Make the answer a rotation
Another task is to turn each picture and ask the network how far you turned it. The turn you chose supplies the answer. Try it on digits, then look at a six or a nine turned halfway around. The task can be ambiguous when the picture itself doesn't reveal which turn you chose.
image = train[0].reshape(8, 8)
turns = torch.arange(4)
views = torch.stack([torch.rot90(image, int(turn), dims=(0, 1)) for turn in turns])
print(views.shape, (turns * 90).tolist())torch.Size([4, 8, 8]) [0, 90, 180, 270]
Run on Python 3.13, PyTorch 2.15.0, scikit-learn 1.9.1. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: The training loop
The loader shuffles the 1,437 training pictures and hands them out in batches of 64. Training runs for 10 epochs. How many steps does it take in all?
2 of 3
One network fills in one hidden pixel of each digit; another, the hidden bottom half. A rule that only looks at the 8 pixels next door fills in the one pixel almost as well. Which network had to learn what digits look like?
3 of 3
A sentence is five tokens. One line turns it into questions and answers, as in the lesson. What does this print?
tokens = [5, 9, 2, 7, 1]
x, y = tokens[:-1], tokens[1:]
print(x[2], y[2])The ideas in this lesson
- Self-supervised learning
- Hide part of the data and train the network to fill it in: the answer comes from the data, not from people.
- A task hard enough
- If the hidden part can be filled in from what is next to it, little is learned; hide enough that it must know the data.
- Learning from two views
- Two crops of one photo must get close descriptions; keep other photos apart, or all collapse into one.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
No labels
Here's a puzzle. The pictures in this course came with labels. People wrote down the answer for each one. Most photos and text have no labels at all. So how can a network learn from them?
Fill in the bottom
Let's try one. A network sees each digit with its bottom half hidden, and it has to fill that half in. No labels at all. After thirty epochs, what will it draw there? The bottoms of digits, a gray blur, or nothing at all?
What labels were for
First, what were the labels for? The training loop compares the network's answer with the right one. The loss says how wrong it is. For the digits, people wrote each answer down. But the photos and the text on the web have no answers written down.
Hide a part
So could the data hold its own answers? Hide the bottom half of each digit. Set those pixels to zero. Then ask the network to fill them in.
It's like a page with coffee spilled on it. You can figure out the hidden words, because the page itself holds the answer.
The answer is the hidden half, cut from the picture itself. The loss is the squared miss on the hidden pixels. It's the training loop you know. But no label is used.
It learns
So, your guess.
After two epochs, it draws a gray blur.
After thirty... it draws a round bottom under the top of a zero, and a flat stroke under the top of a two.
Measure its miss on the pictures set aside, which it never learns from. It's about zero point zero five. A network that always drew the average of all the digits would miss by about zero point zero eight. To fill the half in, it had to learn what digits look like.
Answers from the data
The answers came from the data itself, not from people. That's self-supervised learning.
The next token
Is that how language models learn too? Yes. A language model reads text as tokens, small pieces of words. Hide the next token, and ask for it. So every text holds its own questions and answers. Many large language models, or LLMs, start by learning this way. The largest can train on trillions of tokens.
Too easy
So far, we've hidden part of the data and trained a network to fill it in. But does any hidden part work?
Hide just one pixel. The network misses it by just under zero point zero four.
Now take a simple rule. It only looks at the eight pixels next to it, and knows nothing about digits. It misses by zero point zero four. Almost the same.
So what did the network need to know?
Almost nothing about digits. Filling in one pixel is an easy job, so the network doesn't learn much from it. For the bottom half, the pixels next door are hidden too. A task that's too easy doesn't teach much. That's why masked autoencoders hide three quarters of a photo.
Two crops
Self-supervised learning makes its answers from the data. But is hiding the only way?
No. Cut two different crops from one photo: one of a penguin's head, one of its feet on the ice.
Each crop goes through the network, and comes out as a description: the numbers of a hidden layer. Train the network so the two descriptions come out close. To match a head and feet, the network has to find what they share: one penguin.
Collapse
So what could go wrong?
Give every photo the same description. Then any two crops match. A perfect score... and nothing learned. That's called collapse.
One way to stop that is to add a second rule: keep the descriptions of different photos apart.
Both at once
DINOv2 learned from over a hundred million photos, with no labels.
It uses both ideas at once. Two crops have to agree, and the network predicts a description of each hidden square. Its makers used those descriptions for other tasks, like telling what's in a picture. The network could stay as it was.
In code
In code, a sentence's tokens are numbers. This sentence is seven tokens. One line makes the questions and the answers: every token but the last, and every token but the first. How many pairs does that make?
Six. Each token is an answer, and the tokens before it are its question.
For the digits: a digit is sixty-four pixels, so its bottom half is the last thirty-two.
Copy the pictures, and set those last pixels to zero. Then score what the network fills in only on those thirty-two.
On the pictures set aside, that's our miss of about zero point zero five.
From the data itself
So, hide part of the data and fill it in, or make two crops agree. Either way, the answers come from the data itself.
Fill it in
Hide part of the data, and learn to fill it in. Now try it on this lesson's page, and take the quiz. Find the bottom half that's hardest to fill in.
You use this lesson in Lab 6: A tiny word maker, taught by rewards, after Reinforcement learning.
Facts last checked on .
