Adam
Adaptive Moment Estimation
The most widely used optimization algorithm. Adaptively adjusts the learning rate. An improvement on SGD.
Adaptive Moment Estimation
The most widely used optimization algorithm. Adaptively adjusts the learning rate. An improvement on SGD.
Adam (Adaptive Moment Estimation) is the most widely used gradient descent optimization algorithm in deep learning. By combining the benefits of Momentum (fast convergence through inertia) and RMSprop (automatic learning-rate adjustment), it provides stable training on most problems without separate tuning.
It was proposed in 2014 by Diederik Kingma and Jimmy Ba in the ICLR paper "Adam: A Method for Stochastic Optimization." Since its publication it has quickly become a standard optimizer, and with more than 120,000 citations to date it is one of the most influential papers in the history of deep learning.
Adam maintains two moving averages. The first moment (m) is the mean of the gradients and plays the role of Momentum, while the second moment (v) is the mean of the squared gradients and scales the learning rate like RMSprop. Bias correction also resolves the instability at the start of training.
The default hyperparameters (lr=0.001, beta1=0.9, beta2=0.999, epsilon=1e-8) work well in most cases. AdamW (decoupled weight decay) is used for Transformer training, and 8-bit Adam or Adafactor for large language models. SGD+Momentum may be better in final performance, but Adam converges quickly without tuning, making it ideal for prototyping.
import torch
import torch.nn as nn
import torch.optim as optim
# 간단한 모델 정의
model = nn.Sequential(
nn.Linear(784, 256),
nn.ReLU(),
nn.Linear(256, 10)
)
# Adam 옵티마이저 설정 (기본값이 대부분 최적)
optimizer = optim.Adam(
model.parameters(),
lr=0.001, # 학습률 (기본값 권장)
betas=(0.9, 0.999), # 모멘텀 계수
eps=1e-8, # 0으로 나누기 방지
weight_decay=0 # L2 정규화 (AdamW 권장)
)
# AdamW 사용 (Weight Decay를 올바르게 처리)
optimizer_w = optim.AdamW(
model.parameters(),
lr=0.001,
weight_decay=0.01 # Transformer에서 일반적으로 0.01~0.1
)
# 학습 루프 예시
criterion = nn.CrossEntropyLoss()
for epoch in range(10):
for batch_x, batch_y in dataloader:
optimizer.zero_grad() # 기울기 초기화
outputs = model(batch_x)
loss = criterion(outputs, batch_y)
loss.backward() # 기울기 계산
optimizer.step() # 파라미터 업데이트
# 학습률 스케줄러와 함께 사용
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=100)
# 매 에폭 후: scheduler.step()
print(f"현재 학습률: {optimizer.param_groups[0]['lr']}")
"If the loss is diverging, try lowering the Adam learning rate from 0.001 to 0.0001. If that doesn't help, add gradient clipping, and if it's a Transformer, switch to AdamW and set weight decay to 0.01."
"Explain the difference between Adam and SGD. Adam converges quickly thanks to its adaptive learning rate, but some studies show that SGD+Momentum gives better generalization performance. That's why people sometimes fine-tune with SGD in production."
"This is BERT fine-tuning, so you should use AdamW instead of Adam. In Adam, weight_decay is implemented as L2 regularization, which conflicts with Adam's adaptive learning rate. AdamW fixes this problem."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Always use AdamW when you need regularization. Adam's weight_decay parameter is implemented as L2 regularization and interferes with Adam's adaptive learning rate. This is especially important for Transformer models.
Adam converges quickly but can fall into sharp minima. If final performance matters, consider training quickly with Adam and then fine-tuning with SGD+Momentum.
Adam stores two states (m, v) for each parameter, so it needs 3 times the memory of SGD. For large models, consider 8-bit Adam or Adafactor.