পাঠ ১২ · ৪০-এর মধ্যে · মডিউল ২
Home / AI Courses / ডিপ লার্নিং / Momentum ও Nesterov

Momentum ও Nesterov

Momentum & Nesterov accelerated gradient
৬ মিনিট পড়া মাঝারি · Intermediate PyTorch hands-on

এই পাঠে যা শিখবেন

  • Vanilla SGD-এর সীমাবদ্ধতা — ravine ও oscillation
  • Classical momentum — exponential moving average of gradients
  • Nesterov accelerated gradient — look-ahead update
  • $\beta$-এর intuition (typically 0.9, 0.99)
  • PyTorch SGD(momentum=...)

১ · Vanilla SGD-এর সীমাবদ্ধতা

Loss surface সব জায়গায় symmetric নয়। Ravine — সরু গিরিখাত — এক direction-এ গভীর, অন্য direction-এ shallow। Vanilla SGD এই landscape-এ:

  • সরু direction-এ overshooting — oscillation।
  • লম্বা direction-এ slow progress।
  • Convergence painfully slow।
ভাবুন একটি বল কোনো U-আকার গিরিখাতে গড়িয়ে পড়ছে। দু'পাশের দেয়ালে বারবার ধাক্কা খেয়ে — কিন্তু আস্তে আস্তে নিচের দিকে এগোয়। যদি বল-এর momentum থাকে — দেয়াল-এর ধাক্কা cancel out হয়, valley-এর দিকে fast forward। এটাই momentum।

২ · Classical momentum (Polyak ১৯৬৪)

Update rule:

$$v_t = \beta v_{t-1} + \nabla L(w_t)$$ $$w_{t+1} = w_t - \eta v_t$$

যেখানে $v$ হলো "velocity" — past gradient-এর exponential moving average। $\beta \in [0, 1)$ — momentum coefficient।

  • $\beta = 0$: vanilla SGD।
  • $\beta = 0.9$: গত 10 step memory (effective)।
  • $\beta = 0.99$: গত 100 step।
Velocity-এর interpretation

Velocity = "exponentially weighted average of past gradients"। Recent gradient বেশি weight, অতীত fade out। যদি consecutive steps-এ same direction → velocity build up → bigger step। Direction reverse → velocity cancel।

৩ · Effect — দু'টি benefit

(১) Acceleration: consistent direction-এ velocity accumulate → effective step size বড়। Slow convergence direction-এ momentum সাহায্য।

(২) Damping: oscillating direction-এ opposite gradient cancel → smooth path।

মূল geometric reason:

  • Ravine-এ — দু'পাশের gradient direction প্রায়ই বিপরীতমুখী → cancel।
  • Bottom-এর দিকে gradient consistent → accumulate।
  • Net effect — bottom-এ fast progress, oscillation reduced।

৪ · Nesterov Accelerated Gradient (NAG)

Nesterov (১৯৮৩) — momentum-এর "smarter" version। Idea: gradient compute করো future position-এ (যেখানে momentum তোমাকে নিয়ে যাবে), current position-এ নয়।

$$v_t = \beta v_{t-1} + \nabla L(\underbrace{w_t - \eta \beta v_{t-1}}_{\text{look-ahead position}})$$ $$w_{t+1} = w_t - \eta v_t$$

Classical momentum = বল গড়িয়ে পড়ছে — কিন্তু সামনে দেখে না। NAG = বল প্রথমে momentum direction-এ "তাকায়", তারপর সেখানের slope-এ correction করে। অনেকটা — pre-emptive course correction। যদি সামনে valley-এর দেয়াল থাকে, agent আগে থেকেই brake।

Theoretical advantage: convex problem-এ NAG-এর convergence rate $O(1/T^2)$ — vanilla GD-এর $O(1/T)$ থেকে quadratic improvement।

৫ · PyTorch implementation

PyTorch-এ practical Nesterov formula কিছুটা different — efficiency-এর জন্য:

Python · PyTorch
import torch
import torch.nn as nn

torch.manual_seed(0)
model = nn.Linear(10, 1)

# Vanilla SGD
opt_sgd = torch.optim.SGD(model.parameters(), lr=0.01)

# SGD + classical momentum
opt_mom = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)

# SGD + Nesterov momentum
opt_nag = torch.optim.SGD(
    model.parameters(),
    lr=0.01,
    momentum=0.9,
    nesterov=True,
)

# Training loop pattern same
x = torch.randn(32, 10)
y = torch.randn(32, 1)

for opt, name in [(opt_sgd, "SGD"), (opt_mom, "Momentum"), (opt_nag, "Nesterov")]:
    # reset
    model = nn.Linear(10, 1)
    opt = type(opt)(
        model.parameters(),
        lr=0.01,
        momentum=getattr(opt, 'param_groups', [{}])[0].get('momentum', 0),
        nesterov=getattr(opt, 'param_groups', [{}])[0].get('nesterov', False),
    ) if name != "SGD" else torch.optim.SGD(model.parameters(), lr=0.01)
    print(f"{name} opt configured")

    

৬ · Scratch implementation — ravine demo

Python · NumPy
import numpy as np

# একটি ravine-like loss: L(x, y) = x² + 100 y²
def grad(p):
    x, y = p
    return np.array([2 * x, 200 * y])

def loss(p):
    return p[0] ** 2 + 100 * p[1] ** 2

# Compare three optimizers
def sgd(lr=0.01, steps=50):
    p = np.array([5.0, 1.0])
    path = [p.copy()]
    for _ in range(steps):
        p = p - lr * grad(p)
        path.append(p.copy())
    return np.array(path)

def momentum(lr=0.01, beta=0.9, steps=50):
    p = np.array([5.0, 1.0])
    v = np.zeros(2)
    path = [p.copy()]
    for _ in range(steps):
        v = beta * v + grad(p)
        p = p - lr * v
        path.append(p.copy())
    return np.array(path)

def nesterov(lr=0.01, beta=0.9, steps=50):
    p = np.array([5.0, 1.0])
    v = np.zeros(2)
    path = [p.copy()]
    for _ in range(steps):
        look = p - lr * beta * v
        v = beta * v + grad(look)
        p = p - lr * v
        path.append(p.copy())
    return np.array(path)

p_sgd  = sgd()
p_mom  = momentum()
p_nag  = nesterov()

print(f"SGD final loss     : {loss(p_sgd[-1]):.4f}")
print(f"Momentum final loss: {loss(p_mom[-1]):.4f}")
print(f"Nesterov final loss: {loss(p_nag[-1]):.4f}")

    
Ravine-এ momentum/NAG SGD-এর চেয়ে অনেক দ্রুত minimum-এ পৌঁছায়। Real DL training-এ এই difference convergence speed-এ direct impact।
Ravine landscape — vanilla SGD vs Momentum contour: narrow valley, oscillation issue minimum SGD — oscillates Momentum — smooth, fast Momentum: oscillation cancel + consistent direction-এ acceleration → faster convergence।
Ravine landscape-এ vanilla SGD oscillate করে; momentum smooth path follow করে।

৭ · $\beta$ tuning

  • $\beta = 0.9$: default — most cases ভাল।
  • $\beta = 0.99$: very smooth, very long memory — large dataset-এ।
  • $\beta = 0.5$: conservative — early training-এ sometimes useful।
  • $\beta$ schedule: early small, later increase — কখনো useful।

৮ · Bias correction (Adam-এর preview)

Plain momentum-এ early steps-এ velocity zero থেকে শুরু — bias। Adam optimizer এই bias correct করে: $\hat{v}_t = v_t / (1 - \beta^t)$। L13-এ বিস্তারিত।

Modern DL practice-এ vanilla SGD খুব কম ব্যবহৃত। SGD + momentum 0.9 — minimum baseline। Computer vision-এ SGD+momentum এখনো golden, NLP-এ Adam dominant।

ভাবনার প্রশ্ন

প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।

প্র ০১ SGD+momentum image-এ ResNet train-এ এখনো standard, কিন্তু Transformer/NLP-এ Adam dominant। এই difference-এর reason কী?

Optimizer choice — domain-specific phenomenon। 2010s-এ এই pattern emerge করেছে।

SGD+momentum strengths in Vision:

  • Better generalization — flat minima preference।
  • ImageNet, COCO benchmark — top result usually SGD।
  • ResNet, VGG paper — SGD।
  • Less hyperparameter sensitivity in vision।

Adam strengths in NLP/Transformer:

  • Per-parameter adaptive lr — handle gradient scale variation।
  • Sparse gradient (rare token) handle better।
  • Faster initial convergence।
  • BERT, GPT — সবই Adam।

Why vision favors SGD:

  • Convolutional features local, structure-rich।
  • Loss landscape relatively benign।
  • Batch normalization makes scaling uniform।
  • Long training schedule mitigates slow start।

Why NLP favors Adam:

  • Embedding parameter — vastly different gradient magnitude (rare vs frequent words)।
  • Attention layer — diverse parameter scales।
  • Layer norm replace batch norm — less normalization built-in।
  • Variable sequence length → variable gradient।

Empirical evidence:

  • Wilson et al. (২০১৭) "marginal value of adaptive methods" — SGD সবসময় match বা beat Adam-কে CV-তে।
  • Zhang et al. (২০২০) "Adam optimal for transformers" — adaptive necessary।

Recent theoretical work:

  • Heavy-tailed gradient distribution (Zhang ২০২০) Transformer-এ — Adam better।
  • Loss surface geometry vision vs NLP-এ ভিন্ন।
  • "Sharpness" measure correlates with optimizer choice।

Modern practice:

  • Vision: SGD+momentum 0.9 + cosine decay। AdamW সমালোচক।
  • NLP: AdamW universal।
  • Multi-modal: AdamW often default।
  • Fine-tuning: AdamW with low lr।

SAM (Sharpness-Aware Minimization):

  • Foret et al. (২০২১) — explicitly flat minima seek।
  • Vision-এ SOTA improve।
  • SGD/Adam both with SAM benefit।

Lion (২০২৩):

  • Google-discovered optimizer।
  • Sign of momentum — memory-efficient।
  • Vision ও language দু'টোতে competitive।

মূল উপলব্ধি: "One optimizer to rule them all" — exists not। Domain matters। Default choice — vision SGD+momentum, NLP AdamW। Always tune। Recent research narrowing the gap (Lion, Sophia)। Architecture + optimizer co-design এমেরজিং trend।

প্র ০২ Heavy ball method, Polyak momentum, Nesterov — সবই "momentum"। কিন্তু theoretical convergence rate ভিন্ন। কেন NAG convex-এ optimal?

Optimization theory-র সবচেয়ে elegant result-গুলোর একটি। Nesterov ১৯৮৩ paper-এ প্রমাণ করেছিলেন।

Convex optimization landscape:

  • $L$-smooth convex function: $\|\nabla L(x) - \nabla L(y)\| \le L \|x - y\|$।
  • $\mu$-strongly convex: $L - \mu/2 \|x\|^2$ convex।
  • Condition number: $\kappa = L/\mu$।

Convergence rates (smooth convex):

  • Gradient descent: $O(1/T)$ — sub-optimal।
  • Heavy ball: not always faster (counter-examples exist)।
  • Nesterov: $O(1/T^2)$ — optimal in this class।
  • Lower bound: Nemirovsky-Yudin — কোনো first-order method $O(1/T^2)$-এর চেয়ে faster না।

Strongly convex case:

  • GD: $(1 - 1/\kappa)^T$ — linear, slow if $\kappa$ large।
  • Nesterov: $(1 - 1/\sqrt{\kappa})^T$ — quadratic improvement।
  • Crucial for ill-conditioned problems।

Why "look ahead" helps — intuition:

  • Polyak: gradient at current $\to$ overshoot if curvature increases।
  • Nesterov: gradient at look-ahead $\to$ pre-emptive correction।
  • Like Newton's method but using only first-order info।

Mathematical machinery:

  • Lyapunov function — energy function decreasing।
  • Estimate sequence — bounded suboptimality।
  • ODE limit (Su-Boyd-Candes ২০১৪) — second-order ODE।

Continuous-time view:

  • NAG ≈ damped harmonic oscillator।
  • $\ddot{x} + \frac{3}{t} \dot{x} + \nabla L(x) = 0$।
  • $3/t$ damping critical।

Non-convex DL — theory breaks:

  • $O(1/T^2)$ rate convex-এর জন্য।
  • Non-convex (DL): $O(1/\sqrt{T})$ to stationary point।
  • Momentum still helps empirically — saddle escape, ravine।
  • Theoretical gap — DL practice ও convex theory-র মধ্যে।

Heavy ball vs Nesterov empirically:

  • সাধারণ DL training-এ — barely distinguishable।
  • Convex problems — Nesterov clearly winner।
  • PyTorch nesterov=True — overhead minimal।

Variants:

  • Quasi-hyperbolic momentum: NAG-এর smooth interpolation।
  • Aggregated momentum: multiple $\beta$ averaged।
  • FISTA: Nesterov for proximal gradient।

মূল উপলব্ধি: Nesterov optimal first-order method convex world-এ। Theoretical elegance. DL non-convex-এ direct application না, but inspiration। Practical DL — vanilla momentum already 80% benefit। NAG marginal extra।

প্র ০৩ "Momentum saddle point থেকে escape করতে সাহায্য করে" — DL high-D-এ saddle point কেন এত গুরুত্বপূর্ণ? Pure local minima-এর চেয়ে বেশি কেন?

DL theory-র এক counter-intuitive result। Dauphin et al. (২০১৪) — "Identifying and attacking the saddle point problem in high-dimensional non-convex optimization"।

Saddle point কী:

  • Critical point (∇L = 0)।
  • Hessian-এর কিছু eigenvalue positive, কিছু negative।
  • কোনো direction-এ local min, অন্য direction-এ local max।

Low-D intuition:

  • 2D-তে saddle "horse saddle"-এর মতো।
  • 3D-তে rare।
  • Local minima বেশি common।

High-D-এ statistics:

  • $n$-D-এ Hessian-এর $n$ eigenvalue।
  • Random Hessian-এ — eigenvalue half positive, half negative likely।
  • "Pure local minimum" (সব positive) probability $2^{-n}$ — vanishingly small।
  • Saddle far more common।

Empirical observation in DL:

  • Loss landscape predominantly saddle।
  • Most "stuck" points actually saddle।
  • Local minima usually OK quality।
  • Random matrix theory — Goodfellow et al.-এর analysis।

Why SGD escapes saddles:

  • Gradient noise → random perturbation।
  • Some perturbation in negative-curvature direction → escape।
  • Pure GD can stuck at saddle।

Why momentum helps:

  • Velocity carries momentum past saddle।
  • Even if instantaneous gradient small at saddle — past gradient pushed।
  • Like rolling ball with momentum — saddle slow but pass।

Theoretical result (Jin et al. ২০১৭):

  • Perturbed gradient descent (noise added) escapes saddle in polynomial time।
  • SGD natural-ই perturbed।
  • Strict saddle property — DL functions assumption।

Saddle-free Newton:

  • Dauphin et al. — Newton method modification।
  • Negative curvature actively use to escape।
  • Computationally expensive — DL-এ rare practical use।

Modern view:

  • DL "loss landscape" research very active।
  • Filter visualization — Li et al. (২০১৮)।
  • Mode connectivity — separate minima often connected by low-loss path।
  • "Loss landscape" book-length topic।

Practical implications:

  • Don't worry about local minima — saddle bigger issue।
  • SGD/Adam-এর noise feature, not bug।
  • Deterministic optimizer (full-batch GD) saddle-এ আটকাতে পারে।
  • Momentum mandatory practical concern।

Bangladesh research opportunity:

  • Loss landscape of Bangla NLP models — scarcely studied।
  • Domain-specific landscape analysis।
  • Visualization tool development।

মূল উপলব্ধি: High-D-এ saddle dominate, local minima rare। SGD noise + momentum saddle escape mechanism। DL-এর "magic" optimization এই geometric reality-এর সমাধান। Bangladesh-এ optimization research করতে — high-D geometry intuition গড়া essential।

প্র ০৪ আপনি একটি model-এ momentum=0.99 set করেছেন এবং দেখছেন training বিস্ফোরণ ঘটাচ্ছে। কেন? কীভাবে fix?

High momentum + standard learning rate — common pitfall।

The math:

  • Momentum 0.99: effective memory 100 steps।
  • Velocity build up consistently same direction।
  • Effective step size: $\eta / (1 - \beta) = \eta \times 100$।
  • Original $\eta = 0.01$ → effective $\sim 1$ — explosion।

Empirical effect:

  • Loss curve smoothly decline → suddenly spike।
  • Velocity-এর accumulated build-up।
  • Eventually NaN।

Why $\beta = 0.9$ default works:

  • Effective amplification ~10।
  • Standard $\eta$-এ stable।
  • Polyak ১৯৬৪ থেকে empirically validated।

When to use $\beta = 0.99$ or higher:

  • Very large dataset, very long training।
  • Smooth landscape (well-conditioned)।
  • Combined with very small lr।
  • Specific applications (e.g., reinforcement learning trajectory)।

Fix strategies:

  • (১) Lower learning rate:
    # Old: lr=0.01, momentum=0.99 — explode
    # New: lr=0.001, momentum=0.99 — stable
  • (২) Reduce momentum:
    # lr=0.01, momentum=0.9 — usually fine
  • (৩) Gradient clipping:
    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
  • (৪) Warmup: early stage low effective step।
    def warmup_lr(step, base_lr, warmup_steps):
        return base_lr * min(step / warmup_steps, 1)
  • (৫) Momentum schedule:
    # Start low, increase
    beta = 0.5 if step < 1000 else 0.9

Practical recipe:

  • SGD: lr=0.1, momentum=0.9, weight_decay=1e-4 (CIFAR-style)।
  • SGD ImageNet: lr=0.1, momentum=0.9, decay 30/60/90 epoch।
  • Fine-tuning: lr=0.001, momentum=0.9।

Diagnostic for high momentum issue:

  • Plot velocity norm over time — increasing unboundedly?
  • Plot effective step size: $\eta \cdot \|v\|$।
  • Compare with vanilla SGD baseline।

Adam alternative:

  • Adam-এ $\beta_1 = 0.9$ default।
  • Bias correction stabilize early steps।
  • Typically no explosion এই issue-এ।

মূল উপলব্ধি: Momentum amplification factor $1/(1-\beta)$ — visualize learning rate-এর effective increase। $\beta$ ও $\eta$ দু'টো interlinked। Tune jointly — গাণিতিক relationship-এ। Default 0.9 reason সহ default — most cases optimal trade-off।

অনুশীলন

  1. Effective step: $\eta = 0.01, \beta = 0.9$, gradient consistently 1। Equilibrium velocity কত? Effective step size?

    Equilibrium: $v = \beta v + g \Rightarrow v(1-\beta) = g \Rightarrow v = \frac{1}{1-\beta} = \frac{1}{0.1} = 10$।

    Effective step = $\eta v = 0.01 \times 10 = 0.1$ — vanilla SGD-এর 10x।

  2. Code: SGD + Nesterov momentum 0.9 দিয়ে একটি optimizer তৈরি।
    opt = torch.optim.SGD(
        model.parameters(),
        lr=0.01,
        momentum=0.9,
        nesterov=True,
        weight_decay=1e-4,
    )
  3. Compare: একটি simple loss $L = x^2 + 100y^2$-এ vanilla SGD vs momentum — ৫০ steps পর কে minimum-এর কাছে?

    Momentum। Ravine landscape-এ momentum oscillation cancel করে এবং long axis-এ accelerate করে। Section ৬-এর code চালিয়ে verify করুন।

আরও পড়ুন · ABCL TECH-এ আপনার পরবর্তী পদক্ষেপ

কোড রানার কাজ না করলে? ব্রাউজারে কাজ না করলে Google Colab ব্যবহার করুন — Google-এর ফ্রি অনলাইন Python পরিবেশ, শুধু Gmail অ্যাকাউন্ট লাগে।
পূর্ববর্তী পাঠ
পাঠ ১১ · SGD ও Mini-batch