Docsity

transformers and nlp process notes, Summaries of Computer Science

Toggle sidebar
bg1
CS 7810 - Advanced Deep Learning | Notes: Wk 3-4
Topics: backprop, optimization, attention mechanism, transformer architecture
1. Backpropagation
Foundation of DL. Just chain rule applied to computational graphs. People overcomplicate this.
Chain rule: if L = f(g(x)), then dL/dx = (dL/df)(df/dx) <- works for scalars; for vectors need Jacobians
Backprop in a graph: forward pass computes activations and caches them. Backward pass computes gradients
starting from loss, propagates backward through graph using chain rule at each node.
Computational complexity: forward = O(params), backward = O(params) too. Memory: need to cache all
intermediate activations for backward pass -> memory scales w/ depth. Gradient checkpointing trades compute
for memory (recompute activations during backward instead of storing).
1.1 Vanishing/Exploding Gradients
Deep networks suffer from this. Gradients get multiplied many times during backprop.
- Vanishing: gradients shrink to ~0 in early layers. Early layers don't learn. Common w/ sigmoid/tanh.
- Exploding: gradients blow up. Weights diverge. Common in RNNs.
Solutions:
- Better activations: ReLU doesn't saturate for positive inputs (gradient = 1 for x>0). But has "dying ReLU"
problem - neurons that always get negative input never update. Leaky ReLU, ELU, GELU fix this.
- Weight init: Xavier (Glorot) init for tanh/sigmoid, He (Kaiming) init for ReLU. Scale based on fan-in and
fan-out.
- Batch normalization, residual connections (see below)
- Gradient clipping for RNNs: clip by value or by norm (clip by norm usually better - preserves direction)
2. Optimization
2.1 SGD and Variants
Vanilla SGD: theta <- theta - lr * gradient. Too slow, sensitive to lr, gets stuck in saddle points.
SGD + Momentum: accumulate exponentially decaying moving avg of past gradients. v <- beta*v - lr*g, theta
<- theta + v. Beta ~= 0.9 typically.
pf3
pf4
pf5

Partial preview of the text

Download transformers and nlp process notes and more Summaries Computer Science in PDF only on Docsity!

CS 7810 - Advanced Deep Learning | Notes: Wk 3- Topics: backprop, optimization, attention mechanism, transformer architecture

1. Backpropagation

Foundation of DL. Just chain rule applied to computational graphs. People overcomplicate this. Chain rule: if L = f(g(x)), then dL/dx = (dL/df)(df/dx) <- works for scalars; for vectors need Jacobians Backprop in a graph: forward pass computes activations and caches them. Backward pass computes gradients starting from loss, propagates backward through graph using chain rule at each node. Computational complexity: forward = O(params), backward = O(params) too. Memory: need to cache all intermediate activations for backward pass -> memory scales w/ depth. Gradient checkpointing trades compute for memory (recompute activations during backward instead of storing).

1.1 Vanishing/Exploding Gradients

Deep networks suffer from this. Gradients get multiplied many times during backprop.

  • Vanishing: gradients shrink to ~0 in early layers. Early layers don't learn. Common w/ sigmoid/tanh.
  • Exploding: gradients blow up. Weights diverge. Common in RNNs. Solutions:
  • Better activations: ReLU doesn't saturate for positive inputs (gradient = 1 for x>0). But has "dying ReLU" problem - neurons that always get negative input never update. Leaky ReLU, ELU, GELU fix this.
  • Weight init: Xavier (Glorot) init for tanh/sigmoid, He (Kaiming) init for ReLU. Scale based on fan-in and fan-out.
  • Batch normalization, residual connections (see below)
  • Gradient clipping for RNNs: clip by value or by norm (clip by norm usually better - preserves direction)

2. Optimization

2.1 SGD and Variants

Vanilla SGD: theta <- theta - lr * gradient. Too slow, sensitive to lr, gets stuck in saddle points. SGD + Momentum: accumulate exponentially decaying moving avg of past gradients. v <- betav - lrg, theta <- theta + v. Beta ~= 0.9 typically.

Adam (Kingma & Ba 2014 - prob most cited ML paper ever??):

  • m_t = beta1 * m_{t-1} + (1-beta1) * g_t [1st moment, like momentum]
  • v_t = beta2 * v_{t-1} + (1-beta2) * g_t^2 [2nd moment, like RMSProp]
  • m_hat = m_t / (1-beta1^t) [bias correction - important early in training]
  • v_hat = v_t / (1-beta2^t)
  • theta <- theta - lr * m_hat / (sqrt(v_hat) + epsilon) Typical hyperparams: beta1=0.9, beta2=0.999, epsilon=1e-8, lr=1e-3 or 3e-4. AdamW is Adam + weight decay (applied directly to weights, not through gradient - cleaner for regularization). Note: Adam can generalize worse than SGD in some settings (Wilson et al 2017 controversy). Large batch training papers often use SGD + warmup. For transformers, Adam/AdamW standard.

2.2 Learning Rate Schedules

Constant LR rarely optimal. Common schedules:

  • Step decay: multiply by gamma every k epochs
  • Cosine annealing: lr = lr_min + 0.5(lr_max-lr_min)(1 + cos(pi*t/T))
  • Warmup + decay: linearly increase for first N steps, then decay. Very common for transformers.
  • Cyclic LR (Smith 2017): oscillate between lr bounds, helps escape saddle pts For transformers, original paper used: lr = d_model^(-0.5) * min(step^(-0.5), step * warmup^(-1.5)) ??? -> is the exponent -0.5 or -1.5 for the step part after warmup? check the paper

4.1 Encoder Block

Each encoder layer:

  • Multi-head self-attention (Q=K=V = input)
  • Add & Norm: residual connection + LayerNorm
  • Position-wise FFN: two linear layers w/ ReLU. FFN(x) = max(0, xW1+b1)W2+b2. Hidden dim usually 4x d_model.
  • Add & Norm again Pre-norm vs post-norm: original paper uses post-norm (apply LN after residual add). Pre-norm (LN before sublayer) is more stable for training deep transformers - GPT, BERT-variants often use pre-norm.

4.2 Decoder Block

Has an EXTRA sublayer compared to encoder:

  • Masked multi-head self-attention (causal mask - can only attend to past positions)
  • Add & Norm
  • Cross-attention: Q from decoder, K and V from encoder output
  • Add & Norm
  • FFN + Add & Norm Masking: during training, use "look-ahead mask" (upper triangular matrix of -inf) so each position only attends to previous positions. Critical for autoregressive generation.

4.3 Positional Encoding

Self-attention is permutation invariant (no notion of position). Need to add positional info. Original paper: fixed sinusoidal encoding:

  • PE(pos, 2i) = sin(pos / 10000^(2i/d_model))
  • PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model)) Learned positional embeddings (BERT, GPT-2): just learn a separate embedding for each position. Works well but doesn't extrapolate beyond training length. Modern alternatives: RoPE (rotary position embedding) - encodes relative position in the attention score computation itself. Used in LLaMA, Mistral, etc. ALiBi: add linear bias to attention scores based on distance. Neither requires changing input embeddings.

4.4 Why Transformers Work

Key properties:

  • Direct connections between any two positions (O(1) path length vs O(n) for RNNs) -> easier to model long-range dependencies
  • Highly parallelizable -> train on large corpora
  • Residual connections + LN -> stable training at depth
  • Inductive biases: relatively few (no locality like CNN, no sequentiality like RNN) -> needs more data but more flexible <- the "relatively few inductive biases" thing is double-edged. Good for general-purpose, bad for data efficiency.

Weight decay: L2 penalty on weights. In AdamW, applied directly (not through gradient), i.e., theta <- theta * (1 - lr * lambda) - lr * g. Important distinction from L2 regularization w/ Adam. Mixed precision training (FP16/BF16): store weights in FP32, forward/backward in FP16, scale loss to avoid underflow. BF16 preferred over FP16 for stability (same exponent range as FP32). Huge memory savings.

7. Scaling & BERT/GPT style models

Two major pretraining paradigms:

  • BERT-style (encoder-only): masked language modeling (MLM) + next sentence prediction. Bidirectional, good for classification/NLU tasks.
  • GPT-style (decoder-only): autoregressive LM (predict next token). Unidirectional, good for generation. Scales better apparently (per scaling law papers). Scaling laws (Kaplan et al 2020, Chinchilla 2022): loss scales as power law w/ compute, data, params. Chinchilla showed original GPT-3 was undertrained - optimal allocation is ~20 tokens per param. LLaMA followed this. -> key takeaway: for a fixed compute budget, better to train smaller model on more data than huge model on less data (controversial when published, now widely accepted) Papers to reread: Attention is All You Need (Vaswani 2017), Adam (Kingma 2014), BN (Ioffe 2015), LN (Ba 2016), Scaling Laws (Kaplan 2020), Chinchilla (Hoffmann 2022)