5. The Transformer Decoder
Architecture and Masked Self-Attention
The Transformer Decoder differs from the Encoder primarily through the inclusion of a Masked Multi-Head Attention layer. During autoregressive training, the model must not 'see' future tokens in the sequence it is trying to predict. If the model had access to future words, it could simply copy the next token in the sequence rather than learning to represent the underlying patterns.
We implement this via a causal mask: a triangular matrix of negative infinities added to the attention scores before the softmax operation. This ensures that the attention weight for any position 'i' is effectively zero for all positions 'j > i', enforcing the unidirectional property of the decoder.
import torch import torch.nn.functional as F def apply_causal_mask(scores): seq_len = scores.size(-1) # Create a lower triangular mask of ones mask = torch.tril(torch.ones(seq_len, seq_len)).bool() # Replace zeros with -inf to nullify future positions return scores.masked_fill(~mask, float('-inf')) # Mock attention scores (batch_size=1, heads=1, seq_len=3, seq_len=3) scores = torch.randn(1, 1, 3, 3) masked_scores = apply_causal_mask(scores) probs = F.softmax(masked_scores, dim=-1) print(probs)
Encoder-Decoder Cross-Attention
The second sub-layer in the decoder block is the Encoder-Decoder Cross-Attention layer. Unlike self-attention, the Queries (Q) come from the previous decoder sub-layer, while the Keys (K) and Values (V) come from the output of the final encoder block. This allows the decoder to 'look back' at the entire input sequence produced by the encoder to inform its current generation.
By conditioning the decoder on the encoder's output, the model captures the relationship between the target sequence (in the decoder) and the source sequence (in the encoder). This is vital for tasks like machine translation, where specific segments of the input need to be mapped to corresponding segments of the output.
import torch.nn as nn class CrossAttention(nn.Module): def __init__(self, embed_dim): super().__init__() self.q_proj = nn.Linear(embed_dim, embed_dim) self.k_proj = nn.Linear(embed_dim, embed_dim) self.v_proj = nn.Linear(embed_dim, embed_dim) def forward(self, decoder_hidden, encoder_output): Q = self.q_proj(decoder_hidden) K = self.k_proj(encoder_output) V = self.v_proj(encoder_output) # Scaled dot-product attention attn_scores = torch.matmul(Q, K.transpose(-2, -1)) / (Q.size(-1)**0.5) return torch.matmul(F.softmax(attn_scores, dim=-1), V)
Autoregressive Generation Workflow
Autoregressive generation is the process of generating tokens one by one. The decoder takes an initial token (often a
This iterative process continues until an
def greedy_decode(model, encoder_input, start_token, max_len): generated = [start_token] for _ in range(max_len): decoder_input = torch.tensor(generated).unsqueeze(0) output = model(encoder_input, decoder_input) # Get last token prediction next_token = output[0, -1].argmax().item() generated.append(next_token) if next_token == 2: # Assuming 2 is <EOS> break return generated
Knowledge Check
Ready to test your understanding of 5. The Transformer Decoder?