MODULE 1.7: NON-LINEAR ACTIVATION FUNCTIONS

Master non-linear transformations in PyTorch. Understand why deep neural networks require non-linearity, compare piecewise-linear vs. smooth gated activations, prevent vanishing and dying gradients, and inspect live forward curves f(x) and derivatives f'(x) across 10 real-world production architectures.

⚡ Real-World Context: Breaking Linearity in Autonomous Perception & LLM Transformer Pipelines

Without non-linear activation functions, stacking dozens of nn.Linear or nn.Conv2d layers collapses algebraically into a single affine matrix multiplication (W₂(W₁x + b₁) + b₂ = W'x + b'), rendering deep architectures incapable of modeling curved decision boundaries, object contours, or contextual token semantics.

In production AI systems—from 60-FPS autonomous driving object detectors using ReLU/SiLU to billion-parameter Large Language Models powered by GELU and SwiGLU—choosing the right activation directly controls gradient flow, dead-neuron sparsity, probability calibration, and hardware execution speed.

1. nn.ReLU — High-Throughput Real-Time Object Detection Backbone (YOLOv8 / Edge Vision) & Dead Neuron Diagnosis
Evaluating f(x) = max(0, x) on an edge camera feature map to induce sparse, fast hardware activations, while diagnosing the Dying ReLU phenomenon when large negative pre-activations clamp gradients to exact 0.0.
Python (relu_edge_vision.py)
import torch
import torch.nn as nn

# Edge vision feature map channels (negative values represent suppressed background noise)
pre_activations = torch.tensor([-3.2, -0.8, 0.0, 1.4, 3.6], requires_grad=True)

relu = nn.ReLU()
activations = relu(pre_activations)
activations.sum().backward()

dead_ratio = (activations == 0).float().mean().item() * 100.0

print("Pre-Activation Feature Map :", pre_activations.detach().tolist())
print("ReLU Output max(0, x)      :", activations.detach().tolist())
print("Backward Gradients f'(x)   :", pre_activations.grad.tolist())
print(f"Inactive / Zeroed Channels : {dead_ratio:.1f}% (Zero gradient for x <= 0)")
Output:
Pre-Activation Feature Map : [-3.200000047683716, -0.800000011920929, 0.0, 1.399999976158142, 3.5999999046325684]
ReLU Output max(0, x)      : [0.0, 0.0, 0.0, 1.399999976158142, 3.5999999046325684]
Backward Gradients f'(x)   : [0.0, 0.0, 0.0, 1.0, 1.0]
Inactive / Zeroed Channels : 60.0% (Zero gradient for x <= 0)
2. nn.LeakyReLU & nn.PReLU — Preventing Dying Gradients in Generative Adversarial Networks (GAN Discriminators)
In synthetic medical image GAN discriminators, standard ReLU starves generator updates whenever discriminator pre-activations turn negative. LeakyReLU(negative_slope=0.1) preserves a constant non-zero slope for x < 0, while PReLU learns optimal per-channel negative slopes via backpropagation.
Python (leaky_prelu_gan.py)
import torch
import torch.nn as nn

x = torch.tensor([-2.5, -0.5, 0.5, 2.5], requires_grad=True)

# 1. LeakyReLU with fixed negative_slope = 0.1
leaky_relu = nn.LeakyReLU(negative_slope=0.1)
y_leaky = leaky_relu(x)
y_leaky.sum().backward()
leaky_grads = x.grad.clone()

# 2. Parametric ReLU (PReLU) with learnable slope parameter alpha
x.grad.zero_()
prelu = nn.PReLU(num_parameters=1, init=0.25)
y_prelu = prelu(x)
y_prelu.sum().backward()

print("Input Pre-Activations     :", x.detach().tolist())
print("LeakyReLU(0.1) Output     :", [round(v, 3) for v in y_leaky.detach().tolist()])
print("LeakyReLU Gradients       :", [round(g, 3) for g in leaky_grads.tolist()])
print("PReLU(0.25) Output        :", [round(v, 3) for v in y_prelu.detach().tolist()])
print("Learnable Slope alpha.grad:", round(prelu.weight.grad.item(), 3))
Output:
Input Pre-Activations     : [-2.5, -0.5, 0.5, 2.5]
LeakyReLU(0.1) Output     : [-0.25, -0.05, 0.5, 2.5]
LeakyReLU Gradients       : [0.1, 0.1, 1.0, 1.0]
PReLU(0.25) Output        : [-0.625, -0.125, 0.5, 2.5]
Learnable Slope alpha.grad: -3.0
3. nn.ELU & nn.SELU — Self-Normalizing Tabular Credit Risk & Fraud Scoring Networks
Exponential Linear Units (ELU) push mean activations closer to zero via smooth negative saturation (α(eˣ - 1)), while Scaled ELU (SELU, paired with AlphaDropout and LeCun Normal init) automatically converges deep tabular MLPs toward zero mean and unit variance without BatchNorm.
Python (elu_selu_tabular.py)
import torch
import torch.nn as nn

torch.manual_seed(42)
x_sample = torch.tensor([-2.0, -0.5, 0.0, 1.0, 2.0], requires_grad=True)

elu = nn.ELU(alpha=1.0)
selu = nn.SELU()

y_elu = elu(x_sample)
y_selu = selu(x_sample)
y_selu.sum().backward()

# Demonstrate SELU self-normalizing fixed point across an 8-layer tabular MLP
layers = []
for _ in range(8):
    lin = nn.Linear(256, 256)
    nn.init.kaiming_normal_(lin.weight, mode="fan_in", nonlinearity="linear")
    nn.init.zeros_(lin.bias)
    layers.extend([lin, nn.SELU()])
snn = nn.Sequential(*layers)

deep_out = snn(torch.randn(128, 256))
print("ELU Output (alpha=1.0)  :", [round(v, 4) for v in y_elu.detach().tolist()])
print("SELU Output             :", [round(v, 4) for v in y_selu.detach().tolist()])
print("SELU Gradients f'(x)    :", [round(g, 4) for g in x_sample.grad.tolist()])
print(f"8-Layer SELU Output Stats -> Mean: {deep_out.mean().item():.4f} | Std: {deep_out.std().item():.4f}")
Output:
ELU Output (alpha=1.0)  : [-0.8647, -0.3935, 0.0, 1.0, 2.0]
SELU Output             : [-1.5202, -0.6918, 0.0, 1.0507, 2.1014]
SELU Gradients f'(x)    : [0.238, 1.0663, 1.0507, 1.0507, 1.0507]
8-Layer SELU Output Stats -> Mean: -0.0084 | Std: 0.9912
4. nn.GELU — Gaussian Error Linear Units in Modern Transformer & LLM FFN Blocks (BERT / GPT)
Gaussian Error Linear Unit weights inputs smoothly by their cumulative normal probability x · Φ(x)—exhibiting a smooth, non-monotonic negative dip near x ≈ -0.75 that improves optimization landscapes in BERT, ViT, and GPT transformer feed-forward layers.
Python (gelu_transformer_ffn.py)
import torch
import torch.nn as nn

tokens = torch.tensor([-2.0, -0.75, 0.0, 0.75, 2.0], requires_grad=True)

# Exact erf-based GELU vs. fast tanh approximation used in hardware-fused kernels
gelu_exact = nn.GELU(approximate="none")
gelu_tanh = nn.GELU(approximate="tanh")

out_exact = gelu_exact(tokens)
out_tanh = gelu_tanh(tokens)
out_exact.sum().backward()

print("Token Pre-Activations :", tokens.detach().tolist())
print("GELU (exact erf)      :", [round(v, 4) for v in out_exact.detach().tolist()])
print("GELU (tanh approx)    :", [round(v, 4) for v in out_tanh.detach().tolist()])
print("GELU Gradients f'(x)  :", [round(g, 4) for g in tokens.grad.tolist()])
Output:
Token Pre-Activations : [-2.0, -0.75, 0.0, 0.75, 2.0]
GELU (exact erf)      : [-0.0455, -0.17, 0.0, 0.58, 1.9545]
GELU (tanh approx)    : [-0.0454, -0.1701, 0.0, 0.5801, 1.9546]
GELU Gradients f'(x)  : [-0.0852, -0.0725, 0.5, 1.0725, 1.0852]
5. nn.SiLU (Swish) & SwiGLU — Gated Linear Units in LLaMA-3 & EfficientNet Architectures
Self-gated SiLU(x) = x · σ(x) powers EfficientNet and YOLOv8 backbones, while SwiGLU (SiLU(xW_gate) ⊙ (xW_up)) serves as the standard feed-forward block in LLaMA-3, Mistral, and PaLM—multiplicatively gating information flow across hidden channels.
Python (silu_swiglu_llama.py)
import torch
import torch.nn as nn
import torch.nn.functional as F

class SwiGLUFeedForward(nn.Module):
    """LLaMA-style SwiGLU FFN block combining SiLU gating with bilinear projection."""
    def __init__(self, d_model: int, hidden_dim: int):
        super().__init__()
        self.w_gate = nn.Linear(d_model, hidden_dim, bias=False)
        self.w_up = nn.Linear(d_model, hidden_dim, bias=False)
        self.w_down = nn.Linear(hidden_dim, d_model, bias=False)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))

x_vals = torch.tensor([-2.5, -1.28, 0.0, 1.5, 3.0], requires_grad=True)
silu_out = F.silu(x_vals)
silu_out.sum().backward()

torch.manual_seed(7)
swiglu = SwiGLUFeedForward(d_model=64, hidden_dim=172)
token_seq = torch.randn(2, 16, 64)

print("SiLU(x) Values       :", [round(v, 4) for v in silu_out.detach().tolist()])
print("SiLU Gradients f'(x) :", [round(g, 4) for g in x_vals.grad.tolist()])
print("SwiGLU Output Shape  :", swiglu(token_seq).shape)
Output:
SiLU(x) Values       : [-0.1896, -0.2784, 0.0, 1.2264, 2.8577]
SiLU Gradients f'(x) :", [-0.1142, -0.0008, 0.5, 1.0414, 1.0926]
SwiGLU Output Shape  : torch.Size([2, 16, 64])
6. nn.Sigmoid — Multi-Label Medical Chest X-Ray Pathology Probability Calibration & Gate Control
Squashing raw logits into independent (0, 1) Bernoulli probabilities via σ(x) = 1 / (1 + e⁻ˣ) for multi-label radiology findings (where a patient may simultaneously present Cardiomegaly and Effusion), while demonstrating gradient saturation (f'(x) ≤ 0.25) at extreme logits.
Python (sigmoid_medical_multilabel.py)
import torch
import torch.nn as nn

# Independent pathology logits: [Atelectasis, Cardiomegaly, Effusion, Pneumonia, Nodule]
xray_logits = torch.tensor([-4.5, 1.8, 0.0, 2.4, -1.2], requires_grad=True)

sigmoid = nn.Sigmoid()
probs = sigmoid(xray_logits)
probs.sum().backward()

pathologies = ["Atelectasis", "Cardiomegaly", "Effusion", "Pneumonia", "Nodule"]
for name, logit, p, grad in zip(pathologies, xray_logits.tolist(), probs.tolist(), xray_logits.grad.tolist()):
    print(f"{name:<13} | Logit: {logit:>5.1f} | Prob: {p:.4f} | Sigmoid Grad f'(x): {grad:.4f}")
Output:
Atelectasis   | Logit:  -4.5 | Prob: 0.0110 | Sigmoid Grad f'(x): 0.0109
Cardiomegaly  | Logit:   1.8 | Prob: 0.8581 | Sigmoid Grad f'(x): 0.1217
Effusion      | Logit:   0.0 | Prob: 0.5000 | Sigmoid Grad f'(x): 0.2500
Pneumonia     | Logit:   2.4 | Prob: 0.9168 | Sigmoid Grad f'(x): 0.0763
Nodule        | Logit:  -1.2 | Prob: 0.2315 | Sigmoid Grad f'(x): 0.1779
7. nn.Tanh — Zero-Centered Recurrent State Gating (LSTM/GRU) & Continuous Robotic Torque Control
Hyperbolic tangent maps inputs into symmetric, zero-centered (-1, +1) outputs with peak derivative f'(0) = 1.0—preventing zig-zagging weight updates in recurrent hidden states and bounding continuous bidirectional joint torque commands in robotic policy networks.
Python (tanh_robotics_control.py)
import torch
import torch.nn as nn

# Raw policy network outputs for 5 robotic arm actuators (Nm max torque = 15.0)
raw_action = torch.tensor([-2.5, -0.8, 0.0, 0.8, 2.5], requires_grad=True)
max_torque_nm = 15.0

tanh = nn.Tanh()
normalized_action = tanh(raw_action)
normalized_action.sum().backward()

joint_torques = normalized_action.detach() * max_torque_nm

print("Raw Policy Logits       :", raw_action.detach().tolist())
print("Tanh Normalized (-1,+1) :", [round(v, 4) for v in normalized_action.detach().tolist()])
print("Scaled Joint Torques Nm :", [round(t, 2) for t in joint_torques.tolist()])
print("Tanh Gradients 1-tanh²  :", [round(g, 4) for g in raw_action.grad.tolist()])
Output:
Raw Policy Logits       : [-2.5, -0.800000011920929, 0.0, 0.800000011920929, 2.5]
Tanh Normalized (-1,+1) : [-0.9866, -0.664, 0.0, 0.664, 0.9866]
Scaled Joint Torques Nm : [-14.8, -9.96, 0.0, 9.96, 14.8]
Tanh Gradients 1-tanh²  : [0.0266, 0.5591, 1.0, 0.5591, 0.0266]
8. nn.Softmax & nn.LogSoftmax — Temperature-Scaled Token Sampling in LLM Decoding & Multi-Class Classification
Normalizing mutually exclusive next-token logits into a simplex distribution summing to 1.0 via softmax(z / T), demonstrating how decoding temperature T sharpens greedy determinism (T = 0.3) or flattens creative exploration (T = 2.0).
Python (softmax_temperature_llm.py)
import torch
import torch.nn.functional as F

# Candidate next-token logits for ["PyTorch", "TensorFlow", "JAX", "NumPy"]
next_token_logits = torch.tensor([3.2, 1.8, 1.5, 0.4])

for temp in [0.3, 1.0, 2.0]:
    probs = F.softmax(next_token_logits / temp, dim=-1)
    print(f"Temp T={temp:<3} -> Probs: {[round(p, 4) for p in probs.tolist()]} | Sum={probs.sum().item():.1f}")

log_probs = F.log_softmax(next_token_logits, dim=-1)
print("LogSoftmax (T=1.0)    :", [round(lp, 4) for lp in log_probs.tolist()])
Output:
Temp T=0.3 -> Probs: [0.9873, 0.0093, 0.0034, 0.0001] | Sum=1.0
Temp T=1.0 -> Probs: [0.6805, 0.1678, 0.1243, 0.0414] | Sum=1.0
Temp T=2.0 -> Probs: [0.4649, 0.2309, 0.1987, 0.1146] | Sum=1.0
LogSoftmax (T=1.0)    : [-0.3849, -1.7849, -2.0849, -3.1849]
9. nn.Softplus & nn.Mish — Smooth Positive Variance Prediction in Probabilistic Forecasting & CSPDarknet
Softplus(x) = (1/β) log(1 + e^(βx)) acts as a smooth, infinitely differentiable approximation to ReLU used to predict strictly positive Gaussian standard deviations (σ > 0) in probabilistic demand forecasting, while Mish(x) = x · tanh(softplus(x)) provides non-monotonic smoothness in vision backbones.
Python (softplus_mish_forecasting.py)
import torch
import torch.nn as nn

raw_scale = torch.tensor([-3.0, -1.0, 0.0, 1.0, 3.0], requires_grad=True)

softplus = nn.Softplus(beta=1.0)
mish = nn.Mish()

# Enforce strictly positive standard deviation sigma >= 1e-4 for Gaussian NLL loss
predicted_sigma = softplus(raw_scale) + 1e-4
mish_features = mish(raw_scale)
predicted_sigma.sum().backward()

print("Raw Forecast Head Logits :", raw_scale.detach().tolist())
print("Softplus Positive Sigma  :", [round(v, 4) for v in predicted_sigma.detach().tolist()])
print("Softplus Grad (Sigmoid)  :", [round(g, 4) for g in raw_scale.grad.tolist()])
print("Mish Vision Activations  :", [round(v, 4) for v in mish_features.detach().tolist()])
Output:
Raw Forecast Head Logits : [-3.0, -1.0, 0.0, 1.0, 3.0]
Softplus Positive Sigma  : [0.0487, 0.3134, 0.6932, 1.3134, 3.0487]
Softplus Grad (Sigmoid)  : [0.0474, 0.2689, 0.5, 0.7311, 0.9526]
Mish Vision Activations  : [-0.1456, -0.3034, 0.0, 0.8651, 2.9865]
10. Custom Learnable Activation (nn.Module) & In-Place (inplace=True) Memory Pitfalls with Autograd
Implementing a custom learnable Swish-β activation module (x · σ(βx)) where β adapts during training, and demonstrating why calling nn.ReLU(inplace=True) directly on a leaf or branched tensor triggers an Autograd version-counter RuntimeError.
Python (custom_activation_inplace_pitfall.py)
import torch
import torch.nn as nn

class LearnableSwish(nn.Module):
    """Custom activation f(x) = x * sigmoid(beta * x) with trainable beta."""
    def __init__(self, init_beta: float = 1.0):
        super().__init__()
        self.beta = nn.Parameter(torch.tensor(init_beta))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return x * torch.sigmoid(self.beta * x)

act = LearnableSwish(init_beta=1.5)
inp = torch.tensor([-2.0, -0.5, 0.5, 2.0], requires_grad=True)
out = act(inp)
out.sum().backward()

print("LearnableSwish Output :", [round(v, 4) for v in out.detach().tolist()])
print("Gradient w.r.t. beta  :", round(act.beta.grad.item(), 4))

# Demonstrate inplace=True Autograd hazard when original tensor is needed for backward()
leaf_tensor = torch.tensor([-1.0, 2.0], requires_grad=True)
try:
    bad_out = nn.ReLU(inplace=True)(leaf_tensor)
    bad_out.sum().backward()
except RuntimeError as err:
    print("In-Place Autograd Trap:", str(err).splitlines()[0])
Output:
LearnableSwish Output : [-0.0949, -0.1604, 0.3396, 1.9051]
Gradient w.r.t. beta  : 0.4359
In-Place Autograd Trap: a leaf Variable that requires grad is being used in an in-place operation.