🤖 AI/ML

Transfer Learning

Transfer Learning

Applying a pretrained model to a new task. Solves the problem of insufficient data.

📖 Detailed Explanation

Transfer Learning is a machine learning technique that applies knowledge from a model trained in one domain to a new task in another related domain. It is a core technology that, building on a model pre-trained on a large-scale dataset, makes it possible to achieve excellent performance with a relatively small amount of data.

The background of transfer learning stems from the problem of the enormous amounts of data and computational resources required to train deep learning models. After the success of AlexNet at the ImageNet competition in 2012, reusing pre-trained CNN models for other image classification tasks became widespread. With the emergence of BERT in 2018, transfer learning also became the standard in the NLP field, and it is now an essential technique in large language models such as GPT and LLaMA.

The core principles of transfer learning are Feature Extraction and Fine-Tuning. The feature extraction approach freezes the weights of the pre-trained model and trains only the final classification layer anew. Fine-Tuning further trains the entire model at a low learning rate to adapt it to the new domain. Recently, parameter-efficient fine-tuning (PEFT) techniques such as LoRA and QLoRA have greatly improved memory efficiency.

In practice, transfer learning is essential in three respects: reduced data collection costs, shorter training time, and improved performance. As of 2025, more than 1 million pre-trained models are registered on Hugging Face, and most AI projects start with transfer learning by default instead of training from scratch. In specialized domains such as healthcare and law in particular, domain adaptation of general models is a key competitive advantage.

💻 Code Example

Text classification fine-tuning example using Hugging Face Transformers:

# 전이학습 파인튜닝 예제 (Hugging Face Transformers)
from transformers import AutoModelForSequenceClassification, AutoTokenizer
from transformers import Trainer, TrainingArguments
from datasets import load_dataset

# 1. 사전학습된 모델과 토크나이저 로드
model_name = "klue/bert-base"  # 한국어 BERT
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(
    model_name,
    num_labels=2  # 이진 분류
)

# 2. 데이터셋 준비
dataset = load_dataset("nsmc")  # 네이버 영화 리뷰 감성분류

def tokenize_function(examples):
    return tokenizer(
        examples["document"],
        padding="max_length",
        truncation=True,
        max_length=128
    )

tokenized_datasets = dataset.map(tokenize_function, batched=True)

# 3. 학습 설정 (LoRA 없이 전체 파인튜닝)
training_args = TrainingArguments(
    output_dir="./results",
    num_train_epochs=3,
    per_device_train_batch_size=16,
    per_device_eval_batch_size=64,
    learning_rate=2e-5,  # 파인튜닝은 낮은 학습률 사용
    warmup_ratio=0.1,
    weight_decay=0.01,
    evaluation_strategy="epoch",
    save_strategy="epoch",
    load_best_model_at_end=True,
)

# 4. Trainer로 학습
trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_datasets["train"],
    eval_dataset=tokenized_datasets["test"],
)

# 5. 파인튜닝 실행
trainer.train()

# 6. 모델 저장 및 추론
trainer.save_model("./nsmc-classifier")
print("파인튜닝 완료! 저장 경로: ./nsmc-classifier")

Parameter-efficient fine-tuning example using LoRA:

# PEFT(LoRA)를 활용한 효율적 전이학습
from peft import LoraConfig, get_peft_model, TaskType
from transformers import AutoModelForCausalLM

# 베이스 모델 로드
model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-3.2-1B",
    torch_dtype="auto",
    device_map="auto"
)

# LoRA 설정 - 전체 파라미터의 약 0.1%만 학습
lora_config = LoraConfig(
    task_type=TaskType.CAUSAL_LM,
    r=16,                    # rank 크기
    lora_alpha=32,           # 스케일링 팩터
    lora_dropout=0.1,        # 드롭아웃
    target_modules=["q_proj", "v_proj"],  # 적용 레이어
)

# PEFT 모델 생성
peft_model = get_peft_model(model, lora_config)

# 학습 가능한 파라미터 확인
peft_model.print_trainable_parameters()
# 출력: trainable params: 4,194,304 || all params: 1,500,000,000 || trainable%: 0.28%

📊 Performance & Cost

Comparison of transfer learning efficiency versus pre-trained models (as of 2025):

Training Method Required Data GPU Hours Cost (A100 basis) Performance (KLUE)
Training from Scratch 100M+ tokens 1,000+ hours $2,000+ -
Full Fine-Tuning 10K samples 2-4 hours $4-8 90%+
LoRA Fine-Tuning 10K samples 0.5-1 hour $1-2 89%+
Prompt Tuning 100 samples 10 minutes $0.3 85%+

* Performance is based on the KLUE benchmark average; cost is based on AWS p4d.24xlarge at $2 per hour

🗣️ Say It Like This in Practice

💬 In a Meeting
"We only have 10,000 medical-domain records, so training from scratch would lead to overfitting. If we fine-tune BERT as the base and also use data augmentation, we should get an F1 of 0.9 or higher."
💬 In an Interview
"When the domain gap is large in transfer learning, it is effective to go through intermediate-domain pre-training. For example, rather than doing medical classification directly from a general BERT, use a model that has been further pre-trained on a medical corpus, like PubMedBERT."
💬 In a Technical Discussion
"For LLM fine-tuning, LoRA is pretty much the standard. With rank 16 and alpha 32, you can get 95% of the performance of full fine-tuning by training only 0.3% of the parameters. If you quantize to 4-bit with QLoRA, you can fine-tune a 70B model even with 8GB of VRAM."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌

Fine-tuning while ignoring the domain gap

Fine-tuning an English model directly on a Korean task, or a general-domain model directly on a specialized domain, significantly degrades performance. You must first go through a domain adaptation stage (Domain-Adaptive Pre-training).

❌

Setting the learning rate too high

If the learning rate is too high in fine-tuning (e.g., 1e-3), the pre-trained knowledge is destroyed, causing a phenomenon called "catastrophic forgetting." You should usually use a low learning rate of around 2e-5 to 5e-5.

✅

The right approach

Use a Gradual Unfreezing strategy. Train only the classification layer at first, and then gradually unfreeze the layers one by one from the upper layers to the lower layers so they become trainable; this enables stable fine-tuning.

🔗 Related Terms

📚 Learn More