🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Transformers for Text Generation

🟢 Free Lesson

Transformers for Text Generation

Transformers are the architecture behind GPT, Claude, and virtually all modern language models. Unlike RNNs that process words sequentially, Transformers look at all words simultaneously using attention mechanisms - like a crowd simultaneously looking at every person in a room to understand the full context. This parallelization enables training on massive datasets and capturing long-range dependencies.

Transformer Encoder-Decoder Architecture

Sponsored
Transformer Encoder-Decoder ArchitectureInputEmbedding+ Positional EncEncoder (N layers)Multi-Head Self-Attention+ Add & NormFeed Forward Network+ Add & NormRepeat N times (6-96)Cross-AttnDecoder (N layers)Masked Self-Attention+ Add & NormCross-Attention+ Add & NormFeed Forward + NormRepeat N timesLinear +SoftmaxOutputTokensOutputEmbeddingShifted RightKey Components■ Encoder: Understands input■ Decoder: Generates output■ Cross-Attention: Encoder→Decoder■ Positional Encoding: Word order

What the Three Projections Actually Learn

Q, K, and V are three independent linear maps over the same input sequence, and each answers a different question about a token. The query vector is what this token is looking for, the key vector is what this token offers to others, and the value vector is what this token actually contributes once it is selected. In the sentence "the bank raised the rate", the token "bank" emits a query that matches the key on "rate", then passes along its value, which by that layer has been shaped toward the financial reading rather than the riverbank one.

Keeping them separate matters because the similarity used for routing and the payload that gets routed are different quantities. Fusing keys and values would force every token to be indexed by exactly the content it hands over, which removes the ability to say "attend to me, but send something else". The output projection is the fourth map, and it mixes information across the heads once each head has finished its own routing, which is why one layer can combine a syntactic relation and a semantic one.

Self-Attention Mechanism

Self-Attention: Q, K, V MatricesInput TokensThecatsatonmatW_QW_KW_VLearned projectionsQueryQ = X · W_Q"What am I looking for?"[seq_len × d_k]KeyK = X · W_K"What do I contain?"[seq_len × d_k]ValueV = X · W_V"What info to pass?"[seq_len × d_v]Scaled Dot-Product AttentionAttention(Q, K, V) =softmax(Q·Kᵀ / √d_k) · V1. Compute similarity: Q·Kᵀ2. Scale: divide by √d_k3. Normalize: softmax → weights4. Weighted sum: weights · VAttention Weights Example (how "cat" attends to other words)The: 0.1cat: 0.4sat: 0.3on: 0.05mat: 0.15

Reading an Attention Map to Debug Text Errors

Attention weights are the cheapest diagnostic available, and a head-by-head inspection explains a surprising share of production failures. Extract the weights for one layer, find the rows belonging to the tokens that produced the bad output, and check four things: whether the model attends to the clause it is supposed to copy, whether attention leaks to padding or to a boilerplate system prefix, whether a long document loses attention after the first few hundred tokens, and whether a high-weight token is one you inserted without intending it to be influential, such as a file path or an example identifier.

Patterns worth recognising by name. A head that puts nearly all of its mass on the first token behaves like a bias term rather than a content selector. A head whose weights mostly track the previous token is learning position, which is common early in the stack and redundant late. Attention spread uniformly across the whole sequence usually means the head produces a pooled statistic, and ablating it often changes nothing. Not every answer lives in the attention map, because later layers overwrite early reads, so treat a suspicious pattern as a lead to confirm with an ablation rather than as proof.

Multi-Head Attention

Multi-Head Attention: Parallel Attention ComputationInput XHead 1Syntacticattentionsubject-verbHead 2Semanticattentionword meaningHead 3Positionalattentionnearby wordsHead 4CoreferenceattentionpronounsConcat Heads[h1; h2; h3; h4]Linear W_O→ OutputMultiHead(Q,K,V) = Concat(head_1,...,head_h) · W_O where head_i = Attention(Q·W_Q^i, K·W_K^i, V·W_V^i)

Positional Information: Three Families

Attention is symmetric over its inputs, so without an explicit signal the sentence "dog bites man" and "man bites dog" are the same set of tokens. Three families of positional information fix that, and they differ in how they behave beyond the length seen in training.

  • Sinusoidal or learned absolute positions add a vector to each token embedding according to its index. They are simple and cheap, but the model only ever learns the positions present in training, so a context limit change usually requires retraining or interpolation.
  • Rotary encoding rotates each query and key pair by an angle proportional to the position, so attention scores depend only on relative offsets. Because a relative shift is a rotation rather than a lookup, models transfer to longer contexts more gracefully, and rotary has become the default in open-weight language models.
  • Relative bias terms such as Alibi add a penalty to the score matrix that grows with distance, which trains short and extrapolates to long by construction, though it hands the model less expressive capacity than rotary.

Whatever you choose, the practical constraint is the same: train and serve with the same positional scheme and the same context length, because a mismatch shows up as fluent text that quietly loses coherence after the first mismatched region.

GPT Autoregressive Generation

Sponsored
GPT: Autoregressive Token-by-Token GenerationStep 1Thecatsat?Input: "The cat sat"Predict: next tokenGPTDecoderOnly layersonP("on") = 0.35Step 2Thecatsaton?Input: "The cat sat on"Predict: next tokentheP("the") = 0.42Step 3Thecatsatonthe?Continue until EOS or max lengthOutput: "The cat sat on the mat"

How Transformers Learn

Imagine you're reading a sentence with special glasses that let you look at every word simultaneously. When processing "The cat sat on the mat," the word "sat" instantly sees its subject "cat" (2 words back), the preposition "on" (1 word ahead), and even "mat" (3 words ahead). This parallel visibility is what attention enables.

Unlike RNNs that pass information sequentially (losing context over long distances), Transformers create direct connections between all positions. The self-attention mechanism computes relevance scores: "cat" strongly attends to "The" (determiner) and "sat" (verb it performs), while weakly attending to "mat" (distant, less relevant).

Multi-head attention runs this process in parallel with different learned projections. One head might focus on syntax (subject-verb agreement), another on semantics (word meanings), and another on coreference (pronoun resolution). This parallel processing captures diverse relationships simultaneously.

Python Example: Simple Transformer

python
import torch
import torch.nn as nn
import math

class MultiHeadAttention(nn.Module):
    def __init__(self, d_model=512, n_heads=8):
        super().__init__()
        self.d_model = d_model
        self.n_heads = n_heads
        self.d_k = d_model // n_heads

        self.W_q = nn.Linear(d_model, d_model)
        self.W_k = nn.Linear(d_model, d_model)
        self.W_v = nn.Linear(d_model, d_model)
        self.W_o = nn.Linear(d_model, d_model)

    def forward(self, x, mask=None):
        batch_size, seq_len, _ = x.size()

        Q = self.W_q(x).view(batch_size, seq_len, self.n_heads, self.d_k).transpose(1, 2)
        K = self.W_k(x).view(batch_size, seq_len, self.n_heads, self.d_k).transpose(1, 2)
        V = self.W_v(x).view(batch_size, seq_len, self.n_heads, self.d_k).transpose(1, 2)

        scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k)
        if mask is not None:
            scores = scores.masked_fill(mask == 0, -1e9)
        attn_weights = torch.softmax(scores, dim=-1)
        output = torch.matmul(attn_weights, V)

        output = output.transpose(1, 2).contiguous().view(batch_size, seq_len, self.d_model)
        return self.W_o(output)

class TransformerBlock(nn.Module):
    def __init__(self, d_model=512, n_heads=8, d_ff=2048):
        super().__init__()
        self.attention = MultiHeadAttention(d_model, n_heads)
        self.norm1 = nn.LayerNorm(d_model)
        self.norm2 = nn.LayerNorm(d_model)
        self.ff = nn.Sequential(
            nn.Linear(d_model, d_ff),
            nn.ReLU(),
            nn.Linear(d_ff, d_model)
        )

    def forward(self, x, mask=None):
        attn_out = self.attention(x, mask)
        x = self.norm1(x + attn_out)
        ff_out = self.ff(x)
        x = self.norm2(x + ff_out)
        return x

Hands-on Project: Text Generator

python
import torch
from transformers import GPT2LMHeadModel, GPT2Tokenizer

model = GPT2LMHeadModel.from_pretrained('gpt2')
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')

def generate_with_analysis(prompt, max_tokens=50):
    input_ids = tokenizer.encode(prompt, return_tensors='pt')

    for _ in range(max_tokens):
        with torch.no_grad():
            outputs = model(input_ids)
            logits = outputs.logits[:, -1, :] / 0.7  # temperature
            probs = torch.softmax(logits, dim=-1)
            next_token = torch.multinomial(probs, 1)
            input_ids = torch.cat([input_ids, next_token], dim=-1)

    return tokenizer.decode(input_ids[0])

# Analyze attention patterns
text = "The cat sat on the mat because it was tired"
output = generate_with_analysis(text)
print(output)

The Cost of Long Context

Attention builds a full score matrix, so memory and compute both grow with the square of sequence length. Doubling context quadruples the matrix, which is why a model that answers comfortably in 8k can become unaffordable at 128k. The remedies split into two groups. Kernel-level fixes such as flash attention change how the matrix is read rather than how many entries it has, giving the same result with far less memory traffic and roughly a doubling to tripling of practical throughput. Structural fixes change the computation: sliding-window attention lets each token see only a local band, grouped-query attention shares key and value heads across many query heads so the cache shrinks in proportion, and retrieval-based context sends most input to an index rather than into the window.

The product-side levers matter as much as the model ones. Truncating oldest-first destroys the instructions that usually sit at the top, so keep system instructions and the most recent turns, summarise the middle, and always tokenise before you estimate. Measure prefill and decode separately: prefill is compute-bound and grows with prompt length, while decode is memory-bound and grows with cached history. A prompt that triples prefill will dominate your latency budget long before it looks expensive in token counts.

Choosing a Decoding Strategy

The same weights produce wildly different text depending on how the next token is picked, and the setting belongs in configuration rather than in code. Greedy decoding is deterministic and always available as a debug mode, but it collapses into repetition on open-ended prompts. Beam search keeps several hypotheses and rarely repeats, yet for conversational text it systematically drifts toward generic, high-probability phrasing because length-normalised scores reward hedging.

Sampling with a temperature and a truncation rule is the production default. Raise temperature toward 1 for brainstorming and creative drafting, drop it toward 0.2 for extraction and formatting tasks where variance is pure risk. Nucleus sampling, which cuts the tail at a cumulative probability rather than a fixed count, adapts to how peaked the distribution is, so it behaves sensibly on both confident and uncertain tokens where a fixed top-k does not. Fix the seed during evaluation, keep sampling settings beside the prompt version in your logs, and remember that changing temperature is a quality trade, not a free improvement.

Common Pitfalls in Practice

Common Mistakes

Comparing models at different context lengths without retesting

Fix: Retrain or revalidate after any positional scheme change, since coherence breaks at the first mismatched region

Tuning temperature while judging a task that should be deterministic

Fix: Use greedy decoding for extraction and formatting, and reserve sampling for genuinely open-ended output

Adding context to fix quality when the prompt already fits the window

Fix: Diagnose with an attention inspection first, then change instructions, structure, or retrieval rather than length

Summary

Advertisement

Transformers revolutionized NLP by enabling parallel processing of sequences through self-attention. The encoder-decoder architecture with multi-head attention captures diverse relationships between tokens simultaneously. GPT uses decoder-only transformers for autoregressive text generation, predicting one token at a time based on all previous context. Understanding attention mechanisms, Q/K/V projections, and positional encoding is essential for working with modern language models.

Next: We explore advanced generation techniques like beam search, top-k sampling, and nucleus sampling for controlling output quality.

Key Takeaways

  • Q routes, K indexes, and V carries the payload, so separating the three lets a token be found for one reason and contribute another
  • Attention maps are a cheap debugging tool: leakage, first-token bias, and uniform spread each point to a specific class of failure
  • Absolute positions are lookups, rotary encodes relative offset by rotation, and all three break when train and serve contexts disagree
  • Context cost grows with the square of length, so flash kernels, local windows, and shared key-value heads are what make long prompts affordable
  • Decoding strategy belongs in configuration: greedy for determinism, low temperature for extraction, nucleus sampling for open-ended drafting
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-16

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement