The Decoder Revolution
While BERT (Sub-chapter 5.4) demonstrated the power of the Transformer encoder for understanding tasks, OpenAI pursued the opposite strategy: use only the decoder stack, train it to predict the next word, and scale it up. The result was GPT — a model family that did not just understand language but could generate it fluently.
The key insight: if a model can reliably predict the next token in any sequence, it must have implicitly learned grammar, facts, reasoning patterns, and even rudimentary coding skills. Next-token prediction, far from being a trivial task, turned out to be a remarkably powerful training objective.
GPT models are the engines behind ChatGPT, GitHub Copilot, and countless other tools that civil engineers increasingly encounter. Understanding how they work — their strengths, their failure modes, and the mathematics behind their outputs — is essential for any engineer who wants to use these tools responsibly and effectively.
This sub-chapter assumes familiarity with the Transformer architecture from Sub-chapter 5.3 (self-attention, feed-forward layers, positional encoding) and BERT from Sub-chapter 5.4. GPT uses the Transformer decoder stack — the half that BERT discarded.
Why GPT Matters for Civil Engineers
GPT-class models are already being deployed in construction and engineering contexts. They can draft inspection reports, summarise lengthy specifications, generate Python scripts for structural analysis, translate between design codes, and answer technical questions about standards. Understanding the autoregressive generation process helps you anticipate when these tools will be reliable and when they may confidently produce incorrect information — a critical distinction for safety-sensitive engineering work.
The Autocomplete Drafter Analogy
GPT is like an extraordinarily well-read junior engineer who has memorised every engineering document ever written — but can only write one word at a time. When you give this engineer the beginning of a sentence ("The reinforced concrete beam shall have a minimum cover of"), they draw on their vast reading to predict the most likely next word ("40"), then continue from there ("mm"), and so on until the document is complete.
This engineer never looks ahead. They have not read the rest of the sentence they are writing — they can only see what has been written so far. This is the causal (left-to-right) nature of GPT. Compare this to the BERT inspector from Sub-chapter 5.4, who reads entire documents bidirectionally but cannot write new text.
The temperature setting controls how creative or conservative this drafter is. At low temperature, they write exactly what a standard specification would say. At high temperature, they might suggest unusual but sometimes innovative phrasing — or occasionally produce nonsense.
This analogy captures the essential trade-off in decoder models: they are powerful generators but inherently unidirectional. Every token is produced based solely on the tokens that came before it, never on tokens that will come after.
The Decoder-Only Architecture
In the original Transformer (Sub-chapter 5.3), the decoder receives information from the encoder via cross-attention. GPT simplifies this drastically: it removes the encoder entirely and uses only the decoder stack. Without an encoder, there is no cross-attention — the model relies solely on masked self-attention (also called causal self-attention) and feed-forward layers.
GPT Architecture Summary
- GPT-1: 12 decoder layers, 768 hidden dimensions, 12 attention heads, 117M parameters
- GPT-2: 48 decoder layers, 1600 hidden dimensions, 25 attention heads, 1.5B parameters
- GPT-3: 96 decoder layers, 12288 hidden dimensions, 96 attention heads, 175B parameters
- GPT-4: Architectural details not publicly disclosed; estimated >1 trillion parameters (rumoured MoE)
- Core mechanism: Causal (masked) self-attention — each token attends only to itself and preceding tokens
The simplicity of the decoder-only design is part of its genius. There is only one type of attention block, one type of layer, and one training objective. This uniformity makes scaling straightforward: add more layers, add more data, add more compute.
Encoder vs. Decoder: The Key Difference
The fundamental difference between BERT (encoder) and GPT (decoder) is the attention mask. In BERT, every token can attend to every other token — a fully visible attention matrix. In GPT, attention is causal: token i can only attend to tokens 0 through i. Future tokens are masked out, which is precisely what enables autoregressive generation.
Causal masking is like a construction schedule where each activity can only depend on activities that have already been completed. When pouring the second-floor slab, you can reference the as-built conditions of the first floor and the foundation — but you cannot reference the third-floor framing that has not happened yet. Each step in the sequence is informed only by the past, never the future.
Autoregressive Generation
GPT generates text one token at a time. Given a sequence of tokens [t1, t2, …, tn], the model predicts the probability distribution over the entire vocabulary for the next token tn+1. A token is sampled from this distribution, appended to the sequence, and the process repeats.
The Autoregressive Formula
P(text) = P(t1) × P(t2|t1) × P(t3|t1,t2) × … × P(tn|t1,…,tn-1)
The probability of an entire text sequence is the product of conditional probabilities. Each token's probability is conditioned on all previous tokens. This is the chain rule of probability applied to language modelling.
This process is inherently sequential: you cannot generate token 5 until you have generated tokens 1 through 4, because token 5's probability depends on all preceding tokens. This is why GPT generation can feel slow compared to BERT inference, which processes all tokens in parallel.
The Training Objective
During training, GPT is given large corpora of text and learns to minimise the cross-entropy loss of next-token prediction. For every position in the training data, the model predicts the next token and is penalised when it assigns low probability to the correct token. Over billions of tokens, this simple objective forces the model to learn grammar, facts, reasoning patterns, and even stylistic conventions.
Training vs. Inference
- Training: The model sees the entire text at once (with causal masking) and predicts the next token at every position simultaneously. This is highly parallelisable and efficient on GPUs.
- Inference (generation): The model must generate one token at a time, feed it back in, and generate the next. This sequential process is the bottleneck in generation speed.
Causal Masking in Detail
Causal masking is the mechanism that makes autoregressive generation possible during training. The attention matrix is multiplied by a lower-triangular mask: for each query position i, the attention weights for all key positions j > i are set to negative infinity before the softmax, effectively zeroing them out.
The Causal Attention Mask
For a 5-token sequence, the mask looks like:
t1 t2 t3 t4 t5 t1 [ 1 0 0 0 0 ] t2 [ 1 1 0 0 0 ] t3 [ 1 1 1 0 0 ] t4 [ 1 1 1 1 0 ] t5 [ 1 1 1 1 1 ]
A 1 means "can attend"; a 0 means "cannot attend." Token t3 can attend to t1, t2, and t3, but not t4 or t5. This ensures each position can only use information from the past and present, never the future.
The causal mask is what separates GPT from BERT at a fundamental level. BERT uses a fully visible mask (all 1s), allowing bidirectional attention. GPT uses a lower-triangular mask, enforcing unidirectional (left-to-right) attention. This single difference determines whether a model is suited for understanding (BERT) or generation (GPT).
Why Not Bidirectional Generation?
You might wonder: why not let the model see the full context when generating? The answer is logical consistency. If token 5 could attend to token 8 during generation, token 8 would need to have already been generated — but token 8 depends on token 5. This creates a circular dependency. Causal masking breaks this cycle by enforcing a strict left-to-right order.
Temperature & Sampling Strategies
Once the model produces a probability distribution over the vocabulary, we must decide how to select the next token. This decision dramatically affects the quality and creativity of the generated text.
Temperature
The raw output of the model (logits) is divided by a temperature parameter T before applying softmax:
Temperature Scaling
P(tokeni) = exp(logiti / T) / Σ exp(logitj / T)
- T → 0: The distribution becomes a spike on the highest-probability token (greedy / deterministic). Like a specification writer who always uses the most conventional phrasing.
- T = 1.0: The original distribution is used as-is. Balanced creativity.
- T > 1.0: The distribution is flattened, giving low-probability tokens more chance. Like an experimental architect exploring unusual design options.
Top-k Sampling
Instead of sampling from the entire vocabulary (which may include nonsensical tokens with tiny probabilities), top-k sampling restricts the selection to the k highest-probability tokens. The probabilities of these k tokens are renormalised, and the remaining vocabulary is discarded.
Top-p (Nucleus) Sampling
Top-p sampling (also called nucleus sampling) is more adaptive. Instead of fixing the number of candidate tokens, it selects the smallest set of tokens whose cumulative probability exceeds a threshold p. When the model is confident, this set is small; when it is uncertain, the set is larger.
Practical Sampling Settings
- Deterministic tasks (specification writing, code generation): T = 0.0–0.3, or greedy decoding
- Balanced tasks (report drafting, Q&A): T = 0.5–0.8, top-p = 0.9
- Creative tasks (brainstorming, alternative designs): T = 0.9–1.2, top-k = 50
Temperature is like the factor of safety in structural design. A low factor of safety (low temperature) produces the most efficient, predictable design — but leaves no room for variation. A high factor of safety (high temperature) introduces more margin and variability — useful for uncertain conditions, but potentially wasteful. The engineer must choose the right level based on the context and consequences of failure.
GPT Evolution: From GPT-1 to GPT-4
The GPT family demonstrates a remarkable trajectory: the same fundamental architecture (decoder-only Transformer with causal masking), scaled up by orders of magnitude in parameters, data, and compute. Each generation unlocked emergent capabilities that were absent in the previous one.
GPT-1 (June 2018) — Proof of Concept
OpenAI's original GPT had 117 million parameters and was trained on the BookCorpus dataset (about 7,000 unpublished books). It demonstrated that unsupervised pre-training on a language modelling objective, followed by supervised fine-tuning, could achieve strong performance on a range of NLP tasks.
- 12 decoder layers, 768 hidden dimensions
- Trained on ~5 GB of text
- Required fine-tuning for each downstream task
- Key contribution: validated the "pre-train + fine-tune" paradigm for decoders
GPT-2 (February 2019) — Zero-Shot Capability
GPT-2 scaled to 1.5 billion parameters and was trained on WebText, a dataset of 8 million web pages curated by following outbound links from Reddit posts with at least 3 karma. The key discovery: at sufficient scale, the model could perform tasks without any fine-tuning (zero-shot), simply by conditioning on a natural language prompt.
- 48 decoder layers, 1600 hidden dimensions
- Trained on ~40 GB of text
- OpenAI initially withheld the full model, citing misuse concerns
- Key contribution: demonstrated emergent zero-shot task performance
GPT-3 (June 2020) — Few-Shot Learning
GPT-3 was a landmark: 175 billion parameters, trained on a filtered version of Common Crawl plus books and Wikipedia. Its defining capability was few-shot learning: by providing just a few examples in the prompt, the model could perform new tasks without any gradient updates.
- 96 decoder layers, 12288 hidden dimensions
- Trained on ~570 GB of filtered text
- Cost approximately $4.6 million to train (estimated)
- API-only access — model weights not publicly released
- Key contribution: in-context learning without weight updates
GPT-4 (March 2023) — Multimodal Reasoning
GPT-4 is OpenAI's most capable model, accepting both text and image inputs. While architectural details remain unpublished, it demonstrated dramatic improvements in reasoning, factuality, and safety. It passed the bar exam in the 90th percentile and scored in the top percentiles on numerous professional and academic exams.
- Architecture not disclosed; rumoured Mixture-of-Experts (MoE)
- Multimodal: accepts text + image inputs
- 128k token context window (extended version)
- Trained with RLHF (Reinforcement Learning from Human Feedback)
- Key contribution: human-level performance on professional benchmarks
In-Context Learning & Few-Shot Prompting
One of the most surprising properties of large GPT models is in-context learning: the ability to learn a new task at inference time simply from examples provided in the prompt, without any gradient updates or fine-tuning. The model's weights remain frozen; the "learning" happens entirely through the attention mechanism operating over the prompt.
Prompting Paradigms
- Zero-shot: No examples. Just a task description. "Classify this construction deficiency report as structural, architectural, or MEP."
- One-shot: One example. "Classify this report. Example: 'Cracking in basement wall' → Structural. Now classify: 'HVAC duct disconnected'"
- Few-shot: Several examples (typically 3–10). The model identifies the pattern and applies it to new inputs.
In-context learning is remarkable because it means a single model can perform thousands of different tasks depending on the prompt. For civil engineers, this means you do not need to train a separate model for each task — you need to learn how to write effective prompts.
How Does In-Context Learning Work?
The mechanism is still debated in the research community, but the leading hypothesis is that during pre-training, the model learns to identify and replicate patterns in its context window. When you provide examples of "input → output" pairs in the prompt, the model's attention heads effectively implement a pattern-matching algorithm that generalises to the new input.
CE Example: Few-Shot Classification
A few-shot prompt for classifying construction daily log entries:
Entry: "Poured 45 m3 of C30 concrete for Level 2 slab" Category: Concrete Works Entry: "Installed 200 m of 16mm rebar in grid lines A-D" Category: Reinforcement Entry: "Rain delay from 10:00 to 14:00, site flooded" Category: Weather Delay Entry: "Completed formwork for columns C1-C12" Category:
The model would predict "Formwork" by recognising the pattern from the preceding examples.
Civil Engineering Applications
GPT-class models are finding practical applications across the construction and civil engineering industries. Here are three major use cases where decoder models excel:
1. Generating Inspection Report Drafts
Site inspectors can use GPT models to draft inspection reports from field notes and photographs. The model generates structured, professional prose from bullet points:
Input: "L2 slab pour, C30 concrete, 45 m3,
slump 120mm, weather clear, 2 cube samples taken, rebar
checked OK, formwork alignment within tolerance"
GPT output: "The Level 2 floor slab concrete
pour was completed on [date]. A total of 45 cubic metres of
C30 grade concrete was placed. The measured slump was 120 mm,
which is within the specified range. Two concrete cube samples
were collected for compressive strength testing at 7 and 28
days. Reinforcement placement was inspected and found to comply
with the structural drawings. Formwork alignment was verified
and found to be within the specified tolerances. Weather
conditions during the pour were clear and dry."
2. Code Generation for Analysis Scripts
Engineers can describe a structural analysis task in natural language and receive working Python code. GPT models excel at translating engineering requirements into code for libraries like NumPy, SciPy, and OpenSeesPy.
# Prompt: "Calculate the moment of inertia of a
# rectangular beam cross-section with width b
# and depth d, and find the maximum bending
# stress for a simply supported beam with
# uniformly distributed load w over span L."
import numpy as np
def beam_analysis(b, d, w, L):
I = (b * d**3) / 12 # moment of inertia
M_max = (w * L**2) / 8 # max bending moment
y_max = d / 2 # distance to extreme fibre
sigma_max = (M_max * y_max) / I # max bending stress
return I, M_max, sigma_max
3. Specification Summarisation
Construction specifications can span hundreds of pages. GPT models can summarise key requirements, extract critical parameters, and create comparison tables across different specification sections or editions.
A prompt like "Summarise the concrete requirements from Section 03 30 00 of this specification, focusing on strength grades, admixtures, and curing requirements" can produce a concise, structured summary that would take a human engineer 30 minutes to compile manually.
GPT models can generate plausible but factually incorrect information (hallucinations). In civil engineering, this is especially dangerous: an incorrect load value, a wrong code reference, or a fabricated design formula could have safety-critical consequences. Always verify GPT-generated content against authoritative sources before using it in engineering practice.
Byte-Pair Encoding (BPE) Tokenization
While BERT uses WordPiece tokenization (Sub-chapter 5.4), GPT models use Byte-Pair Encoding (BPE). The principle is similar — decompose text into subword tokens — but the algorithm differs.
How BPE Works
- Start with individual characters as the initial vocabulary
- Count all adjacent character pairs in the training corpus
- Merge the most frequent pair into a single new token
- Repeat until the desired vocabulary size is reached
GPT-2 uses a vocabulary of 50,257 tokens. GPT-3 and GPT-4 use variations of BPE with similar vocabulary sizes. Common words become single tokens; rare words are split into subword pieces.
Engineering Term Tokenization
Understanding how BPE tokenizes engineering terms explains some model behaviours:
- "concrete" → single token (very common word)
- "prestressed" →
prest+ressed(moderately common) - "geotechnical" →
ge+ot+echn+ical(domain-specific) - "28-day f'c" →
28+-+day+f+'+c(mixed notation)
Rare engineering terms consume more tokens, which means they use more of the context window and may be less well-represented in the model's internal representations.
Demo 1: Next-Token Predictor
This interactive demo simulates the autoregressive generation process. Select a civil engineering prompt and watch as the model completes it token by token. The probability bars show the model's confidence for each predicted token and its top alternatives.
Select a prompt and press "Generate" to watch the model predict one token at a time. Probability bars show the top candidates at each step.
Notice how early tokens often have high confidence (the prompt strongly constrains the likely continuations), while later tokens may show more competition between alternatives. This is a fundamental property of autoregressive generation: uncertainty tends to accumulate over longer sequences.
Demo 2: Temperature Effects
This demo shows how the temperature parameter affects token selection. The same prompt is completed at different temperatures, illustrating the spectrum from deterministic (greedy) to creative (high temperature) generation.
Adjust the temperature slider and press "Generate" to see how temperature affects the probability distribution and selected tokens.
At temperature 0 (or very close to it), the model always picks the single most likely token — the output is entirely deterministic and reproducible. As temperature increases, the model begins to explore less likely but still plausible alternatives. Above temperature 1.0, the distribution is flattened beyond its natural shape, and outputs become increasingly random and potentially incoherent.
RLHF & Alignment
Raw GPT models trained solely on next-token prediction are powerful but difficult to control. They may produce toxic content, refuse to follow instructions, or generate plausible-sounding misinformation. Reinforcement Learning from Human Feedback (RLHF) is the technique used to align GPT models with human intentions.
The RLHF Pipeline
- Supervised Fine-Tuning (SFT): Fine-tune the base model on high-quality instruction-response pairs written by humans
- Reward Model Training: Train a separate model to predict human preferences. Human labellers rank multiple model outputs for the same prompt; the reward model learns to assign higher scores to preferred outputs
- PPO Optimisation: Use Proximal Policy Optimisation to fine-tune the SFT model to maximise the reward model's scores, while staying close to the original model (KL penalty)
RLHF is what transforms a base GPT model (which simply predicts the next likely token) into a helpful assistant (which follows instructions, refuses harmful requests, and admits uncertainty). ChatGPT, for example, is GPT-3.5/GPT-4 with RLHF applied.
RLHF is like the professional mentorship process for a graduate engineer. The graduate (base GPT) has learned from textbooks (pre-training) and has strong technical knowledge. But they need guidance on professional judgement: when to be conservative, how to communicate with clients, and when to say "I don't know." The senior engineer (human feedback) reviews their work, ranks different approaches, and the graduate learns to produce outputs that meet professional standards.
Limitations & Hallucinations
Understanding GPT's limitations is arguably more important for engineers than understanding its capabilities. A model that sounds authoritative but is sometimes wrong is more dangerous than a model that is obviously limited.
Key Limitations
- Hallucinations: GPT can generate factually incorrect statements with high confidence. It may cite non-existent code sections, invent material properties, or produce incorrect calculations
- No real-time knowledge: The model's knowledge is frozen at its training cutoff date. It cannot access current project data, live sensor readings, or recent code updates
- Limited reasoning: Despite impressive performance on benchmarks, GPT struggles with multi-step mathematical reasoning, especially for novel problem types not well-represented in training data
- Context window limits: Even GPT-4's 128k token window cannot hold an entire set of construction drawings and specifications
- No physical understanding: The model has no grounding in physics. It cannot truly reason about structural behaviour, material properties, or spatial relationships
Mitigation Strategies for Engineers
- Always verify: Cross-check GPT outputs against design codes, textbooks, and hand calculations
- Use low temperature: For factual engineering tasks, use T = 0 to minimise creative (and potentially incorrect) outputs
- Provide context: Include relevant code sections, material data, and constraints in the prompt
- Chain-of-thought: Ask the model to show its reasoning step by step, making errors easier to spot
- Human-in-the-loop: Treat GPT as a drafting assistant, not a decision-maker. A qualified engineer must review and approve all outputs
CE Applications: GPT for Automated Report Generation
GPT's autoregressive generation creates fluent, contextual text — perfect for drafting engineering reports, site narratives, and technical memos that follow established formats.
Bridge Inspection Reports
Feed field photos and notes into GPT to generate NBI-format bridge inspection narratives. The model produces condition ratings, element descriptions, and maintenance recommendations following DOT templates.
Geotechnical Boring Logs
GPT converts raw SPT data (blow counts, soil descriptions, moisture content) into formatted geotechnical boring log narratives — generating subsurface profiles and foundation recommendations.
Site Communication
Generate RFIs, submittals, and daily site reports from bullet-point notes. GPT formats them professionally while maintaining technical accuracy — saving 2-3 hours of documentation daily.
Knowledge Check
Test your understanding of GPT and decoder models with these four questions.
What is the fundamental training objective of GPT models?
What does the causal (masked) self-attention mechanism in GPT ensure?
When using a GPT model to draft an engineering specification, which temperature setting would produce the most deterministic and conservative output?
What is "in-context learning" (also called few-shot learning) in GPT models?
Summary
Key Takeaways
- Decoder-only architecture: GPT uses only the Transformer decoder with causal (masked) self-attention, discarding the encoder entirely
- Autoregressive generation: Text is generated one token at a time, with each token conditioned on all preceding tokens
- Causal masking: A lower-triangular attention mask prevents each token from attending to future tokens, enabling left-to-right generation
- Temperature: Controls the randomness of generation. Low temperature = deterministic; high temperature = creative but potentially incoherent
- Top-k / top-p sampling: Strategies for restricting the candidate token set to improve output quality
- Scaling trajectory: GPT-1 (117M) → GPT-2 (1.5B) → GPT-3 (175B) → GPT-4 (>1T) demonstrated that scaling unlocks emergent capabilities
- In-context learning: Large GPT models can perform new tasks from examples in the prompt without weight updates
- CE applications: Report drafting, code generation, specification summarisation — always with human verification
- Critical limitation: Hallucinations make GPT unsuitable as a sole decision-maker in safety-critical engineering
In the next sub-chapter, we will explore Scaling Laws — the mathematical relationships between model size, dataset size, compute, and performance that explain why making GPT models bigger continues to make them better, and what limits this trajectory might eventually hit.