In Part 3 of this series, we saw why ReLU (max(0, x)) displaced sigmoid and tanh inside deep hidden layers. Holding a slope of 1 across positive inputs keeps backward learning signals alive across depth, while requiring only a single comparison against zero.
Look closely around zero, however, and ReLU enforces a rigid binary policy. Every negative score collapses cleanly to 0, every positive score passes unchanged, and right at x = 0 the curve bends through an abrupt corner where the slope jumps from 0 to 1. That raises two practical questions: what happens inside hidden layers if we replace that hard cutoff with a smooth curve or input-dependent gate, and what happens at the output layer when scores must turn into probabilities?
To answer both cleanly, we split activations by where they sit inside Linear -> Activation -> ... -> Output. Inside hidden layers, we derive ELU, GELU, SiLU (Swish), and Softplus on the exact same test inputs (x = +1 and x = -1) so every curve and slope sits side by side without black boxes. At the output layer, we derive Softmax from raw logits, unpack its numerical stability trick and a notorious PyTorch loss trap, and establish one guiding rule for matching every layer to its target range.
ELU: smoothing the negative side instead of going flat
The Exponential Linear Unit (ELU), introduced by Clevert, Unterthiner, and Hochreiter in 2015, keeps ReLU's exact linear highway on the positive side while bending smoothly downward below zero instead of dropping flat:
Look at why the left branch subtracts 1 inside alpha * (e^x - 1). Because e^0 = 1, setting x = 0 yields alpha * (1 - 1) = 0, so the negative curve meets the positive line y = x seamlessly at (0, 0). Even better, when PyTorch uses its default alpha = 1.0, the left-branch derivative alpha * e^x evaluates at x = 0 to 1.0 * e^0 = 1, matching the positive slope 1 on the nose. Unlike ReLU or Leaky ReLU, ELU(alpha=1.0) has zero kink in either value or slope at the origin.
Trace our two benchmark inputs, x = +1 and x = -1, using alpha = 1.0:
- At
x = +1: sincex > 0, ELU acts as the identity, returningELU(1) = 1.000with gradient slope1.000. - At
x = -1: sincex <= 0,e^(-1) ≈ 0.368, givingELU(-1) = 0.368 - 1 = -0.632with non-zero gradient slope0.368. - Far left (
x -> -infinity):e^x -> 0, so outputs glide gently toward the horizontal floor-alpha(-1.0whenalpha = 1.0) rather than plunging linearly forever.
GELU: weighting inputs by a smooth bell-curve gate
Rather than carving x <= 0 and x > 0 with two separate formulas, the Gaussian Error Linear Unit (GELU), introduced by Dan Hendrycks and Kevin Gimpel in 2016, reframes activation as a smooth probability gate. Instead of strictly flipping inputs on or off at zero, GELU scales every value x by where x lands along a standard normal bell curve:
To strip away any mystery from Phi(x) (the standard normal cumulative distribution function), picture drawing random numbers from a standard bell curve centered at 0 with spread 1. For any score x, Phi(x) simply answers: what fraction of that bell curve falls at or below x? Because total area under the bell curve equals 1, Phi(x) grows smoothly from 0 on the far left to 0.5 at the midpoint x = 0, then approaches 1 on the far right.
Plug in our test points directly from that bell-curve geometry:
- At
x = 0: exact symmetry places half the bell curve to the left, soPhi(0) = 0.500andGELU(0) = 0 * 0.500 = 0.000(with slope0.500). - At
x = +1: one standard deviation above the center covers half the curve below zero plus half of the68.3%middle band inside[-1, +1], totaling50% + 34.1% = 84.1%(Phi(1) ≈ 0.841), soGELU(1) ≈ 1 * 0.841 = 0.841. Strongly positive scores stay nearly intact (GELU(3) ≈ 2.996), while small positive scores are gently damped. - At
x = -1: by left-right symmetry, only15.9%of the curve sits below-1(Phi(-1) = 1 - 0.841 = 0.159), givingGELU(-1) ≈ (-1) * 0.159 = -0.159. Strongly negative inputs get gated close to zero (GELU(-3) ≈ -0.004), while mildly negative evidence keeps a soft voice.
One geometric surprise pops out near -0.75: because multiplying a small negative x by a shrinking positive weight Phi(x) briefly drops faster than Phi(x) decays, GELU is not strictly monotonic on the left. It dips to a shallow minimum of -0.170 near x ≈ -0.752 before returning smoothly toward 0 on the left and climbing through (0, 0) on the right, giving a smooth curve that became a common default inside modern Transformer blocks such as BERT and GPT-style feed-forward networks.
If you ever see that tanh approximation in a paper or codebase, do not memorize its constants. Early accelerators lacked fast hardware instructions for the Gaussian error function erf, so Hendrycks and Gimpel fitted a fast tanh polynomial that matches exact GELU to within roughly 0.0004 across [-3, 3]. In modern PyTorch, calling nn.GELU() uses the exact erf form (approximate="none") by default, while passing approximate="tanh" switches to the classic approximation if you explicitly need parity with an older checkpoint.
SiLU (Swish): self-gating with the sigmoid you already know
What happens if you keep GELU's exact multiplicative gating idea (x * gate), yet build the gate out of the ordinary logistic sigmoid sigma(x) = 1 / (1 + e^(-x)) from Part 3 instead of a Gaussian bell curve? You get SiLU, the Sigmoid-Weighted Linear Unit, also widely known as Swish:
Trace that mechanism as a two-branch circuit: input x splits down two parallel wires. The top wire passes x through sigma(x) to produce a smooth valve value strictly inside (0, 1). The bottom wire carries raw x untouched. Multiplication then joins the two wires back together. Because x opens or closes the gate that multiplies x itself, engineers describe SiLU as self-gated. Notice the dual history in the literature too: Elfwing, Uchibe, and Doya introduced it under the name SiLU in 2017, and Ramachandran, Zoph, and Le popularized the same form (x * sigma(beta * x) with default beta = 1) after automated architecture search under the name Swish.
- At
x = +1: earlier we sawsigma(1) = 1 / (1 + e^(-1)) ≈ 0.731, soSiLU(1) ≈ 1 * 0.731 = 0.731(slope≈ 0.928). Because sigmoid approaches1more gradually thanPhi(x), SiLU dampsx = +1a little more strongly than GELU's0.841. - At
x = 0:sigma(0) = 0.500, soSiLU(0) = 0.000with slope0.500, matching GELU right through the origin. - At
x = -1:sigma(-1) = 1 - 0.731 = 0.269, givingSiLU(-1) ≈ (-1) * 0.269 = -0.269. SiLU's negative pocket dips slightly deeper (reaching-0.278nearx ≈ -1.278) before approaching0on the far left.
Many recent Transformer architectures (including several open-weight language models following Shazeer, 2020) build their feed-forward blocks around a two-projection cousin called SwiGLU, which gates one linear projection using SiLU applied to a separate learned projection (SiLU(x W_gate) * (x W_up)). Full Transformer block dimensions belong to a dedicated architecture lesson later on, yet seeing SiLU here already makes every piece of that name click.
Comparing ReLU, ELU, GELU, and SiLU: evolution, not strict replacement
Plotting the activation values alongside their exact derivatives across x in [-3, 3] makes clear what smoothing around zero changes and what stays invariant:
ELU shown with default alpha = 1.0, and GELU uses exact erf
ReLU snaps hard onto y = 0 for all x <= 0. ELU drops smoothly toward -1.0, while GELU and SiLU dip briefly negative near zero before fading back toward 0 on the left.
| Input x | ReLU | ELU (alpha = 1) | GELU | SiLU (Swish) |
|---|---|---|---|---|
| -3 | 0 | -0.95 | -0.004 | -0.142 |
| -2.5 | 0 | -0.918 | -0.016 | -0.19 |
| -2 | 0 | -0.865 | -0.046 | -0.238 |
| -1.5 | 0 | -0.777 | -0.1 | -0.274 |
| -1 | 0 | -0.632 | -0.159 | -0.269 |
| -0.5 | 0 | -0.393 | -0.154 | -0.189 |
| 0 | 0 | 0 | 0 | 0 |
| 0.5 | 0.5 | 0.5 | 0.346 | 0.311 |
| 1 | 1 | 1 | 0.841 | 0.731 |
| 1.5 | 1.5 | 1.5 | 1.4 | 1.226 |
| 2 | 2 | 2 | 1.954 | 1.762 |
| 2.5 | 2.5 | 2.5 | 2.484 | 2.31 |
| 3 | 3 | 3 | 2.996 | 2.858 |
Negative slopes on GELU and SiLU reflect their slight non-monotonic dip left of zero
ReLU jumps discontinuously from 0 to 1 at the origin. ELU rises continuously to 1 at zero when alpha = 1, while GELU and SiLU pass smoothly through slope 0.5 at x = 0.
| Input x | ReLU slope | ELU slope | GELU slope | SiLU slope |
|---|---|---|---|---|
| -3 | 0 | 0.05 | -0.012 | -0.088 |
| -2.5 | 0 | 0.082 | -0.038 | -0.099 |
| -2 | 0 | 0.135 | -0.085 | -0.091 |
| -1.5 | 0 | 0.223 | -0.127 | -0.041 |
| -1 | 0 | 0.368 | -0.083 | 0.072 |
| -0.5 | 0 | 0.607 | 0.133 | 0.26 |
| 0 | 0 | 1 | 0.5 | 0.5 |
| 0.5 | 1 | 1 | 0.867 | 0.74 |
| 1 | 1 | 1 | 1.083 | 0.928 |
| 1.5 | 1 | 1 | 1.127 | 1.041 |
| 2 | 1 | 1 | 1.085 | 1.091 |
| 2.5 | 1 | 1 | 1.038 | 1.099 |
| 3 | 1 | 1 | 1.012 | 1.088 |
Think of the arc across Sigmoid and Tanh -> ReLU -> Leaky ReLU and ELU -> GELU and SiLU as a story of problem -> trade-off -> design evolution, not a strict historical replacement chain where every newcomer obsoletes the previous one. ReLU remains widely used across convolutional networks, tabular MLPs, and latency-critical edge models precisely because comparing against zero is nearly free in hardware. Meanwhile, many modern Transformers choose GELU or SiLU where smoother gating around zero helps gradient optimization.
Softplus: the always-positive smooth twin of ReLU
One more hidden-style curve belongs in your toolkit because it pops up whenever an output quantity must stay strictly positive rather than merely nonlinear. The Softplus function is defined using the natural logarithm (ln, base e):
Read why Softplus hugs ReLU closely at both tails directly from the algebra. When x is large and positive (say x = +3), e^3 ≈ 20.086 dominates 1, so ln(1 + 20.086) = 3.049 tracks y = x smoothly from just above. When x is strongly negative (say x = -3), e^(-3) ≈ 0.050 is tiny, so ln(1.050) ≈ 0.049 glides gently toward 0 without ever touching zero or going negative. Right at x = 0, e^0 = 1, giving Softplus(0) = ln(2) ≈ 0.693. And differentiating ln(1 + e^x) gives e^x / (1 + e^x), and dividing both numerator and denominator by e^x turns it into 1 / (e^(-x) + 1) = sigma(x), rising smoothly from 0 to 1!
Softplus crosses x = 0 at ln(2) ≈ 0.693 and stays strictly positive everywhere
Softplus tracks ReLU asymptotically on both sides while removing the corner at zero and keeping all outputs strictly above 0.
| Input x | ReLU | Softplus |
|---|---|---|
| -3 | 0 | 0.049 |
| -2.5 | 0 | 0.079 |
| -2 | 0 | 0.127 |
| -1.5 | 0 | 0.201 |
| -1 | 0 | 0.313 |
| -0.5 | 0 | 0.474 |
| 0 | 0 | 0.693 |
| 0.5 | 0.5 | 0.974 |
| 1 | 1 | 1.313 |
| 1.5 | 1.5 | 1.701 |
| 2 | 2 | 2.127 |
| 2.5 | 2.5 | 2.579 |
| 3 | 3 | 3.049 |
Why do most hidden layers still prefer ReLU, GELU, or SiLU over Softplus? First, Softplus demands both an exponential and a logarithm (exp + log), making it heavier per neuron than ReLU's single max comparison (and in PyTorch, nn.Softplus(beta=1, threshold=20) quietly returns x once beta * x > threshold to prevent e^x overflow). Second, Softplus shifts outputs upward by 0.693 at x = 0 and stays non-zero everywhere, forfeiting ReLU's clean zero sparsity. Where Softplus truly shines is on specialized outputs that must be smoothly positive without zero plateaus, such as predicted standard deviations (sigma > 0), variances, or event rates.
| Activation | f(+1) | f(-1) | f'(+1) | f'(-1) | Primary trade-off |
|---|---|---|---|---|---|
| ReLU | 1.000 | 0.000 | 1.000 | 0.000 | Fastest compute and exact zero sparsity, sharp corner at 0, can suffer dead units |
| ELU (alpha = 1) | 1.000 | -0.632 | 1.000 | 0.368 | Smooth match at 0 and bounded -alpha tail, still saturates far left, uses exp |
| GELU | 0.841 | -0.159 | 1.083 | -0.083 | Smooth bell-curve gate common in Transformers, higher compute cost than ReLU |
| SiLU (Swish) | 0.731 | -0.269 | 0.928 | 0.072 | Smooth sigmoid self-gate with slightly deeper negative dip, uses sigmoid and multiply |
| Softplus | 1.313 | 0.313 | 0.731 | 0.269 | Always positive and smooth everywhere (slope = sigmoid), exp + log overhead |
Softmax: turning output logits into competing probabilities
Notice something shared by all five functions above: every single one runs neuron by neuron on each number independently. At the output layer of a multiclass classifier (cat vs. dog vs. bird), that independence breaks down. When an example must belong to one mutually exclusive category, boosting the cat score has to pull down the share of probability left for dog and bird.
Recall from Part 1 and Part 2 that a classifier's final Linear layer outputs unconstrained raw numbers called logits (z_1, ..., z_C). Why can we not simply divide each raw logit z_i by sum(z_j) to form percentages? Because logits can easily be negative (-1.5), or sum right to 0.0, producing nonsensical negative probabilities or dividing by zero.
Softmax fixes both problems cleanly in two steps:
Step 1 passes each logit through e^(z_i). No matter whether z_i is +50, 0, or -50, e^(z_i) is always strictly positive (> 0), preserves rank order (cat still beats dog), and amplifies differences smoothly. Step 2 divides each positive score by the sum across all classes. Every resulting probability sits cleanly inside (0, 1), and the probabilities across all classes sum strictly to 1.
Walk through a concrete 3-class example with logits [cat: 2.0, dog: 1.0, bird: 0.1]: taking exponentials produces [e^2.0 ≈ 7.389, e^1.0 ≈ 2.718, e^0.1 ≈ 1.105], whose denominator sum is 11.213. Dividing each entry by 11.213 yields [0.659, 0.242, 0.099], meaning cat carries 65.9%, dog carries 24.2%, and bird carries 9.9%. Now keep dog = 1.0 and bird = 0.1 completely frozen and increase only cat from 2.0 to 3.0: e^3.0 ≈ 20.086 pushes the shared denominator to 23.909, lifting cat to 0.840 while automatically pushing dog down to 0.114 and bird down to 0.046.
Using modern activations and Softmax safely in PyTorch
All five functions live directly in torch.nn as zero-parameter modules (nn.ELU(alpha=1.0), nn.GELU(), nn.SiLU(), nn.Softplus(), and nn.Softmax(dim=-1)). Pay close attention to dim=-1 on Softmax. In real batches of shape (batch_size, num_classes) such as (32, 10), axis 0 runs across the 32 separate examples in the batch, while axis -1 (the trailing class axis) normalizes across the 10 class scores of each individual example so every row sums to 1.
Just as with binary BCEWithLogitsLoss() in Part 3, never apply nn.Softmax inside your training forward pass if you train with nn.CrossEntropyLoss(). Inside CrossEntropyLoss, PyTorch automatically computes a numerically fused log_softmax followed by negative log-likelihood loss. Feeding already-normalized probs = torch.softmax(logits, dim=-1) into CrossEntropyLoss runs Softmax a second time on numbers squeezed inside (0, 1)!
Check the exact arithmetic damage of that double-Softmax bug on our 3-class example: even if raw logits [10, 0, 0] give p_cat = 0.99991, squishing [0.99991, 0.00005, 0.00005] through Softmax again caps top confidence near e^1 / (e^1 + 2 e^0) ≈ 0.5761 and locks cross-entropy loss at a floor of 0.5515 instead of letting it drop toward 0. Pass raw logits into nn.CrossEntropyLoss(), and call torch.softmax(logits, dim=-1) only when reading out predicted probabilities at inference:
import torchimport torch.nn as nn# Hidden activations swap cleanly in the same 1,994-parameter architecture from Parts 2 & 3for act in (nn.ELU(alpha=1.0), nn.GELU(), nn.SiLU()):model = nn.Sequential(nn.Linear(20, 64),act,nn.Linear(64, 10), # 10 raw logits out, NO Softmax inside the training head)print(f"{act.__class__.__name__:5s} -> {sum(p.numel() for p in model.parameters())} params")logits = torch.tensor([[2.0, 1.0, 0.1]])targets = torch.tensor([0]) # true class is index 0 (cat)criterion = nn.CrossEntropyLoss()loss = criterion(logits, targets) # computes fused log_softmax + NLL internally# Need human-readable probabilities at evaluation or inference? Apply softmax outside the loss:with torch.no_grad():probs = torch.softmax(logits, dim=-1)print("Inference probs:", probs.squeeze(0).tolist()) # [0.659..., 0.242..., 0.098...]
Run the pure-Python experiment below directly in your browser to inspect every activation value and local derivative side by side (including extreme values like 1000.0 or -1000.0 without overflow), watch Softmax couple [cat, dog, bird] probabilities when cat jumps from 2.0 to 3.0, verify max-shift stability on huge logits, and measure the double-Softmax cross-entropy ceiling:
import mathdef sigmoid(x):if x >= 0.0:return 1.0 / (1.0 + math.exp(-x))ez = math.exp(x)return ez / (1.0 + ez)def softplus(x):return max(x, 0.0) + math.log1p(math.exp(-abs(x)))def normal_cdf(x):return 0.5 * (1.0 + math.erf(x / math.sqrt(2.0)))def inspect_hidden(x):relu_v, relu_g = (x, 1.0) if x > 0.0 else (0.0, 0.0)elu_v, elu_g = (x, 1.0) if x > 0.0 else (math.expm1(x), math.exp(x))phi = normal_cdf(x)pdf = math.exp(-0.5 * x * x) / math.sqrt(2.0 * math.pi)gelu_v, gelu_g = x * phi, phi + x * pdfs = sigmoid(x)silu_v, silu_g = x * s, s + x * s * (1.0 - s)sp_v, sp_g = softplus(x), sprint(f"--- x = {x:+.1f} ---")for name, val, slope in (("ReLU", relu_v, relu_g),("ELU", elu_v, elu_g),("GELU", gelu_v, gelu_g),("SiLU", silu_v, silu_g),("Softplus", sp_v, sp_g),):print(f" {name:8s} out={val:7.4f} slope={slope:7.4f}")def stable_softmax(logits):top = max(logits)exps = [math.exp(z - top) for z in logits]denom = sum(exps)return [e / denom for e in exps]for x in (1.0, -1.0):inspect_hidden(x)print()base = [2.0, 1.0, 0.1]raised = [3.0, 1.0, 0.1]huge = [1002.0, 1001.0, 1000.1]print("Softmax [2.0, 1.0, 0.1] ->", [round(p, 3) for p in stable_softmax(base)])print("Softmax [3.0, 1.0, 0.1] ->", [round(p, 3) for p in stable_softmax(raised)])print("Softmax [1002, 1001, 1000.1] ->", [round(p, 3) for p in stable_softmax(huge)])# Double-softmax bug check on confident raw logits [10, 0, 0] for class 0confident_logits = [10.0, 0.0, 0.0]raw_probs = stable_softmax(confident_logits)double_probs = stable_softmax(raw_probs)print(f"Correct CE loss(raw logits) = {-math.log(raw_probs[0]):.4f} (p={raw_probs[0]:.4f})")print(f"Double-Softmax CE loss = {-math.log(double_probs[0]):.4f} (capped p={double_probs[0]:.4f})")
Choosing an activation by layer position
Instead of memorizing long rulebooks, anchor every design choice in one single question: what range and behavior should this layer's output have? Tracing where the layer sits inside the network gives the answer immediately:
- Hidden layers: pick
ReLU,Leaky ReLU,GELU, orSiLU. Their job is breaking linear collapse and transmitting gradients backward across depth, not shaping final predictions. - Binary classification output: emit
1raw logit per sample and train withnn.BCEWithLogitsLoss(), keeping sigmoid conceptually for turning that logit into a(0, 1)positive probability at inference. - Multiclass mutually exclusive output: emit
Craw logits and train withnn.CrossEntropyLoss(), keepingtorch.softmax(logits, dim=-1)for probability readouts at inference. (If multiple tags can be true simultaneously rather than competing, treat each tag as its own binary logit withBCEWithLogitsLossrather than Softmax.) - Continuous regression output: leave the final
Linearlayer completely bare with no activation function when targets span arbitrary numbers like-100,0,25, or1,000, soSigmoid,Tanh, orReLUnever clip valid values. UseSoftplusonly when modeling a positive-only continuous scale such as standard deviation.
| Layer position | Typical output | PyTorch training loss / activation | Inference interpretation |
|---|---|---|---|
| Hidden layer | d_hidden feature vector | nn.ReLU(), nn.GELU(), nn.SiLU(), nn.LeakyReLU() | Feeds next linear transformation |
| Binary output | 1 raw logit | nn.BCEWithLogitsLoss() on raw logit | torch.sigmoid(logit) in (0, 1) |
| Multiclass output | C raw logits | nn.CrossEntropyLoss() on raw logits | torch.softmax(logits, dim=-1) summing to 1 |
| Regression output | 1 or k scalars | No output activation (nn.MSELoss() / nn.L1Loss()) | Direct unbounded numerical prediction |
Brain Link on YouTube
How Do You Choose the Right Activation Function? | Ep. 4
Watch the full Brain Link walkthrough tracing ELU, GELU, SiLU, Softplus, live Softmax probability bars, and the layer-by-layer selection rule.
Stepping back across Part 3 and this guide, an activation function is never mere decoration dropped between weight matrices. Paired with a Linear layer's weighted evidence, hidden activations create nonlinear features while shaping local derivatives, and gradients flow through those slopes to govern how well weights actually learn, while output heads shape logits into the target space the task requires. What turns those logits, probabilities, or scalar predictions into a training update is measuring exactly how wrong they are, which brings us next to Part 5 of this series.
References
- [1]Fast and Accurate Deep Network Learning by Exponential Linear Units (ELUs) · Djork-Arne Clevert, Thomas Unterthiner, and Sepp Hochreiter (2015)Introduces ELU for smooth negative activations and reduced bias shift toward zero.
- [2]Gaussian Error Linear Units (GELUs) · Dan Hendrycks and Kevin Gimpel (2016)Derives x * Phi(x) alongside the polynomial tanh approximation used across Transformer models.
- [3]Sigmoid-Weighted Linear Units for Neural Network Function Approximation in Reinforcement Learning · Stefan Elfwing, Eiji Uchibe, and Kenji Doya (2017)Defines SiLU as x * sigmoid(x) and analyzes its smooth gradient and negative minimum.
- [4]Searching for Activation Functions · Prajit Ramachandran, Barret Zoph, and Quoc V. Le (2017)Popularizes Swish (x * sigmoid(beta * x)) via neural architecture search across vision and language tasks.
- [5]GLU Variants Improve Transformer · Noam Shazeer (2020)Introduces SwiGLU feed-forward gating built from separate learned projections gated by Swish/SiLU.
- [6]torch.nn.ELU, nn.GELU, nn.SiLU, and nn.Softplus documentation · PyTorch documentationDocuments default approximate='none' vs 'tanh' for GELU alongside sibling zero-parameter activation modules.
- [7]torch.nn.Softmax and nn.CrossEntropyLoss documentation · PyTorch documentationSpecifies raw logit inputs for CrossEntropyLoss via fused log-softmax and negative log likelihood.
- [8]How Do You Choose the Right Activation Function? (video) · Brain Link on YouTube
- [9]Deep Learning Fundamentals playlist · Brain Link on YouTube







