PyTorch torch.nn.LayerNorm function
PyTorch torch.nn Reference Manual
torch.nn.LayerNorm is the layer normalization module in PyTorch.
Unlike batch normalization, layer normalization normalizes over the feature dimensions of a single sample and does not depend on batch size.
Function definition
torch.nn.LayerNorm(normalized_shape, eps=1e-05, elementwise_affine=True)
Parameter Description:
normalized_shape(int or list): the dimensions to normalize.eps(float): epsilon for numerical stability. Default is 1e-5.elementwise_affine(bool): whether to use learnable scale and offset. Default is True.
Mathematical principle
Layer normalization formula:
y = (x - E[x]) / sqrt(Var[x] + eps) * gamma + beta
Difference from batch normalization: layer normalization computes the mean and variance over the last feature dimension.
Usage examples
Example 1: Basic usage
Applying layer normalization to features:
Example
import
torch
import
torch.
nn
as
nn
Layer normalization: normalize over the last dimension
ln
=
nn.
LayerNorm
(
normalized_shape
=
10
)
Input: batch=4, feature dimension=10
x
=
torch.
randn
(
4
,
10
)
Forward propagation
output
=
ln
(
x
)
(
"Input shape:"
,
x.
shape
)
(
"Output shape:"
,
output.
shape
)
(
"nOriginal input first row:"
,
x
[
0
]
.
tolist
(
)
)
(
"First row after normalization:"
,
output
[
0
]
.
tolist
(
)
)
Example 2: Multi-dimensional input
Handling 3D or 4D input:
Example
import
torch
import
torch.
nn
as
nn
Normalizing over the sequence dimension: (batch, seq, features)
ln_seq
=
nn.
LayerNorm
(
normalized_shape
=
64
)
3D input
x_3d
=
torch.
randn
(
2
,
10
,
64
)
output_3d
=
ln_seq
(
x_3d
)
(
"3D input:"
,
x_3d.
shape
,
"-> Output:"
,
output_3d.
shape
)
4D input (e.g. images): (batch, height, width, channels)
LayerNorm normalizes over the last channel dimension
ln_channel
=
nn.
LayerNorm
(
normalized_shape
=
128
)
x_4d
=
torch.
randn
(
2
,
8
,
8
,
128
)
output_4d
=
ln_channel
(
x_4d
)
(
"4D input:"
,
x_4d.
shape
,
"-> Output:"
,
output_4d.
shape
)
Example 3: Using it in a Transformer
Typical LayerNorm usage:
Example
import
torch
import
torch.
nn
as
nn
class
TransformerBlock
(
nn.
Module
)
:
def
init
(
self
,
d_model
,
nhead
)
:
super
(
TransformerBlock
,
self
)
.
init
(
)
self
.
self_attn
=
nn.
MultiheadAttention
(
d_model
,
nhead
,
batch_first
=
True
)
self
.
norm1
=
nn.
LayerNorm
(
d_model
)
self
.
norm2
=
nn.
LayerNorm
(
d_model
)
self
.
ffn
=
nn.
Sequential
(
nn.
Linear
(
d_model
,
d_model *
4
)
,
nn.
GELU
(
)
,
nn.
Linear
(
d_model *
4
,
d_model
)
)
def
forward
(
self
,
x
)
:
Self-attention with residual
attn_out
,
_
=
self
.
self_attn
(
x
,
x
,
x
)
x
=
self
.
norm1
(
x + attn_out
)
FFN with residual
ffn_out
=
self
.
ffn
(
x
)
x
=
self
.
norm2
(
x + ffn_out
)
return
x
Testing
block
=
TransformerBlock
(
d_model
=
512
,
nhead
=
8
)
x
=
torch.
randn
(
4
,
100
,
512
)
(batch, seq, d_model)
output
=
block
(
x
)
(
"Input shape:"
,
x.
shape
)
(
"Output shape:"
,
output.
shape
)
Example 4: Without learnable parameters
Pure normalization without scale and offset:
Example
import
torch
import
torch.
nn
as
nn
No learnable parameters
ln
=
nn.
LayerNorm
(
16
,
elementwise_affine
=
False
)
x
=
torch.
randn
(
4
,
16
)
output
=
ln
(
x
)
No weight and bias
(
"Has weight:"
,
hasattr
(
ln
,
'weight'
)
)
(
"Has bias:"
,
hasattr
(
ln
,
'bias'
)
)
(
"nOutput shape:"
,
output.
shape
)
Comparison of normalization methods
| Method | Normalization dimension | Batch dependence | Applicable scenarios |
|---|---|---|---|
BatchNorm |
batch dimension | Is | CNN, stable batch |
LayerNorm |
Feature dimension | No | Transformer, RNN |
InstanceNorm |
Channels + spatial | No | Style transfer |
GroupNorm |
Channel groups | No | Small batch scenarios |
Common questions
Q1: What is the difference between LayerNorm and BatchNorm?
LayerNorm does not depend on the batch, making it suitable for sequence models and scenarios with large batch variation.
Q2: How to choose normalized_shape?
Usually choose the feature dimension, such as 768 or 1024 in BERT.
Q3: Why do Transformers use LayerNorm?
Transformer input sequences have variable lengths, and LayerNorm is more stable.
Use Cases
nn.LayerNorm Main application scenarios include:
- Transformer Architecture: such as BERT and GPT
- Recurrent neural networks: LSTM, GRU
- Variable-length sequence processing: batch size is not fixed
Tip: LayerNorm is a standard component of Transformers, placed after the residual connection (Post-LN) or before it (Pre-LN).