AI infrastructure and systemsPart 1: Foundations
Chapter 1How AI systems work
Llama 3.3 70B is about 70 billion numbers, and stored at 2 bytes each that is 140 GB, more than the 80 GB on an NVIDIA H100. That one multiplication tells you how many GPUs you need, what it costs and how fast it can answer, and this chapter gives you the model knowledge to do it for any system you are asked to run.
After this chapter you can
- Explain tensors, matrix multiplication and parameters in terms of memory and arithmetic
- Describe the training loop (forward pass, loss, backpropagation, optimizer) and how inference differs
- Trace a token through embeddings and a transformer block, naming the tensor shape at each step
- Estimate the memory and compute a model needs from its parameter count and context length
- Train a small transformer on a laptop CPU and inspect its shapes, parameters and memory
Tensors and matrix multiplication
A tensor is a multi-dimensional array of numbers with a shape and a data type. A vector of 4,096 values has shape (4096,); a batch of 8 sequences of 2,048 tokens, each represented by 4,096 numbers, has shape (8, 2048, 4096). In memory it is one contiguous buffer plus a little metadata (shape, strides, dtype), exactly the layout you would design in C.
| Rank | Example shape | What it holds in a language model |
|---|---|---|
| 0 | () | The loss, a single number |
| 1 | (4096,) | A bias or a normalization scale |
| 2 | (4096, 14336) | A weight matrix |
| 3 | (batch, tokens, 4096) | Activations flowing between layers |
| 4 | (batch, heads, tokens, 128) | Attention queries, keys and values split per head |
Almost all the work in a neural network is matrix multiplication. Multiplying an (M, K) matrix by a (K, N) matrix produces (M, N), and each output element is a dot product of length K.
FLOPs for one matmul = 2 x M x N x K (one multiply + one add per term)
Example: 2,048 tokens x a (4096, 14336) weight matrix
2 x 2048 x 14336 x 4096 = about 240 billion FLOPsEvery output element is independent of every other, so the work splits across thousands of arithmetic units with no coordination. That property is why the next chapter, GPUs and accelerators, is about hardware built for exactly this operation.
Parameters are the model
A layer is a function such as y = x @ W + b, where W and b are learned numbers called parameters (or weights). A trained model is a fixed architecture plus a file full of parameters. When someone says "an 8B model" they mean 8 billion parameters, and the model file on disk is mostly those numbers laid end to end.
The memory needed to hold them is parameters times bytes per parameter:
| Data type | Bytes per parameter | 8B model | 70B model |
|---|---|---|---|
| FP32 | 4 | 32 GB | 280 GB |
| BF16 or FP16 | 2 | 16 GB | 140 GB |
| INT8 or FP8 | 1 | 8 GB | 70 GB |
| 4-bit | 0.5 | 4 GB | 35 GB |
Training is a loop that adjusts parameters
Training starts from random parameters and nudges them, millions of times, toward values that make good predictions. Each iteration follows the same four steps.
Forward pass
Run a batch of inputs through the model to get predictions. For a language model the input is a sequence of tokens and the prediction is a probability for every possible next token at every position.
Loss
Compare the predictions with the right answers and reduce the error to one number. Language models use cross-entropy: the negative log of the probability the model gave to the true next token. Lower is better.
Backpropagation
Compute the gradient: for every parameter, how much the loss would change if that parameter moved slightly. The chain rule is applied backwards through every layer, reusing the activations saved during the forward pass. It costs about twice the forward pass.
Optimizer step
Update each parameter a small distance against its gradient. Adam and AdamW, the usual choices, keep two extra running averages per parameter to adapt the step size, which is extra memory you must budget.
The memory bill for training is much larger than the weights alone. With mixed-precision training and Adam, a common rule of thumb is about 16 bytes per parameter before activations.
BF16 weights 2 bytes
BF16 gradients 2 bytes
FP32 master weights 4 bytes
Adam moment 1 (FP32) 4 bytes
Adam moment 2 (FP32) 4 bytes
-------------------------------
Total 16 bytes per parameter (+ activations)
8B model: 8e9 x 16 = 128 GB before activationsThat is why even a "small" 8B model needs several GPUs or memory-saving tricks to train in full, which the Distributed training and Fine-tuning systems chapters cover.
Inference is the forward pass alone
Inference means using a trained model to make predictions. There is no loss, no gradient and no optimizer, so memory drops to the weights plus a working set. Language models generate text autoregressively: predict one token, append it to the input, and run the model again.
Training
- Forward, backward and update on every batch
- About 16 bytes per parameter plus activations
- Runs for days or weeks on many GPUs
- Measured in tokens processed per second and total cost
- Throughput matters most; nobody waits on one step
Inference
- Forward pass only, once per generated token
- About 2 bytes per parameter (BF16) plus a cache
- Runs forever, behind an API, as requests arrive
- Measured in latency per request and cost per token
- A user is waiting on every step
Most AI infrastructure jobs are about inference, because a model is trained once and served billions of times. The Inference serving part of this track builds on this section.
Tokens and embeddings
Models do not read characters or words. A tokenizer splits text into tokens, chunks from a fixed vocabulary, and maps each to an integer id. Modern vocabularies hold roughly 32,000 to 260,000 entries; for English, a token averages around four characters, but code, numbers and other languages tokenize differently.
"GPUs are fast" -> ["GP", "Us", " are", " fast"] -> [38, 3081, 527, 5043]
(ids are illustrative; every tokenizer is different)The first layer is an embedding table: a matrix of shape (vocab_size, d_model). Looking up a token means reading one row, so a sequence of T token ids becomes a (T, d_model) tensor. d_model, the hidden size, is the width of the vector that represents each token as it moves through the network: 4,096 for Llama 3.1 8B.
The transformer block
Nearly every modern language model is a stack of identical transformer blocks. Each block takes a (T, d_model) tensor and returns one of the same shape, so you can stack 32 or 80 of them. Inside each block are two sub-layers, each wrapped in a normalization and a residual connection.
- Attention lets each token gather information from earlier tokens. Each token's vector is projected into a query, a key and a value. Scores are query-key dot products, a softmax turns them into weights, and the output is the weighted sum of values. It runs in parallel over several heads. In a decoder model a causal mask stops tokens from seeing the future.
- MLP (multilayer perceptron, also called the feed-forward network) is two or three matmuls with a nonlinearity between them, applied to every token independently. It holds most of the parameters: about 70 percent in Llama 3.1 8B.
- Residual connections add a sub-layer's input to its output, so the signal and its gradient have a direct path through dozens of layers.
- Normalization (LayerNorm or RMSNorm) rescales each token vector to a stable range so the numbers neither explode nor vanish.
After the last block, a final projection of shape (d_model, vocab_size) produces logits, one score per vocabulary entry, and a softmax turns those into next-token probabilities. Here is where the 8 billion parameters of Llama 3.1 8B live:
| Component | Shape per layer | Parameters |
|---|---|---|
| Attention Q and O projections | 2 x (4096, 4096) | 33.6 M |
| Attention K and V projections (8 KV heads) | 2 x (4096, 1024) | 8.4 M |
| MLP (gate, up, down) | 3 x (4096, 14336) | 176.2 M |
| One layer in total | about 218 M | |
| 32 layers | about 6.98 B | |
| Embedding plus output head | 2 x (128256, 4096) | 1.05 B |
| Model total | about 8.03 B |
Context windows and what size costs
The context window is the maximum number of tokens the model can attend to at once: prompt plus generated output. Llama 3.1 supports 128K tokens. Two costs grow with context, and both land on your hardware.
During generation the model keeps each layer's keys and values for every earlier token, the KV cache, so it does not recompute them. Its size per token is fixed by the architecture:
KV bytes per token = 2 (K and V) x layers x kv_heads x head_dim x bytes per value
Llama 3.1 8B, BF16: 2 x 32 x 8 x 128 x 2 = 131,072 bytes = 128 KiB per token
One 128K-token conversation: 128 KiB x 131,072 = 16 GiB, as much as the weightsCompute is equally predictable. A forward pass costs about 2 FLOPs per parameter per token (one multiply and one add per weight), and training costs about 6, because the backward pass is roughly twice the forward pass.
Inference: FLOPs per token = 2 x N
Training: total FLOPs = 6 x N x D (D = training tokens)
8B model: inference = 1.6e10 FLOPs per token
training on 15 trillion tokens = 6 x 8e9 x 1.5e13 = 7.2e23 FLOPsThe Performance and cost math chapter turns these numbers into latency, throughput and dollars; Inference fundamentals goes deep on the KV cache.
Key terms
- Tensor
- A multi-dimensional array with a shape and a data type, stored as one contiguous buffer.
- Parameter
- A learned number inside the model; the weight file is a list of them.
- Forward pass
- Running inputs through the model to produce outputs.
- Loss
- One number measuring how wrong the predictions were; training minimizes it.
- Backpropagation
- Computing every parameter's gradient by applying the chain rule backwards through the layers.
- Optimizer
- The algorithm, such as AdamW, that turns gradients into parameter updates.
- Token
- A chunk of text from a fixed vocabulary, mapped to an integer id.
- Embedding
- A table lookup that turns a token id into a vector of d_model numbers.
- Attention
- The operation that lets each token take a weighted mix of information from other tokens.
- KV cache
- Stored keys and values for earlier tokens, kept so generation does not recompute them.
Train a tiny character-level model on your CPU
Goal: build and train a 4-layer transformer that writes fake Shakespeare, and check its parameter count, tensor shapes and memory against the formulas in this chapter.
You need: Python 3.11 or newer and about 1 GB of free RAM. No GPU. Install the CPU build of PyTorch with pip install torch numpy (on Linux, pip install torch --index-url https://download.pytorch.org/whl/cpu avoids a large CUDA download). Recent PyTorch releases do not ship wheels for Intel Macs; there, use the newest version pip offers or run the lab in Google Colab.
- Make a project folder and download the dataset, about 1 MB of Shakespeare plays.
mkdir tiny-gpt && cd tiny-gpt
python3 -m venv .venv && source .venv/bin/activate
pip install torch numpy
curl -LO https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt- Save the model and training loop as
tiny_gpt.py. Each character is a token, so the vocabulary is tiny (65), and the block mirrors the diagram above.
import math, time, torch, torch.nn as nn, torch.nn.functional as F
torch.manual_seed(0)
text = open("input.txt").read()
chars = sorted(set(text))
vocab = len(chars)
stoi = {c: i for i, c in enumerate(chars)}
data = torch.tensor([stoi[c] for c in text], dtype=torch.long)
print(f"characters: {len(text):,} vocab: {vocab}")
# Hyperparameters: small enough for a laptop CPU
ctx, d, heads, layers, batch = 64, 128, 4, 4, 32
def get_batch():
ix = torch.randint(len(data) - ctx - 1, (batch,))
x = torch.stack([data[i:i + ctx] for i in ix])
y = torch.stack([data[i + 1:i + ctx + 1] for i in ix])
return x, y
class Block(nn.Module):
def __init__(self):
super().__init__()
self.ln1, self.ln2 = nn.LayerNorm(d), nn.LayerNorm(d)
self.qkv = nn.Linear(d, 3 * d)
self.proj = nn.Linear(d, d)
self.mlp = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d))
def forward(self, x):
B, T, C = x.shape
q, k, v = self.qkv(self.ln1(x)).split(d, dim=2)
q, k, v = (t.view(B, T, heads, C // heads).transpose(1, 2) for t in (q, k, v))
att = F.scaled_dot_product_attention(q, k, v, is_causal=True)
x = x + self.proj(att.transpose(1, 2).reshape(B, T, C)) # residual 1
x = x + self.mlp(self.ln2(x)) # residual 2
return x
class TinyGPT(nn.Module):
def __init__(self):
super().__init__()
self.tok = nn.Embedding(vocab, d)
self.pos = nn.Embedding(ctx, d)
self.blocks = nn.Sequential(*[Block() for _ in range(layers)])
self.ln = nn.LayerNorm(d)
self.head = nn.Linear(d, vocab)
def forward(self, idx, targets=None):
B, T = idx.shape
x = self.tok(idx) + self.pos(torch.arange(T))
logits = self.head(self.ln(self.blocks(x)))
loss = None if targets is None else F.cross_entropy(logits.view(-1, vocab), targets.view(-1))
return logits, loss
model = TinyGPT()
n_params = sum(p.numel() for p in model.parameters())
print(f"parameters: {n_params:,} fp32 bytes: {n_params * 4 / 1e6:.2f} MB")
for name, p in model.named_parameters():
if name.startswith("blocks.0") or not name.startswith("blocks"):
print(f" {name:24s} {str(tuple(p.shape)):12s} {p.numel():>8,}")
x, y = get_batch()
logits, loss = model(x, y)
print(f"input {tuple(x.shape)} -> logits {tuple(logits.shape)} initial loss {loss.item():.3f} (ln(vocab) = {math.log(vocab):.3f})")
opt = torch.optim.AdamW(model.parameters(), lr=3e-3)
t0 = time.time()
for step in range(1501):
x, y = get_batch()
_, loss = model(x, y) # forward pass
opt.zero_grad()
loss.backward() # backpropagation
opt.step() # optimizer update
if step % 250 == 0:
print(f"step {step:5d} loss {loss.item():.3f} {time.time() - t0:.0f}s")
# Inference: generate one character at a time
model.eval()
idx = torch.zeros((1, 1), dtype=torch.long)
with torch.no_grad():
for _ in range(300):
logits, _ = model(idx[:, -ctx:])
probs = F.softmax(logits[:, -1, :], dim=-1)
idx = torch.cat([idx, torch.multinomial(probs, 1)], dim=1)
print("".join(chars[i] for i in idx[0].tolist()))- Run it and watch the shapes print before training starts.
python tiny_gpt.pyExpect parameters: 818,241 and input (32, 64) -> logits (32, 64, 65). The initial loss should be close to ln(65) = 4.174 (you will see something like 4.3), which is what a model that guesses uniformly at random scores. Note that PyTorch stores a linear layer's weight as (out_features, in_features), so qkv.weight prints as (384, 128).
-
Watch the loss fall. It should pass about 2.0 within the first few hundred steps and end near 1.5 by step 1,500; the run takes 2 to 5 minutes depending on your CPU. The generated text at the end will have speaker names, line breaks and word-shaped strings: structure learned from nothing but next-character prediction.
-
Check the parameter count by hand. Each block has four weight matrices:
qkvmaps 128 to 384,projmaps 128 to 128, and the two MLP layers map 128 to 512 and back. That is12 x 128 x 128 = 196,608weights per block, plus biases and norms. Fill in this table from the printed output and confirm it sums to 818,241.
| Part | Parameters |
|---|---|
| Token and position embeddings | |
| One block (from the printout) | |
| 4 blocks | |
| Final norm and head |
- Measure memory. On Linux run
/usr/bin/time -v python tiny_gpt.pyand read "Maximum resident set size"; on macOS use/usr/bin/time -land read "peak memory footprint". Compare it with the 16-bytes-per-parameter rule: about 13 MB for weights, gradients and Adam state. The rest is the Python runtime, PyTorch itself and activations.
Check your work: your table sums to the printed parameter count, the loss falls from about 4.3 to around 1.5, and you can explain in one sentence why peak memory is far larger than 13 MB.
Stretch: double d to 256 and predict the new parameter count before running. Then double ctx to 128 instead and observe that parameters barely change (only the position table grows) while time per step rises. Write down which costs scale with model width and which with context length.
Check yourself
A team wants to fully fine-tune a 7B-parameter model with AdamW in mixed precision. Roughly how much accelerator memory do weights, gradients and optimizer state need, before activations?
Your tiny model's first loss is 4.17 with a vocabulary of 65 characters. What does that tell you?
You double the context length of a deployed model from 32K to 64K tokens. What happens to the weight memory and the per-request KV cache memory?
In a transformer block, which component holds most of the parameters in a model like Llama 3.1 8B?
Why is training a model so much more memory-hungry than serving it?
Recap
- A neural network is mostly matrix multiplications over tensors, and a matmul of (M, K) by (K, N) costs 2 x M x N x K FLOPs.
- Model memory starts at parameters times bytes per parameter: 2 bytes each in BF16, about 16 bytes each for mixed-precision Adam training.
- Training repeats forward pass, loss, backpropagation and optimizer step; inference is the forward pass alone, repeated once per generated token.
- Text becomes token ids, then embedding vectors of width d_model, then flows through a stack of attention-plus-MLP blocks with residuals and normalization.
- Compute is about 2N FLOPs per token for inference and 6ND for training, and the KV cache grows linearly with context length.
Go deeper
- Neural Networks: Zero to Hero: Andrej Karpathy's video course that builds a GPT from scratch; the best next step after this lab.
- The Illustrated Transformer: Jay Alammar's visual walk-through of attention and the transformer block.
- Attention Is All You Need: the 2017 paper that introduced the transformer; readable once you know the shapes.
- Transformer inference arithmetic: parameter, FLOP and KV cache counting for real models, done carefully.
- How to Scale Your Model: a free systems-level book on transformer compute, memory and parallelism.