← Index
Computer Vision · Module 03

🔀
Transfer
Learning

Học chuyển giao trong Computer Vision — từ Feature Extraction đến Foundation Models và kỷ nguyên 2025+.

01 Nền tảng cốt lõi02 Kiến trúc Backbone03 Quy trình Fine-tuning04 Vấn đề thường gặp05 Foundation Models 2025
SCROLL

01Bản chất cốt lõi

Tái sử dụng
tri thức
đã học.

Trong ML truyền thống, training data và test data phải cùng phân phối — một giả định hiếm khi thỏa mãn trong thực tế. Transfer Learning phá vỡ rào cản này bằng cách tái dùng weights từ một bài toán nguồn quy mô lớn (ImageNet: 1.2M ảnh, 1000 lớp) để giải quyết bài toán đích có dữ liệu hạn chế.

Lớp nông (shallow): Cạnh, góc, dải màu — giống bộ lọc Gabor
Lớp vừa (mid): Kết cấu (texture), hình khối vật thể
Lớp sâu (deep): Biểu diễn trừu tượng, ngữ nghĩa cụ thể theo task
Traditional ML vs Transfer Learning

Truyền thống: N datasets độc lập → Transfer: Knowledge base tái sử dụng

01.2Hai chiến lược triển khai

Feature Extraction vs Fine-tuning

Feature Extraction
🔒

Feature Extraction

Toàn bộ convolutional base bị frozen — autograd không cập nhật weights. Chỉ thay lớp classifier cuối và train phần đó. Backbone là bộ lọc tĩnh.

Tốc độ train cực nhanh
VRAM tối thiểu (không lưu gradient backbone)
Kháng overfit mạnh trên data nhỏ
Ổn định, ít rủi ro
Kém thích ứng nếu domain khác xa ImageNet
Có thể underfit nếu target domain quá đặc thù
DÙNG KHI: Dataset nhỏ (<1000/class) · Domain giống ImageNet
Fine-tuning
🔓

Fine-tuning

Sau bước warmup, rã đông (unfreeze) một phần hoặc toàn bộ backbone để cập nhật weights theo loss của task đích. Can thiệp sâu vào biểu diễn đặc trưng.

Độ chính xác vượt trội
Domain-specific adaptation
Tận dụng tối đa sức mạnh model
Đòi hỏi data lớn hơn
Nguy cơ catastrophic forgetting nếu LR cao
Train lâu hơn, VRAM lớn hơn
DÙNG KHI: Dataset lớn (>10K/class) · Muốn đẩy tới SOTA
Overview: Feature Transfer vs Fine-tuning — Parameters frozen vs updated
Feature Transfer vs Fine-tuning overview

01.3Ma trận quyết định

Chọn chiến lược đúng dựa trên 2 trục.

Hai trục chính: Dataset Size (kích thước dữ liệu đích) và Domain Similarity (độ tương đồng giữa miền nguồn và đích). Đánh giá domain bằng LEEP hoặc LogME trước khi training.

Data lớn · Domain cao

Full Fine-tuning

Đủ data điều chỉnh mọi param không sợ memorize noise. LR nhỏ, đẩy tới SOTA.

Data lớn · Domain thấp

Fine-tune sâu / Train lại

Weights ImageNet chỉ là điểm khởi tạo tốt. Unfreeze toàn bộ hoặc train scratch.

Data nhỏ · Domain cao

Feature Extraction

Domain tương đồng → features bậc cao vẫn dùng được. Chỉ train linear head.

Data nhỏ · Domain thấp

Partial Fine-tune + Regularize

Freeze lớp nông, unfreeze vài lớp sâu. Áp dụng Dropout, Weight Decay nghiêm ngặt.

Decision matrix

Sai chiến lược = lãng phí GPU và overfit. Dùng LEEP (Log Expected Empirical Prediction) hoặc LogME để đo transferability mà không cần train thử.

02Backbone Architectures

CNNs vs Vision Transformers

CONVOLUTIONAL NEURAL NETWORKS — Inductive bias mạnh, hiệu quả trên data nhỏ

CNN

ResNet-50

Skip connections giải quyết vanishing gradient. Baseline ổn định cho mọi tác vụ. Tốt trong chẩn đoán y tế, trích xuất đặc trưng cục bộ.

CNN

EfficientNetV2

Compound scaling đồng đều depth + width + resolution (NAS). Fused-MBConv tăng tốc train. Balance acc/VRAM/latency tốt nhất cho dataset nhỏ-vừa.

CNN

ConvNeXt

CNN hiện đại hoá theo ViT: GELU, LayerNorm, large-kernel depthwise, patchify stem. Duy trì inductive bias + đạt acc ngang Swin ở cùng budget.

VISION TRANSFORMERS — Global self-attention, tổng quát hóa cao

ViT

ViT (standard)

Chia ảnh thành patches 16×16, xử lý qua transformer. Self-Attention toàn cục từ lớp đầu. Cần pre-train lớn (JFT-300M), nhưng features khi TL rất flexible, shape bias cao.

ViT

Swin Transformer

Shifted window attention: tính attention trong cửa sổ cục bộ, dịch chuyển ranh giới giữa các lớp. Hierarchical feature maps, độ phức tạp tuyến tính. Lý tưởng cho detection/segmentation.

TIÊU CHÍCNNsViTs
Phụ thuộc data fine-tuneRất thấp ✦Tương đối cao
Robustness domain shiftKháXuất sắc ✦ (shape bias)
Inference latency / EdgeTối ưu ✦ (TensorRT, CoreML)Nặng hơn
Global contextHạn chếVượt trội ✦
Dense predictionTốtXuất sắc ✦ (Swin)

03.1Chuẩn bị dữ liệu

Preprocessing & Augmentation

📐 Data Preprocessing

Resizing & Cropping

Resize về 224×224 hoặc 384×384. Giữ aspect ratio tự nhiên, tránh biến dạng đối tượng chính.

Normalization — BẮTBUỘC

Phải normalize theo thống kê ImageNet: Mean=[0.485,0.456,0.406]Std=[0.229,0.224,0.225]. Bỏ qua → distribution shift ngay tại lớp đầu vào.

🎲 Data Augmentation Nâng cao

MixUp

Nội suy tuyến tính 2 ảnh + nhãn one-hot. Decision boundaries mượt hơn, giảm overconfidence.

CutMix

Cắt patch từ ảnh này dán lên ảnh kia, nhãn mix theo diện tích. Ép model phân tích toàn cấu trúc, không chỉ 1 vùng.

RandAugment

Chọn ngẫu nhiên chuỗi transform với cường độ định sẵn. Đặc biệt tốt với ViTs cần data đa dạng.

03.2 – 03.3Freezing · BN · Learning Rate

Quy trình Fine-tuning an toàn

1️⃣ Gradual Unfreezing

Giai đoạn 1 — Warmup Head

Freeze toàn bộ backbone. Train classifier mới 1-2 epochs để weights ngẫu nhiên hội tụ về trạng thái ổn định.

Giai đoạn 2 — Top-Down Unfreeze

Loss ổn định → unfreeze dần từ lớp sâu nhất lên. Lớp sâu chứa task-specific features, lớp nông chỉ cần cạnh/màu sắc chung.

⚠️ Batch Normalization Trap

BN ở training mode liên tục cập nhật running_mean / running_var. Nếu data đích phân phối khác → statistics sai lệch → phá vỡ cân bằng gamma/beta ImageNet.

FIX: Ép BN layers ở eval() mode

for m in model.modules():
if isinstance(m, BN):
m.eval()

📈 Learning Rate Strategy

Differential LR (phân tầng)

Classifier head1e-3 → 1e-4
Deep blocks1e-5
Shallow blocks1e-6

Cosine Annealing + Linear Warmup

Warmup: tăng LR từ ~0 tuyến tính trong 10% steps đầu → tránh "gradient shock". Cosine decay: giảm mượt, tránh local minima, hội tụ tối ưu.

convnext_finetune.py — ConvNeXt Fine-tuning với Gradual Unfreezing
# 1. Load model + thay classifier
weights = ConvNeXt_Base_Weights.IMAGENET1K_V1
model = convnext_base(weights=weights)
model.classifier = nn.Linear(model.classifier.in_features, NUM_CLASSES)

# 2. Gradual Unfreezing + Bảo vệ BN
def configure_fine_tuning(model, unfreeze_blocks=2):
    for param in model.parameters():      # Freeze all
        param.requires_grad = False
    for param in model.classifier.parameters():   # Unfreeze head
        param.requires_grad = True
    for block in model.features[-unfreeze_blocks:]:  # Unfreeze deep blocks
        for param in block.parameters():
            param.requires_grad = True
    for m in model.modules():             # Lock BN stats
        if isinstance(m, (nn.BatchNorm2d, nn.LayerNorm)):
            m.eval()
            m.weight.requires_grad = False
            m.bias.requires_grad = False

# 3. Differential LR với AdamW
optimizer = optim.AdamW([
    {'params': model.classifier.parameters(), 'lr': 1e-3},
    {'params': model.features[-2:].parameters(), 'lr': 1e-5},
], weight_decay=1e-4)

# 4. Cosine Annealing + Linear Warmup
scheduler = get_cosine_schedule_with_warmup(
    optimizer,
    num_warmup_steps=int(0.1 * total_steps),
    num_training_steps=total_steps
)

# 5. Training loop — BN luôn eval() đầu mỗi epoch
for epoch in range(epochs):
    model.train()
    for m in model.modules():
        if isinstance(m, (nn.BatchNorm2d, nn.LayerNorm)):
            m.eval()
    for inputs, labels in dataloader:
        loss = criterion(model(inputs), labels)
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        optimizer.step(); scheduler.step(); optimizer.zero_grad()

04Các vấn đề thường gặp

Pitfalls & Solutions

😵 Overfitting

Model hàng triệu params 'ghi nhớ' hoàn toàn dataset nhỏ, không học được đặc trưng khái quát.

Model Simplification

Dùng ConvNeXt-Tiny, MobileNetV3 thay vì ViT-Large — giảm capacity, ép model lọc thông tin

Dropout + Weight Decay

AdamW với weight_decay=1e-4. Phạt weights lớn, phân bổ tri thức đồng đều

Early Stopping

Giám sát Validation Loss, dừng khi bắt đầu tăng (hình chữ U)

🔄 Negative Transfer

Khi source domain và target domain quá khác biệt, weights cũ áp đặt thiên kiến sai → hiệu suất còn tệ hơn train từ đầu.

LEEP (Log Expected Empirical Prediction)

Đo log-likelihood giữa label distributions. Không cần train lại, phát hiện sớm nguy cơ negative transfer

LogME (Logarithm of Maximum Evidence)

Đánh giá liên kết features↔labels đích. Chi phí tính toán cực thấp

RED (Reducing Environmental Disagreement)

Adversarial network tách domain-invariant vs non-causal features

🌊 Domain Shift

Model hoạt động tốt trong lab nhưng giảm hiệu suất nghiêm trọng khi deploy vào môi trường thực (khác ánh sáng, nhiễu, góc chụp).

Unsupervised Domain Adaptation (UDA)

Domain Discriminator học features bất biến giữa source và target — không cần nhãn target

Test-Time Adaptation (TTA)

Fine-tune online trực tiếp lúc inference: chỉ cập nhật BN gamma/beta + Entropy Minimization để tăng confidence

05Xu hướng tương lai · 2025+

Fine-tuning truyền thống đang biến mất.

Thay vì fine-tune hàng triệu params tốn kém, Foundation Models mở ra kỷ nguyên Prompt Engineering: chỉ cần thiết kế câu prompts (text/visual) để hướng dẫn model làm task mới — không cần training.

MAE — Masked Autoencoder: mask 75% patches → reconstruct → rich representations

MAE — Masked Autoencoder: mask 75% patches → reconstruct → rich representations

DINOv2 — Self-distillation: Teacher-Student + Sinkhorn + KoLeo → SOTA features

DINOv2 — Self-distillation: Teacher-Student + Sinkhorn + KoLeo → SOTA features

🔗CLIP

Contrastive Language-Image Pretraining (OpenAI). Embedding text+image chung 1 space. Zero-shot classification: mô tả class bằng text prompt, so similarity cosine với image embedding — không cần label.

✂️SAM

Segment Anything Model (Meta). Huấn luyện trên SA-1B: 11M ảnh, 1 tỷ masks. Promptable: click / bbox / text → mask tức thì. Thay thế Mask R-CNN / U-Net mà không cần fine-tune.

🎭MAE

Masked Autoencoders (He et al.). Mask 75% patches ngẫu nhiên → ViT encoder-decoder reconstruct pixel. Học spatial relationships tinh vi. Representations ổn định khi fine-tune downstream tasks.

🦕DINOv2

Distillation with No Labels v2 (Meta AI). Teacher-Student self-distillation + Sinkhorn normalization + KoLeo regularizer. Frozen features đánh bại supervised fine-tuning trên nhiều dense prediction tasks — 2025 SOTA.

2026 Trend: Kết hợp frozen DINOv2 features + SAM segmentation + CLIP zero-shot — pipeline "Transfer Learning không cần training" — biến mọi tác vụ vision thành bài toán Prompt Engineering thuần tuý.