PyTorch torch.nn.GELU function
PyTorch torch.nn Reference Manual
torch.nn.GELU is the Gaussian Error Linear Unit activation function in PyTorch.
It is the default activation function for the Transformer architecture, offering better performance and smoother gradients than ReLU.
Function definition
torch.nn.GELU(approximate='none')
Parameter Description:
approximate(str): approximation algorithm, optional'none','tanh'. Defaults to'none'.
Mathematical principle
The mathematical formula for GELU:
GELU(x) = x * Φ(x)
where Phi(x) is the cumulative distribution function (CDF) of the standard normal distribution.
When using the tanh approximation:
GELU(x) ≈ 0.5x * (1 + tanh(√(2/π) * (x + 0.044715 * x³)))
Usage examples
Example 1: Basic usage
Creating and using GELU activation:
Example
import
torch
import
torch.
nn
as
nn
Create a GELU activation layer
gelu
=
nn.
GELU
(
)
Test input
x
=
torch.
tensor
(
[
2.0
,
1.0
,
0.0
,
1.0
,
2.0
]
)
Forward propagation
output
=
gelu
(
x
)
(
"Input:"
,
x.
tolist
(
)
)
(
"Output:"
,
output.
tolist
(
)
)
(
"nObservation: negative values are slightly activated (non-zero), positive values keep growing"
)
Example 2: Comparing different activation functions
Comparing GELU, ReLU, and Sigmoid:
Example
import
torch
import
torch.
nn
as
nn
x
=
torch.
linspace
(
4
,
4
,
21
)
Different activation functions
gelu
=
nn.
GELU
(
)
relu
=
nn.
ReLU
(
)
sigmoid
=
nn.
Sigmoid
(
)
tanh
=
nn.
Tanh
(
)
(
"x GELU ReLU Sigmoid Tanh"
)
(
"-"
50
)
for
i
in
range
(
0
,
21
,
3
)
:
xi
=
x
[
i:i+
3
]
(
f
"{xi[0]:6.2f} {gelu(xi)[0]:8.4f} {relu(xi)[0]:8.4f} {sigmoid(xi)[0]:8.4f} {tanh(xi)[0]:8.4f}"
)
Example 3: Using it in a Transformer
A typical Transformer FFN layer:
h2 class="example">Example
import
torch
import
torch.
nn
as
nn
class
FeedForward
(
nn.
Module
)
:
def
init
(
self
,
d_model
,
dim_feedforward
=
2048
,
dropout
=
0.1
)
:
super
(
FeedForward
,
self
)
.
init
(
)
self
.
linear1
=
nn.
Linear
(
d_model
,
dim_feedforward
)
self
.
dropout
=
nn.
Dropout
(
dropout
)
self
.
activation
=
nn.
GELU
(
)
self
.
linear2
=
nn.
Linear
(
dim_feedforward
,
d_model
)
def
forward
(
self
,
x
)
:
x
=
self
.
linear1
(
x
)
x
=
self
.
activation
(
x
)
x
=
self
.
dropout
(
x
)
x
=
self
.
linear2
(
x
)
return
x
Test the FFN
ffn
=
FeedForward
(
d_model
=
512
,
dim_feedforward
=
2048
)
x
=
torch.
randn
(
32
,
100
,
512
)
(batch, seq, d_model)
output
=
ffn
(
x
)
(
"Input shape:"
,
x.
shape
)
(
"Output shape:"
,
output.
shape
)
Example 4: Using the tanh approximation
Using the tanh approximation to speed up computation:
Example
import
torch
import
torch.
nn
as
nn
Exact version
gelu_exact
=
nn.
GELU
(
approximate
=
'none'
)
tanh approximation version
gelu_approx
=
nn.
GELU
(
approximate
=
'tanh'
)
x
=
torch.
randn
(
1000
)
output_exact
=
gelu_exact
(
x
)
output_approx
=
gelu_approx
(
x
)
Compute the difference
diff
=
(
output_exact - output_approx
)
.
abs
(
)
.
max
(
)
.
item
(
)
(
f
"Maximum difference: {diff:.8f}"
)
Performance Comparison
import
time
for
_
in
range
(
100
)
:
_
=
gelu_exact
(
x
)
start
=
time
.
time
(
)
for
_
in
range
(
1000
)
:
_
=
gelu_exact
(
x
)
time_exact
=
time
.
time
(
)
- start
start
=
time
.
time
(
)
for
_
in
range
(
1000
)
:
_
=
gelu_approx
(
x
)
time_approx
=
time
.
time
(
)
- start
(
f
"Exact version time: {time_exact:.4f}s"
)
(
f
"Approximate version time: {time_approx:.4f}s"
)
Comparison of activation functions
| Activation function | Feature | Applicable scenarios |
|---|---|---|
nn.GELU |
Smooth, non-zero negatives, Transformer default | Transformer, BERT, GPT |
nn.ReLU |
Simple, sparse activation, dead neurons | CNN, general deep learning |
nn.SiLU |
Smooth, self-gating | MobileNet, EfficientNet |
Common questions
Q1: What advantages does GELU have over ReLU?
- Negative values are slightly activated, so information is not lost
- Smoother gradients help training
- Better performance in Transformers
Q2: When to use the approximate version?
When inference speed matters and precision requirements are not strict, the tanh approximation is faster.
Q3: Can GELU be used in the output layer?
It is usually not used in the output layer. Use Softmax for classification tasks and the identity function for regression tasks.
Use Cases
nn.GELU Main application scenarios include:
- Transformer Architecture: models such as BERT and GPT
- Deep neural networks: situations requiring smooth activation
- Pretrained models: modern NLP models
Tip: GELU is currently the most widely used activation function in NLP and is a standard component of Transformers.