🤖AI/ML

Gradient Descent

Gradient Descent

An optimization algorithm that iteratively updates parameters in the direction opposite to the gradient in order to minimize a loss function. It has many variants, including SGD, Momentum, and Adam, and is at the heart of all deep learning training.

📖 Detailed Explanation

Gradient Descent is an optimization algorithm that iteratively adjusts parameters to minimize the value of a loss function. It calculates the gradient of the function and moves in the direction in which the gradient decreases most steeply, and it is at the core of all learning processes in machine learning and deep learning.

Gradient descent was first proposed by the 19th-century mathematician Augustin-Louis Cauchy. In deep learning, it is combined with backpropagation and used to learn the weights of neural networks. It became mainstream after Rumelhart's 1986 backpropagation paper, and with the emergence of the Adam optimizer in 2014, it became the standard of modern deep learning.

θ = θ - η × ∇L(θ)

θ: parameters, η (eta): learning rate, ∇L: gradient of the loss function

Batch GD calculates the gradient using the entire dataset, so it is stable but slow. SGD (Stochastic) calculates with a single sample, so it is fast but noisy. Mini-batch GD is a compromise between the two and is the most widely used. Momentum converges quickly by using previous gradients, and Adam is the most versatile optimizer thanks to its adaptive learning rate.

In practice, setting the learning rate is the most important hyperparameter. If it is too large, training diverges; if it is too small, training is slow. LLMs such as GPT and BERT use the combination of AdamW + Warmup + Cosine Decay as a standard. Learning rate schedulers and Gradient Clipping are essential techniques for stable training.

📊 Optimizer Comparison

Optimizer Features Recommended Learning Rate Use case
SGD Simple, memory-efficient 0.01 ~ 0.1 CNN, image classification
SGD + Momentum Reduced oscillation, fast convergence 0.01 (momentum 0.9) ResNet, VGG
Adam Adaptive learning rate, general-purpose 1e-3 ~ 1e-4 Most deep learning
AdamW Decoupled Weight Decay 1e-4 ~ 5e-5 BERT, GPT, LLM
LAMB/LARS Large-batch training Layer-wise adjustment Distributed training, TPU

💻 Code Example

An example implementing and comparing gradient descent using PyTorch and NumPy.

# pip install torch numpy matplotlib

import torch
import torch.nn as nn

# 간단한 신경망
class SimpleNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(10, 64)
        self.fc2 = nn.Linear(64, 1)

    def forward(self, x):
        x = torch.relu(self.fc1(x))
        return self.fc2(x)

# 데이터 준비
X = torch.randn(1000, 10)
y = torch.randn(1000, 1)

# 옵티마이저 비교
optimizers = {
    'SGD': torch.optim.SGD,
    'SGD+Momentum': lambda p, lr: torch.optim.SGD(p, lr=lr, momentum=0.9),
    'Adam': torch.optim.Adam,
    'AdamW': torch.optim.AdamW,
}

for name, opt_class in optimizers.items():
    model = SimpleNet()
    if callable(opt_class) and name == 'SGD+Momentum':
        optimizer = opt_class(model.parameters(), 0.01)
    else:
        optimizer = opt_class(model.parameters(), lr=0.01)

    criterion = nn.MSELoss()

    # 학습 루프
    for epoch in range(100):
        optimizer.zero_grad()        # 1. 기울기 초기화
        output = model(X)            # 2. 순전파
        loss = criterion(output, y)  # 3. 손실 계산
        loss.backward()              # 4. 역전파 (기울기 계산)
        optimizer.step()             # 5. 파라미터 업데이트

    print(f"{name:15} | Final Loss: {loss.item():.6f}")

# 출력 예시:
# SGD             | Final Loss: 0.987234
# SGD+Momentum    | Final Loss: 0.956123
# Adam            | Final Loss: 0.012456
# AdamW           | Final Loss: 0.011234
# NumPy로 경사하강법 처음부터 구현
import numpy as np

def gradient_descent_from_scratch():
    """선형 회귀를 위한 경사하강법 구현"""

    # 1. 데이터 생성 (y = 2x + 1 + noise)
    np.random.seed(42)
    X = np.random.randn(100, 1)
    y = 2 * X + 1 + np.random.randn(100, 1) * 0.3

    # 2. 파라미터 초기화
    w = np.random.randn(1, 1)  # 가중치
    b = np.zeros((1, 1))        # 편향
    lr = 0.1                    # 학습률
    epochs = 100

    # 3. 경사하강법
    for epoch in range(epochs):
        # 순전파
        y_pred = X @ w + b

        # 손실 계산 (MSE)
        loss = np.mean((y_pred - y) ** 2)

        # 기울기 계산
        dw = (2 / len(X)) * (X.T @ (y_pred - y))
        db = (2 / len(X)) * np.sum(y_pred - y)

        # 파라미터 업데이트 (핵심!)
        w = w - lr * dw  # θ = θ - η × ∇L
        b = b - lr * db

        if epoch % 20 == 0:
            print(f"Epoch {epoch:3d} | Loss: {loss:.4f} | w: {w[0,0]:.3f} | b: {b[0,0]:.3f}")

    print(f"\n최종 결과: y = {w[0,0]:.3f}x + {b[0,0]:.3f}")
    print(f"실제 함수: y = 2.000x + 1.000")

gradient_descent_from_scratch()

# 출력:
# Epoch   0 | Loss: 4.2134 | w: 1.234 | b: 0.156
# Epoch  20 | Loss: 0.1234 | w: 1.912 | b: 0.978
# ...
# 최종 결과: y = 1.998x + 1.003
# 학습률 스케줄러 - LLM 학습의 필수 요소
import torch
import torch.nn as nn
from torch.optim.lr_scheduler import (
    CosineAnnealingLR,
    OneCycleLR,
    LinearLR,
    SequentialLR
)

model = nn.Linear(10, 1)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)

# 1. Cosine Annealing (가장 널리 사용)
scheduler = CosineAnnealingLR(optimizer, T_max=100, eta_min=1e-6)

# 2. Warmup + Cosine Decay (BERT, GPT 표준)
warmup_epochs = 10
total_epochs = 100

warmup = LinearLR(optimizer, start_factor=0.1, total_iters=warmup_epochs)
decay = CosineAnnealingLR(optimizer, T_max=total_epochs - warmup_epochs)
scheduler = SequentialLR(optimizer, [warmup, decay], milestones=[warmup_epochs])

# 3. OneCycleLR (빠른 학습에 효과적)
# scheduler = OneCycleLR(optimizer, max_lr=1e-3, total_steps=1000)

# 학습 루프
for epoch in range(total_epochs):
    # ... 학습 코드 ...

    scheduler.step()  # 에포크마다 학습률 조정

    if epoch % 10 == 0:
        current_lr = scheduler.get_last_lr()[0]
        print(f"Epoch {epoch:3d} | LR: {current_lr:.2e}")

# 출력:
# Epoch   0 | LR: 1.00e-04  (warmup)
# Epoch  10 | LR: 1.00e-03  (peak)
# Epoch  50 | LR: 5.00e-04  (decay)
# Epoch  99 | LR: 1.00e-06  (minimum)

🗣️ Examples of Practical Conversations

💬 In a Training Troubleshooting Meeting

"If training doesn't converge, try lowering the learning rate to 1e-4. The Adam default of 1e-3 may be too large for our model. Adding 10% Warmup will also resolve the early instability."

💬 In an Interview

"Adam calculates a per-parameter adaptive learning rate using the first moment (mean) and the second moment (variance). Bias correction also resolves the early instability. AdamW handles weight decay outside the optimizer, so the regularization is more accurate."

💬 In an LLM Training Discussion

"GPT-4-class models use the combination of AdamW + Linear Warmup + Cosine Decay. Set Gradient Clipping to 1.0, and if the batch size is large, also consider LAMB or 8-bit Adam. It saves memory."

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

⚠️ Cautions

❌
Using a Fixed Learning Rate

If you use the same learning rate throughout the entire training process, convergence becomes difficult in the later stages. You must use a Scheduler to decrease it gradually.

❌
Excessive Worry About Local Minima

In high dimensions, saddle points are a bigger problem than local minima. Adam or Momentum escape them well. In practice, the loss landscape is flatter than you might expect.

✅
The right approach

AdamW + Warmup + Cosine Annealing works well in most cases. Prevent exploding gradients with Gradient Clipping (max_norm=1.0), and if the loss is NaN, try lowering the learning rate by a factor of 10.

🔥 Real-World Incidents

OpenAI GPT-3 2020

Thousands of Dollars in GPU Costs Wasted Due to Training Instability

Cause: Failure to set the learning rate for a 175B-parameter model, loss spike occurred

Impact: Thousands of GPU hours lost due to training restarts

Resolution: Strengthened Gradient Clipping, extended Warmup period, conservatively set the learning rate to 3e-4

📎 GPT-3 Paper
DeepMind AlphaFold 2021

Training Failure Due to Exploding Gradients

Cause: Exploding gradient in the Attention layer

Impact: Training halted due to NaN loss, restart required

Resolution: Adopted the Pre-LayerNorm structure, applied Gradient Clipping and learning rate warmup

📎 AlphaFold Paper

📝 Comprehension Quiz

Q1. What problem occurs in gradient descent when the learning rate is too large?

Q2. Why is the Adam optimizer more widely used than SGD?

Q3. Why is AdamW preferred over Adam in LLM training?

🔗 Related Terms

📚 Learn More