Foundation Models Handbook
First-Principles Handbook

How Foundation Models Actually Work

A clean mental model of tokens, embeddings, parameters, attention, context, memory, retrieval, multimodality, training, inference, and reasoning — built for architecture decisions, not exams.

Version · 2026-08-19
Sections · 58
Purpose · Functional literacy for AI system architects, not advanced mathematics
RAW INFORMATION
TOKENIZATION
EMBEDDINGS
TRANSFORMER + ATTENTION
LEARNED WEIGHTS
REASONING
OUTPUT
Part I

The Core Mental Model

01

The Core Mental Model

This handbook builds a clean mental model of modern foundation models without requiring advanced mathematics. It focuses on the concepts that matter for architecture, model selection, agent design, context engineering, and AI economics.

Training Data
Tokenization
Neural Network Training
Learned Parameters / Weights
Trained Model
Inference
Reasoning / Generation
Output

When the model is used inside an agentic system:

User / System Input
Context Assembly
Model Inference
Reasoning
Tool Calls / Retrieval / Actions
New Observations
Model Continues

The model itself is only one component of the full system.

02

Training vs Inference

Training

Training is the process of creating the model's learned capability.

massive dataset
tokenization
model predicts
prediction compared with target
loss calculated
weights adjusted
repeat at enormous scale

Training changes the model's parameters.

The goal is not to build a searchable database of documents. The goal is to optimize the network so that useful patterns, relationships, language structures, and higher-order capabilities emerge in the learned weights.

Inference

Inference happens after training, when the trained model is used.

Prompt
Trained Model
Inference
Response

Inference normally uses the existing learned weights rather than changing them.

03

Inference Is Not the Same as Reasoning

INFERENCE
= using the trained model
REASONING
= computational work performed during inference to solve a problem

Simple inference

Direct factual lookup
“What is the capital of Japan?”
Tokyo

Complex inference

Multi-step reasoning task

“Compare three financing structures, identify structural risks, and recommend the most defensible option.”

multi-step reasoning
final answer

All model reasoning happens during inference, but not every inference requires deep reasoning.

Part II

Tokens, Parameters & Embeddings

04

Tokenization

Models do not directly process human language as sentences. Text is first converted into tokens.

“OpenClaw is useful”
Open Claw is useful

Each token maps to a numerical token ID.

text
tokenizer
token IDs
model

Tokenizer Design vs Tokenization Operation

The tokenizer vocabulary/mapping is effectively fixed for a trained model family. But tokenization itself happens every time the model is used:

User text
fixed tokenizer
token IDs
model inference

Tokenizer design is fixed for a trained model; tokenization continues during every inference.

05

Training Sequences vs RAG Chunks

The word “chunking” can create confusion.

During Training
  • Huge corpus → tokens → training sequences → model training
During RAG
  • Document → chunks → embeddings → retrieval index
TRAINING SEQUENCE
= unit used to train model weights
RAG CHUNK
= unit stored for future retrieval
06

Parameters and Weights

A modern neural network contains a very large number of learnable numerical values. These are called parameters. A major subset of those parameters are weights.

PARAMETERS
= learned numerical values inside the model
WEIGHTS
= the dominant learned values that control mathematical transformations
w1 = 0.72
w2 = -1.14
w3 = 0.08

Real models contain billions or trillions of such values.

07

What Weights Do

A neural network repeatedly performs mathematical transformations. Very simplified:

input vector
matrix multiplication
weighted combination
non-linear transformation
new vector

During training:

prediction
loss
gradient
adjust weights slightly
repeat

Training searches for parameter values that reduce prediction error and improve generalization.

08

Parameters Are Capacity, Not Guaranteed Intelligence

A larger parameter count gives a model more representational capacity, but more parameters do not automatically produce a better model.

MODEL QUALITY
Architecture
Parameter Capacity
Training Data Quality
Training Objective
Optimization Quality
Post-Training
Inference Strategy

More parameters ≠ automatically more intelligence.

A smaller but better-trained model can outperform a larger poorly trained one.

09

Weights and Probability

At generation time, learned weights transform the current representations into a probability distribution over possible next tokens.

Current context
Transformer
learned weights
probability distribution

Example

Paris
82%
London
5%
Rome
3%

Training adjusts the weights so that good continuations become more probable across many examples.

A good model is not merely “more confident.” It should be accurate, calibrated, and context-sensitive.

10

Architecture vs Parameters

The architecture is designed first. Parameters are learned within that architecture.

ARCHITECTURE
= shape/design of the machine
PARAMETERS / WEIGHTS
= learned numbers inside the machine
TRAINING
= process that adjusts those numbers

Useful analogy

Architecture
= nervous system design
Weights
= strengths of learned connections
Training
= adaptation of those connections
11

Embeddings

Tokens are numerical IDs, but neural networks need continuous numerical representations. A token maps to a vector:

Token ID
Embedding Matrix
Vector

Example

"cat" →

The values are high-dimensional learned numbers.

12

Vector Space

A vector space is the high-dimensional geometry in which representations exist.

Do not imagine a literal database containing one fixed coordinate for every human concept.

Instead:

Learned parameters
embedding representations
repeated transformations
high-dimensional semantic geometry emerges

Semantically related concepts can develop related representations.

13

Vector Space Is Contextual

A token's initial embedding is not its final meaning.

Example

“bank” in —
  • “I deposited money at the bank.”
“bank” in —
  • “We sat on the river bank.”

The initial token representation enters the network, but contextual processing transforms it differently.

initial embedding
attention + transformations
contextual representation

Meaning is dynamically shaped by context.

Part III

Transformers & Attention

14

Transformer Architecture

The Transformer architecture was a major breakthrough because it enabled models to process relationships across sequences efficiently and scale extremely well.

Tokens
Embeddings
Transformer Layer 1
Transformer Layer 2
Transformer Layer 3
...
Final representation
Next-token probabilities

The key mechanism inside Transformers is attention.

15

Why Transformers Mattered So Much

Transformers enabled a combination of:

Capability Leap
better long-range relationships
parallelizable training
massive scaling
strong representation learning

The capability leap came from the combination:

Transformer Architecture
Massive Data
Accelerator Compute
Scaling
Better Training
Post-Training
Infrastructure

Transformer architecture was the foundation that allowed the rest to scale.

16

Attention

Which pieces of available information are most relevant to the representation currently being processed?

Example

“Roy bought a laptop because he wanted to study agents.”
Roy
78%
bought
12%
laptop
22%
because
8%
he
0%

When processing “he”, the model should strongly relate it to “Roy”, not “laptop”.

Attention assigns different relevance weights to different tokens.

17

Query, Key, Value

The intuitive mental model:

Q
Query

What am I looking for?

K
Key

What information do I represent?

V
Value

What information do I carry?

When processing “he”

Q("he") ≈ "Who does this pronoun refer to?"

Other tokens provide keys:

K("Roy")
K("laptop")
K("study")

The query is compared with keys. More relevant keys receive higher attention weight, and their values contribute more strongly to the updated representation.

Query
compare with Keys
attention weights
combine Values
updated representation
18

Self-Attention

Self-attention means tokens inside the same sequence attend to one another.

each token asks: “Which other tokens matter to me?”
token A
token B
token C
token D

This helps capture:

  • subject-object relationships;
  • pronoun references;
  • causality;
  • grammar;
  • semantic relationships;
  • long-distance dependencies.
19

Multi-Head Attention

Models use multiple attention heads.

HEAD 1

one relationship pattern

HEAD 2

another relationship pattern

HEAD 3

long-range dependency

HEAD 4

entity relationship

These roles are not manually assigned in a simple human-readable way; they emerge during training.

Multiple heads let the model examine several relationships simultaneously.

20

Is Self-Attention a Loop?

It is iterative across layers, but not a dynamic loop that runs until the model decides meaning is “finished”.

More accurately:

Representation
Attention Layer
Updated Representation
Feed-Forward Transformation
Next Transformer Layer
Attention Again
Richer Representation

The number of Transformer layers is fixed by the model architecture.

21

Three Kinds of Repetition

Transformer depth

Within one forward pass:

Layer 1
Layer 2
Layer 3
...
Layer N

Fixed by architecture.

Autoregressive generation

predict token 1 → append
predict token 2 → append
predict token 3 → append

Continues until a stopping condition.

Reasoning / test-time compute

Some reasoning models use more computation for difficult tasks.

Easy task
  • little reasoning compute
Hard task
  • more reasoning compute

This is different from network depth.

22

Autoregressive Generation

Language models typically generate output one token at a time.

Context
predict next token
append token
predict next token
append
repeat

Stopping conditions may include:

  • end-of-sequence token;
  • max output length;
  • tool call;
  • runtime stop condition.
Part IV

Context Engineering

23

Context

Context is the information actually available to the model during a particular inference. It may include:

CONTEXT
system instructions
conversation history
current user prompt
retrieved memory
RAG passages
tool results
files
state

The model directly reasons over the current context plus the capabilities encoded in its learned weights.

24

Context Window

The context window is the maximum working capacity available for the current inference.

Analogy

Library
= memory / RAG storage
Desk
= current context
Desk size
= context window

Everything actively needed for inference must fit on the desk.

25

Large Context Does Not Mean Perfect Recall

A model may support a huge context window, but that does not mean every token is used equally well.

Large context ≠ perfect attention ≠ perfect retrieval ≠ perfect reasoning

Very large context can increase:

  • noise;
  • cost;
  • latency;
  • attention dilution;
  • retrieval difficulty.

Context capacity and context quality are different things.

26

Context Engineering

A good system does not simply maximize context size.

Bad
  • 900,000 tokens → “find what matters”
Better
  • retrieve relevant evidence → compress state → remove noise → provide focused context

This improves reliability and cost.

27

Long Coding Sessions and Context Growth

Long technical chats accumulate:

Accumulated Context
requirements
code
errors
logs
architecture decisions
prior fixes
file contents
current question

If everything is repeatedly carried forward:

context grows
token cost grows
noise grows
retrieval becomes harder

This is why modular development and structured state matter.

28

Why Modular Code Helps LLMs

Modularity is not only software hygiene. It is also context-efficiency architecture.

Instead of
  • 10,000-line monolith
Prefer
  • data_ingestion/
  • compute/
  • validation/
  • reporting/
  • api_adapter/

Then a validation task can receive only:

Validation Task Context
validation module
interface contract
relevant dependency
current error

This reduces irrelevant context.

29

JSON as Structured State

JSON is useful for:

  • state;
  • contracts;
  • schemas;
  • configuration;
  • structured outputs;
  • metadata.
{
  "module": "payroll_compute",
  "input_contract": "...",
  "output_contract": "...",
  "immutable_rules": [],
  "known_dependencies": []
}

It can be more efficient than reconstructing long conversational history.

Do not convert everything into JSON.

Code should remain code. Narrative methodology can remain prose. JSON is best where explicit structure matters.

30

Max Output

Max output is the maximum number of output tokens a model may generate in one response. This is separate from the context window.

Context Window
= total working-space ceiling
Max Output
= generation ceiling

A model can have a large context window while still imposing a much smaller maximum output length.

Part V

Memory & Retrieval

31

Memory

Memory is information intentionally preserved for future use.

HISTORY
= what happened
STATE
= where work currently stands
MEMORY
= what should persist
CONTEXT
= what the model sees now

Memory may include:

  • durable preferences;
  • long-lived decisions;
  • recurring facts;
  • stable operational information.
32

Memory Is Not Automatically in Context

Memory exists ≠ Model currently sees it

Relevant memory must be retrieved and injected into the current context.

Memory Store
Retrieval
Context Assembly
Model
33

Retrieval

Retrieval selects relevant stored information for the current task. Sources may include:

Retrieval Sources
memory
RAG
database
files
past sessions
knowledge base

The goal is not to retrieve everything.

Retrieve the smallest set of information sufficient for good reasoning.

34

RAG

RAG stands for Retrieval-Augmented Generation. Typical pipeline:

Documents
Chunking
Embeddings
Index / Vector DB
Query
Retrieve relevant chunks
Insert into context
Model reasons

RAG gives the model access to knowledge outside its learned weights.

35

RAG vs Model Training

Training
  • data → tokens → optimization → weights change
RAG
  • documents → chunks → embeddings → storage → retrieval at inference

Training changes the model. RAG changes the information available to the model at runtime.

36

RAG vs Memory

The mechanisms may look similar technically, but their semantics differ.

MEMORY
= experiential / persistent information
RAG
= authoritative / canonical knowledge retrieval
Example memory
  • “User prefers architecture-first explanations.”
Example RAG source
  • “Company payroll policy version 3.2”

Both can be retrieved into context, but they represent different categories of truth.

37

Embedding Models

Embedding models are not primarily chat models. They transform input into vectors:

text
embedding model
vector

Used for:

  • semantic search;
  • similarity;
  • clustering;
  • retrieval.

They are central to many RAG systems.

Part VI

Multimodality

38

Multimodality

A multimodal model can process more than one type of input or output modality.

Multimodal Model
Text
Image
Audio
Video
Text / Image / Audio
Multimodal Model
Text / Image / Audio / Actions
39

How Images Enter a Model

A model does not “see” an image in the human sense.

Image
visual encoder / visual tokenization
visual representations
Transformer

Those representations become numerical vectors that can participate in attention and reasoning.

40

Cross-Modal Alignment

Multimodal systems must connect representations across modalities.

Text: "button"
attention / alignment
Visual UI element

This lets the model connect a user's text request to visual regions in a screenshot.

41

Audio Follows the Same Principle

Audio
audio encoding
vector/token-like representations
model

Different modalities become representations that can participate in a shared reasoning process.

42

Shared Representation Space

A multimodal system attempts to align related concepts across modalities.

semantic concept
Text: "dog"
Image of dog

The vectors do not need to be identical; they need enough alignment for cross-modal reasoning.

43

Attention in Multimodal Models

Attention is not limited to text. A multimodal system may need to decide:

  • Which text matters?
  • Which visual region matters?
  • Which audio segment matters?
  • How do they relate?
Attention
Text representations
Image representations
Audio representations
Attention
Contextual multimodal representation
Reasoning
44

Structured Data vs Multimodal Data

When structured data is available, structured access is usually preferable.

1
Structured API / JSON (most preferred)
2
Parsed document
3
Image / screenshot interpretation (least preferred)

Do not ask a model to read a screenshot of a spreadsheet if a clean JSON/API exists.

Multimodal reasoning is most valuable where the world is inherently unstructured.

Part VII

Truth, Agents & Model Selection

45

Model Knowledge Is Not a Source of Truth

Training gives a model general knowledge, but learned model knowledge may be:

  • incomplete;
  • outdated;
  • probabilistic;
  • difficult to trace;
  • occasionally wrong.

Healthy architecture

MODEL KNOWLEDGE
= general intelligence
RAG
= canonical knowledge
TOOLS / API
= current truth
DETERMINISTIC CODE
= exact calculation
46

Model vs Agent

A model is not an agent.

MODEL = intelligence engine

An agent system adds:

Agent System Additions
goal
state
memory
tools
permissions
stopping conditions
retry logic
orchestration
AGENT SYSTEM
MODEL
TOOLS
STATE
MEMORY
LOOP
PERMISSIONS
47

Model Selection Is an Architectural Choice

Most system builders do not modify frontier-model weights. They select the model that best fits the workload.

Practical questions become:

  • Is the data clean?
  • Is the context efficient?
  • Is reasoning needed?
  • Which model class is sufficient?
  • How expensive is each inference?
  • How many calls happen per task?
  • Can deterministic code replace model work?
48

Model Quality Is Multidimensional

Do not ask only: “Which model is smartest?”

Ask instead:

  • Reasoning quality?
  • Instruction following?
  • Tool discipline?
  • Structured output reliability?
  • Context performance?
  • Coding?
  • Vision?
  • Latency?
  • Cost?
  • Stability?
  • Hallucination rate?

A model can be excellent in one dimension and mediocre in another.

49

Dense vs Mixture-of-Experts

A dense model activates most of its parameters for each token. A Mixture-of-Experts (MoE) model contains many expert blocks, but only some are activated for each token.

Input → Router
Expert 1
Expert 2 (selected)
Expert 3
Expert 4 (selected)
Input
Router
Selected Experts
Output

Total Parameters ≠ Active Parameters

This matters for compute efficiency and model economics.

50

Open-Weight vs Closed Models

Closed Models
  • weights remain controlled by provider
  • accessed through API/service
Open-Weight Models
  • weights can be downloaded/self-hosted
  • subject to license

Trade-offs

Cloud
  • easy access
  • frontier capability
  • usage billing
  • provider-controlled
Local / Open-Weight
  • more control
  • privacy
  • hardware requirement
  • operational burden
Part VIII

Economics & Synthesis

51

Context and Cost

Context is not free. In agent systems, one human request may create multiple model calls.

Example

Call 1 → plan
Tool call
Call 2 → inspect result
Tool call
Call 3 → reason
Call 4 → verify
Call 5 → summarize

Each model call may carry part of the context again.

Agent Task Cost
sum of model calls
input context
output tokens
reasoning compute
retries
subagents

Architecture and economics cannot be separated.

52

Context Efficiency Is an Economic Discipline

Poor architecture

Context size
Number of agents
Retries
Frontier model use

Better architecture

deterministic pre-filtering
small relevant context
cheap model for routine work
strong model only when needed
Context size
Number of agents
Retries
Frontier model use

The second system may be both cheaper and more reliable.

53

Practical System Formula

SYSTEM QUALITY
MODEL QUALITY
DATA QUALITY
CONTEXT QUALITY
ARCHITECTURE QUALITY
TOOL QUALITY
GOVERNANCE

Economically

AI VALUE  ≈  Decision Quality × Reliability × Speed  ÷  Cost

A technically impressive system can still be economically poor.

54

The Complete Semantic Map

Every concept in this handbook fits into one composite pipeline — the core generative path, surrounded by the systems that make it contextual, grounded, and multimodal.

RAW INFORMATION
TOKENIZATION
EMBEDDINGS
VECTOR REPRESENTATIONS
TRANSFORMER
SELF-ATTENTION
Q / K / V RELATIONSHIPS
DEEPER CONTEXTUAL REPRESENTATIONS
LEARNED WEIGHTS / PARAMETERS
NEXT-TOKEN PROBABILITIES
AUTOREGRESSIVE GENERATION

Around that core

CONTEXT WINDOW
current working capacity
MEMORY
durable stored information
RETRIEVAL
selecting relevant stored information
RAG
retrieving canonical knowledge
MULTIMODALITY
extending representations beyond text
INFERENCE
using the trained model
REASONING
problem-solving computation during inference
55

Final Distinctions to Lock In

Keep this table mentally available.

Concept Practical Meaning
Token Unit of model input/output
Tokenizer Converts text into token IDs
Embedding Numerical vector representation
Vector Space Geometry of learned representations
Parameter Learnable numerical value
Weight Major learned parameter controlling transformations
Transformer Neural architecture processing representations
Attention Dynamic relevance weighting
Query What information is being sought
Key What a representation offers for matching
Value Information contributed after matching
Self-Attention Tokens attending to other tokens in the same sequence
Multi-Head Attention Multiple relationship patterns processed in parallel
Context Information available in the current inference
Context Window Maximum working-context capacity
Max Output Maximum generation length
Memory Information retained for later
Retrieval Selecting relevant stored information
RAG Retrieval of external canonical knowledge
Multimodal Processing multiple modalities
Training Learning model parameters
Inference Using the trained model
Reasoning Problem-solving computation during inference
Agent Model plus tools, state, memory, loop, and permissions
56

What You Do Not Need to Master

You do not need to derive advanced Transformer mathematics to make strong architecture decisions.

You do not need to calculate attention equations manually.

You do not need to train a frontier foundation model.

What you do need is functional understanding of:

  • what the model knows
  • what the model does not know
  • what context it receives
  • how attention uses that context
  • how retrieval changes that context
  • what memory preserves
  • what deterministic systems should handle
  • when reasoning is needed
  • how model calls create cost

That level of literacy is sufficient to design strong agentic and business-intelligence systems.

57

Architectural Principles

01

A model is a probabilistic intelligence engine, not a database.

02

Training changes weights; inference uses weights.

03

Parameters provide capacity; training quality determines how well capacity is used.

04

Embeddings create numerical representations; meaning becomes contextual through Transformer processing.

05

Attention determines what information matters relative to the current representation.

06

Context capacity is not the same as context quality.

07

Memory is useful only when relevant information is retrieved into context.

08

RAG complements model knowledge with external source-of-truth knowledge.

09

Structured data should be preferred over visual interpretation when available.

10

Model quality alone does not determine system quality.

11

Context engineering is both a reliability discipline and a cost discipline.

12

The best model is not necessarily the best model for every task.

13

Deterministic logic should stay deterministic.

14

Reasoning should be used where ambiguity genuinely exists.

15

AI architecture is also economic architecture.

58

Closing Mental Model

TRAINING
data → tokens → optimization
learned parameters
TRAINED MODEL
INFERENCE
CONTEXT
MEMORY / RAG
TOOLS
TRANSFORMER
ATTENTION
contextual meaning
REASONING
probabilities
next-token generation
OUTPUT

The model is powerful because learned weights create a high-dimensional transformation system capable of extracting relationships from context.

The system becomes useful because architecture determines what context, knowledge, tools, memory, permissions, and economic constraints surround that model.

Reference

Further Reading

These sources are useful for going deeper into the mechanisms summarized in this handbook:

One-Sentence Summary

A foundation model is a learned probabilistic transformation system: training shapes billions or trillions of numerical parameters; inference applies those learned weights to tokenized, vectorized context; attention dynamically routes relevant information; reasoning uses that machinery to solve problems; and system architecture determines whether the resulting intelligence is reliable, contextual, multimodal, retrievable, and economically useful.