PyTorch torch.nn.TransformerEncoderLayer function
PyTorch torch.nn Reference Manual
nn.TransformerEncoderLayer is the single-layer structure of a Transformer encoder.
It contains self-attention and a feed-forward network, forming the basic unit of a complete encoder.
Function definition
torch.nn.TransformerEncoderLayer(d_model, nhead, dim_feedforward=2048, dropout=0.1, activation='gelu', batch_first=True)
Parameters
d_model: Model dimensionnhead: Number of attention headsdim_feedforward: FFN hidden layer dimension
Usage examples
Example 1: Basic usage
Example
import
torch
import
torch.
nn
as
nn
Encoder layer
layer
=
nn.
TransformerEncoderLayer
(
d_model
=
512
,
nhead
=
8
,
batch_first
=
True
)
Input
x
=
torch.
randn
(
32
,
100
,
512
)
output
=
layer
(
x
)
(
"Input:"
,
x.
shape
,
"-> Output:"
,
output.
shape
)
Example 2: Custom activation function
Example
import
torch
import
torch.
nn
as
nn
Use ReLU activation
layer_relu
=
nn.
TransformerEncoderLayer
(
d_model
=
256
,
nhead
=
4
,
activation
=
'relu'
,
batch_first
=
True
)
x
=
torch.
randn
(
8
,
50
,
256
)
out
=
layer_relu
(
x
)
(
"ReLU activation output:"
,
out.
shape
)
Example 3: Stacking multiple layers
Example
import
torch
import
torch.
nn
as
nn
Stack multiple layers
layer
=
nn.
TransformerEncoderLayer
(
256
,
4
,
batch_first
=
True
)
encoder
=
nn.
Sequential
(
layer
,
nn.
TransformerEncoderLayer
(
256
,
4
,
batch_first
=
True
)
,
nn.
TransformerEncoderLayer
(
256
,
4
,
batch_first
=
True
)
)
x
=
torch.
randn
(
4
,
30
,
256
)
out
=
encoder
(
x
)
(
"3-layer encoder output:"
,
out.
shape
)
Use Cases
- Build an encoder
- Models such as BERT
- Text Understanding