6. Modern Transformer Architectures
Encoder-Only and Decoder-Only Foundations
Encoder-only architectures like BERT (Bidirectional Encoder Representations from Transformers) are designed for deep contextual understanding. By utilizing masked language modeling (MLM), BERT can attend to tokens in both the past and future simultaneously, creating dense contextual embeddings ideal for classification, named entity recognition, and question answering. Because the self-attention mechanism is fully bidirectional, the model effectively builds a representation of a word that is deeply informed by its surrounding context.
Conversely, decoder-only architectures like GPT (Generative Pre-trained Transformer) leverage causal language modeling. These models are autoregressive, meaning they predict the next token in a sequence by attending only to previously generated tokens. This unidirectional attention mask is essential for generative tasks where the model must construct a coherent sequence step-by-step. The architecture's simplicity and the scalability of the causal objective have made it the industry standard for Large Language Models.
import torch import torch.nn as nn # Mocking a causal mask for GPT-style architectures seq_len = 5 # Create a lower triangular matrix to mask future tokens causal_mask = torch.tril(torch.ones(seq_len, seq_len)) # Replace 0s with negative infinity for softmax stability mask = causal_mask.masked_fill(causal_mask == 0, float('-inf')).masked_fill(causal_mask == 1, 0.0) # Visualize the mask: positions only see themselves and preceding positions print(mask)
Encoder-Decoder Architectures
Encoder-Decoder models like T5 (Text-to-Text Transfer Transformer) and BART provide a unified framework for sequence-to-sequence problems. The encoder processes the input sequence, while the decoder generates an output sequence based on both the encoder's encoded representation and previously generated tokens. This dual-structure is highly efficient for machine translation, summarization, and paraphrasing, where the input and output have distinct structures.
In T5, every task is framed as a text-to-text problem by prepending specific prefixes to inputs. This allows the model to leverage transfer learning effectively across disparate NLP tasks. BART, on the other hand, combines the bidirectional encoder of BERT with the autoregressive decoder of GPT, allowing it to reconstruct noisy input sequences, which is particularly effective for abstractive summarization.
import torch # Conceptualizing Encoder-Decoder cross-attention # Encoder hidden states (batch, seq_enc, dim) enc_outputs = torch.randn(1, 10, 512) # Decoder hidden states (batch, seq_dec, dim) dec_states = torch.randn(1, 5, 512) # Cross-attention: Decoder queries (Q) attended to Encoder keys (K) and values (V) attn_scores = torch.matmul(dec_states, enc_outputs.transpose(-2, -1)) / (512 ** 0.5) weights = torch.softmax(attn_scores, dim=-1) context = torch.matmul(weights, enc_outputs) print(context.shape)
Scaling Laws and Compute Budget
Scaling laws describe the empirical relationship between model performance (measured by cross-entropy loss) and three core factors: the number of model parameters (N), the size of the training dataset (D), and the amount of compute used for training (C). Kaplan et al. demonstrated that performance scales predictably as a power law, provided that N, D, and C are increased in proportion to one another.
In practice, it is often sub-optimal to increase the parameter count without a proportional increase in data. Chinchilla-optimal scaling research by DeepMind suggested that most early LLMs were undertrained, meaning they had too many parameters relative to their data size. A compute-optimal training strategy involves finding the sweet spot where adding more parameters or more tokens yields the greatest marginal reduction in loss.
def estimate_compute(params, tokens): # Simple heuristic: 6 * params * tokens FLOPS return 6 * params * tokens # Compare two regimes config_small = {'params': 1e9, 'tokens': 20e9} config_large = {'params': 10e9, 'tokens': 200e9} compute_small = estimate_compute(**config_small) compute_large = estimate_compute(**config_large) print(f"Compute Ratio: {compute_large / compute_small}")
Knowledge Check
Ready to test your understanding of 6. Modern Transformer Architectures?