Activation Functions II: Modern Deep Activations (ReLU, LeakyReLU, GELU, SiLU & SwiGLU)
How ReLU's constant 1.0 slope sparked the Deep Learning revolution, how to cure the Dying ReLU trap, and why modern Transformers & LLMs run on GELU, SiLU & SwiGLU!
ReLU unlocked 100-layer ResNets, GELU powered BERT & GPT-2/3, and SwiGLU powers Llama 3, Mistral & Gemma!
Knowing the exact activation + initialization pairing (ReLU → Kaiming He init, GELU/SiLU → Transformers, SwiGLU → 2/3 hidden-dim scaling) is essential when building or debugging modern PyTorch architectures.
Spotting 'Dead ReLU' collapse (when 40% of hidden neurons output permanent zeros and loss flatlines!) lets you fix broken training runs in seconds instead of guessing.
Favorite modern ML interview question: 'Why did GPT/BERT switch from ReLU to GELU, why did Llama switch from GELU to SwiGLU, and why does SwiGLU shrink its hidden width from 4d to (8/3)d?'
Suppose a ReLU neuron receives a huge bad gradient step that slams its bias down to b = −50, so its pre-activation z = w·x + b is negative for EVERY training example. What happens on all future training steps?
- Explain why ReLU(x) = max(0, x) solved positive-side vanishing gradients and accelerated training 6× over Tanh/Sigmoid
- Diagnose the Dying ReLU problem and cure it with LeakyReLU, PReLU, ELU, or lower learning rates
- Understand exact GELU(x) = x·Φ(x) and SiLU/Swish(x) = x·σ(x) — why smooth non-monotonic dips improve deep optimization
- Trace the modern SwiGLU gated FFN architecture used in Llama, Gemma, and PaLM and implement it from scratch in PyTorch
Imagine passing a whispered message down a line of 20 people. With Sigmoid, every person speaks at 25% volume — by person #10 it's silent. With ReLU, every active person speaks at 100% volume (slope = 1.0), so the message arrives loud and clear at person #20! Then GELU and SiLU sand down ReLU's sharp corner at x = 0 into a silky-smooth curve, and SwiGLU gives every neuron its own learned volume knob!
1. ReLU & LeakyReLU: The Constant-1.0 Gradient Highway vs. Dying ReLU
In AlexNet (2012), swapping Tanh for ReLU(x) = max(0, x) made deep CNNs converge 6× faster! Why? For every positive activation (x > 0), the derivative is identically 1.0 — no exponential decay (1¹⁰⁰ = 1) and zero expensive exp() calls! Try killing and rescuing a ReLU neuron below.
ReLU Family Formulas
- ReLU: — induces natural sparsity (~50% zeros), super fast, non-saturating for .
- LeakyReLU (): — leaves a tiny non-zero slope () in the negative half so neurons can never permanently die!
- PReLU: Makes a learnable parameter trained by backprop!
- ELU: Smoothly curves toward for (), pushing mean activations closer to zero.
Pre-Activation z = -2.0 → Watch Gradient Flatline vs. Revive
2. Smooth Modern Activations: GELU & SiLU (Swish)
Why did BERT, GPT-2, GPT-3, and ViT drop ReLU for GELU (Gaussian Error Linear Unit), and why did EfficientNet & Llama adopt SiLU / Swish? Because ReLU's hard kink at x = 0 causes abrupt gradient jumps, whereas GELU & SiLU curve smoothly through zero with a gentle non-monotonic dip!
Exact Formulas for GELU & SiLU
- Intuition for GELU: Instead of deterministically zeroing out like ReLU, GELU weights by the probability that beats random Gaussian noise ()!
- Non-zero negative gradient near 0: Slightly negative inputs (e.g., ) still pass a smooth negative value and non-zero gradient, smoothing the loss landscape and preventing dead neurons!
At x = 0, what are the outputs and derivatives of GELU(0) and SiLU(0)?
3. SwiGLU: The Gated Powerhouse Inside Frontier LLMs (Llama / Gemma)
In 2020, Noam Shazeer discovered that replacing a standard 2-matrix FFN (W_down · GELU(W_up · x)) with a Gated Linear Unit using SiLU (SwiGLU) consistently improved perplexity across every model scale — becoming the universal default in Llama 2/3, Mistral, PaLM, and Gemma!
The SwiGLU Equation & Parameter-Budget Trick
- Why 3 matrices instead of 2? One branch computes the content () and a parallel branch computes a smooth dynamic gate () that selectively amplifies or suppresses features per token!
- Interview Gold (The Rule): Because SwiGLU uses 3 weight matrices instead of 2, to keep the EXACT same parameter count as a classic -wide FFN (), Llama shrinks its hidden width to ()!
Hand-Trace a SwiGLU Gate on One Feature Vector
Suppose x·W_gate = [2.0, −3.0] and x·W_up = [4.0, 5.0]. Watch how the SiLU gate filters the value branch!
SiLU(2.0) = 2.0 × σ(2.0) = 2.0 × 0.881 = +1.762. SiLU(−3.0) = −3.0 × σ(−3.0) = −3.0 × 0.047 = −0.142.
A classic Transformer FFN has d_model = 4096 and d_ff = 4 × 4096 = 16,384 (2 matrices: up & down). What hidden width d_ff should a 3-matrix SwiGLU FFN use to keep the exact same parameter count?
4. Practical Activation Cheat-Sheet (Which One Should I Pick Today?)
With 10+ activations out there, here is the exact decision rule used by top Deep Learning engineers in 2026:
Modern Activation Selection Guide
- Default for CNNs & Fast Edge Vision:
nn.ReLU()(ornn.SiLU()for EfficientNet/YOLOv8/ConvNeXt). - Default for MLPs & Standard Transformers:
nn.GELU()(smooth, zero dying neurons). - Default for Frontier LLMs & High-Capacity FFNs: SwiGLU (
F.silu(gate(x)) * up(x)). - If You See Dead Neurons in a ReLU Net: Switch to
nn.LeakyReLU(0.01)ornn.GELU()and lower your learning rate! - Output Layer: None (regression / PyTorch
CrossEntropyLoss),Sigmoid(binary/multi-label inference),Softmax(multi-class inference).
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
In practice, PyTorch uses a subgradient and simply defines ReLU'(0) = 0! Because floating-point numbers hit exact 0.0000000 with almost zero probability during training, this works seamlessly.
10-Layer Backward Gradient Survival: Sigmoid vs. ReLU vs. GELU vs. SwiGLU
Watch the reverse crimson gradient wave travel from Loss (Layer 10) back to Layer 1!
ResNets & MobileNets (ReLU / ReLU6)
ReLU's zero-cost thresholding runs ultra-fast on mobile NPUs and embedded edge cameras.
BERT, GPT & ViT (GELU)
Smooth Gaussian gating eliminates ReLU kinks across deep Transformer blocks.
Llama 3, Mistral & Gemma (SwiGLU)
Gated SiLU FFNs consistently win scaling-law benchmarks at equal parameter budgets.
GAN Discriminators (LeakyReLU)
LeakyReLU (0.2) prevents sparse zero gradients from collapsing GAN training!
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
# 1. Exact GELU & SiLU from scratch in PyTorch
def exact_gelu(x: torch.Tensor) -> torch.Tensor:
return 0.5 * x * (1.0 + torch.erf(x / math.sqrt(2.0)))
def silu_scratch(x: torch.Tensor) -> torch.Tensor:
return x * torch.sigmoid(x)
# 2. Production Llama-style SwiGLU Feed-Forward Network
class SwiGLUFFN(nn.Module):
def __init__(self, d_model: int, d_ff: int):
super().__init__()
self.w_gate = nn.Linear(d_model, d_ff, bias=False)
self.w_up = nn.Linear(d_model, d_ff, bias=False)
self.w_down = nn.Linear(d_ff, d_model, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
# x: (B, T, d_model) -> gated: (B, T, d_ff) -> out: (B, T, d_model)
return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))
(8/3)d instead of 4d.(2/3) × 4d = (8/3)d keeps total parameters & FLOPs identical!nn.ReLU(inplace=True) carelessly when a residual skip branch still needs the pre-ReLU tensor.inplace=False unless memory-constrained.2 / fan_in)!⊙ symbol represent in SwiGLU(x) = (SiLU(xW_gate) ⊙ (xW_up)) W_down?