To perform linear probing in Transformers, you evaluate the quality of pre-trained representations by training a simple linear classifier on top of the fixed features extracted from the Transformer. This technique is commonly used in self-supervised learning to assess how informative the learned representations are for downstream tasks. Below is a structured guide on how to implement linear probing in a Transformer-based model (e.g., BERT or Vision Transformer).
Steps to Perform Linear Probing
1. Load the Pre-Trained Transformer Model
Use a pre-trained model from Hugging Face's transformers library or another framework. For example, using BERT:
from transformers import BertModel, BertTokenizer
# Load pre-trained BERT model and tokenizer
model_name = 'bert-base-uncased'
tokenizer = BertTokenizer.from_pretrained(model_name)
base_model = BertModel.from_pretrained(model_name)
2. Freeze the Transformer Parameters
Prevent the Transformer's weights from updating during training:
for param in base_model.parameters():
param.requires_grad = False
3. Add a Linear Classifier
Add a linear layer (e.g., torch.nn.Linear) on top of the Transformer's output. For classification tasks, the [CLS] token is typically used as the aggregated representation:
import torch.nn as nn
class LinearProbe(nn.Module):
def __init__(self, base_model, num_labels):
super().__init__()
self.base_model = base_model
self.classifier = nn.Linear(base_model.config.hidden_size, num_labels)
def forward(self, input_ids, attention_mask):
outputs = self.base_model(input_ids, attention_mask=attention_mask)
cls_embedding = outputs.last_hidden_state[:, 0, :] # [CLS] token
logits = self.classifier(cls_embedding)
return logits
# Example: Binary classification
num_labels = 2
model = LinearProbe(base_model, num_labels)
4. Prepare the Dataset
Tokenize and format your dataset for training:
from torch.utils.data import Dataset, DataLoader
class TextDataset(Dataset):
def __init__(self, texts, labels, tokenizer, max_length=512):
self.texts = texts
self.labels = labels
self.tokenizer = tokenizer
self.max_length = max_length
def __len__(self):
return len(self.texts)
def __getitem__(self, idx):
text = self.texts[idx]
label = self.labels[idx]
encoding = self.tokenizer(text, truncation=True, padding='max_length', max_length=self.max_length, return_tensors='pt')
return {key: val.squeeze(0) for key, val in encoding.items()}, label
# Example usage
texts = ["Sample text 1", "Sample text 2"] # Replace with your dataset
labels = [0, 1] # Replace with your labels
dataset = TextDataset(texts, labels, tokenizer)
dataloader = DataLoader(dataset, batch_size=8, shuffle=True)
5. Train the Linear Classifier
Train only the linear layer while keeping the Transformer frozen:
import torch.optim as optim
import torch
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
# Define optimizer (only train the classifier)
optimizer = optim.Adam(model.classifier.parameters(), lr=1e-3)
criterion = nn.CrossEntropyLoss()
# Training loop
model.train()
for epoch in range(5): # Number of epochs
for batch in dataloader:
inputs, labels = batch
input_ids = inputs['input_ids'].to(device)
attention_mask = inputs['attention_mask'].to(device)
labels = labels.to(device)
optimizer.zero_grad()
logits = model(input_ids, attention_mask)
loss = criterion(logits, labels)
loss.backward()
optimizer.step()
print(f"Epoch {epoch+1}, Loss: {loss.item()}")
6. Evaluate the Model
Test the linear probe on a validation/test set to measure representation quality:
model.eval()
correct = 0
total = 0
with torch.no_grad():
for batch in dataloader:
inputs, labels = batch
input_ids = inputs['input_ids'].to(device)
attention_mask = inputs['attention_mask'].to(device)
labels = labels.to(device)
logits = model(input_ids, attention_mask)
predictions = torch.argmax(logits, dim=1)
total += labels.size(0)
correct += (predictions == labels).sum().item()
print(f"Accuracy: {100 * correct / total}%")
Key Considerations
- Representation Choice: Use the
[CLS] token for BERT-like models. For Vision Transformers (ViT), use the [CLS] token or average patch embeddings.
- Learning Rate: Experiment with the learning rate for the linear layer (e.g.,
1e-3 to 1e-1).
- Regularization: Add L2 regularization to the linear layer if overfitting occurs.
- Pooling Methods: Alternative pooling strategies (e.g., average/max pooling) may improve performance depending on the task.
Why Use Linear Probing?
Linear probing isolates the quality of the pre-trained representations by avoiding complex fine-tuning. If a linear model achieves high accuracy, it indicates the Transformer has learned meaningful, task-specific features.
By following these steps, you can effectively evaluate and leverage Transformer models for downstream tasks using linear probing.