MLCrack

    ML MATH & LINEAR ALGEBRA Β· INTERVIEW QUESTION

    What is the vanishing/exploding gradient problem? How do modern architectures solve it?

    🟑 intermediate · Calculus & Optimization

    Hint: Think about what happens when you multiply many small or large numbers together.

    Answer

    During backpropagation, gradients are multiplied through layers:

    βˆ‚Lβˆ‚w1=βˆ‚Lβˆ‚hnβ‹…βˆ‚hnβˆ‚hnβˆ’1β‹―βˆ‚h2βˆ‚h1β‹…βˆ‚h1βˆ‚w1\frac{\partial \mathcal{L}}{\partial w_1} = \frac{\partial \mathcal{L}}{\partial h_n} \cdot \frac{\partial h_n}{\partial h_{n-1}} \cdots \frac{\partial h_2}{\partial h_1} \cdot \frac{\partial h_1}{\partial w_1}

    For scalar states, repeated derivative magnitudes below one can make gradients vanish, while magnitudes above one can make them explode. For vector states, the backward-ordered Jacobian product, its singular values, and gradient alignment govern amplification or contraction.

    Solutions for Vanishing Gradients

    1. ReLU activation: f(x)=max⁑(0,x)f(x) = \max(0, x) β€” gradient = 1 for positive values
    2. Residual connections: y=f(x)+xy = f(x) + x provides gradient highway
    3. LSTM gates: additive memory paths can help, although gates still multiply the recurrent gradient
    4. LayerNorm/BatchNorm: keeps activations in good range
    5. He/Xavier initialization: proper variance scaling

    Solutions for Exploding Gradients

    1. Gradient clipping: torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
    2. Weight regularization
    3. Careful learning rate selection

    Transformers use residual connections and LayerNorm to mitigate gradient instability; initialization, architecture and optimizer settings still matter.