TransformerEncoder
- class torch.nn.modules.transformer.TransformerEncoder(encoder_layer, num_layers, norm=None, enable_nested_tensor=True, mask_check=True)
TransformerEncoder is a stack of N encoder layers.
TransformerEncoder is a stack of N encoder layers.
This TransformerEncoder layer implements the original architecture described in the Attention Is All You Need paper. The intent of this layer is as a reference implementation for foundational understanding and thus it contains only limited features relative to newer Transformer architectures. Given the fast pace of innovation in transformer-like architectures, we recommend exploring this tutorial to build efficient layers from building blocks in core or using higher level libraries from the PyTorch Ecosystem.
encoder_layer (TransformerEncoderLayer) – an instance of the TransformerEncoderLayer() class (required).
num_layers (int) – the number of sub-encoder-layers in the encoder (required).
norm (Module | None) – the layer normalization component (optional).
enable_nested_tensor (bool) – if True, input will automatically convert to nested tensor
(and convert back on output). This will improve the overall performance of
TransformerEncoder when padding rate is high. Default: True (enabled).
>>> encoder_layer = nn.TransformerEncoderLayer(
... d_model=512, nhead=8, batch_first=True
... )
>>> transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=6)
>>> src = torch.rand(32, 10, 512)
>>> out = transformer_encoder(src)
Pass the input through the encoder layers in turn.
src (Tensor) – the sequence to the encoder (required).
mask (Tensor | None) – the mask for the src sequence (optional).
src_key_padding_mask (Tensor | None) – the mask for the src keys per batch (optional).
is_causal (bool | None) – If specified, applies a causal mask as mask.
Default: None; try to detect a causal mask.
Warning:
is_causal provides a hint that mask is the
causal mask. Providing incorrect hints can result in
incorrect execution, including forward and backward
compatibility.
see the docs in Transformer.