Dự đoán
Vision Transformer (ViT): chia ảnh 224×224 thành lưới patches 16×16, mỗi patch flatten → linear projection → embedding. 196 patches = 196 'tokens'. Thêm [CLS] token + positional encoding → đưa vào Transformer encoder. Patches = tokens!
Evaluating routing across providers.
AI Researcher
Áp dụng kiến trúc Transformer trực tiếp cho hình ảnh bằng cách chia ảnh thành các patch
Vision Transformer (ViT): chia ảnh 224×224 thành lưới patches 16×16, mỗi patch flatten → linear projection → embedding. 196 patches = 196 'tokens'. Thêm [CLS] token + positional encoding → đưa vào Transformer encoder. Patches = tokens!
Hãy tưởng tượng bạn có tấm ảnh chụp phố cổ Hội An và cắt thành 9 mảnh ghép (jigsaw). Mỗi mảnh tự hỏi: "Mảnh nào liên quan đến tôi?" — đó là self-attention! Mảnh có đèn lồng sẽ "chú ý" đến mảnh có phố — dù chúng cách xa nhau.
ViT coi ảnh là chuỗi patches, giống Transformer coi văn bản là chuỗi tokens. Patches = tokens! Self-attention cho mỗi patch "nhìn" toàn bộ ảnh ngay từ lớp đầu tiên — CNN phải xếp nhiều lớp mới "nhìn xa" được.
14 × 14 = 196 patches. Thêm 1 [CLS] token = 197. Attention matrix: 197 × 197 = ~39K elements — rất nhẹ! So sánh: nếu mỗi pixel 1 token → 50K tokens → attention 2,5 tỷ elements. Patches là cách brilliant để giữ sequence ngắn.
Vision Transformer (ViT) (Dosovitskiy et al., 2020) chứng minh kiến trúc Transformer thuần túy (không CNN) đạt SOTA trên image classification nhờ self-attention trên các patch ảnh.
= patch flatten, = linear projection, = positional embedding.
import torch
import torch.nn as nn
class ViT(nn.Module):
def __init__(self, img_size=224, patch_size=16, d_model=768,
n_layers=12, n_heads=12, num_classes=1000):
super().__init__()
n_patches = (img_size // patch_size) ** 2 # 196
# Patch embedding: flatten patch → linear projection
self.patch_embed = nn.Conv2d(
3, d_model, kernel_size=patch_size, stride=patch_size
) # (B, 3, 224, 224) → (B, 768, 14, 14)
self.cls_token = nn.Parameter(torch.zeros(1, 1, d_model))
self.pos_embed = nn.Parameter(torch.zeros(1, n_patches + 1, d_model))
# Transformer encoder
encoder_layer = nn.TransformerEncoderLayer(
d_model=d_model, nhead=n_heads, batch_first=True
)
self.transformer = nn.TransformerEncoder(encoder_layer, n_layers)
self.head = nn.Linear(d_model, num_classes)
def forward(self, x):
B = x.shape[0]
# 1. Patch embedding
x = self.patch_embed(x).flatten(2).transpose(1, 2) # (B, 196, 768)
# 2. Prepend [CLS] token
cls = self.cls_token.expand(B, -1, -1)
x = torch.cat([cls, x], dim=1) # (B, 197, 768)
# 3. Add positional encoding
x = x + self.pos_embed
# 4. Transformer
x = self.transformer(x)
# 5. [CLS] output → classification
return self.head(x[:, 0])