02.1 Neural Network Basics

Understand LLMsLesson 1 of 1015,034 wordsDeep-dive10 parts
Module 02 · 0 of 9 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

Every LLM you will work with, whether GPT, Claude, Gemini, Llama, Qwen or DeepSeek, is a neural network. This lesson builds a complete, accurate mental model of what a neural network is, how it learns, and how that connects to the LLMs you'll build products with.

What you'll learn

  • How machine learning differs from traditional programming, and where neural networks fit within AI
  • What a neuron computes, and why activation functions are essential
  • How neurons form layers and networks, and why that's "just matrix multiplication" (and why GPUs matter)
  • What parameters are, how to count them, and how to estimate a model's memory needs
  • Precision, quantization (including 4-bit formats), mixture-of-experts, and what's inside a downloadable model file
  • How training works: loss functions, gradient descent, backpropagation, batches, epochs, optimizers, and why deep networks were once hard to train (vanishing gradients)
  • Generalization, overfitting and memorization, and why they matter for LLMs
  • Training vs inference, and what that means for every API call you make (including what fine-tuning and LoRA change)
  • A short history of neural networks and why transformers won
  • Common misconceptions you'll hear at work and in the media

What you don't need

  • Calculus or linear algebra beyond multiplying and adding numbers. Every maths idea here is explained in plain English.
  • Implementing training for real models. As an applied AI engineer, you use trained models through APIs and open-weight downloads.

Setup

The code samples need Python 3.11+ and NumPy:

bash
uv add numpy        # or: pip install numpy

First time? Create a project with uv init llm-basics && cd llm-basics, then run scripts with uv run python file.py.


What you must be able to do after this lesson#

This lesson is optional, so the list below is the goal for readers who take it. It is not a requirement for the rest of the path.

  • Explain what a neuron computes and why activation functions are needed
  • Describe how layers of neurons form a network
  • Estimate a model's parameter count and memory needs
  • Explain loss, gradient descent and backpropagation in plain words
  • Distinguish training from inference
  • Explain overfitting and memorization

Why this matters for an AI engineer#

You won't train LLMs in this path, but you will constantly run into decisions and jargon that this lesson explains from the ground up (the core lessons explain what you need of them as they go, so this lesson is a deeper background, not a prerequisite):

You'll hear... You'll understand it after...
"This is a 70B parameter model." Part 4: Parameters and model size
"We need an 80 GB GPU to run it." 4.4 Precision and memory
"Use the 4-bit quantized version." 4.5 Quantization
"It's a mixture-of-experts model with 37B active parameters." 4.6 Dense vs mixture-of-experts
"We released the open weights under a custom licence." 4.7 What's inside a model file
"The model has a knowledge cutoff of early 2025." Part 7: Training vs inference
"Why doesn't the bot remember what I told it yesterday?" Part 7: Training vs inference
"Should we fine-tune or just improve the prompt?" 7.4 Changing what a model does
"We trained a LoRA adapter on our support tickets." 7.4 Changing what a model does
"Only load safetensors files, never pickles." 4.7 What's inside a model file
"The model memorized that from its training data." Part 6: Generalization
"Nobody knows exactly why the model did that." Part 9: The black box problem

Part 1: The big idea#

1.1 Traditional programming vs machine learning#

In traditional programming, you write the rules:

python
def is_spam(email: str) -> bool:
    text = email.lower()
    return "free money" in text or "click here" in text

This breaks quickly. Spammers change their wording, legitimate emails sometimes contain "click here", and you can never write a rule for every case.

Machine learning flips this around. You provide examples together with the correct answers, and an algorithm learns the rules itself:

flowchart LR
    subgraph trad [Traditional programming]
        A[Rules] --> C[Program]
        B[Data] --> C
        C --> D[Answers]
    end
    subgraph ml [Machine learning]
        E[Data] --> G[Training]
        F[Answers] --> G
        G --> H["Learned rules<br/>(the model)"]
    end

Once trained, the model is applied to new data it has never seen to produce answers. That's the whole point: it should work on future emails, not just the ones it learned from.

1.2 Kinds of learning#

Machine learning comes in a few flavours, depending on where the "correct answers" come from. LLMs use three of them during their creation, so these terms will come back in lesson 06.

Kind Where the answers come from Example Used in LLMs?
Supervised learning Humans label each example ("spam" / "not spam") Spam filter, image classifier ✅ Instruction tuning: training on example conversations, written by humans or, increasingly, generated by other models (lesson 06, Part 6)
Unsupervised learning No answers at all; find structure in data Grouping customers into segments Indirectly: self-supervised learning (next row) is often classed as a kind of unsupervised learning, since no human provides the answers
Self-supervised learning The answers are hidden inside the data itself Hide the next word of a sentence and predict it ✅ Pretraining, the main phase. Every sentence on the internet becomes a training example for free
Reinforcement learning A reward signal says how good an outcome was Game-playing AI, robotics ✅ RLHF (reinforcement learning from human feedback, lesson 06, 7.2) and reasoning training: rewarding better answers

Self-supervised learning is the key insight behind LLMs. Take the sentence "The cat sat on the mat". Without any human labelling, it already contains training examples:

Input Correct next word
The cat
The cat sat
The cat sat on
The cat sat on the
The cat sat on the mat

Do this over trillions of words of text and you get a model that has absorbed grammar, facts, reasoning patterns and writing styles, all from the single task of predicting what comes next.

1.3 Where neural networks fit#

These terms are often used interchangeably, but they're nested:

flowchart TB
    subgraph ai ["Artificial Intelligence: any technique that makes machines act intelligently"]
        subgraph mlearn ["Machine Learning: systems that learn from data"]
            subgraph dl ["Deep Learning: ML using neural networks with many layers"]
                subgraph genai ["Generative AI: models that create new content"]
                    llm["Large Language Models<br/>(GPT, Claude, Gemini, Llama...)"]
                end
            end
        end
    end
  • AI also includes non-learning approaches such as rule-based expert systems and search algorithms (for example a classic chess engine).
  • Machine learning includes non-neural methods too, such as decision trees and linear regression, which are still widely used for tabular data.
  • Deep learning is machine learning with deep neural networks, the subject of this lesson.
  • Generative AI produces new text, images, audio or video. It also covers image generators (Module 09).
  • LLMs are deep neural networks trained on huge amounts of text to predict the next token.

1.4 Everything is numbers#

A neural network can only do arithmetic. It can't read text, see images or hear sound. Every input must first be converted into numbers, and every output comes out as numbers that we convert back.

Data How it becomes numbers
Image Each pixel's red, green and blue brightness (0–255)
Audio Sound-wave amplitude measured many thousands of times per second (typically 16,000 for speech models and 44,100–48,000 for music and video)
Tabular data Columns are already numbers, or categories mapped to numbers
Text Split into tokens (lesson 02), and each token is mapped to a list of numbers called an embedding (lesson 03)

A list of numbers like [0.2, -1.3, 0.8] is called a vector. You'll see this word constantly in AI engineering, from "vector databases" to "embedding vectors".


Part 2: The neuron#

2.1 Inspired by biology, loosely#

The human brain has roughly 86 billion neurons, cells that receive signals from other neurons, and "fire" a signal onward if the combined input is strong enough. In the 1940s and 1950s, researchers created a mathematical imitation: the artificial neuron. Warren McCulloch and Walter Pitts described the first one in 1943, and Frank Rosenblatt's perceptron (1958) was the first that could learn its own weights from examples.

2.2 Anatomy of a neuron#

Imagine you're deciding whether to go out this weekend. You consider three factors:

Input Value
Is it sunny? 1 (yes)
Are friends going? 1 (yes)
Is it cheap? 0 (no)

Not every factor matters equally to you. Friends matter a lot, weather matters somewhat, and cost barely matters. These importances are weights. You also have a baseline tendency, such as "I usually prefer staying home". That's the bias.

A neuron performs exactly three steps:

  1. Multiply each input by its weight.
  2. Add them all up, then add the bias. The result is called the weighted sum (often written z).
  3. Activate: pass z through an activation function, which transforms it into the neuron's output.
flowchart LR
    S["sunny = 1"] -- "× 2.0" --> N(("Σ + bias<br/>→ activation"))
    F["friends = 1"] -- "× 3.0" --> N
    C["cheap = 0"] -- "× 0.5" --> N
    N --> O["output: 0.73<br/>(73% chance I go out)"]

With weights [2.0, 3.0, 0.5] and bias -4.0:

text
z = (1 × 2.0) + (1 × 3.0) + (0 × 0.5) + (-4.0) = 1.0
output = sigmoid(1.0) = 0.73

That's it: multiply, add, activate. Everything in this lesson, up to LLMs with more than a trillion parameters, is built from this operation repeated at enormous scale.

2.3 Try it: a single neuron#

python
import numpy as np

def sigmoid(z):
    return 1 / (1 + np.exp(-z))

inputs = np.array([1.0, 1.0, 0.0])   # sunny, friends going, cheap
weights = np.array([2.0, 3.0, 0.5])  # how much each input matters
bias = -4.0                           # baseline: "I'd rather stay home"

z = np.dot(inputs, weights) + bias    # weighted sum
output = sigmoid(z)                   # squash into 0..1
print(f"Weighted sum: {z:.2f}")
print(f"Chance I go out: {output:.0%}")
Output2 lines
Weighted sum: 1.00
Chance I go out: 73%

2.4 What weights and bias actually mean#

  • Sign of a weight: a positive weight means "this input pushes the output up". A negative weight means "this input pushes it down". If rain were an input, it would get a negative weight.
  • Size of a weight: a large weight (positive or negative) means "this input matters a lot". A weight near zero means "ignore this input".
  • Bias: shifts the threshold. A large negative bias means the neuron needs strong evidence before it "fires". A positive bias means it fires easily.

The neuron's entire "opinion" lives in these numbers. Change them and you change its behaviour. Training is nothing more than finding good values for these numbers automatically.

2.5 Activation functions#

Why they're essential

Without an activation function, a neuron is just a weighted sum, and a weighted sum of weighted sums is still just a weighted sum. However many layers you stacked, the whole network would collapse into the equivalent of a single layer, only able to learn straight-line (linear) relationships.

The real world isn't linear. "I'll go out if it's sunny and friends are going, but not if it's raining unless it's a concert" is full of bends and conditions. Non-linear activation functions are what let stacked layers represent these complex, curved patterns. Without them, deep learning wouldn't work.

The common ones

Function What it does Output range Where it's used
Sigmoid Squashes any number smoothly into 0..1 0 to 1 Yes/no outputs (probability of "spam"); historically in hidden layers
Tanh Like sigmoid but centred on zero -1 to 1 Older networks, RNNs
ReLU (Rectified Linear Unit) Keeps positive numbers, turns negatives into 0 0 to ∞ The default for most modern networks: simple and fast
GELU A smooth version of ReLU that lets small negative values through ≈ -0.17 to ∞ GPT-2, BERT and many transformers
SiLU / Swish Also smooth like GELU: the input multiplied by its own sigmoid ≈ -0.28 to ∞ Inside SwiGLU; config files list it as "hidden_act": "silu"
SwiGLU Not a single function but a "gated" MLP design: two parallel paths, one passed through SiLU, multiplied together — Llama, Qwen, Mistral, PaLM and many modern LLMs (lesson 04, 6.2)

Try it: compare activation functions

python
import numpy as np

def sigmoid(z):
    return 1 / (1 + np.exp(-z))

def relu(z):
    return np.maximum(0, z)

def gelu(z):  # tanh approximation used by GPT-2
    return 0.5 * z * (1 + np.tanh(np.sqrt(2 / np.pi) * (z + 0.044715 * z**3)))

def silu(z):  # also called Swish; used inside SwiGLU (Llama, Qwen, Mistral...)
    return z * sigmoid(z)

z = np.array([-3.0, -1.0, 0.0, 1.0, 3.0])
print("input   :", z)
print("sigmoid :", sigmoid(z).round(3))
print("tanh    :", np.tanh(z).round(3))
print("relu    :", relu(z))
print("gelu    :", gelu(z).round(3))
print("silu    :", silu(z).round(3))
Output6 lines
input   : [-3. -1.  0.  1.  3.]
sigmoid : [0.047 0.269 0.5   0.731 0.953]
tanh    : [-0.995 -0.762  0.     0.762  0.995]
relu    : [0. 0. 0. 1. 3.]
gelu    : [-0.004 -0.159  0.     0.841  2.996]
silu    : [-0.142 -0.269  0.     0.731  2.858]

Notice how sigmoid and tanh flatten out at the extremes (0.953 at 3, approaching 1 but never reaching it), while ReLU, GELU and SiLU keep growing for positive inputs. GELU and SiLU behave like a softened ReLU: small negative inputs come through as small negative outputs instead of being cut to 0. That flattening is one reason sigmoid and tanh fell out of favour for deep networks: when a function is flat, its slope is almost zero, so training signals passing through many such layers shrink towards nothing. This is called the vanishing gradient problem. You'll see it happen in numbers in 5.3, once you know how training signals flow backwards through a network.


Part 3: Networks of neurons#

3.1 Layers#

One neuron can only make simple decisions. Real problems need many neurons, organized into layers:

flowchart LR
    subgraph inputs [Input layer]
        I1((x1))
        I2((x2))
        I3((x3))
    end
    subgraph hidden [Hidden layer]
        H1((h1))
        H2((h2))
        H3((h3))
        H4((h4))
    end
    subgraph outputs [Output layer]
        O1((y))
    end
    I1 --> H1 & H2 & H3 & H4
    I2 --> H1 & H2 & H3 & H4
    I3 --> H1 & H2 & H3 & H4
    H1 & H2 & H3 & H4 --> O1
  • The input layer isn't really neurons. It's just the input numbers being fed in.
  • Each hidden layer is a group of neurons. Every neuron receives all outputs of the previous layer as its inputs, each with its own weight. They're called "hidden" because you never see their values directly; they're internal.
  • The output layer produces the final answer.

When every neuron connects to every output of the previous layer, it's called a fully connected or dense layer. A network made of dense layers is called a multi-layer perceptron (MLP) or feedforward network, because data flows forward in one direction from input to output.

3.2 The forward pass#

Running inputs through the network, layer by layer, to get an output is called the forward pass:

  1. Input numbers go into hidden layer 1. Each neuron multiplies, adds and activates.
  2. Layer 1's outputs become layer 2's inputs, and so on.
  3. The last layer's outputs are the answer.

Every time you call an LLM API, the model runs a forward pass, in fact one forward pass for every token it generates (lesson 05).

3.3 Layers are matrix multiplications#

Computing neurons one at a time would be slow. Instead, all neurons in a layer are computed at once using matrix multiplication.

python
import numpy as np

# One example with 3 inputs: sunny, friends going, cheap
x = np.array([1.0, 1.0, 0.0])

# A layer of 4 neurons: one column of weights per neuron (3 inputs x 4 neurons)
W = np.array([
    [ 2.0, -1.0,  0.5,  1.0],
    [ 3.0,  0.5, -2.0,  1.0],
    [ 0.5,  2.0,  1.0, -1.0],
])
b = np.array([-4.0, 0.0, 1.0, -0.5])   # one bias per neuron

z = x @ W + b          # all 4 weighted sums in a single matrix multiplication
print("Weighted sums:", z)
print("Parameters in this layer:", W.size + b.size)

# A batch of 2 examples is processed in the same single operation
batch = np.array([[1.0, 1.0, 0.0],
                  [0.0, 1.0, 1.0]])
print("Batch output shape:", (batch @ W + b).shape)
Output3 lines
Weighted sums: [ 1.  -0.5 -0.5  1.5]
Parameters in this layer: 16
Batch output shape: (2, 4)

The first neuron's weighted sum (1.0) is exactly what we computed by hand in Part 2, since its column holds the same weights [2.0, 3.0, 0.5] and bias -4.0. The last line shows something important: many examples (a batch) can be processed at once, also with a single matrix multiplication. The output has 2 rows (examples) × 4 columns (neurons).

Why this matters: GPUs

Matrix multiplication is millions of independent multiply-and-add operations, and they can all run in parallel. GPUs (graphics processing units), originally built to calculate millions of pixels in parallel for video games, turned out to be perfect for this. This is why:

  • AI companies spend billions on GPUs (and specialized chips such as Google's TPUs).
  • GPU memory determines which models you can run locally (Module 11C).
  • Providers can serve many users at once by batching their requests together through the same matrix multiplications (lesson 05, 11.2).

3.4 Depth and learned features#

Why stack many layers instead of using one very wide layer? Because each layer builds on the patterns detected by the layer before it, letting the network learn a hierarchy of increasingly abstract features.

In a network that recognizes images, researchers found:

Layers What neurons tend to detect
Early Edges, colours, simple textures
Middle Shapes and parts: eyes, wheels, windows
Late Whole objects: faces, cars, buildings

Nobody programmed these features. The network discovered them during training because they were useful for the task. This automatic discovery of useful internal features is called representation learning, and it's the reason deep learning beat hand-engineered approaches.

LLMs work the same way with text. Earlier layers tend to handle surface features such as word pieces and syntax, while later layers capture more abstract concepts such as meaning, tone and the relationships between ideas.

3.5 How powerful can a network be?#

A famous result called the universal approximation theorem says that a network with even a single hidden layer, given enough neurons, can approximate essentially any continuous input → output relationship as closely as you like.

Two practical caveats:

  • "Enough neurons" can be impractically many. Depth (more layers) is usually far more efficient than width.
  • The theorem says a good set of weights exists. It doesn't say training will find it, or that the result will work on new data.

The takeaway: neural networks are extremely flexible function-learners. The hard parts are training them well and making them generalize (Part 6).

3.6 Output layers: shaping the answer#

The output layer's design depends on what kind of answer you need:

Task Output layer Example
Predict a number (regression) One neuron, no activation House price: 342,500
Yes/no (binary classification) One neuron with sigmoid Spam probability: 0.97
Pick one of many options (multi-class classification) One neuron per option, then softmax Cat 64%, dog 24%, car 9%, tree 3%

The raw numbers coming out of the final layer, before conversion to probabilities, are called logits. Softmax turns a list of logits into probabilities that are all positive and add up to exactly 1. Higher logits get a bigger share.

python
import numpy as np

def softmax(scores):
    exps = np.exp(scores - scores.max())   # subtract max for numerical stability
    return exps / exps.sum()

# Raw scores (logits) a network produced for 4 possible answers
labels = ["cat", "dog", "car", "tree"]
logits = np.array([2.0, 1.0, 0.1, -1.0])

probs = softmax(logits)
for label, p in zip(labels, probs):
    print(f"{label:5s} {p:.1%}")
print("Sum:", probs.sum())
Output5 lines
cat   63.8%
dog   23.5%
car   9.5%
tree  3.2%
Sum: 1.0

This is exactly how an LLM produces output. Its final layer has one output per token in its vocabulary (typically 32,000 to about 262,000 tokens, and 100,000+ for most current models; lesson 02, 3.2), and softmax turns them into a probability for every possible next token. Choosing one token from that distribution is called sampling, and parameters such as temperature reshape the distribution before the choice is made. That's the subject of lesson 05.


Part 4: Parameters and model size#

4.1 Parameters: the learned knobs#

All the weights and biases in a network together are called its parameters. They are:

  • The only thing that changes during training.
  • Everything the model "knows": language, facts, skills and style, all encoded as numbers.

Counting them for a dense layer:

text
parameters = (inputs × neurons) + neurons
             └─── weights ───┘   └ biases ┘

For the network in 3.1:

Layer Weights Biases Total
Hidden (3 inputs → 4 neurons) 3 × 4 = 12 4 16
Output (4 inputs → 1 neuron) 4 × 1 = 4 1 5
Network 21

(Many modern LLMs leave the bias out of most layers, as 2.2 explains. For those layers the count is just inputs × neurons.)

When someone says "an 8B model", they mean 8 billion of these numbers.

4.2 Parameters vs hyperparameters#

These two terms are easy to confuse:

Parameters Hyperparameters
What Weights and biases Settings that control the architecture and the training process
Set by Training (learned automatically) Humans (chosen before training)
Examples The billions of numbers in the model file Number of layers, neurons per layer, learning rate, batch size, number of training steps

4.3 Real model sizes#

Model Year Parameters
GPT-1 2018 117 million
GPT-2 2019 1.5 billion
GPT-3 2020 175 billion
Llama 3.1 2024 8B, 70B, 405B (three sizes)
DeepSeek-V3 2024 671B total (mixture-of-experts, see 4.6)
gpt-oss-120b (OpenAI) 2025 ~117B total, ~5.1B active (mixture-of-experts)
Kimi K2 (Moonshot AI) 2025 1 trillion total, 32B active (mixture-of-experts)
Kimi K3 (Moonshot AI) 2026 ~2.8 trillion total, ~104B active (mixture-of-experts)
GPT-4/5 family, Claude, Gemini — Not publicly disclosed

As of October 2026, several open-weight models have more than a trillion total parameters (Kimi K3 has about 2.8 trillion), and almost all of the largest are mixture-of-experts models. At the other end, useful models start well below a billion parameters: this course's own demos use GPT-2 (124M) and Qwen2.5-0.5B. Lesson 09, 3.2 lists the current families and sizes.

Most closed-model providers don't publish parameter counts. You'll see estimates online, but treat them as rumours. As an engineer, you should choose closed models by measured behaviour (quality, speed, cost on your task, Module 10A), not by guessed size.

4.4 Precision and memory#

Each parameter is a number stored in memory, and how many bytes each one takes depends on its precision (number format):

Precision Bytes per parameter Notes
FP32 (32-bit float) 4 Full precision. Rarely used to store large models today
FP16 / BF16 (16-bit) 2 The standard for training and serving. BF16 keeps FP32's range with less precision, which suits neural networks
FP8 (8-bit float) 1 Increasingly used for serving and even training on recent GPUs
INT8 (8-bit integer) 1 Quantized (4.5)
INT4 (4-bit integer) 0.5 Heavily quantized; popular for running models locally
FP4 (4-bit float: MXFP4, NVFP4) 0.5 4-bit floating-point formats where each small block of numbers shares a scale factor. NVIDIA's Blackwell GPUs compute in them natively. OpenAI's gpt-oss and Moonshot's Kimi K3 ship their main weights in MXFP4

The rule of thumb: memory for weights ≈ parameters × bytes per parameter.

python
BYTES_PER_PARAM = {"fp32": 4, "bf16/fp16": 2, "int8": 1, "int4": 0.5}

def weights_memory_gb(params_billions: float, precision: str) -> float:
    return params_billions * 1e9 * BYTES_PER_PARAM[precision] / 1e9

for size in [8, 70, 405]:
    row = ", ".join(f"{p}: {weights_memory_gb(size, p):6.1f} GB" for p in BYTES_PER_PARAM)
    print(f"{size:>3}B -> {row}")
Output3 lines
  8B -> fp32:   32.0 GB, bf16/fp16:   16.0 GB, int8:    8.0 GB, int4:    4.0 GB
 70B -> fp32:  280.0 GB, bf16/fp16:  140.0 GB, int8:   70.0 GB, int4:   35.0 GB
405B -> fp32: 1620.0 GB, bf16/fp16:  810.0 GB, int8:  405.0 GB, int4:  202.5 GB

What this means in practice:

  • An 8B model at 4-bit (about 5 GB) runs on a decent laptop.
  • A 70B model at BF16 (140 GB) doesn't fit on a single 80 GB data-centre GPU, so it must be split across at least two. Newer GPUs with 141–192 GB (such as NVIDIA's H200 or AMD's MI300X) can hold those weights, but leave little room for anything else.
  • A 405B model needs a multi-GPU server even when quantized.

These numbers cover the weights only. Running a model also needs memory for intermediate calculations and especially for the KV cache, the model's working memory of the conversation so far, which grows with every token in the conversation and with every user served at once. For short chats it's small. At long contexts it can exceed the weights themselves: Llama 3.1 8B needs about 16 GB for its BF16 weights but about 17 GB of cache for a single 128K-token conversation (lesson 04, 11.4). Size hardware for your real context length and number of simultaneous users, not just the weights. Lesson 07 covers what this means for cost and latency.

4.5 Quantization#

Quantization means storing parameters at lower precision, for example converting 16-bit numbers into 8-bit or 4-bit ones, after training.

  • ✅ Smaller: 4-bit uses about ¼ of the memory of 16-bit.
  • ✅ Often faster, because moving data out of memory is usually the bottleneck when generating text (lesson 04, 10.2).
  • ⚠️ Some quality loss, small at 8-bit, usually acceptable at 4-bit with good methods, and increasingly noticeable below that.

An analogy: it's like saving a photo as a compressed JPEG. Fewer bits, and most of the picture survives. You'll see quantized files labelled with names like Q4_K_M or AWQ/GPTQ when downloading open models (Module 11C).

Quantization can happen at different points:

  • After training (post-training quantization), by the model's publisher or by the community. This is where most Q4_K_M, AWQ and GPTQ files come from. (Here "post-training" simply means "after training is finished". It's a different sense from the post-training stage in lesson 06, the SFT and RLHF steps that turn a pretrained model into an assistant.)
  • During training (quantization-aware training), so the model learns to cope with low precision. Some recent models are released natively in a 4-bit format such as MXFP4, so the 4-bit version is the official one.
  • By whoever serves the model. When several inference hosts offer the same open model, some run it at FP8 or FP4 to cut cost, and quality can differ between them, especially on long or difficult tasks. OpenRouter shows each host's declared precision (lesson 09, 5.4).
  • The KV cache too. Serving engines can store the KV cache at lower precision (for example FP8) to fit more users or longer contexts (lesson 04, 11.4).

What this means for you as an engineer: "the same model" isn't always the same. When you run an open model yourself, pick the quantization deliberately and test it on your task. When you call a hosted open model, check which precision the host serves, and evaluate the exact endpoint you'll use in production (Module 10A).

4.6 Dense vs mixture-of-experts (MoE)#

In a dense model, every parameter is used for every token it processes.

In a mixture-of-experts (MoE) model, the MLP block in each transformer layer (3.1) is replaced by many smaller MLPs called experts, plus a small router that picks a few experts for each token at each layer. The rest sit idle for that token. The attention part of each layer is unchanged (lesson 04, 12.4). Some designs also add one or more shared experts that every token uses.

An analogy: a large hospital has many specialist departments, but each patient is seen by only two or three of them. The hospital needs buildings for every department (memory), but each patient's visit only costs the time of the departments they actually saw (compute).

Model Year Total parameters Active per token
Mixtral 8x7B 2023 ~47B ~13B
DeepSeek-V3 2024 671B 37B
gpt-oss-120b 2025 ~117B ~5.1B
Kimi K3 2026 ~2.8T ~104B

Model names often encode this. Qwen3.6-35B-A3B means 35 billion total parameters, of which about 3 billion are active per token (lesson 09, 3.5).

Why this matters to you:

  • Speed and compute cost depend mostly on active parameters, so an MoE model can be much faster and cheaper per token than a dense model of the same total size.
  • Memory depends on total parameters, since all experts must be loaded even if only a few are used per token.
  • When comparing models, always check whether a quoted size is total or active.

4.7 What's inside a model file#

When a company releases open weights, you can download (typically from Hugging Face):

File What it is
Weights (*.safetensors, or *.gguf for local tools such as llama.cpp and Ollama) The billions of parameters, often split across multiple files ("shards")
Config (config.json) The architecture: number of layers, hidden size, attention heads, vocabulary size, activation function, and so on
Tokenizer files (tokenizer.json, tokenizer_config.json) How to convert text to tokens and back (lesson 02), usually including the chat template that formats a conversation into the exact text the model was trained on (lesson 06, 6.2)
Generation config (generation_config.json) The default generation settings, such as temperature, top-p and the tokens that end a reply. These apply whenever you don't set your own (lesson 05)
Model card (README.md) Intended use, training details, benchmark results, limitations, licence

The weights alone are meaningless numbers. You also need inference code that implements the architecture described in the config. Libraries such as Hugging Face Transformers, vLLM and llama.cpp provide this.


Part 5: Training: how the knobs get set#

A new network starts with random weights, so its outputs are nonsense. Training is the process of adjusting the weights until the outputs are good. It needs three ingredients: a way to measure how wrong the network is, a way to figure out which direction to adjust each weight, and a loop that repeats this many times.

5.1 Loss: measuring how wrong we are#

A loss function takes the network's predictions and the correct answers and returns a single number: how wrong the network is. Bigger is worse, and 0 means perfect. Training is the search for weights that make the loss as small as possible.

The two loss functions you'll meet most:

Mean squared error (MSE), for predicting numbers: average the squared differences between predictions and correct answers. Predict 310 when the answer is 300 and the error is (310 − 300)² = 100. Squaring makes big misses count much more than small ones.

Cross-entropy, for predicting categories: look at the probability the model gave to the correct answer, and take the negative logarithm:

Probability given to the correct answer Cross-entropy loss
0.99 (confident and right) 0.010
0.90 0.105
0.50 (a coin flip) 0.693
0.10 2.303
0.01 (confident and wrong) 4.605

Cross-entropy barely punishes confident correct answers, but punishes confident wrong answers very heavily. It pushes the model towards putting high probability on the right answer.

This is the loss used to pretrain every LLM. At each position in the training text, the model outputs probabilities for every possible next token, and the loss is the cross-entropy of the actual next token. Lowering this number across trillions of tokens is, quite literally, the entire pretraining objective (lesson 06, 3.1).

Model reports and quantization comparisons often quote perplexity instead. It's the same loss turned into a more intuitive number: roughly "how many equally likely options the model was choosing between" at each token. A perplexity of 2 means the model was, on average, about as unsure as a coin flip; lower is better (lesson 06, 3.2).

5.2 Gradient descent: walking downhill#

Picture the loss as a landscape. Every possible combination of weight values is a location, and the loss is the height at that location. Good weights sit in a valley.

The foggy-mountain analogy: you're standing on a mountain in thick fog and want to reach the valley. You can't see far, but you can feel which way the ground slopes under your feet. So you take a small step downhill, feel the slope again, and repeat.

That's gradient descent:

  • The gradient is the slope: for each weight, which direction increases the loss and how steeply.
  • Each step moves every weight a little in the opposite direction (downhill): new_weight = old_weight − learning_rate × gradient.
  • The learning rate is the size of the step, and it's one of the most important hyperparameters.

Here's gradient descent on the simplest possible "mountain": a single weight w, where the loss is lowest at w = 3:

python
# The "hill": loss = (w - 3)^2. The lowest point (best weight) is w = 3.
def loss(w):
    return (w - 3) ** 2

def slope(w):            # the gradient: which way is uphill, and how steep
    return 2 * (w - 3)

for learning_rate in [0.01, 0.1, 0.95, 1.1]:
    w = 0.0              # start far from the answer
    path = [w]
    for _ in range(10):
        w = w - learning_rate * slope(w)    # step downhill
        path.append(w)
    print(f"lr={learning_rate:<4}  w after 10 steps = {w:9.3f}   loss = {loss(w):10.3f}")
    print("         path:", " → ".join(f"{p:.1f}" for p in path[:6]), "...")
Output8 lines
lr=0.01  w after 10 steps =     0.549   loss =      6.008
         path: 0.0 → 0.1 → 0.1 → 0.2 → 0.2 → 0.3 ...
lr=0.1   w after 10 steps =     2.678   loss =      0.104
         path: 0.0 → 0.6 → 1.1 → 1.5 → 1.8 → 2.0 ...
lr=0.95  w after 10 steps =     1.954   loss =      1.094
         path: 0.0 → 5.7 → 0.6 → 5.2 → 1.0 → 4.8 ...
lr=1.1   w after 10 steps =   -15.575   loss =    345.038
         path: 0.0 → 6.6 → -1.3 → 8.2 → -3.2 → 10.5 ...

Four very different outcomes from the same starting point:

Learning rate What happened
0.01 (too small) Barely moved: 0.0 → 0.549. It would take hundreds of steps to get there.
0.1 (good) Moved smoothly towards 3, reaching 2.678.
0.95 (too big) Overshoots back and forth across the valley (5.7 → 0.6 → 5.2...), zig-zagging only slowly inwards. After 10 steps it's still further from 3 (1.954) than the 0.1 run.
1.1 (far too big) Every step overshoots further. The loss explodes and training diverges.

On this perfectly smooth hill, one particular learning rate lands exactly on 3 in a single step (Exercise 2 lets you find it). Real loss landscapes have no such shortcut, so practitioners find a good learning rate by experiment, usually by trying several values on a small run.

Real training is the same idea, except the landscape has billions of dimensions (one per weight) instead of one.

5.3 Backpropagation: assigning blame#

In a network with millions of weights spread across many layers, how do we compute the gradient for every weight? An output error is caused by the output layer, which was fed by the last hidden layer, which was fed by the layer before that...

Backpropagation solves this by working backwards from the output:

  1. Compute the error at the output.
  2. Work out how much each weight in the last layer contributed to it.
  3. Pass the "blame" back to the previous layer, in proportion to how much each neuron influenced the next layer.
  4. Repeat, layer by layer, back to the input.

Mathematically this uses the chain rule from calculus, but you don't need it. Modern frameworks such as PyTorch and JAX compute gradients automatically (autograd). You define the forward pass, and the framework handles backpropagation for you.

One full training step is therefore: forward pass → loss → backward pass (backpropagation) → update weights.

flowchart LR
    A["1. Forward pass<br/>run a batch of examples<br/>through the network"] --> B["2. Loss<br/>compare predictions<br/>with correct answers"]
    B --> C["3. Backward pass<br/>backpropagation computes<br/>a gradient for every weight"]
    C --> D["4. Update<br/>nudge every weight<br/>a little downhill"]
    D -- "repeat with the next batch" --> A

Why depth used to be hard: vanishing and exploding gradients

There's a catch in step 3 of backpropagation. On its way back, each layer's share of the blame is multiplied by that layer's weights and by the slope of its activation function. Multiply many numbers together and the result depends heavily on whether they're below or above 1:

  • Vanishing gradients: sigmoid's slope is at most 0.25, and close to zero wherever the function is flat (2.5). Multiply by factors like that twenty times and the training signal reaching the early layers shrinks to almost nothing, so those layers barely learn.
  • Exploding gradients: if the factors are larger than 1, the signal grows at every layer instead, and the weight updates become so large that training blows up, just like the 1.1 learning rate in 5.2.

This demo builds a 20-layer network with random weights, runs one forward pass, and then measures how big the backpropagated blame is when it reaches each layer:

python
import numpy as np

def sigmoid(z):
    return 1 / (1 + np.exp(-z))

def sigmoid_slope(z):
    s = sigmoid(z)
    return s * (1 - s)              # never more than 0.25

def relu(z):
    return np.maximum(0, z)

def relu_slope(z):
    return (z > 0) * 1.0            # exactly 1 for positive inputs, 0 otherwise

def blame_per_layer(activation, slope, weight_scale, depth=20, width=64, seed=0):
    rng = np.random.default_rng(seed)
    weights = [rng.normal(scale=weight_scale / np.sqrt(width), size=(width, width))
               for _ in range(depth)]
    # Forward pass: remember each layer's weighted sums
    h, sums = rng.normal(size=width), []
    for W in weights:
        z = h @ W
        sums.append(z)
        h = activation(z)
    # Backward pass: start with a blame of 1 per output and pass it back,
    # multiplying by each layer's activation slope and weights on the way
    blame, sizes = np.ones(width), []
    for W, z in zip(reversed(weights), reversed(sums)):
        blame = (blame * slope(z)) @ W.T
        sizes.append(np.abs(blame).mean())
    return sizes[::-1]              # sizes[0] is layer 1, the first layer

sig = blame_per_layer(sigmoid, sigmoid_slope, weight_scale=1.0)
good = blame_per_layer(relu, relu_slope, weight_scale=np.sqrt(2))   # careful initialization
big = blame_per_layer(relu, relu_slope, weight_scale=2.0)           # weights a bit too large

print("Size of the training signal reaching each layer (20-layer network)")
for layer in [20, 15, 10, 5, 1]:
    i = layer - 1
    print(f"  layer {layer:>2} | sigmoid {sig[i]:7.1e} | ReLU {good[i]:7.1e} | ReLU, big weights {big[i]:7.1e}")
Output6 lines
Size of the training signal reaching each layer (20-layer network)
  layer 20 | sigmoid 1.9e-01 | ReLU 8.9e-01 | ReLU, big weights 1.3e+00
  layer 15 | sigmoid 1.2e-04 | ReLU 1.6e+00 | ReLU, big weights 1.2e+01
  layer 10 | sigmoid 1.0e-07 | ReLU 2.7e+00 | ReLU, big weights 1.2e+02
  layer  5 | sigmoid 5.4e-11 | ReLU 2.1e+00 | ReLU, big weights 5.3e+02
  layer  1 | sigmoid 1.3e-13 | ReLU 1.8e+00 | ReLU, big weights 1.9e+03
  • Sigmoid: the signal shrinks by roughly a factor of 4 or more at every layer. By layer 1 it's about a ten-trillionth of its starting size, so the first layers would learn essentially nothing. This is the vanishing gradient problem, and it's why deep networks were so hard to train before the 2010s.
  • ReLU with carefully scaled random weights: the signal stays roughly the same size all the way back, because ReLU's slope is exactly 1 wherever it's active. Every layer gets a useful training signal.
  • ReLU with weights only about 40% too large: the signal grows at every layer, reaching about 1,900 by layer 1. That's the start of exploding gradients.

Three ideas made today's very deep networks trainable:

  1. ReLU-family activations (ReLU, GELU, SiLU), whose slope stays near 1 for positive inputs.
  2. Careful weight initialization: scaling the starting random weights to the layer size (the weight_scale / np.sqrt(width) in the demo) so signals neither shrink nor grow.
  3. In transformers, residual connections and normalization. Residual connections let each layer add its result to its input instead of replacing it, which gives the gradient a direct path back through dozens of layers. Normalization keeps the numbers flowing between layers in a steady range (lesson 04, 6.3 and 6.4).

Training code also commonly uses gradient clipping, which caps the size of any single update so one bad batch can't blow training up.

What this means for you as an engineer: you won't tune these yourself, but they explain names you'll see in architecture descriptions and config files ("pre-norm", "RMSNorm", "initializer_range"), and the "loss spikes" that model developers report during training.

5.4 The training loop vocabulary#

Term Meaning
Batch / mini-batch A group of training examples processed together in one step. Gradients are averaged over the batch, which is more stable than using one example and far cheaper than using all of them.
Step / iteration One update of the weights (one batch processed).
Epoch One full pass through the entire training dataset. Small models are often trained for many epochs. LLMs see most of their pretraining data only about once, because there's so much of it.
SGD (stochastic gradient descent) Gradient descent using random mini-batches instead of the full dataset. "Stochastic" means random.
Optimizer The algorithm that turns gradients into weight updates. Plain SGD is the simplest. Adam / AdamW keep a running memory of recent gradients to take smarter, adaptive steps, and are the standard for training LLMs.
Weight initialization How weights are set before training begins: small random numbers. If every weight started equal (for example all zeros), every neuron in a layer would receive identical updates and stay identical forever, and the layer would behave like a single neuron. Randomness breaks this symmetry, and scaling the random numbers to the layer size keeps training signals from vanishing or exploding (5.3).
Convergence When the loss stops improving meaningfully: training has found its valley.

5.5 Try it: watch a neuron learn#

Let's put it all together. We give a neuron 8 examples of weekend decisions. The hidden rule is "go out only if it's sunny and friends are going", and cost is irrelevant. The neuron starts with random weights and must discover this rule on its own.

python
import numpy as np

def sigmoid(z):
    return 1 / (1 + np.exp(-z))

# Every combination of: sunny, friends going, cheap
X = np.array([
    [0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1],
    [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1],
], dtype=float)
# Hidden rule the neuron must discover: go out only if sunny AND friends going
y = np.array([0, 0, 0, 0, 0, 0, 1, 1], dtype=float)

rng = np.random.default_rng(seed=42)
weights = rng.normal(size=3)   # start with random knobs
bias = 0.0
learning_rate = 0.5

for step in range(2001):
    # 1. Predict (forward pass)
    predictions = sigmoid(X @ weights + bias)

    # 2. Measure how wrong we are (cross-entropy loss)
    loss = -np.mean(y * np.log(predictions) + (1 - y) * np.log(1 - predictions))

    # 3. Work out which direction to nudge each knob (the gradient)
    error = predictions - y
    weight_nudges = X.T @ error / len(y)
    bias_nudge = error.mean()

    # 4. Nudge the knobs a little (gradient descent)
    weights -= learning_rate * weight_nudges
    bias -= learning_rate * bias_nudge

    if step % 500 == 0:
        print(f"step {step:4d}  loss {loss:.3f}")

print("\nLearned weights (sunny, friends, cheap):", weights.round(2))
print("Learned bias:", round(bias, 2))
print("Predictions:", sigmoid(X @ weights + bias).round(2))
Output9 lines
step    0  loss 0.839
step  500  loss 0.067
step 1000  loss 0.035
step 1500  loss 0.023
step 2000  loss 0.017

Learned weights (sunny, friends, cheap): [ 7.44  7.44 -0.37]
Learned bias: -11.15
Predictions: [0.   0.   0.02 0.02 0.02 0.02 0.98 0.97]

What happened:

  • The loss dropped from 0.839 to 0.017. The neuron became steadily less wrong.
  • It discovered which inputs matter. "Sunny" and "friends" got large weights (7.44 each), while "cheap" ended up close to zero (−0.37) because it never affected the correct answer.
  • The large negative bias (−11.15) means "stay home unless both strong signals are present". One signal alone isn't enough (7.44 − 11.15 < 0), but both together are (7.44 + 7.44 − 11.15 > 0).
  • Predictions match the rule: about 98% when both are true, 2% or less otherwise.

Nobody told the neuron the rule. It learned it from examples. An LLM learns in essentially the same way, with billions of parameters, trillions of tokens of text, and thousands of GPUs instead of a laptop.

5.6 Try it: why we need hidden layers#

Some patterns are impossible for a single neuron. The classic example is XOR ("exclusive or"): the output is 1 when exactly one of two inputs is 1.

Input A Input B XOR
0 0 0
0 1 1
1 0 1
1 1 0

A single neuron can only separate outputs with a straight line. Try drawing one line that puts (0,1) and (1,0) on one side and (0,0) and (1,1) on the other: you can't. Let's prove it, and then fix it with a hidden layer:

python
import numpy as np

def sigmoid(z):
    return 1 / (1 + np.exp(-z))

def bce_loss(p, y):
    return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))

# XOR: output is 1 when exactly one input is 1
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
y = np.array([[0], [1], [1], [0]], dtype=float)
rng = np.random.default_rng(seed=0)
lr = 0.5

# --- Attempt 1: a single neuron (no hidden layer) ---
w = rng.normal(size=(2, 1))
b = np.zeros(1)
for step in range(5000):
    p = sigmoid(X @ w + b)
    err = (p - y) / len(X)
    w -= lr * X.T @ err
    b -= lr * err.sum(axis=0)
print("Single neuron")
print("  loss:", round(bce_loss(p, y), 3))
print("  predictions:", p.ravel().round(2))

# --- Attempt 2: a hidden layer of 4 neurons ---
W1 = rng.normal(size=(2, 4)); b1 = np.zeros(4)
W2 = rng.normal(size=(4, 1)); b2 = np.zeros(1)
for step in range(5000):
    # Forward pass
    h = np.tanh(X @ W1 + b1)          # hidden layer
    p = sigmoid(h @ W2 + b2)          # output layer

    # Backward pass (backpropagation): pass the blame back layer by layer
    d_out = (p - y) / len(X)
    d_hidden = (d_out @ W2.T) * (1 - h**2)   # (1 - h^2) is the slope of tanh

    # Nudge every parameter
    W2 -= lr * h.T @ d_out;    b2 -= lr * d_out.sum(axis=0)
    W1 -= lr * X.T @ d_hidden; b1 -= lr * d_hidden.sum(axis=0)
print("With a hidden layer")
print("  loss:", round(bce_loss(p, y), 3))
print("  predictions:", p.ravel().round(2))
Output6 lines
Single neuron
  loss: 0.693
  predictions: [0.5 0.5 0.5 0.5]
With a hidden layer
  loss: 0.001
  predictions: [0. 1. 1. 0.]
  • The single neuron gives up. It predicts 0.5 for everything, a pure coin flip, and its loss is stuck at 0.693, the exact cross-entropy for 50% confidence from the table in 5.1. No straight line works, so the best it can do is hedge.
  • With a hidden layer, the network solves XOR perfectly. The hidden neurons learn intermediate features (for example, something like "at least one input is on" and "both inputs are on"; the exact features vary with the random starting weights), and the output neuron combines them non-linearly. This is representation learning (3.4) in miniature.
  • Look at d_hidden: that's backpropagation, passing the output's error back through W2 to work out the hidden layer's share of the blame.

Part 6: Generalization, overfitting and memorization#

6.1 The real goal: working on unseen data#

A model that's perfect on its training examples is worthless if it fails on new ones. The ability to perform well on new, unseen data is called generalization, and it's the true goal of training.

To measure it honestly, data is split into three sets:

Set Used for Analogy
Training set Adjusting the weights Studying from the textbook
Validation set Choosing hyperparameters and deciding when to stop training Practice exams
Test set A final, honest score, used only once The real exam, with questions you've never seen

6.2 Underfitting, overfitting and memorization#

  • Underfitting: the model is too simple to capture the pattern. It's bad on training data and on new data.
  • Good fit: it captures the real pattern and does well on both.
  • Overfitting: the model is so flexible that it learns the noise and quirks of the training examples instead of the underlying pattern. Training error is excellent, but new data does worse. In the extreme, it simply memorizes the training examples.

This demo fits models with different numbers of parameters to 10 noisy points drawn from a smooth curve, then tests them on 100 points they've never seen:

python
import numpy as np

rng = np.random.default_rng(seed=1)

def true_pattern(x):
    return np.sin(x)

# 10 noisy training points, and 100 unseen test points
x_train = np.linspace(0, 6, 10)
y_train = true_pattern(x_train) + rng.normal(scale=0.2, size=10)
x_test = np.linspace(0, 6, 100)
y_test = true_pattern(x_test)

for degree in [1, 3, 9]:
    coeffs = np.polyfit(x_train, y_train, degree)   # "train" a model with degree+1 parameters
    train_err = np.mean((np.polyval(coeffs, x_train) - y_train) ** 2)
    test_err = np.mean((np.polyval(coeffs, x_test) - y_test) ** 2)
    print(f"{degree + 1:>2} parameters | training error {train_err:.3f} | test error {test_err:.3f}")
Output3 lines
 2 parameters | training error 0.224 | test error 0.197
 4 parameters | training error 0.016 | test error 0.009
10 parameters | training error 0.000 | test error 0.079
Parameters Diagnosis
2 Underfitting. A straight line can't follow a wave, so it's bad everywhere.
4 Good fit. Low error on both training data and new data.
10 Overfitting / memorization. With 10 parameters for 10 points, it passes through every training point exactly (training error 0.000), including the noise. On new data it's almost 9× worse than the 4-parameter model.

6.3 Fighting overfitting#

Common techniques, worth recognizing by name:

  • More (and more varied) data: the most effective fix of all.
  • Early stopping: stop training when validation error starts rising, even if training error is still falling.
  • Weight decay (regularization): penalize large weights, nudging the model towards simpler solutions. The "W" in AdamW stands for this.
  • Dropout: randomly switch off some neurons during training, so the network can't rely too heavily on any single one. (Many modern LLMs are pretrained with little or no dropout, relying on data volume and weight decay instead; Llama 3.1's config, for example, sets "attention_dropout": 0.0.)

6.4 Why this matters for LLMs#

Why don't giant models overfit? The demo in 6.2 suggests that more parameters means more overfitting, yet LLMs have billions of parameters. Two things change at this scale:

  • There's far more data than the model can memorize. LLMs are pretrained on trillions of tokens, mostly seen only once (5.4). Text the model sees only once has little chance of being memorized, so during pretraining LLMs usually underfit rather than overfit: their loss on new text is about the same as on training text. (Text that's repeated many times across the internet is the exception, as the next list shows.)
  • Very large neural networks often generalize better as they grow, even past the size at which they could memorize their whole training set. Researchers call this surprising effect double descent: as model size increases, test error first falls, then rises (the classic overfitting picture from 6.2), then falls again. The simple "U-shaped" picture from small models doesn't carry over directly.

Overfitting becomes your problem when you fine-tune a model on a small dataset (a few thousand examples) for several epochs. Then the classic rules apply: hold out a validation set, watch validation loss, and stop early when it starts rising (7.4, Module 13A).

The other consequences for LLMs:

  • LLMs generalize remarkably well. They handle prompts nobody has ever written before, which is only possible because they learned general patterns rather than memorizing text.
  • But they also memorize some training data, especially text that appeared many times (famous quotes, popular code, licence texts). They can sometimes reproduce it word for word, which raises copyright and privacy concerns (lesson 10, 2.8, Module 12).
  • Benchmark contamination: if a benchmark's questions leaked into the training data, the model's high score may reflect memorization, not ability. This is the training/test split rule being broken at internet scale, and it's why you should evaluate models on your own data (lesson 06, 14.5, lesson 09, Module 10A).
  • Hallucination is closely related. The model learned to produce plausible-sounding text, which is usually but not always true text (lesson 10, Part 2).

Part 7: Training vs inference#

7.1 Two very different phases#

Training Inference
What happens Weights are adjusted to learn from data (forward pass + backward pass + update) Weights are frozen and used only to compute outputs (forward pass only)
Who does it The model provider (OpenAI, Anthropic, Google, Meta, ...) You, every time you call the API or run a local model
Cost Enormous: weeks to months on thousands of GPUs Small per request; you pay per token
How often Once per model version Millions of times a day

7.2 The model does not learn from your conversations#

This is the single most important practical takeaway in this lesson:

When you chat with an LLM, its weights do not change. The model is frozen. It does not learn from your conversation, your corrections or your feedback during that conversation.

If a chatbot seems to "remember" what you said earlier in a chat, that's because the whole conversation is sent to the model again with every request. Usually your application does this; sometimes a provider feature stores the history for you and re-sends it behind the scenes (and still bills it as input on every turn). Either way, the model reads it all again from scratch each time. This is called being stateless. Start a new conversation and the model knows nothing about the old one. You'll see this first-hand in lesson 07, 3.1, and what provider-side conversation storage really does in 3.5.

Consequences for you as an engineer:

  • "Memory" features are application code, not model features. Assistant products that "remember you" store information separately and add it to future prompts (Module 08B).
  • Data sent to an API isn't automatically absorbed into the model's weights. Whether a provider may use your data to train future models depends on their data policy and your account settings. Check this for every provider you use, especially with customer data (Module 12).

7.3 Knowledge cutoff#

Because the model only knows what was in its training data, collected up to some date, it has a knowledge cutoff. Ask about events after it and the model either says it doesn't know or, worse, makes something up. To give a model current or private information, you put it into the prompt at request time, which is the core idea behind RAG (Module 07) and tool use (Module 08A).

Three details catch engineers out: the cutoff is usually months before the model's release date, models often can't state their own cutoff reliably, and they don't know today's date unless you tell them, for example in the system prompt (the instructions your application sends before the user's message; see lesson 02, 4.3) (lesson 06, 11.5, lesson 10, 3.1).

7.4 Changing what a model does: context vs weights#

There are only two ways to change an LLM's behaviour:

Approach What changes Examples Cost and speed
Change the input (context) Nothing in the model; you change what you send Better prompts (Module 04), adding documents (RAG, Module 07), tools (Module 08A) Cheap, instant, easy to iterate
Change the weights The model's parameters, through more training Fine-tuning Expensive, slow to iterate, needs data and expertise

For the vast majority of applied AI work, you change the context, not the weights. This learning path focuses there. Lesson 06, 13.2 previews the choice between prompting, RAG and fine-tuning, and Module 13A has a decision guide for the rare cases where fine-tuning is worth it.

7.5 Is a neural network deterministic?#

The network itself is a fixed mathematical function: same weights + same input → same output probabilities. So why do LLMs give different answers to the same prompt?

  • Sampling: the model outputs probabilities, and the next token is usually randomly chosen from them. That's controlled by settings such as temperature (lesson 05), where the provider exposes them; most current frontier models fix these settings and either reject or ignore attempts to change them (lesson 05, 6.1).
  • Tiny numerical differences: on GPUs, computation order can vary (for example depending on which other requests are batched with yours), causing minuscule rounding differences that occasionally flip which token is chosen. In MoE models such a difference can also send a token to a different expert. This is why even "temperature 0" isn't always perfectly reproducible through provider APIs (lesson 05, Part 7).

Part 8: A short history, and why transformers won#

Deep-dive

8.1 Timeline#

Year Milestone Why it mattered
1943 Artificial neuron (Warren McCulloch & Walter Pitts) The first mathematical model of a neuron
1958 Perceptron (Frank Rosenblatt) The first trainable artificial neuron
1969 Perceptrons book (Minsky & Papert) Showed single-layer limits (XOR) and contributed to the first "AI winter"
1986 Backpropagation popularized (Rumelhart, Hinton, Williams) Made multi-layer networks trainable
1997 LSTM (Hochreiter & Schmidhuber) Networks that could handle sequences such as text and speech better
2012 AlexNet wins the ImageNet competition A deep network trained on GPUs crushed traditional methods and started the deep learning boom
2017 Transformer ("Attention Is All You Need", Google) The architecture behind almost every modern LLM (lesson 04)
2018–2020 GPT-1, GPT-2, GPT-3 Showed that scaling up transformers trained on next-token prediction produces surprisingly general abilities
2022 ChatGPT Instruction tuning and RLHF turned raw LLMs into helpful assistants, and the public took notice
2023–now GPT-4/5, Claude, Gemini, Llama, Qwen, DeepSeek, Kimi... Rapid progress in capability, multimodality and efficiency; open-weight mixture-of-experts models pass a trillion parameters (lesson 09)
2024–2025 Reasoning models (OpenAI o1, DeepSeek-R1) Reinforcement learning taught models to "think" at length before answering (lesson 06, 8.3, lesson 08)

The recipe that unlocked modern AI wasn't one invention. It was old ideas (neurons, backpropagation) combined with massive data (the internet), massive compute (GPUs), and the right architecture (the transformer).

8.2 Families of neural networks#

Architecture Built for How it works (in one line) Status
MLP / feedforward Fixed-size inputs (tabular data) Dense layers, data flows straight through A building block inside every transformer
CNN (convolutional) Images Small filters slide across the image to detect local patterns Still used in vision, often alongside transformers
RNN / LSTM (recurrent) Sequences (text, audio) Reads one item at a time, carrying a "memory" forward Largely replaced by transformers for language; recurrent-style ideas are returning inside hybrid models
Transformer Sequences, and eventually almost everything Every token can directly "look at" every other token via attention The foundation of nearly all modern LLMs, and many vision and audio models

Why transformers beat RNNs for language:

  • Parallelism: an RNN must read word 1 before word 2 before word 3, which is slow and makes poor use of GPUs. A transformer processes all tokens of the training text at the same time, so it can be trained on vastly more data.
  • Long-range connections: in an RNN, information from early words must survive being passed through every step in between, and it fades. In a transformer, any token can attend directly to any other, however far apart.

The trade-off: a transformer's memory and compute per token grow with the length of the context (that's the KV cache from 4.4), while an RNN carries a fixed-size state, so its cost per token stays constant however long the input gets. That's why some newer models are hybrids that mix attention layers with recurrent-style layers such as state-space models (Mamba) or linear attention. Attention-based transformers still dominate frontier LLMs, but hybrids are a growing family (lesson 04, 12.5).

You'll see exactly how attention works in lesson 04.


Part 9: The black box problem#

Deep-dive

We understand the mechanics of neural networks completely: every operation is just multiplying, adding and activating, and we can inspect every single weight. Yet for large models, we can't easily explain why a specific output was produced. The "reasoning" is spread across billions of numbers, with concepts distributed and overlapping across neurons (3.4).

A research field called interpretability (including mechanistic interpretability) works on reverse-engineering what's happening inside models, for example finding internal features that correspond to specific concepts. It's making real progress, but it doesn't yet let us fully predict or explain model behaviour.

What this means for you as an engineer:

  • You can't reason about an LLM's behaviour by reading its internals. You have to test its behaviour empirically, which is why evaluation (Module 10A) is the core discipline of AI engineering.
  • Asking the model why it answered doesn't open the box either. Its explanation is newly generated text, often plausible but not a guaranteed account of the computation that actually produced the answer (lesson 10, 6.5).
  • Small input changes can cause surprising output changes, so treat prompts as code: version them and test them (Module 04).
  • Plan for failure modes (wrong answers, ignored instructions) with validation, guardrails and human review (Module 12), rather than assuming the model will always behave.

Part 10: From a toy neuron to an LLM#

Our toy neuron (5.5) A modern LLM
Input 3 numbers (sunny, friends, cheap) Text, converted to tokens (02) and then to embedding vectors (03)
Building block Multiply, add, activate The same: multiply, add, activate, inside MLP blocks and attention
Architecture 1 neuron A transformer with dozens to over a hundred layers (04)
Output 1 probability (sigmoid) A probability for every token in the vocabulary (softmax) (05)
Parameters 4 Hundreds of millions to trillions (total, for the largest MoE models)
Training data 8 examples Trillions of tokens of text, plus curated conversations (06)
Loss Cross-entropy Cross-entropy on the next token, plus extra training stages such as RLHF (06)
Training method Gradient descent on a laptop, in a second Gradient descent with AdamW on thousands of GPUs, over weeks to months
At inference Weights frozen Weights frozen; one forward pass per generated token

At its core, an LLM is a neural network trained to answer one question extremely well: "Given this text, what token comes next?" Everything else you'll build in this path, including chat, RAG, agents, coding assistants and voice apps, sits on top of that single capability.


Common misconceptions#

Misconception Reality
"Neural networks work like the human brain." They're loosely inspired by neurons but are essentially large mathematical functions. They don't work like brains.
"The model stores a database of facts it looks up." There's no database inside. Knowledge is encoded implicitly and approximately across billions of weights, which is why recall can be fuzzy or wrong (lesson 10).
"The model learns from my conversations." Weights are frozen during inference. Apparent memory is the conversation being re-sent with every request, by your app or by a provider feature. Future model versions may be trained on data depending on the provider's policy, but not in real time.
"More parameters always means a better model." Data, training techniques and architecture matter as much. Newer small models often beat older large ones, and MoE models complicate size comparisons.
"With billions of parameters, LLMs must just be memorizing their training data." They see trillions of tokens, mostly once, and very large networks often generalize better as they grow (double descent). They do memorize some frequently repeated text, but overfitting is mainly a risk when you fine-tune on a small dataset.
"Each MoE expert specializes in a topic, such as maths or French." Routing is learned per token and per layer, and experts rarely match human subjects.
"If the weights fit in GPU memory, the model will run." The KV cache and activations need memory too, and at long contexts or with many users the KV cache can exceed the weights.
"A 4-bit model takes exactly parameters × 0.5 bytes." Quantized files also store scale factors and keep some layers at higher precision: about 4.9 bits per weight for llama.cpp's Q4_K_M.
"Downloading a model file is as safe as downloading data." Pickle-based files (.bin, .pt) and trust_remote_code=True can run arbitrary code. Prefer safetensors and trusted sources.
"Someone programmed the model's rules and behaviours." Behaviours emerge from training on data. Developers shape them through data and training techniques, not by writing rules.
"Engineers can open the model and see why it gave an answer." Mechanics are transparent, reasoning isn't. Interpretability is still an active research area.
"Open weights means open source." Usually the weights only, without training data or code, and licences vary. Read them.
"Temperature 0 means perfectly reproducible output." Usually close, but numerical effects on GPUs mean exact reproducibility isn't guaranteed through most APIs.

Key takeaways#

  • Machine learning learns rules from examples. LLMs mainly use self-supervised learning: predicting the next token in vast amounts of text.
  • A neuron multiplies inputs by weights, adds a bias, and applies a non-linear activation function. Without non-linearity, deep networks would collapse into a single linear layer.
  • Neurons form layers, and layers form networks. Each layer is a matrix multiplication, which is why GPUs dominate AI.
  • Deep networks learn their own features (representation learning), with concepts distributed across many neurons.
  • Softmax turns raw logits into probabilities. An LLM's output is a probability for every token in its vocabulary.
  • Parameters (weights and biases) are everything a model knows. Memory for weights ≈ parameters × bytes per parameter. Quantization reduces bytes per parameter at a small cost in quality; real 4-bit files are a little larger (about 4.9 bits per weight for Q4_K_M), and hosts may quantize models you call through an API.
  • Weights aren't the only memory cost. The KV cache grows with context length and with the number of users, and at long contexts it can exceed the weights.
  • MoE models replace each layer's MLP with many experts and use only a few per token: compute follows active parameters, memory follows total. Experts aren't topic specialists.
  • Prefer safetensors files. Pickle-based weights and trust_remote_code can run arbitrary code.
  • Training = forward pass → loss (cross-entropy for LLMs) → backpropagation → gradient descent update, repeated in batches with optimizers like AdamW. The learning rate must be neither too small nor too big.
  • Backpropagation multiplies the training signal by every layer's slope and weights, so in deep networks it can vanish or explode. ReLU-family activations, careful initialization, residual connections and normalization are what make deep networks trainable.
  • The goal is generalization. Perfect training scores can mean overfitting or memorization, so always evaluate on unseen data. Giant LLMs rarely overfit during pretraining, but your own small fine-tuning runs can.
  • During inference the weights are frozen. Models are stateless, don't learn from your conversations, have a knowledge cutoff, and are changed in practice by changing the context (prompts, RAG, tools), rarely by changing the weights. When weights do change, it's usually through small LoRA adapters rather than full fine-tuning.
  • Neural networks are black boxes in practice, so AI engineering relies on empirical evaluation.

Terms introduced in this lesson#

Term One-line definition
Model The learned parameters plus the code that uses them
Self-supervised learning Learning where the answers come from the data itself (for example the next word)
Vector A list of numbers
Neuron Multiply inputs by weights, add a bias, apply an activation
Weight A learned number expressing how much an input matters
Bias A learned number shifting a neuron's threshold (left out of most layers in many modern LLMs)
Weighted sum The total of each input times its weight, plus the bias, before the activation
Dot product Multiply matching items of two lists of numbers and add the results
Activation function A non-linear function applied to a neuron's weighted sum (ReLU, GELU, SiLU, sigmoid...)
SiLU / Swish A smooth ReLU-like activation (the input times its own sigmoid), used inside SwiGLU
SwiGLU A gated MLP design used by most modern LLMs, with two paths, one passed through SiLU, multiplied together
Layer / dense layer A group of neurons; dense means fully connected to the previous layer
Hidden layer A layer between the input and the output, whose values you never see directly
MLP / feedforward network A network of dense layers, with data flowing in one direction
Forward pass Running inputs through the network to get outputs
Matrix / matrix multiplication A grid of numbers; multiplying by one computes a whole layer's weighted sums at once
Tensor A grid of numbers with any number of dimensions (a vector has 1, a matrix 2); how frameworks and model files store weights
Representation learning A network discovering its own useful internal features during training
Distributed representation / superposition Concepts stored as patterns across many neurons, with more concepts than neurons packed in by overlapping
Universal approximation theorem The result that a large enough network can approximate almost any continuous function
Regression / classification Predicting a number / picking one of a set of categories
Logits Raw output scores before conversion to probabilities
Softmax Converts logits into probabilities that sum to 1
Parameters All weights and biases
Hyperparameters Human-chosen settings for architecture and training
Precision (FP32, BF16, FP8, INT8, INT4, FP4) How many bits are used to store each number
FP4 (MXFP4, NVFP4) 4-bit floating-point formats where each small block of numbers shares a scale factor
Quantization Storing parameters at lower precision to save memory
Post-training quantization / quantization-aware training Quantizing a finished model / training the model to cope with low precision from the start
KV cache The model's stored working memory of the conversation so far; it grows with context length and users (lesson 04)
Mixture-of-experts (MoE) An architecture where each layer's MLP is split into many experts and only a few are used per token
Expert / router / shared expert One of the smaller MLPs in an MoE layer / the small network that picks experts for each token / an expert every token uses
Total vs active parameters All parameters in an MoE model (decides memory) vs those used per token (decides compute)
Open weights Published model parameters you can download and run
Chat template / generation config Files shipped with a model: how to format a conversation, and the default generation settings
safetensors / pickle A weight format that holds only numbers / Python's format, which can run code when loaded
Loss / loss function A number measuring how wrong the predictions are
Cross-entropy The loss for classification, and for LLM next-token prediction
Perplexity Cross-entropy loss turned into "how many options the model was choosing between" (lesson 06)
Gradient The direction and steepness of the loss for each weight
Gradient descent Repeatedly nudging weights downhill to reduce loss
Learning rate The size of each gradient descent step
Learning rate schedule (warmup, decay) Changing the learning rate during training: ramp it up first, then shrink it
Backpropagation Computing gradients by passing blame backwards through the layers
Autograd Framework feature (PyTorch, JAX) that computes gradients automatically
Vanishing / exploding gradients Training signals shrinking towards zero / growing out of control as they pass back through many layers
Gradient clipping Capping the size of an update so one bad batch can't blow training up
Batch, step, epoch A group of examples; one weight update; one pass through all the data
Optimizer (SGD, Adam, AdamW) The algorithm that turns gradients into weight updates
Weight initialization Setting the starting weights to small, carefully scaled random numbers
Convergence The point at which the loss stops improving meaningfully
Logistic regression A single neuron with a sigmoid output trained with cross-entropy
Generalization Performing well on new, unseen data
Overfitting / memorization Learning the training examples' noise instead of the real pattern
Underfitting Being too simple to capture the pattern, so performance is poor everywhere
Training / validation / test set Data for learning; for tuning; for a final honest score
Early stopping, weight decay, dropout Ways to fight overfitting: stop when validation loss rises, penalize large weights, randomly switch off neurons
Double descent Test error falling, rising, then falling again as models grow, so very large networks can generalize better
Benchmark contamination Benchmark questions leaking into training data, inflating scores
Inference Using a trained model with frozen weights to produce outputs
Generation settings (inference settings) Request settings such as temperature and max_tokens that control how output is generated, not training
Stateless The model keeps nothing between requests; the conversation is re-sent each time (lesson 07)
Knowledge cutoff The date after which the model has no, or only thin, training data
Fine-tuning Further training an existing model on your own data, changing its weights
PEFT / LoRA / QLoRA Fine-tuning only small added matrices (an adapter) instead of every weight / the most common such method / LoRA on a 4-bit base model
Hybrid model A model mixing attention layers with recurrent-style layers (lesson 04)
Interpretability Research into understanding what happens inside a model

All terms are also collected in the glossary.


Exercises#

Run the code from this lesson and experiment:

  1. Single neuron (2.3): find weights and a bias where the neuron says "go out" (above 50%) only when it's cheap, regardless of anything else.
  2. Learning rate (5.2): try learning_rate = 0.5 and 1.0. Before running, predict what will happen. Then explain the result using the foggy-mountain analogy.
  3. Training (5.5): change the hidden rule to "go out if sunny or friends are going". Retrain and inspect the learned weights and bias. How did the bias change, and why?
  4. XOR (5.6): reduce the hidden layer to 1 neuron, then 2. Does the network still solve XOR? Try several seeds.
  5. XOR (5.6): replace np.tanh with no activation at all (h = X @ W1 + b1, and change (1 - h**2) to 1). What happens to the loss, and which idea from 2.5 does this demonstrate?
  6. Overfitting (6.2): increase the training points from 10 to 50. What happens to the 10-parameter model's test error, and why?
  7. Memory (4.4): a colleague wants to run a 32B model on a laptop with a 24 GB GPU. Which precisions could fit the weights, and what other memory needs must they consider? Then redo the 4-bit estimate using 4.9 bits per weight for Q4_K_M, and work out roughly how much memory is left for the KV cache and everything else.
  8. Vanishing gradients (5.3): in the 20-layer demo, change the ReLU network's weight_scale from np.sqrt(2) to 1.0. What happens to the signal reaching layer 1, and what does that tell you about weight initialization? Then try depth=5 for the sigmoid network. Why were shallow networks trainable with sigmoid when deep ones weren't?
  9. MoE (4.6): for a model named Qwen3.6-35B-A3B, estimate the memory for its weights at BF16 and at Q4_K_M, and the arithmetic per generated token using the rule in 7.1. Which of the two numbers would a dense 35B model change?
Hints and what you should see
  1. Put zero weight on "sunny" and "friends" and a positive weight on "cheap", with a negative bias that only the "cheap" weight can overcome. For example weights [0.0, 0.0, 4.0] and bias -2.0: cheap gives z = 2.0 (88%), not cheap gives z = -2.0 (12%).
  2. With the slope 2 * (w - 3), a rate of 0.5 gives w - 0.5 * 2 * (w - 3) = 3: it lands exactly on the answer in one step and stays there. A rate of 1.0 gives 6 - w, so w bounces between 0 and 6 forever and the loss stays at 9: every step overshoots the valley floor by exactly as much as it started away from it. In the fog analogy, the step is so long that you stride across the whole valley each time.
  3. The rule becomes y = [0, 0, 1, 1, 1, 1, 1, 1] (the row order of X is sunny, friends, cheap, counting in binary). "Sunny" and "friends" both get a large positive weight and "cheap" stays near zero. The bias is still negative but much smaller in size than before: it only has to hold the output down when neither signal is present, so each signal alone can push the neuron over the line. In a pure-Python rerun of this exercise the weights ended near 8.7 and the bias near -3.8, compared with 7.4 and -11.2 for the AND rule. Your exact values depend on the seed.
  4. One hidden neuron never solves XOR (the loss stays far above 0.001, about 0.48 in a pure-Python rerun): a single tanh of one straight-line combination is still a straight-line boundary for the output. Two hidden neurons can solve it, but whether they do depends on the starting weights: some seeds converge to a loss near 0.001, others get stuck around 0.35 with a prediction of 0.5 for one input. Four neurons solved it for every seed we tried, which is why the lesson uses four.
  5. The loss goes back to 0.693 and every prediction is 0.5, exactly as with the single neuron. Without a non-linear activation, the hidden layer and the output layer collapse into one linear layer (2.5), and no straight line separates XOR.
  6. The 10-parameter model's test error drops to about the same level as the 4-parameter model's (for example 0.007 against 0.006 in a pure-Python rerun with 50 points). With 50 points and only 10 parameters the curve can no longer pass through every noisy point, so it has to follow the real pattern. Overfitting depends on the ratio of parameters to data, not on the parameter count alone.
  7. Weights alone: BF16 needs 64 GB and INT8 needs 32 GB, so neither fits. 4-bit at 0.5 bytes per parameter is 16 GB, which fits. At 4.9 bits per weight, Q4_K_M is 32 × 4.9 ÷ 8 ≈ 19.6 GB, leaving about 4.4 GB for the KV cache, activations, the GPU runtime's own overhead and anything else on that GPU, which is tight for long contexts. Quantize the KV cache, shorten the context, or choose a smaller model.
  8. With weight_scale = 1.0 the ReLU signal shrinks by about 0.7 at every layer (half the neurons are switched off, so about half of the signal's energy is lost), and the signal reaching layer 1 is roughly a thousand times smaller than at layer 20 (about 1e-3 in a pure-Python rerun, against about 1 for np.sqrt(2)). The scale is chosen so that, on average, each layer preserves the signal: initialization matters more as networks get deeper. At depth=5 the sigmoid signal still shrinks by a factor of 4 or more per layer, but only four layers' worth (about 100 to 1,000 times in total), which is small but trainable. At depth 20 the same factor compounds to roughly 10 trillion times (the 1.3e-13 in the table). Shrinking is exponential in depth.
  9. BF16: 35 × 2 = 70 GB. Q4_K_M: 35 × 4.9 ÷ 8 ≈ 21.4 GB. Arithmetic per token: about 2 × 3 billion = 6 billion operations (using the active parameters). A dense 35B model would have the same memory (all 35B parameters must be loaded either way) but need about 70 billion operations per token, so the compute number changes and the memory number doesn't.

Check yourself#

  1. What's the difference between traditional programming and machine learning?
  2. Why is LLM pretraining called self-supervised?
  3. What three steps does a single neuron perform?
  4. Why does a deep network need non-linear activation functions?
  5. A dense layer has 512 inputs and 1,024 neurons. How many parameters does it have?
  6. Why are GPUs so important for neural networks?
  7. What does softmax do, and where does an LLM use it?
  8. Approximately how much memory do the weights of a 13B model need at BF16? At INT4?
  9. An MoE model has 120B total and 12B active parameters. Which number mainly determines its memory needs, and which mainly determines its compute per token?
  10. What happens if the learning rate is too high? Too low?
  11. In the XOR experiment, why was the single neuron's loss stuck at exactly 0.693?
  12. A model scores 100% on its training data but poorly on new data. What's happening, and how would you detect it?
  13. A user tells your chatbot their name, and in a brand-new conversation the bot doesn't know it. Why?
  14. Your product needs the model to know about your company's latest pricing. Should you change the context or the weights? Why?
  15. Why is an 8B model's Q4_K_M file about 4.9 GB rather than the 4 GB that "parameters × 0.5 bytes" suggests?
  16. Why did sigmoid fall out of favour in the hidden layers of deep networks, and what made deep networks trainable?
  17. An 8B model's BF16 weights (16 GB) fit comfortably on a 48 GB GPU, but the server runs out of memory when ten users each send long documents. Why?
  18. Why should you prefer .safetensors weight files over pytorch_model.bin?

Further resources#

  • 3Blue1Brown, "Neural Networks" (YouTube series): the best visual explanation of neurons, gradient descent and backpropagation.
  • TensorFlow Playground: train small networks in your browser and watch them learn. Try XOR.
  • Andrej Karpathy, "Neural Networks: Zero to Hero" (YouTube course): build backpropagation and then a small GPT from scratch, for readers who want to go deeper.
  • Michael Nielsen, Neural Networks and Deep Learning (free online book): a gentle, thorough text. Chapter 5 explains why deep networks are hard to train (vanishing gradients).
  • Hu et al., LoRA: Low-Rank Adaptation of Large Language Models (2021, arXiv:2106.09685): the paper behind most of today's fine-tuning.
  • Hugging Face, "Pickle scanning" (Hub documentation): why pickle-based weight files are risky, and what safetensors fixes.

← Module 01C: Concurrency, Parallelism and Python Internals | Module 02 overview | 02.2 — Tokens and Tokenization →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close