Transformer Encoder and Decoder Models

Open In Colab

13import math
15import torch
16import torch.nn as nn
18from labml_nn.utils import clone_module_list
19from .feed_forward import FeedForward
20from .mha import MultiHeadAttention
21from .positional_encoding import get_positional_encoding

Embed tokens and add fixed positional encoding

24class EmbeddingsWithPositionalEncoding(nn.Module):
31    def __init__(self, d_model: int, n_vocab: int, max_len: int = 5000):
32        super().__init__()
33        self.linear = nn.Embedding(n_vocab, d_model)
34        self.d_model = d_model
35        self.register_buffer('positional_encodings', get_positional_encoding(d_model, max_len))
37    def forward(self, x: torch.Tensor):
38        pe = self.positional_encodings[:x.shape[0]].requires_grad_(False)
39        return self.linear(x) * math.sqrt(self.d_model) + pe

Embed tokens and add parameterized positional encodings

42class EmbeddingsWithLearnedPositionalEncoding(nn.Module):
49    def __init__(self, d_model: int, n_vocab: int, max_len: int = 5000):
50        super().__init__()
51        self.linear = nn.Embedding(n_vocab, d_model)
52        self.d_model = d_model
53        self.positional_encodings = nn.Parameter(torch.zeros(max_len, 1, d_model), requires_grad=True)
55    def forward(self, x: torch.Tensor):
56        pe = self.positional_encodings[:x.shape[0]]
57        return self.linear(x) * math.sqrt(self.d_model) + pe

Transformer Layer

This can act as an encoder layer or a decoder layer.

🗒 Some implementations, including the paper seem to have differences in where the layer-normalization is done. Here we do a layer normalization before attention and feed-forward networks, and add the original residual vectors. Alternative is to do a layer normalization after adding the residuals. But we found this to be less stable when training. We found a detailed discussion about this in the paper On Layer Normalization in the Transformer Architecture.

60class TransformerLayer(nn.Module):
  • d_model is the token embedding size
  • self_attn is the self attention module
  • src_attn is the source attention module (when this is used in a decoder)
  • feed_forward is the feed forward module
  • dropout_prob is the probability of dropping out after self attention and FFN
78    def __init__(self, *,
79                 d_model: int,
80                 self_attn: MultiHeadAttention,
81                 src_attn: MultiHeadAttention = None,
82                 feed_forward: FeedForward,
83                 dropout_prob: float):
91        super().__init__()
92        self.size = d_model
93        self.self_attn = self_attn
94        self.src_attn = src_attn
95        self.feed_forward = feed_forward
96        self.dropout = nn.Dropout(dropout_prob)
97        self.norm_self_attn = nn.LayerNorm([d_model])
98        if self.src_attn is not None:
99            self.norm_src_attn = nn.LayerNorm([d_model])
100        self.norm_ff = nn.LayerNorm([d_model])

Whether to save input to the feed forward layer

102        self.is_save_ff_input = False
104    def forward(self, *,
105                x: torch.Tensor,
106                mask: torch.Tensor,
107                src: torch.Tensor = None,
108                src_mask: torch.Tensor = None):

Normalize the vectors before doing self attention

110        z = self.norm_self_attn(x)

Run through self attention, i.e. keys and values are from self

112        self_attn = self.self_attn(query=z, key=z, value=z, mask=mask)

Add the self attention results

114        x = x + self.dropout(self_attn)

If a source is provided, get results from attention to source. This is when you have a decoder layer that pays attention to encoder outputs

119        if src is not None:

Normalize vectors

121            z = self.norm_src_attn(x)

Attention to source. i.e. keys and values are from source

123            attn_src = self.src_attn(query=z, key=src, value=src, mask=src_mask)

Add the source attention results

125            x = x + self.dropout(attn_src)

Normalize for feed-forward

128        z = self.norm_ff(x)

Save the input to the feed forward layer if specified

130        if self.is_save_ff_input:
131            self.ff_input = z.clone()

Pass through the feed-forward network

133        ff = self.feed_forward(z)

Add the feed-forward results back

135        x = x + self.dropout(ff)
137        return x

Transformer Encoder

140class Encoder(nn.Module):
147    def __init__(self, layer: TransformerLayer, n_layers: int):
148        super().__init__()

Make copies of the transformer layer

150        self.layers = clone_module_list(layer, n_layers)

Final normalization layer

152        self.norm = nn.LayerNorm([layer.size])
154    def forward(self, x: torch.Tensor, mask: torch.Tensor):

Run through each transformer layer

156        for layer in self.layers:
157            x = layer(x=x, mask=mask)

Finally, normalize the vectors

159        return self.norm(x)

Transformer Decoder

162class Decoder(nn.Module):
169    def __init__(self, layer: TransformerLayer, n_layers: int):
170        super().__init__()

Make copies of the transformer layer

172        self.layers = clone_module_list(layer, n_layers)

Final normalization layer

174        self.norm = nn.LayerNorm([layer.size])
176    def forward(self, x: torch.Tensor, memory: torch.Tensor, src_mask: torch.Tensor, tgt_mask: torch.Tensor):

Run through each transformer layer

178        for layer in self.layers:
179            x = layer(x=x, mask=tgt_mask, src=memory, src_mask=src_mask)

Finally, normalize the vectors

181        return self.norm(x)


This predicts the tokens and gives the lof softmax of those. You don't need this if you are using nn.CrossEntropyLoss .

184class Generator(nn.Module):
194    def __init__(self, n_vocab: int, d_model: int):
195        super().__init__()
196        self.projection = nn.Linear(d_model, n_vocab)
198    def forward(self, x):
199        return self.projection(x)

Combined Encoder-Decoder

202class EncoderDecoder(nn.Module):
209    def __init__(self, encoder: Encoder, decoder: Decoder, src_embed: nn.Module, tgt_embed: nn.Module, generator: nn.Module):
210        super().__init__()
211        self.encoder = encoder
212        self.decoder = decoder
213        self.src_embed = src_embed
214        self.tgt_embed = tgt_embed
215        self.generator = generator

This was important from their code. Initialize parameters with Glorot / fan_avg.

219        for p in self.parameters():
220            if p.dim() > 1:
221                nn.init.xavier_uniform_(p)
223    def forward(self, src: torch.Tensor, tgt: torch.Tensor, src_mask: torch.Tensor, tgt_mask: torch.Tensor):

Run the source through encoder

225        enc = self.encode(src, src_mask)

Run encodings and targets through decoder

227        return self.decode(enc, src_mask, tgt, tgt_mask)
229    def encode(self, src: torch.Tensor, src_mask: torch.Tensor):
230        return self.encoder(self.src_embed(src), src_mask)
232    def decode(self, memory: torch.Tensor, src_mask: torch.Tensor, tgt: torch.Tensor, tgt_mask: torch.Tensor):
233        return self.decoder(self.tgt_embed(tgt), memory, src_mask, tgt_mask)