🤖 AI/ML

GELU

Gaussian Error Linear Unit

An activation function used in Transformers. Has a stochastic regularization effect.

📖 Detailed Explanation

GELU (Gaussian Error Linear Unit) is an activation function proposed by Dan Hendrycks and Kevin Gimpel in 2016, formed by multiplying the input value by the cumulative distribution function (CDF) of the standard normal distribution. The formula is GELU(x) = x * Phi(x), where Phi is the CDF of the standard normal distribution.

The core idea of GELU is probabilistic regularization. The larger the input value, the higher the probability of passing through, and the smaller it is, the closer it gets to 0. Unlike ReLU's hard zeroing, this provides smooth nonlinearity and allows a small gradient even in the negative region.

GELU is used as the standard activation function in most Transformer-based models, such as BERT, GPT, and ViT. According to research, GELU shows an average performance improvement of 0.3-0.5% over ReLU on NLP tasks, and is particularly effective in pretrained models.

In practice, an approximate version is often used instead of the exact GELU. PyTorch's tanh approximation (x * 0.5 * (1 + tanh(sqrt(2/pi) * (x + 0.044715 * x^3)))) is computationally efficient while showing nearly the same performance as the original.

💻 Code Example

import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt

# PyTorch 내장 GELU
gelu_layer = nn.GELU()

# 정확한 GELU 구현
def gelu_exact(x):
    """GELU(x) = x * Phi(x) where Phi is CDF of standard normal"""
    return x * 0.5 * (1.0 + torch.erf(x / np.sqrt(2.0)))

# 빠른 근사 GELU (tanh approximation)
def gelu_tanh_approx(x):
    """Fast GELU approximation using tanh"""
    return 0.5 * x * (1.0 + torch.tanh(
        np.sqrt(2.0 / np.pi) * (x + 0.044715 * torch.pow(x, 3))
    ))

# Transformer 블록에서 GELU 사용 예시
class TransformerFFN(nn.Module):
    def __init__(self, d_model=768, d_ff=3072, dropout=0.1):
        super().__init__()
        self.linear1 = nn.Linear(d_model, d_ff)
        self.linear2 = nn.Linear(d_ff, d_model)
        self.dropout = nn.Dropout(dropout)
        self.gelu = nn.GELU()

    def forward(self, x):
        # FFN: Linear -> GELU -> Dropout -> Linear -> Dropout
        x = self.linear1(x)
        x = self.gelu(x)
        x = self.dropout(x)
        x = self.linear2(x)
        x = self.dropout(x)
        return x

# 활성화 함수 비교 시각화
x = torch.linspace(-4, 4, 1000)

plt.figure(figsize=(10, 6))
plt.plot(x.numpy(), F.relu(x).numpy(), label='ReLU', linewidth=2)
plt.plot(x.numpy(), gelu_exact(x).numpy(), label='GELU (exact)', linewidth=2)
plt.plot(x.numpy(), gelu_tanh_approx(x).numpy(), label='GELU (approx)',
         linewidth=2, linestyle='--')
plt.axhline(y=0, color='gray', linestyle='-', alpha=0.3)
plt.axvline(x=0, color='gray', linestyle='-', alpha=0.3)
plt.xlabel('Input')
plt.ylabel('Output')
plt.title('Activation Function Comparison')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

# BERT/GPT 스타일 모델에서 사용
class BertConfig:
    hidden_size = 768
    intermediate_size = 3072
    hidden_act = "gelu"  # GPT-2는 "gelu_new" 사용

print(f"GELU(-1.0) = {gelu_exact(torch.tensor(-1.0)).item():.4f}")  # ~-0.1587
print(f"GELU(0.0) = {gelu_exact(torch.tensor(0.0)).item():.4f}")    # 0.0
print(f"GELU(1.0) = {gelu_exact(torch.tensor(1.0)).item():.4f}")    # ~0.8413

🗣️ Say It Like This in Practice

Technical Interview Scenario

"Why does GELU show better performance than ReLU in Transformers?" - "GELU allows a small gradient even for negative inputs, so it has fewer dying neuron problems, and its smooth nonlinearity fits well with the attention mechanism. In particular, it enables more stable training during pretraining."

Project Meeting

"What's the difference between gelu and gelu_new in Hugging Face models?" - "gelu_new is the tanh approximation version used in GPT-2. It shows nearly the same performance as the exact GELU while being faster to compute. In most cases it doesn't matter which one you use, but it's important to use the same version as the pretrained model."

Code Review

"Is there a reason you used GELU instead of ReLU in the FFN layer?" - "We used GELU following the BERT paper. In our experiments too, GELU was about 2% lower in validation loss, and the difference was especially large on the masked language modeling task."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

1
Be Careful When Choosing the Approximation Version

In PyTorch, nn.GELU(approximate='tanh') and the default version differ slightly. When fine-tuning a pretrained model, you must use the same version as the original to ensure reproducibility.

2
Computational Cost

The exact GELU uses the erf function and is about 3-4 times slower than ReLU. When inference speed matters, consider using the tanh approximation or SiLU (Swish).

3
Numerical Stability

For very large negative inputs, the GELU gradient becomes almost 0. Underflow problems can occur during mixed precision training, so gradient clipping is recommended.

🔗 Related Terms

📚 Learn More