Lesson 1 of 4 · AI for Engineers
How LLMs Actually Work (For Engineers)
It was 2:47 AM and Marcus was staring at his terminal. He'd been prompting Claude to refactor a gnarly state machine in his payment processing service for the past hour. Sometimes the AI nailed it. Sometimes it produced code that compiled but subtly changed the business logic. The inconsistency drove him crazy.
"Why does it sometimes get it perfectly right and other times completely miss?" he asked his tech lead the next morning.
"Because you're thinking of it as a compiler," she said. "It's not. It's a probabilistic text predictor with emergent reasoning abilities. Once you understand the mechanics, you can predict when it'll succeed and when it'll fail."
That conversation changed how Marcus worked with AI forever. And that's exactly what we're going to cover in this lesson -- not the hand-wavy "AI is like a brain" analogy, but the actual engineering that makes LLMs work, explained for people who think in systems, architectures, and data structures.
The Transformer Architecture: What You Actually Need to Know
Every modern LLM -- GPT-4, Claude, Gemini, Llama -- is built on the transformer architecture introduced in the 2017 paper "Attention Is All You Need." As an engineer, you don't need to derive the math, but you do need to understand the data flow, because it directly explains the tool's capabilities and limitations.
The High-Level Pipeline
Here's what happens when you send a prompt to an LLM:
Each of these stages has engineering implications:
1. Tokenization -- Your text is split into tokens, not words. This matters more than most engineers realize.
Key insight: common programming patterns tokenize efficiently (fewer tokens), while unusual variable names, obscure APIs, or novel syntax burn through tokens faster. This directly affects what fits in your context window and how well the model "understands" your code.
At current API pricing, every token costs money. GPT-4o runs about $2.50 per million input tokens. A 100K-token context window costs $0.25 per request just for input. Understanding tokenization helps you estimate costs and optimize context usage.
2. Embeddings -- Each token is converted into a high-dimensional vector (typically 4,096 to 12,288 dimensions for large models). These vectors encode semantic meaning. The word "function" in JavaScript, the word "function" in Python, and the word "function" in mathematics all get similar but distinct embeddings based on surrounding context.
3. Transformer Blocks -- This is where the magic happens. Let's dig in.
Self-Attention: The Core Mechanism
The transformer's key innovation is self-attention -- the mechanism that lets each token "look at" every other token in the sequence and decide which ones are relevant.
Here's the simplified version of what happens in a single attention head:
Why does this matter for you as an AI-assisted engineer?
Self-attention is why context matters so much. When the model processes your prompt, every token attends to every other token. If you give it a function signature at the beginning of a 2,000-token prompt, the model can still "see" that signature when generating code at the end. But attention is diluted across all tokens -- the more irrelevant noise in your context, the weaker the signal from the important parts.
Use How LLMs Actually Work (For Engineers) in a low-risk branch or scratch project first. That keeps the lesson concrete without making your first attempt carry production pressure.
This is the engineering reason why focused, well-structured prompts outperform massive context dumps.
Multi-Head Attention: Parallel Pattern Recognition
Modern LLMs don't use a single attention mechanism -- they use multiple attention heads running in parallel (typically 32-128 heads). Each head learns to attend to different types of relationships:
- Head A might learn syntax relationships (matching brackets, indentation patterns)
- Head B might learn type relationships (variable declarations and their usage sites)
- Head C might learn semantic relationships (function name implies return type)
- Head D might learn positional relationships (nearby code is often related)
This is why LLMs can simultaneously understand your code's syntax, semantics, types, and conventions -- they're running dozens of parallel attention computations, each specializing in different aspects.
If How LLMs Actually Work (For Engineers) becomes part of a recurring workflow, document the exact trigger, boundary, and verification step now. Future speed comes from clarity, not from memory.
Layer Stacking: From Tokens to Understanding
A typical large model stacks 80-120 transformer blocks sequentially. Research shows these layers develop a hierarchy:
| Layer Range | What It Learns | Engineering Implication |
|---|---|---|
| Early (1-20) | Syntax, token patterns, basic grammar | Can identify language, basic structure |
| Middle (20-60) | Semantic relationships, code patterns, idioms | Understands common patterns, API usage |
| Late (60-100+) | Abstract reasoning, task understanding, planning | Can architect solutions, understand intent |
This layered processing explains why LLMs handle syntactically similar tasks well (early layers activate) but sometimes struggle with novel architectural decisions (requires deep late-layer reasoning with less training signal).
Context Windows: The Engineering Constraints
The context window is the total number of tokens the model can process in a single forward pass. Here's the current landscape:
| Model | Context Window | Approx. Lines of Code |
|---|---|---|
| GPT-4o | 128K tokens | ~50,000 lines |
| Claude 3.5/4 | 200K tokens | ~80,000 lines |
| Gemini 1.5 Pro | 2M tokens | ~800,000 lines |
| Llama 3.1 405B | 128K tokens | ~50,000 lines |
Decompose How LLMs Actually Work (For Engineers)
- Pick a real task that feels slightly too large for one uninterrupted pass.
- Split it into 2-3 focused responsibilities the way this lesson recommends.
- Run the work and note where clear ownership reduced confusion or rework.
But raw context size is misleading. Here's what engineers need to know:
The "Lost in the Middle" Problem
Research from Stanford and UC Berkeley demonstrated that LLMs perform best on information placed at the beginning and end of the context window, with degraded performance on content in the middle. This has direct implications for how you structure prompts:
┌─────────────────────────────────────────────────┐
│ HIGH ATTENTION: System prompt, key instructions │ ← Put critical context here
├─────────────────────────────────────────────────┤
│ │
│ LOWER ATTENTION: Supporting context, examples │ ← OK for reference material
│ │
├─────────────────────────────────────────────────┤
│ HIGH ATTENTION: Current task, question │ ← Put the actual ask here
└─────────────────────────────────────────────────┘10K-30K
Effective Context Sweet Spot
Despite models accepting 200K+ tokens, most engineers find peak performance with 10K-30K tokens of carefully selected context -- not a full repo dump.
Just because a model accepts 200K tokens doesn't mean it effectively uses all of them. Performance degrades as context grows. In practice, most engineers find the sweet spot is 10K-30K tokens of carefully selected context, not a full repo dump.
KV Cache and Why Long Conversations Slow Down
When you chat iteratively with an AI coding tool, each message includes the entire conversation history in the context. The model maintains a Key-Value cache (KV cache) to avoid recomputing attention for previous tokens, but this cache grows linearly with conversation length.
This is why long coding sessions with AI tools feel progressively slower and less accurate. The practical engineering response: start fresh conversations when you shift to a new task or when quality degrades.
Compare Solo vs Delegated Work
- Try one task as a single uninterrupted Claude request.
- Try a second task by delegating or sequencing focused subtasks.
- Compare accuracy, context pressure, and review effort between the two approaches.
Temperature, Top-p, and Sampling: Controlling Output
When the model processes your prompt through all transformer layers, the final output is a probability distribution over the entire vocabulary for the next token. How the model selects from this distribution is controlled by sampling parameters.
Temperature
Temperature scales the logits (raw scores) before the softmax function:
For code generation, most tools use temperature 0 to 0.3. Here's why:
Top-p (Nucleus Sampling)
Top-p sampling is an alternative to temperature that's often more intuitive. Instead of scaling probabilities, it truncates the distribution to the smallest set of tokens whose cumulative probability exceeds p:
For code generation: temperature 0, top-p 1 (deterministic). For code review comments and documentation: temperature 0.3-0.5, top-p 0.9 (slightly creative but grounded). For brainstorming architectural approaches: temperature 0.7-0.8, top-p 0.95 (more exploratory).
How Training Data Shapes Code Generation
LLMs are trained on massive datasets that include public code repositories, documentation, Stack Overflow, technical books, and more. This training process has direct implications for what the model can and cannot do:
What's Well-Represented (Model Excels)
What's Under-Represented (Model Struggles)
Predicting AI Reliability from Training Data
Ask yourself before prompting: 'How many examples of this pattern exist in public code?' Millions = great results. Dozens = expect hallucinations.
Blindly trust AI output for niche libraries, custom DSLs, or freshly released APIs -- always cross-check against official docs.
The Knowledge Cutoff Problem
LLMs have a training data cutoff date. Code patterns, library APIs, and framework conventions that emerged after this date may produce hallucinated or outdated suggestions:
Quick Check
What is the main benefit of using How LLMs Actually Work (For Engineers) well in Claude Code?
When the model generates code using a specific library version, always verify the API actually exists in the version you're using. This is the single most common source of AI-generated bugs. Use your IDE's autocomplete or the official docs as a cross-check.
Autoregressive Generation: Why Order Matters
LLMs generate text one token at a time, left to right. Each new token is conditioned on all previous tokens (both your prompt and the model's own prior output). This autoregressive nature has important implications:
The Snowball Effect
If the model makes a slightly wrong choice early in its output, all subsequent tokens are conditioned on that mistake. This can snowball:
This is why plan-then-implement prompting works so well -- it forces the model to lay out the correct structure before committing to code:
Beam Search vs. Greedy Decoding
Most production systems use variations of greedy decoding (always pick the most likely next token) or sampling with low temperature. Some systems use beam search, which maintains multiple candidate sequences in parallel:
For code generation, greedy decoding at temperature 0 is usually preferred because code has strong syntactic constraints that naturally guide the model toward correct sequences.
Quick Check
After reading this lesson, what should you validate when applying How LLMs Actually Work (For Engineers)?
Putting It All Together: A Mental Model for Engineers
Here's the mental model that will serve you throughout this course:
┌────────────────────────────────────────────────┐
│ YOUR PROMPT │
│ ┌──────────────────────────────────────────┐ │
│ │ System context + Instructions │ │
│ │ Relevant code files │ │
│ │ Specific task description │ │
│ └──────────────────────────────────────────┘ │
│ ↓ │
│ TOKENIZATION │
│ (Text → integer sequences) │
│ ↓ │
│ EMBEDDING LAYER │
│ (Integers → semantic vectors) │
│ ↓ │
│ 80-120 TRANSFORMER BLOCKS │
│ ┌──────────────────────────────────────────┐ │
│ │ Multi-Head Self-Attention │ │
│ │ (Every token attends to every other) │ │
│ │ Feed-Forward Network │ │
│ │ Layer Normalization │ │
│ │ Residual Connections │ │
│ └──────────────────────────────────────────┘ │
│ ↓ │
│ PROBABILITY DISTRIBUTION │
│ (Scores for every token in vocabulary) │
│ ↓ │
│ SAMPLING (temperature, top-p) │
│ (Select next token from distribution) │
│ ↓ │
│ REPEAT until stop token or max length │
│ ↓ │
│ DETOKENIZATION │
│ (Integer sequences → text) │
│ ↓ │
│ MODEL OUTPUT │
│ (Code, explanation, etc.) │
└────────────────────────────────────────────────┘Every capability and limitation of AI coding tools traces back to this pipeline:
- Why does it know React so well? → Massive training data with React examples
- Why does it hallucinate APIs? → Probability-based generation, not lookup-based retrieval
- Why does more context sometimes hurt? → Attention is diluted across more tokens
- Why does it fail on novel algorithms? → Fewer training examples in late-layer abstract reasoning
- Why is it better at writing code than debugging? → Generation is the core training task; debugging requires multi-step reasoning that's harder to learn from text
Explore Tokenization Yourself
- Visit platform.openai.com/tokenizer↗ (works with GPT-style tokenizers, similar principles apply to Claude)
- Paste a function from your current project and note the token count
- Now paste the same function with all comments removed -- compare token counts
- Try renaming variables from descriptive names to single letters -- watch the token count drop
- Paste a function using an obscure library vs. a popular one -- notice how the popular library's API tokenizes more efficiently
Reflection question: Based on the token counts, what percentage of a 200K context window would your typical PR fill?
Why This Matters for Your Daily Work
Understanding transformer architecture isn't academic -- it directly informs practical decisions:
1. Prompt Structure Follows Attention Patterns
Place your most important instructions at the beginning and end of prompts. Put supporting context in the middle. This aligns with how attention mechanisms actually weight information.
2. Token Budget is Your Resource Constraint
Just like memory or CPU, context window tokens are a finite resource. You need to make deliberate choices about what to include. A 200-line relevant file beats a 2,000-line entire module dump.
3. Predict Success Based on Training Data
Before asking the AI to help with a task, ask yourself: "How many examples of this pattern exist in public code?" If the answer is "millions" (React components, REST APIs, SQL queries), expect excellent results. If it's "dozens" (your custom DSL, a niche library), expect more hallucinations.
4. Use Temperature Intentionally
Don't just accept default settings. If you're generating boilerplate, use temperature 0. If you're exploring architectural options, bump it up. If you can control the temperature (API calls, some tools), treat it like any other engineering parameter.
5. Fresh Conversations for Fresh Context
Long conversation threads accumulate tokens and dilute attention. When you notice degrading quality, start a new conversation with clean, focused context.
Key Takeaways
- LLMs are probabilistic next-token predictors built on the transformer architecture, not deterministic code generators
- Self-attention allows every token to interact with every other token, which is why context quality matters more than context quantity
- Tokenization directly affects cost, context usage, and model performance -- common code patterns tokenize more efficiently
- Context windows have a "lost in the middle" problem -- place critical information at the start and end of prompts
- Temperature controls randomness: use 0 for deterministic code, 0.3-0.5 for documentation, 0.7+ for brainstorming
- Training data composition determines model strengths -- popular frameworks and patterns get dramatically better results
- Autoregressive generation means early errors snowball, which is why plan-then-implement prompting is effective
Use ← → to navigate, Space to mark complete