πŸ€– AI/ML

Optimizer

Optimizer

An algorithm that minimizes the loss function. SGD, Adam, AdamW.

πŸ“– Detailed Explanation

An optimizer is an algorithm that updates weights in order to minimize the loss function of a deep learning model. It plays a key role in adjusting parameters so that the model reduces the error between its predictions and the actual values on the training data.

The history of optimizers begins with gradient descent in the 1950s. They have since developed with the emergence of Momentum in the 1980s, AdaGrad in 2011, and Adam in 2014. In particular, Adam combines momentum with adaptive learning rates and is currently the most widely used.

The core principle is to compute the gradient and update the parameters in the direction in which the loss decreases. SGD simply moves in the direction of the gradient, while Adam uses the first and second moments of past gradients to adaptively adjust the learning rate for each parameter.

In practice, the choice of optimizer has a major impact on model performance. Adam or AdamW is generally the default choice, but for training large language models (LLMs), the combination of AdamW and a learning rate scheduler is the standard.

πŸ’» Code Example

# PyTorch μ˜΅ν‹°λ§ˆμ΄μ € 예제
import torch
import torch.nn as nn
import torch.optim as optim

# κ°„λ‹¨ν•œ λͺ¨λΈ μ •μ˜
model = nn.Sequential(
    nn.Linear(10, 64),
    nn.ReLU(),
    nn.Linear(64, 1)
)

# λ‹€μ–‘ν•œ μ˜΅ν‹°λ§ˆμ΄μ € 비ꡐ
# 1. SGD (Stochastic Gradient Descent)
optimizer_sgd = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)

# 2. Adam (κ°€μž₯ 널리 μ‚¬μš©λ¨)
optimizer_adam = optim.Adam(model.parameters(), lr=0.001, betas=(0.9, 0.999))

# 3. AdamW (Weight Decay 뢄리 - LLM ν•™μŠ΅ ν‘œμ€€)
optimizer_adamw = optim.AdamW(model.parameters(), lr=1e-4, weight_decay=0.01)

# ν•™μŠ΅ 루프 예제
criterion = nn.MSELoss()
optimizer = optimizer_adamw  # AdamW 선택

for epoch in range(100):
    # μˆœμ „νŒŒ
    outputs = model(torch.randn(32, 10))
    loss = criterion(outputs, torch.randn(32, 1))

    # μ—­μ „νŒŒ 및 κ°€μ€‘μΉ˜ μ—…λ°μ΄νŠΈ
    optimizer.zero_grad()  # κ·Έλž˜λ””μ–ΈνŠΈ μ΄ˆκΈ°ν™”
    loss.backward()        # κ·Έλž˜λ””μ–ΈνŠΈ 계산
    optimizer.step()       # κ°€μ€‘μΉ˜ μ—…λ°μ΄νŠΈ

    if epoch % 20 == 0:
        print(f"Epoch {epoch}, Loss: {loss.item():.4f}")

πŸ—£οΈ Say It Like This in Practice

πŸ’¬ In a Meeting
"The instability in training may be caused by the optimizer settings. I'll switch from SGD to AdamW and lower the learning rate to 1e-4."
πŸ’¬ In an Interview
"Adam is an optimizer that combines the advantages of momentum and RMSprop. It tracks the moving average of the gradient with the first moment and the moving average of the squared gradient with the second moment, applying an adaptive learning rate for each parameter."
πŸ’¬ In a Technical Discussion
"AdamW is the standard for LLM fine-tuning. Unlike regular Adam, it applies weight decay separately from L2 regularization, so it is more effective at preventing overfitting."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Common Mistakes & Cautions

❌
Setting the learning rate too high

If the learning rate is too high, the loss diverges (NaN) or overshoots the optimum. For Adam, 1e-3 to 1e-4 is usually appropriate, and for fine-tuning, 1e-5 to 1e-4.

❌
Missing optimizer.zero_grad()

If you forget to reset the gradients, the gradients from the previous batch accumulate and training becomes unstable. Always call it before backward().

βœ…
The right way

Use the combination of AdamW and a Cosine Annealing scheduler, and apply warmup at the beginning of training. Adjust the learning rate according to the model size.

πŸ”— Related Terms

πŸ“š Learn More