🤖 AI/ML

Learning Rate

Learning Rate

A hyperparameter that determines the size of weight updates. Too large causes divergence.

📖 Detailed Explanation

Learning Rate is a scaler that is multiplied by the gradient when updating model weights. In the formula w_new = w_old - lr * gradient, lr is the learning rate. It is the most important hyperparameter in deep learning: if it is too large, training diverges, and if it is too small, convergence is slow.

Typical ranges: 1e-3~1e-2 for CNNs, 1e-5~1e-4 for Transformers/LLMs, and 1e-5~5e-5 for fine-tuning. The Adam optimizer works well at lower learning rates than SGD.

Learning Rate Schedule: dynamic adjustment is more effective than a fixed lr. Typical examples are Warmup (increase gradually at the beginning), Step Decay (decrease every set number of epochs), Cosine Annealing (decrease along a cosine curve), and OneCycleLR (increase, then decrease within a single cycle).

Learning rate in the LLM era: large models require Warmup (usually 1~3% of the total), and are trained through to the end with Cosine Decay. As the batch size grows, the learning rate can also be increased linearly (Linear Scaling Rule).

💻 Code Example

import torch
from torch.optim import Adam, AdamW, SGD
from torch.optim.lr_scheduler import (
    StepLR, CosineAnnealingLR, OneCycleLR,
    LinearLR, CosineAnnealingWarmRestarts
)

model = MyModel()

# 1. 기본 옵티마이저 설정
optimizer = AdamW(model.parameters(), lr=1e-4, weight_decay=0.01)

# 2. Step Decay (30 epoch마다 0.1배)
scheduler = StepLR(optimizer, step_size=30, gamma=0.1)

# 3. Cosine Annealing (최소 lr까지 코사인 감소)
scheduler = CosineAnnealingLR(
    optimizer,
    T_max=100,        # 총 epoch
    eta_min=1e-6      # 최소 lr
)

# 4. Warmup + Cosine Decay (LLM 표준)
from transformers import get_cosine_schedule_with_warmup

total_steps = len(dataloader) * num_epochs
warmup_steps = int(total_steps * 0.03)  # 3% warmup

scheduler = get_cosine_schedule_with_warmup(
    optimizer,
    num_warmup_steps=warmup_steps,
    num_training_steps=total_steps
)

# 5. OneCycleLR (빠른 수렴)
scheduler = OneCycleLR(
    optimizer,
    max_lr=1e-3,      # 피크 lr
    total_steps=total_steps,
    pct_start=0.3,    # 30%까지 상승
    anneal_strategy='cos'
)

# 6. Learning Rate Finder (최적 lr 찾기)
from torch_lr_finder import LRFinder

finder = LRFinder(model, optimizer, criterion)
finder.range_test(train_loader, end_lr=1, num_iter=100)
finder.plot()  # 기울기가 가장 가파른 지점의 lr 선택
# 보통 loss가 감소하기 시작하는 lr의 1/10을 선택

# 학습 루프
for epoch in range(num_epochs):
    for batch in dataloader:
        loss = model(batch)
        loss.backward()
        optimizer.step()
        scheduler.step()  # 배치마다 호출 (OneCycleLR, Warmup)
        optimizer.zero_grad()
    # scheduler.step()  # epoch마다 호출 (StepLR, CosineAnnealing)

🗣️ Say It Like This in Practice

💬 In a Meeting
"The loss was spiking early in training, so I increased the warmup from 3% to 5% and it stabilized. The final performance is the same, and the probability of training failure went down."
💬 In an Interview
"I confirmed with LR Finder that 1e-3 was optimal, then used OneCycleLR to raise it up to 3e-3 and bring it down to 1e-5. Compared to a fixed lr, convergence was 30% faster, and the final accuracy was 0.5% higher."
💬 In a Technical Discussion
"If you increased the batch size from 256 to 1024, you should increase the lr by 4x as well. That's the Linear Scaling Rule. But an lr that is too large hurts generalization performance, so it's better to adjust the per-layer lr with the LARS or LAMB optimizer."

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

⚠️ Common Mistakes & Cautions

❌
Using a high lr in fine-tuning

The pretrained weights get destroyed. Start fine-tuning at 1e-5~5e-5, which is 1/10~1/100 of the pretraining level.

❌
Training a large model without warmup

The initial gradients are unstable and cause divergence. Warmup is essential for LLMs/Transformers (1~5% of steps).

✅
The right way

After exploring the appropriate range with LR Finder, use a combination of Warmup + Cosine Decay. When you change the batch size, adjust the lr proportionally as well.

🔗 Related Terms

📚 Learn More