🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Transfer Learning Pipeline

AI System DesignTransfer LearningđŸŸĸ Free Lesson

Transfer Learning Pipeline

What You'll Learn

  • 1Decide between feature extraction, layer-wise unfreezing and full fine-tuning from data size
  • 2Compute LoRA parameter counts and the trainable fraction for a target model
  • 3Estimate fine-tuning FLOPs with the 6 x P x T rule and convert to GPU hours
  • 4Recognize domain shift and catastrophic forgetting as failure modes

Why This Matters

Transfer learning leverages knowledge from pre-trained models to solve new tasks with limited data. It dramatically reduces training time, data requirements, and compute costs. Understanding transfer learning pipelines is essential for building production ML systems efficiently.


Architecture Overview

Transfer Learning Pipeline ArchitecturePre-trained Model HubResNetBERTGPTViTCLIPT5WhisperModel Selection and Task MatchingTask SimilarityDomain SimilarityData Size MatchingCompute BudgetFine-Tuning StrategiesFull Fine-TuningUpdate all layersHigh compute, max flexibilityFeature ExtractionFreeze base layersTrain only classifier headLayer-wise UnfreezingGradually unfreeze layersBottom-up approachAdapter ModulesInsert small adapter layersParameter-efficientLoRALow-RankAdaptationDomain AdaptationAdversarial TrainingDomain-Adversarial NetsCorrelation AlignmentSelf-Training / Pseudo-LabelsFew-Shot and Prompt TuningMeta-Learning (MAML)Prompt EngineeringIn-Context LearningPrefix TuningAdapted Model - Deployment (Model Serving)Validation | Compression | Monitoring | A/B Testing

Core Components

1. Transfer Learning Pipeline

The transfer learning pipeline manages the full workflow from source model to adapted target model:

  • Model selection: Scores pre-trained models based on task similarity, domain similarity, data size requirements, and compute budget.
  • Strategy selection: Chooses between full fine-tuning, feature extraction, layer-wise unfreezing, adapter modules, or LoRA based on dataset size and similarity.
  • Layer freezing: In feature extraction mode, all layers except the classification head are frozen. In layer-wise mode, layers are unfrozen gradually from top to bottom.
  • Trainable parameter counting: Tracks the number of unfrozen parameters to estimate compute requirements.
  • Transfer evaluation: Measures transfer gap (accuracy drop from source task), data efficiency, training speedup, and parameter efficiency.

2. LoRA (Low-Rank Adaptation)

LoRA freezes the original model weights and trains only low-rank decomposition matrices:

  • Low-rank decomposition: Instead of updating a full weight matrix W (d x d), LoRA learns two small matrices A (d x rank) and B (rank x d) where rank << d.
  • Forward pass: The output is original_output + x @ A @ B * scaling where scaling = alpha / rank.
  • Weight merging: After training, LoRA weights can be merged into the original weights: W_merged = W + A @ B * scaling.
  • Parameter efficiency: Reduces trainable parameters by 10-100x while maintaining 95%+ of full fine-tuning performance.

3. Few-Shot Learning

Few-shot learning enables classification with very few examples per class:

  • Episode-based training: Each training episode samples K support examples per class (K-shot) and Q query examples.
  • Prototype networks: Computes class prototypes as the mean of support embeddings, then classifies queries by nearest prototype distance.
  • Meta-learning: Trains across many episodes so the model learns to learn from few examples.
  • Evaluation: Reports accuracy averaged across many test episodes.

4. Prompt Tuning

Prompt tuning prepends learnable soft tokens to input embeddings while keeping the model frozen:

  • Soft prompts: Learnable continuous vectors (typically 20-100 tokens) prepended to the input embedding sequence.
  • Optimization: Soft prompts are updated via gradient descent while all model parameters remain frozen.
  • Multi-task serving: One base model with different soft prompts per task, enabling efficient multi-task deployment.

Budgeting the Fine-Tune

The first number is how many parameters actually move. LoRA attaches rank matrices and to a frozen weight of shape , so the trainable count is:

For and that is 65,536 parameters against the 16,777,216 in the frozen matrix, a fraction of 0.39 percent. Applied across attention projections in a 7 billion parameter model, the total trainable set lands near 0.1 to 1 percent of the model, which is what lets a single job keep several task adapters resident in memory.

Compute follows the standard training estimate, six FLOPs per parameter per token:

Fine-tuning 7 billion parameters on 100 million tokens is FLOPs, or 4.2 EFLOPs. At 40 percent model FLOPs utilization on an A100 delivering 312 TFLOPS dense FP16, effective throughput is 124.8 TFLOPS, giving seconds, about 9.4 hours on one GPU. Compare that with pretraining on 1.4 trillion tokens, which costs FLOPs: fine-tuning is roughly 14,000 times cheaper than the pretraining run that created the capability you are reusing.

The trainable fraction tells you which strategy is appropriate:

With under about 0.01, treat it as feature extraction or prompt tuning: freeze everything, train a head or a set of soft prompts, and iterate in minutes. Between 0.01 and 0.5, use LoRA or layer-wise unfreezing of the top blocks. Above 0.5 you are doing full fine-tuning and should expect catastrophic forgetting risk plus the memory cost of optimizer states for every parameter.

Failure Modes

Catastrophic forgetting shows up as a model that scores well on the new task while degrading on the old one, usually because the learning rate is high enough to overwrite features that were not task-specific. Hold the backbone at 10x to 100x lower learning rate than the new head, or use LoRA so the original weights are never touched. Domain shift appears when the pretraining corpus and your target data disagree: a language model pre-trained mostly on English legal text will underperform on medical chat even with clean fine-tuning, so measure the gap on a held-out target slice before tuning anything. Data leakage appears when the evaluation set was part of pretraining, making the fine-tuned numbers look better than the deployed system will ever be, so check for and, where possible, decontaminate the eval split.

Common Mistakes

Jumping to full fine-tuning because it should be best

Fix: Match the strategy to the data: under about 10K samples use feature extraction, and reach full fine-tuning only when the target domain genuinely differs and you can afford forgetting risk.

Using one learning rate for the backbone and the new head

Fix: Drop the backbone 10x to 100x below the head rate, or freeze it entirely with LoRA, so shared features are not overwritten.

Evaluating on an eval split that may be inside the pretraining corpus

Fix: Decontaminate against known pretraining sources and confirm gains on a slice that was collected after pretraining.

Best Practices

  • Start with feature extraction, then unfreeze only the last blocks once the head plateaus
  • Store one LoRA adapter per task and keep a single shared base model in memory
  • Report accuracy on both the target and a held-out source slice to catch forgetting early

Key Takeaways

  • LoRA on a 4096 square weight at rank 8 trains 65,536 parameters, about 0.39 percent of the matrix
  • Fine-tuning 7B parameters on 100M tokens costs 4.2 EFLOPs, about 9.4 hours on one A100 at 40 percent MFU
  • That fine-tune is roughly 14,000x cheaper than pretraining on 1.4T tokens
  • Let the trainable fraction f choose the strategy: small f means feature extraction, large f means full fine-tuning

Frequently Asked Questions

When should I use feature extraction instead of full fine-tuning?

Use feature extraction when the target dataset is small, typically under 10,000 labeled examples, when source and target tasks are close, or when iteration speed matters more than a final point of accuracy. Freeze the backbone, train only a new head, and you can sweep hyperparameters in minutes on one GPU. Move to full fine-tuning when the domain differs materially, you have enough data to avoid overfitting the head, and you have measured that the frozen features actually cap your accuracy.

What is the advantage of LoRA over full fine-tuning?

LoRA freezes the original weights and trains low-rank factors, cutting trainable parameters by 10x to 100x, dropping optimizer memory roughly in proportion, and letting you keep one base model with many small adapters per task. Because the adapter can be merged into the base weights at inference time, there is no runtime penalty. The main cost is choosing the rank: too small and the task needs more capacity than the adapter can express.

How do you handle domain shift?

Four levers, ordered by cost. Domain-adversarial training adds a head that predicts the domain and reverses the gradient, pushing the encoder toward domain-invariant features. CORAL aligns feature covariance matrices between source and target. Self-training generates pseudo-labels on unlabeled target data and retrains on them, which is cheap when target labels are scarce. Data augmentation targeting the specific shift, such as color jitter for imaging style differences, usually pays for itself first.

Interview Questions

Q1: When should you use feature extraction vs full fine-tuning?

Use feature extraction when the target set is under about 10K samples, the source and target tasks are close, or you need fast iteration: freeze the backbone and train only a head. Use full fine-tuning when you have enough data, the domains differ substantially, and you need maximum performance. Layer-wise unfreezing from the top block downward is the middle ground that most teams settle on.

Q2: What is the advantage of LoRA over full fine-tuning?

LoRA freezes the base model and trains rank-r factors, cutting trainable parameters by 10 to 100 times, reducing optimizer memory, and letting you keep one base with small per-task adapters that merge cleanly at inference. Because only the adapter moves, forgetting of the base capability is much less likely. The trade-off is that you must pick a rank and occasionally raise it if the adapter saturates.

Q3: How do you handle domain shift in transfer learning?

Domain-adversarial training makes features domain-invariant, CORAL aligns feature distributions, self-training adds pseudo-labeled target data, and targeted augmentation covers the specific shift such as imaging style or vocabulary. Start with augmentation and extra target data since they are cheapest, then add adversarial alignment if the residual gap remains. Measure the gap on a held-out target slice before and after each change.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-07

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert AI System Design Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement