---
title: "AI Research archive"
description: "Learn AI research in order: math, PyTorch, attention, RL for LLM reasoning, Llama 4 from scratch, fine-tuning and MLOps. Start with the free lessons."
canonical_url: "https://fanout.sh/ai/overview"
md_url: "https://fanout.sh/ai/overview.md"
last_updated: "2026-10-30"
access: "public"
---

# AI Research archive

Learn AI research in order: math, PyTorch, attention, RL for LLM reasoning, Llama 4 from scratch, fine-tuning and MLOps. Start with the free lessons.

## Math Fundamentals

The mathematical foundations you need for AI research — from functions and derivatives to information theory and SVD.

### Functions

Video: https://fanout.sh/ai/lessons/math-fundamentals-functions

Give a rule the number 2. It doubles the number, adds 1, and returns 5. Give it 3 and it returns 7.

That rule is a **function**: for each allowed input, it gives one output. The letter f is just a name for our rule.

```math
f(x) = 2x + 1
```

Read f(x) as “the output of f when its input is x.” It does not mean f multiplied by x. The expression 2x does mean 2 multiplied by x.

Before moving the input below, predict the output for x = −1.

```experiment
function-machine
```

The answer is −1: double −1 to get −2, then add 1. Negative inputs follow exactly the same rule.

## Inputs can share an output

Try a different rule: g(x) = x². Both 2 and −2 produce 4. This is still a function. Each input has one answer; different inputs are allowed to have the same answer.

**Predict:** Could “take x and return either x + 1 or x − 1, without specifying which” define an ordinary function of x alone?

```answer
No. For x = 2 it leaves two possible outputs, 3 and 1, without choosing one. The rule needs more information. For example, an extra input could choose which operation to use.
```

We also need to say which inputs are allowed. The rule 1/x works for real numbers except zero. That allowed collection is the **domain**.

## A small model is also a function

Our first rule can be written as f(x) = wx + b. Here w and b are numbers we choose, called **parameters**. With w = 2 and b = 1, it is exactly the rule above. Learning will mean adjusting parameters using examples. For now, keep them fixed.

If you know a little Python, this is the same calculation:

```python
def predict(x, w=2, b=1):
    return w * x + b

print(predict(3))
print(predict(3, w=4))
```

The outputs are 7 and 13. The input stayed at 3; changing a parameter changed the rule.

A straight-line rule with an added offset, such as 2x + 1, is called **affine** in linear algebra. A linear map has no offset: 2x is an example. You may hear both called “linear functions” in introductory algebra.

Neural networks compose many functions. Some bend the relationship rather than drawing a straight line: x² is one example. The useful question is still what output a particular input produces.

**Try on a graph:** Open the free [Desmos calculator](https://www.desmos.com/calculator). Enter `y = 2x + 1` and `y = x^2`. Inspect x = −2 and x = 2. Which rule gives the same output at both inputs?

If the Python syntax is unfamiliar, the [Python tutorial’s section on defining functions](https://docs.python.org/3/tutorial/controlflow.html#defining-functions) explains `def` and `return`.

#### Quick notes

- A function assigns one output to each allowed input. Different inputs can share an output.
- In f(x) = 2x + 1, f(x) means the output at input x. At x = 3, the output is 7.
- The domain is the set of allowed inputs. For 1/x over real numbers, exclude zero.
- In wx + b, w and b are parameters. Changing them changes the rule.
- In linear algebra, wx + b is affine; with b = 0 it is linear.

### Derivatives

Video: https://fanout.sh/ai/lessons/math-fundamentals-derivatives

Take the rule f(x) = 2x + 1: double the input, then add 1. Increasing x from 3 to 4 changes the output from 7 to 9. Wherever we start, adding 1 to the input adds 2 to the output.

For g(x) = x², the rate depends on where you start. Around x = 3, a small change in x produces roughly six times that change in the output. Let's inspect the numbers.

| Input change | Output change | Output change ÷ input change |
| --- | --- | --- |
| 3 → 3.1 | 9 → 9.61, a change of 0.61 | 6.1 |
| 3 → 3.01 | 9 → 9.0601, a change of 0.0601 | 6.01 |
| 3 → 3.001 | 9 → 9.006001, a change of 0.006001 | 6.001 |

These ratios approach 6. That limiting local rate is the **derivative** at x = 3. We write it as g′(3) = 6. The prime mark means “derivative.”

## Use the rate before memorizing rules

If x moves from 3 to 3.02, the derivative predicts an output change of approximately 6 × 0.02 = 0.12. The exact change is 3.02² − 3² = 0.1204. Close, but not identical: the curve's slope changes as we move.

```math
g(x + h) - g(x) \approx g'(x)\,h
```

Here h is a small input change. The derivative is the rate; multiplying by h estimates the output change. This approximation applies where the function is differentiable, and becomes useful over a sufficiently small step.

**Try predicting:** At x = −2, the derivative of x² is −4. If x increases to −1.99, should the output increase or decrease? Estimate the change.

```answer
It should decrease. The input change is +0.01, so the estimated output change is −4 × 0.01 = −0.04. The exact change is (−1.99)² − (−2)² = −0.0399.

A negative derivative means increasing the input locally decreases the output. It does not mean the output itself is negative.
```

## Where the 6 came from

For x², compare the outputs at x and x + h, then divide by the nonzero input change:

```math
\frac{(x+h)^2-x^2}{h}
=\frac{2xh+h^2}{h}
=2x+h
```

As h approaches zero, this tends to 2x. So g′(x) = 2x, which gives 6 at x = 3 and −4 at x = −2. The numbers in the table were approaching this exact result.

**See the local line:** In [Desmos](https://www.desmos.com/calculator), enter `y=x^2` and `y=9+6(x-3)`. Zoom near (3, 9), then zoom out. The line follows the curve nearby, but drifts away farther from 3. This is why a local rate cannot promise the effect of a large change.

#### Quick notes

- A derivative is a local rate of change. It is not the output change itself.
- For g(x) = x², g′(x) = 2x. At x = 3 the rate is 6.
- For a small input change h, estimate the output change with g′(x) × h.
- A negative derivative means the output locally decreases as the input increases.
- A local rate does not guarantee an accurate prediction for a large step.

### Vectors

Video: https://fanout.sh/ai/lessons/math-fundamentals-vectors

Suppose a tiny model describes a study session with two numbers: hours spent reading and exercises attempted. One session might be [2, 3]. The order matters: [3, 2] describes a different session.

This ordered collection is a **vector**. We'll call it x. In this example x₁ = 2 and x₂ = 3; the subscripts select entries. These are chosen teaching numbers, not a claim about how learning should be scored.

## Give the entries different weights

Choose a second vector w = [4, 1]. Multiply corresponding entries and add the products:

```math
w \cdot x = 4\times2 + 1\times3 = 11
```

The dot symbol names the **dot product**. Each weight says how strongly its input contributes to this particular score.

**Predict:** Keep w fixed. Which change adds more to the score: one more reading hour, or one more attempted exercise?

```answer
One reading hour adds 4. One attempted exercise adds 1. The weights tell us the difference directly.
```

We can calculate the score without a special library:

```python
x = [2, 3]
w = [4, 1]
score = sum(weight * value for weight, value in zip(w, x))
print(score)  # 11
```

Both lists have two entries here. In general, check equal lengths: Python's `zip` stops at the shorter list, which could silently leave out an input.

## Change the whole vector

Adding [1, 2] to x means adding corresponding entries: [2 + 1, 3 + 2] = [3, 5]. Multiplying x by the scalar 2 scales every entry, producing [4, 6]. A **scalar** is a single number.

Now double x but keep w fixed. Predict the new score before expanding the dot product.

```answer
The score doubles to 22, because 4 × 4 + 1 × 6 = 22. Each contribution doubled, so their sum doubled too.
```

If you draw [2, 3] as an arrow from (0, 0) to (2, 3), its ordinary Euclidean length is √(2² + 3²) = √13. This is its **norm**, written ‖x‖. In our study-session data, however, hours and counts have different units. A geometric length is a calculation we chose, not automatically a meaningful measure of effort.

**Optional visual:** In [Desmos](https://www.desmos.com/calculator), enter `(2t,3t)`. Keep the displayed t range from 0 to 1. Then enter `(4t,6t)` with the same range. Both segments follow the same direction; one is twice as long.

For the conventional notation you will see in papers, read the vector examples in [Deep Learning, §2.1](https://www.deeplearningbook.org/contents/linear_algebra.html). Notice that vectors are often printed as columns. The entries and their order remain the same.

#### Quick notes

- A vector is an ordered collection of numbers. Entry order matters.
- Add vectors entry by entry; multiply by a scalar by scaling every entry.
- A dot product multiplies matching entries and adds: [4, 1] · [2, 3] = 11.
- The Euclidean norm of [2, 3] is √13. Its usefulness depends on what the entries and units represent.
- Check equal lengths before using Python's zip for a dot product; zip stops at the shorter input.

### Gradients

Video: https://fanout.sh/ai/lessons/math-fundamentals-gradients

Imagine adjusting two numbers in a model, w and b. These adjustable numbers are its **parameters**. You want to know which small changes might lower its error score.

Use a deliberately small error function, called a **loss**:

```math
L(w,b) = (w-1)^2 + (b+2)^2
```

The loss is smallest at w = 1, b = −2, where both squares are zero. We can see the answer here; that lets us check the method we would use when the answer is harder to see.

## Ask one parameter at a time

Start at w = 3, b = −1. The loss is (3 − 1)² + (−1 + 2)² = 5.

First hold b fixed and change w. We need its **derivative**, the loss's local rate of change as w moves. For a square u², that rate is 2u. Here u = w − 1, which changes by the same amount as w, so the rate is 2(w − 1) = 4.

For example, increasing w from 3 to 3.01 while leaving b at −1 raises the loss from 5 to 5.0401. The change, 0.0401, is close to the rate 4 multiplied by the input change 0.01.

Next hold w fixed and change b. The same calculation gives 2(b + 2) = 2. Each is a **partial derivative**: we changed one input while holding the other fixed.

Collect those two partial derivatives, in the same order as the parameters:

```math
\nabla L(w,b) = [2(w-1),\;2(b+2)],\qquad \nabla L(3,-1)=[4,2]
```

This ordered list of rates is the **gradient**. An ordered list of numbers is also called a vector. The symbol ∇ means we are collecting rates of change, one per input. Compare equally small moves in different directions, using ordinary distance to measure their size. For a smooth loss, following a nonzero gradient gives the fastest local increase. At a zero gradient, it supplies no preferred direction.

To try decreasing the loss, take a small step in the opposite direction. With a step size of 0.25:

```math
[w,b]_{\text{new}}=[3,-1]-0.25[4,2]=[2,-1.5]
```

The new loss is 1² + 0.5² = 1.25. This is **gradient descent**. Its step size is usually called the **learning rate** and written η.

## A direction still needs a sensible step

The gradient describes nearby change. It does not tell us that every step along the opposite direction will improve the loss.

For the plot below, keep only the first term, L(w) = (w − 1)². Start at w = 3, where its derivative is 4. Predict what happens at η = 0.5, then move the slider. After that, try η = 1.2.

```experiment
gradient-step
```

At 0.5 we land on w = 1. At 1.2 we jump past it to w = −1.8, and the loss rises from 4 to 7.84. Even with a correct gradient, a large step can make things worse.

**Your turn:** Return to the two-parameter loss. At w = 0, b = −2, the gradient is [−2, 0]. Where does one step with η = 0.25 take you? Does b change?

```answer
The update is [0, −2] − 0.25[−2, 0] = [0.5, −2]. The negative derivative makes w increase when we subtract the gradient. The zero derivative leaves b unchanged.

The loss falls from 1 to 0.25. A zero component does not mean every parameter has reached the minimum; it only describes that component's current local rate.
```

Real model losses are more complicated than this bowl. Zero gradient need not mean a minimum, and training often estimates gradients from a small batch of examples. Keep those limits in mind without needing to solve them yet.

**Read next if curious:** [Deep Learning, §4.3](https://www.deeplearningbook.org/contents/numerical.html) connects derivatives, gradients and optimization. Find the gradient descent update and match its symbols to the update you just calculated.

#### Quick notes

- A partial derivative measures the local rate as one input changes while the other independent inputs stay fixed.
- The gradient collects those partial derivatives in input order.
- For a smooth function, a nonzero gradient points toward the fastest local increase under ordinary Euclidean distance.
- Gradient descent subtracts learning rate × gradient from the current parameters.
- A large learning rate can raise the loss. A zero gradient need not identify a minimum.

### Matrices

Video: https://fanout.sh/ai/lessons/math-fundamentals-matrices

A **matrix** is a rectangular arrangement of numbers. Here is one with two rows and two columns:

```math
W=\begin{bmatrix}4&1\\0&2\end{bmatrix}
```

A row runs across: the first row contains 4 and 1. A column runs down: the first column contains 4 and 0. We describe the matrix's **shape** as 2 × 2, always rows first, columns second. W is just its name.

We can use those numbers as a rule that turns two inputs into two outputs. Choose the inputs 2 and 3, written in a column:

```math
x=\begin{bmatrix}2\\3\end{bmatrix}
```

This input column has shape 2 × 1: two rows and one column. Let's see how W acts on it.

## Follow one row to one output

Take the first row of W. Multiply its 4 by the first input, 2, and its 1 by the second input, 3. Add the results: 8 + 3 = 11.

Repeat with the second row: 0 × 2 + 2 × 3 = 6. Written together, these two calculations give the **matrix product** Wx:

```math
Wx=\begin{bmatrix}4\times2+1\times3\\0\times2+2\times3\end{bmatrix}
=\begin{bmatrix}11\\6\end{bmatrix}
```

Each row produces one output. The second output ignores the first input because its multiplier is zero. Multiplying corresponding entries and adding them is called a **dot product**; matrix multiplication repeats that operation for each row.

**Predict:** Change only the first input from 2 to 5. Which output changes, and what are the two new outputs?

```answer
The first becomes 4 × 5 + 1 × 3 = 23. The second stays at 6 because its multiplier on the first input is zero.

You can also inspect the first column of W: [4, 0]. Adding 3 to the first input adds 3 × [4, 0] = [12, 0] to the original outputs.
```

## Shapes tell you which calculation is possible

Suppose the next matrix has three rows and two columns. Each row still needs two inputs, and the three rows produce three outputs.

```math
(3\times2)\;(2\times1)\;\longrightarrow\;(3\times1)
```

The inner dimensions must agree because every row needs as many entries as the input supplies. More generally, (m × n) multiplied by (n × p) produces (m × p). Here m, n and p count dimensions; they are not values stored inside the matrices.

Try multiplying W by two input columns at once:

```math
X=\begin{bmatrix}2&5\\3&3\end{bmatrix},\qquad
WX=\begin{bmatrix}11&23\\6&6\end{bmatrix}
```

Each column is a separate pair of inputs. The first gives [11, 6], as above; the second gives [23, 6], matching your prediction. A matrix product can process several input columns this way.

## Rows can become columns

The **transpose** swaps row and column positions, without changing individual values:

```math
W^T=\begin{bmatrix}4&0\\1&2\end{bmatrix}
```

Transposing a 3 × 2 matrix produces a 2 × 3 matrix. This changes which entries participate together in a row's dot product; it does not generally undo the original transformation.

For a neural network's weighted sums, you can now follow which inputs contribute to each output and check whether the shapes fit.

**Optional exercise:** Read the matrix product in [Deep Learning, §2.2](https://www.deeplearningbook.org/contents/linear_algebra.html). Pick one output entry in its notation and identify the row and column that produce it. Then explain why a 2 × 3 matrix cannot multiply a 2 × 1 column directly.

#### Quick notes

- A matrix's shape is rows × columns. A row runs across; a column runs down.
- Matrix multiplication forms each output entry by multiplying a row with a column and adding the products.
- Shape rule: (m × n) @ (n × p) → (m × p). Inner dimensions must match.
- With W = [[4, 1], [0, 2]], input [2, 3] produces [11, 6].
- Transpose swaps row and column positions. It does not generally undo a transformation.

### Hadamard Product (Element-wise Op)

Video: https://fanout.sh/ai/lessons/math-fundamentals-hadamard-product

You have two arrays of the same shape. You want each number in the first array multiplied by the number in the matching position of the second.

That operation is the **Hadamard product**, also called elementwise multiplication. It preserves the shape:

```math
\begin{bmatrix}1&2\\3&4\end{bmatrix}
\odot
\begin{bmatrix}5&6\\7&8\end{bmatrix}
=\begin{bmatrix}5&12\\21&32\end{bmatrix}
```

The ⊙ symbol says “match positions.” The top-right entry is 2 × 6 = 12. It does not mix numbers from other positions.

## Compare it with matrix multiplication

Using the same two arrays, matrix multiplication combines rows with columns:

```math
\begin{bmatrix}1&2\\3&4\end{bmatrix}
\begin{bmatrix}5&6\\7&8\end{bmatrix}
=\begin{bmatrix}19&22\\43&50\end{bmatrix}
```

Its top-right entry is 1 × 6 + 2 × 8 = 22. The shapes happen to match the first result, so checking shape alone would not catch confusing these operations.

**Predict:** To zero the second entry of [3, 7, 2] while preserving the others, what array would you multiply it by elementwise?

```answer
Use [1, 0, 1]. Matching positions produces [3 × 1, 7 × 0, 2 × 1] = [3, 0, 2]. This array is a mask: its zero hides one entry and its ones keep the others.
```

## Inspect both in code

With NumPy installed, run:

```python
import numpy as np

a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
print((a * b).tolist())   # [[5, 12], [21, 32]]
print((a @ b).tolist())   # [[19, 22], [43, 50]]
```

For NumPy arrays, `*` is elementwise multiplication and `@` is matrix multiplication. These meanings depend on the objects: ordinary Python lists do not support list-by-list elementwise multiplication. For example, `[1, 2] * 2` repeats the list instead.

A fixed mask also controls which input changes reach the output. Keep our mask [1, 0, 1]: changing the middle input from 7 to 100 still leaves the middle output at zero. Changing the first input passes straight through. The zero masks that position regardless of its value.

**Try one change:** Replace the lower-right entry of b with zero. Before running the code again, predict which entries change in each result.

```answer
Elementwise multiplication changes only the lower-right result, from 32 to 0. Matrix multiplication changes both entries in the second output column: 22 becomes 6, and 50 becomes 18. In that operation, the changed input contributes to more than one output.
```

The [NumPy multiply reference](https://numpy.org/doc/stable/reference/generated/numpy.multiply.html) shows additional array examples. Start with equal shapes. Its broadcasting cases extend the rules to compatible unequal shapes; they do not change what happened in our matching-position example.

#### Quick notes

- The Hadamard product multiplies matching entries. For equally shaped arrays, the output keeps that shape.
- For NumPy arrays, a * b is elementwise multiplication; a @ b is matrix multiplication.
- Matrix multiplication mixes row and column entries. Equal output shapes do not mean the operations agree.
- A fixed mask [1, 0, 1] preserves the first and third entries and zeros the second.
- Ordinary Python lists follow different rules: [1, 2] * 2 repeats the list.

### Moving Averages (EMA)

Video: https://fanout.sh/ai/lessons/math-fundamentals-moving-averages

Imagine watching a model's loss values arrive: 8, 4, 6, 2. The latest value moves around, making the underlying trend hard to see. A moving average smooths the sequence.

One option is to average the last three values. After 8, 4, 6, the average is 6. When 2 arrives, drop 8 and average 4, 6, 2 to get 4. This is a **simple moving average** with a window of three.

## Blend the new value with the old estimate

An **exponential moving average**, or EMA, keeps a single running estimate. For this example, initialize it with the first value, 8. Each later estimate is half the old estimate plus half the new observation:

| New observation | Calculation | New estimate |
| --- | --- | --- |
| 8 | Initialize with the first observation | 8 |
| 4 | 0.5 × 8 + 0.5 × 4 | 6 |
| 6 | 0.5 × 6 + 0.5 × 6 | 6 |
| 2 | 0.5 × 6 + 0.5 × 2 | 4 |

**Predict:** If the next observation is 10, what is the new estimate? Does the old estimate disappear immediately?

```answer
It becomes 0.5 × 4 + 0.5 × 10 = 7. Half of the previous estimate remains. A single high observation pulls the estimate upward without replacing it entirely.

The three-value simple moving average would instead use 6, 2, 10 and give 6. The two methods happened to agree before this update; they use different weighting rules.
```

The general rule uses β for the fraction of the old estimate we retain:

```math
v_t=\beta v_{t-1}+(1-\beta)x_t,\qquad 0\leq\beta<1
```

xₜ is the new observation, vₜ₋₁ the previous estimate, and vₜ the updated estimate. The subscript t counts time steps. At β = 0.9, each update keeps 90% of the previous estimate and mixes in 10% of the new value. It reacts more slowly than β = 0.5.

## Change the amount of smoothing

This ordinary Python example uses the same four observations:

```python
values = [8.0, 4.0, 6.0, 2.0]
for beta in [0.5, 0.9]:
    estimate = values[0]
    trace = [estimate]
    for value in values[1:]:
        estimate = beta * estimate + (1 - beta) * value
        trace.append(round(estimate, 3))
    print(beta, trace)
# 0.5 [8.0, 6.0, 6.0, 4.0]
# 0.9 [8.0, 7.6, 7.44, 6.896]
```

Before adding `10.0` to the list, predict which estimate will move by a larger amount on that next update. Run it to compare.

The β = 0.5 estimate moves from 4 to 7, a change of 3. The β = 0.9 estimate moves from 6.896 to 7.2064, a change of 0.3104; the code prints that estimate rounded to 7.206.

Strong smoothing can make a training curve easier to read while also hiding a recent change for longer.

## Initialization matters

We initialized with the first observation. Another convention starts with v₀ = 0. With a first observation of 8 and β = 0.5, that produces 4, biased downward by the initial zero.

Dividing by 1 − βᵗ corrects the missing total weight when using zero initialization. At t = 1, the correction is 4 / (1 − 0.5) = 8. Do not apply that correction to our first-observation initialization: it follows a different convention.

**Paper inspection:** [Adam, Algorithm 1](https://arxiv.org/abs/1412.6980) tracks moving averages of gradients and of squared gradients. A gradient is a local rate of loss change with respect to a parameter. Find its zero initial values and the two bias-correction lines. The squared-gradient average is a raw second moment, not the variance; Adam combines these estimates to scale parameter updates.

#### Quick notes

- A simple moving average uses a fixed recent window with equal weights.
- An exponential moving average updates v = β × previous v + (1 − β) × new value.
- Larger β gives more weight to the previous average and a slower response.
- Initialization matters: starting from the first observation differs from starting at zero.
- For the usual zero-initialized EMA, divide by 1 − βᵗ for startup bias correction. Do not apply this unchanged to a first-observation initialization.
- Adam tracks averages of gradients and squared gradients; the latter is a raw second moment, not variance.

## PyTorch Fundamentals

Master the tensor operations that are the building blocks of every neural network implementation.

### 7 PyTorch Tasks (Advanced)

Video: https://fanout.sh/ai/lessons/pytorch-fundamentals-7-pytorch-tasks

Work through seven small tensor tasks using the same six values. Each answer is a complete CPU Python snippet, so you can run it independently with PyTorch installed.

The main tensor is [[1, 2, 3], [4, 5, 6]], shape (2, 3): two rows, three columns. Axis numbers and indices start at zero. Write down the output shape as well as the values before opening an answer. That habit catches mistakes that a printed list alone can hide.

In the video, the tasks build a transformer layer's pieces instead: reductions with `keepdim`, variance and standard deviation (and why PyTorch divides by n − 1 by default), LayerNorm and a Linear layer from scratch, and one training step. The tasks here practise the shape and axis habits those pieces rely on.

## 1. Keep one feature as a column

Select the middle column while keeping shape (2, 1). An integer column index removes an axis; choose a slice that retains it.

````answer
```python
import torch
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
y = x[:, 1:2]
print(y.tolist(), tuple(y.shape))
```

```text
[[2], [5]] (2, 1)
```

The stop index 2 is excluded. `x[:, 1]` selects the same values but gives shape (2,), so it does not satisfy the shape requirement.
````

## 2. Rebuild a batch from separate rows

Take each row of the tensor and combine the rows into shape (2, 3) using `stack`. What would `cat` do to those two one-dimensional rows?

````answer
```python
import torch
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
rows = [x[0], x[1]]
print(torch.stack(rows).tolist())
print(tuple(torch.cat(rows).shape))
```

```text
[[1, 2, 3], [4, 5, 6]]
(6,)
```

Stack adds an axis identifying the row. Cat extends the existing length-three axis and loses the explicit two-row arrangement.
````

## 3. Subtract each row's own mean

Use floating-point values. Produce two rows with mean zero without writing a Python loop. Keep the computed means as a (2, 1) column so they align with rows during subtraction.

````answer
```python
import torch
x = torch.tensor([[1., 2., 3.], [4., 5., 6.]])
means = x.mean(dim=1, keepdim=True)
centered = x - means
print(means.tolist())
print(centered.tolist())
```

```text
[[2.0], [5.0]]
[[-1.0, 0.0, 1.0], [-1.0, 0.0, 1.0]]
```

`dim=1` averages across columns; `keepdim=True` retains that axis with length one. Without it, shape (2,) would not broadcast against this (2, 3) tensor as intended.
````

## 4. Compare every row with every row

Find a (2, 2) table of squared Euclidean distances between the two rows. Squared distance adds the squared differences across features. The diagonal should be zero, because each row is compared with itself.

````answer
```python
import torch
x = torch.tensor([[1., 2., 3.], [4., 5., 6.]])
differences = x[:, None, :] - x[None, :, :]
distances = (differences ** 2).sum(dim=-1)
print(tuple(differences.shape))
print(distances.tolist())
```

```text
(2, 2, 3)
[[0.0, 27.0], [27.0, 0.0]]
```

`None` inserts a size-one axis. Broadcasting then creates one feature-difference vector per row pair. Summing the last axis gives 3² + 3² + 3² = 27 for different rows. For many rows, this temporary all-pairs tensor can be large; the exercise is deliberately tiny.
````

## 5. Change one row without changing the source

Extract the last row, set its first value to 99 and leave the original tensor intact. Decide where to request a copy.

````answer
```python
import torch
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
row = x[-1].clone()
row[0] = 99
print(row.tolist())
print(x.tolist())
```

```text
[99, 5, 6]
[[1, 2, 3], [4, 5, 6]]
```

Basic indexing returns a view sharing storage. Cloning before the assignment gives the row independent storage. Cloning after the assignment would be too late to preserve x.
````

## 6. Flatten after a transpose

Transpose the two axes, then flatten in the transposed reading order. Predict the six-value sequence. Should you require a storage-sharing `view`, or allow `reshape` to copy if necessary?

````answer
```python
import torch
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
y = x.T.reshape(-1)
print(y.tolist())
```

```text
[1, 4, 2, 5, 3, 6]
```

The transposed rows are [1, 4], [2, 5], [3, 6]. Reshape reads them in that order and can copy when the layout cannot support a view. `x.T.view(-1)` fails for this layout; the element count alone does not settle that question.
````

## 7. Normalize scores across the right axis

Treat each row as scores for three competing answers. Apply softmax so each row sums to one. Then deliberately normalize on the other axis and inspect what sums to one instead.

````answer
```python
import torch
x = torch.tensor([[1., 2., 3.], [4., 5., 6.]])
per_example = torch.softmax(x, dim=1)
across_examples = torch.softmax(x, dim=0)
print(per_example.sum(dim=1).tolist())
print(across_examples.sum(dim=0).tolist())
```

```text
[1.0, 1.0]
[1.0, 1.0, 1.0]
```

With `dim=1`, columns compete within each example. With `dim=0`, the two examples compete within each column. Both are mathematically valid normalizations; only the first matches the task.
````

If a task failed, keep the smallest failing expression and print each input's shape before changing it. The [PyTorch tensor tutorial](https://docs.pytorch.org/tutorials/beginner/basics/tensorqs_tutorial.html) provides API examples to compare with your attempt.

**Optional challenge set:** [Tensor Puzzles](https://github.com/srush/Tensor-Puzzles) asks you to rebuild operations with a small set of tensor tools. Try its `outer` puzzle after the pairwise-distance task; inspect how two added axes create every pair. Its notebook has its own setup instructions, separate from these seven snippets.

#### Quick notes

- Write the intended output shape before choosing the operation.
- Use a slice to keep a feature axis, and stack separate rows to create a batch axis.
- Keep row means as columns for rowwise subtraction; add axes deliberately for all-pairs calculations.
- Clone a slice before editing when the source must remain unchanged.
- Transpose changes axis order; reshape can flatten that order and may copy.
- Softmax's dim chooses which entries compete. One row per example usually means normalizing along its answer columns.

## Reinforcement Learning

How agents learn from interaction — from basic environments to PPO and modern LLM reasoning techniques.

### PPO, LLM Reasoning, Importance Ratio, Advantage

Video: https://fanout.sh/ai/lessons/reinforcement-learning-ppo-llm-reasoning

A language model answered a prompt. We scored its response, and now want to make useful choices more likely. But if we train repeatedly on the same recorded response, how much should one batch be allowed to change the model?

**Proximal Policy Optimization**, or PPO, includes a method called PPO-Clip that removes some incentive to keep pushing a recorded action's probability in the same direction. We will inspect that mechanism with one action. The action could be a game move or a language model's next token.

## Compare the old and current probabilities

Suppose the model that collected the response assigned probability 0.20 to a particular token at a particular prefix. After an update, the current model assigns 0.30 to that **same token at the same prefix**.

The ratio is 0.30 / 0.20 = 1.5. The token is now 50% more likely at that prefix. This **importance ratio** compares the current policy with the old policy that generated the data:

```math
r(\theta)=\frac{\pi_\theta(a\mid s)}{\pi_{\text{old}}(a\mid s)}
```

Here π is an action probability, θ means the current model parameters, s is the state or token prefix, and a is the recorded action. Keep the old probability fixed while updating the current model. The two policies are identical at the start of the batch, so the ratio starts at 1.

Now suppose this action's estimated future return is 4 and the baseline expectation is 2. Its **advantage** is +2: better than expected. An advantage of −2 would mean worse than expected. In a language model, a final response score can contribute to advantages for the preceding tokens; it does not identify a separate correct answer for every token.

## Watch where the incentive stops

Without clipping, the policy objective for this sample would be ratio × advantage. At ratio 1.5 and advantage +2, that is 3. Increasing the ratio would keep increasing the objective.

For this example, choose a clipping width ε = 0.2. That gives the interval [0.8, 1.2]. **Clipping** leaves values inside the interval unchanged, replaces smaller ones with 0.8, and replaces larger ones with 1.2. PPO-Clip compares the ordinary product with a product using the clipped ratio, and takes the smaller one. We **maximize** this objective:

```math
\begin{aligned}
L_{\text{clip}} &= \min(r\widehat A,\;\bar r\widehat A) \\
\bar r &= \operatorname{clip}(r,\;1-\varepsilon,\;1+\varepsilon)
\end{aligned}
```

Â is the estimated advantage, held fixed for this policy update. With +2 advantage, increasing the ratio from 1.2 to 1.5 no longer helps this term: it stays at 2.4.

What if the advantage is **negative**? Predict the objective at ratio 0.5 and advantage −2 before opening the answer.

```answer
The ordinary product is 0.5 × −2 = −1. The clipped product is 0.8 × −2 = −1.6. Taking the smaller gives −1.6. Once the ratio falls below 0.8, reducing it further offers no extra benefit for this sample's policy term.
```

The sign matters. For a bad action, increasing its probability is still penalized, even beyond the clipping interval. PPO does not simply replace every ratio with a clipped number.

Run the three ratios for both advantage signs:

```python
def ppo_term(ratio, advantage, epsilon=0.2):
    clipped = max(1 - epsilon, min(1 + epsilon, ratio))
    return min(ratio * advantage, clipped * advantage)

for advantage in [2.0, -2.0]:
    values = [ppo_term(r, advantage) for r in [0.5, 1.0, 1.5]]
    print(advantage, values)
```

```text
2.0 [1.0, 2.0, 2.4]
-2.0 [-1.6, -2.0, -3.0]
```

Change only ε to 0.1. For +2 advantage and ratio 1.5, what is the new ceiling?

```answer
The upper clipped ratio becomes 1.1, so the objective is capped at 1.1 × 2 = 2.2 for that positive-advantage sample. A narrower interval removes the incentive sooner; it does not guarantee a bound on the actual parameter update.
```

## Fit it into language-model training

| Part | In a language model |
| --- | --- |
| Observation | Prompt and generated prefix |
| Action | Next token |
| Policy | Distribution over vocabulary tokens |
| Reward | Feedback on the response, such as a verifier or reward-model score |
| Value estimate | Expected future return at a prefix |

Collect responses with a snapshot of the policy. Score them, estimate advantages, then run a limited number of updates using the saved old log probabilities. A value model is commonly trained alongside the policy. Finally collect fresh responses.

LLM training may also penalize divergence from a separate reference model. That reference is conceptually different from the old policy used in the importance ratio. A larger reward-model score also does not automatically mean a more truthful or useful response; check task performance on held-out prompts.

**Inspect the actual claim:** [Spinning Up's PPO guide](https://spinningup.openai.com/en/latest/algorithms/ppo.html) works through both advantage signs and explains why clipping can still allow a large policy change. Find its early-stopping discussion: implementations may additionally monitor KL divergence, a measure of distribution change. The [original PPO paper, §3](https://arxiv.org/pdf/1707.06347), introduces the clipped objective. Read that section's plot by matching its positive and negative advantage cases to the numbers above. This lesson isolates the policy term; it is not a complete PPO trainer.

#### Quick notes

- The importance ratio compares current and old probabilities for the same recorded action at the same state or prefix.
- Advantage estimates how much better or worse the outcome was than a baseline.
- PPO-Clip maximizes the smaller of ratio × advantage and clipped-ratio × advantage.
- Clipping removes further incentive in the favorable direction; the sign of the advantage determines that direction.
- Old probabilities and advantage estimates stay fixed during the policy update. Fresh data is collected after limited updates.
- Clipping does not guarantee a bound on policy change. A separate reference-model KL penalty is distinct from the old-policy ratio.

### Qwen 3 GSPO & DeepSeek GRPO — LLM Reasoning

Video: https://fanout.sh/ai/lessons/reinforcement-learning-qwen-deepseek-grpo

Ask a model the same arithmetic question four times. A checker gives reward 1 for a correct final answer and 0 otherwise. Suppose the rewards are [1, 0, 1, 0].

The model produced both successful and unsuccessful attempts. We can compare them **within this group** to form a learning signal, instead of training a separate model to predict the expected reward.

This is the starting idea of **Group Relative Policy Optimization**, or GRPO, introduced in [DeepSeekMath](https://arxiv.org/html/2402.03300v3#S4.SS1). We will compare its outcome-reward version with **Group Sequence Policy Optimization**, or GSPO, from the Qwen team. Both adjust a language model using sampled responses and rewards; they weight those responses differently.

## First, compare each reward with its group

Our four rewards have mean 0.5. Each reward lies 0.5 away from that mean. Square those distances, average them, and take the square root: √0.25 = 0.5. That is their **population standard deviation**, a measure of spread. Subtract the mean and divide by that spread:

```math
\widehat A_i=\frac{R_i-\operatorname{mean}(R)}{\operatorname{std}(R)}
```

Rᵢ is response i's reward. The resulting **advantages** are [1, −1, 1, −1]. Positive means better than this group's average, not “proved good in every sense.” For outcome supervision, each generated token in one response receives that response's advantage.

What happens if all four responses earn 0? What if all four earn 1?

```answer
Both groups have zero spread and zero difference from their mean. There is no within-group preference signal. A raw division by zero is invalid; implementations need explicit handling, such as a small denominator stabilizer. That gives zero advantages here. Other loss terms can still update the model, but this group alone cannot tell the reward-based policy term which response to prefer.
```

A final-answer checker also cannot establish that every intermediate reasoning step was correct. A response can reach the correct answer through flawed reasoning; the reward only measures what the checker actually checks.

## The difference is where we form the ratio

Save the probability assigned to each generated token by the old model that sampled it. After an update, recompute the probability of that **same token at the same prefix** under the current model.

For one two-token response, suppose those probabilities are:

| Token position | Old probability | Current probability | Current / old |
| --- | ---: | ---: | ---: |
| 1 | 0.20 | 0.40 | 2.0 |
| 2 | 0.50 | 0.25 | 0.5 |

These are conditional probabilities at different prefixes; a column is not a probability distribution that must sum to 1.

GRPO forms a separate ratio for each token. GSPO forms a ratio from the likelihood of the whole response, then normalizes it by response length. If the token ratios are r₁ through r_T:

```math
s=\left(\prod_{t=1}^{T}r_t\right)^{1/T}
```

For our response, s = √(2 × 0.5) = 1. This is a **geometric mean**, not the arithmetic mean 1.25. The first token became more likely, the second less likely, and the full response likelihood happened to stay unchanged.

## Calculate the difference before training anything

Both methods use a clipped policy term: take the smaller of ratio × advantage and clipped-ratio × advantage, then maximize it. The clipping interval in this arithmetic example is [0.8, 1.2]. Clipping leaves values inside unchanged and replaces values outside with the nearer endpoint: 2 becomes 1.2, while 0.5 becomes 0.8.

For a response with advantage +1, GRPO's two terms are 1.2 and 0.5. Their mean is 0.85. GSPO instead uses the length-normalized sequence ratio 1, giving a term of 1.

Run that comparison. The code also handles a group with zero spread. It is a calculation of the policy terms, not an RL trainer or a performance comparison.

```python
import numpy as np

rewards = np.array([1., 0., 1., 0.])
advantages = (rewards - rewards.mean()) / (rewards.std(ddof=0) + 1e-8)
old = np.array([0.20, 0.50])
current = np.array([0.40, 0.25])
ratios = current / old
sequence_ratio = np.exp(np.mean(np.log(current) - np.log(old)))

def clipped_term(ratio, advantage, epsilon=0.2):
    return np.minimum(ratio * advantage,
                      np.clip(ratio, 1 - epsilon, 1 + epsilon) * advantage)

print("advantages:", np.round(advantages, 3))
print("sequence ratio:", round(float(sequence_ratio), 3))
print("GRPO term:", round(float(clipped_term(ratios, 1.0).mean()), 3))
print("GSPO term:", round(float(clipped_term(sequence_ratio, 1.0)), 3))
```

```text
advantages: [ 1. -1.  1. -1.]
sequence ratio: 1.0
GRPO term: 0.85
GSPO term: 1.0
```

We use +1 exactly for the comparison; the printed normalized advantages differ from ±1 by a tiny amount because of the stabilizer. Real implementations also mask padding and compute response length from actual generated tokens, not the padded array width.

Change the advantage in both `clipped_term` calls to −1. Can you predict which token term stays unclipped?

```answer
The ratio-2 token gives min(−2, −1.2) = −2: making a negative-advantage token more likely is still penalized. The ratio-0.5 token gives min(−0.5, −0.8) = −0.8. GRPO's mean becomes −1.4; GSPO's term becomes −1. Neither method simply clips every ratio and discards the original value.
```

## What the papers establish

DeepSeekMath's [§4.1.2](https://arxiv.org/html/2402.03300v3#S4.SS1.SSS2) describes the group-normalized outcome rewards. Look at its Figure 4 to see which separate value model GRPO removes. Removing that model does not remove the need to score responses, and the paper's complete objective includes a reference-policy KL term that our calculation omits.

The GSPO paper's [§4.1, equations 5–7](https://arxiv.org/html/2507.18071v2#S4.SS1) defines the sequence objective and length normalization. Its §5.1 reports better training efficiency than its GRPO baseline for the tested Qwen3-30B-A3B-based setup. Inspect Figure 1 alongside the stated experimental settings; this is empirical evidence for that comparison, not a guarantee that GSPO wins on every task.

The paper uses substantially different clipping ranges for GSPO and GRPO. Our shared 0.2 was chosen only to make the arithmetic visible; it is not a training recommendation. Sequence-level clipping also does not mean every individual token probability stays close to its old value—the [2, 0.5] example already shows why.

#### Quick notes

- Outcome-based GRPO compares rewards within a group of responses to the same prompt, avoiding a separately trained value model.
- A response's normalized reward supplies its tokens' advantage. Zero reward spread needs explicit handling and gives no relative preference signal.
- GRPO uses token probability ratios; GSPO uses a length-normalized sequence-likelihood ratio, the geometric mean of token ratios.
- For ratios [2, 0.5], GSPO's ratio is 1, not the arithmetic mean 1.25.
- Both use clipped objectives. Actual clipping settings differ; sequence clipping does not bound every token ratio.
- The tiny comparison omits reference-policy KL and a training loop. Paper results depend on the tested setup and reward quality.

## LLM From Scratch

Build state-of-the-art large language models from scratch — LLaMA 4, DeepSeek V3, Qwen 3, and more.

### Llama 4 From Scratch

Video: https://fanout.sh/ai/lessons/llm-from-scratch-llama-4

A large model can store many feed-forward networks without running all of them for every token. Llama 4 uses this idea: a **router** selects a network, called an expert, for the token being processed.

There is also a shared expert that processes every token. That gives us a small piece of the architecture we can build and inspect: one shared path plus one selected path.

## Follow one token through an expert block

Suppose a token is represented by the vector x = [1, 0]. A learned router produces a score for each available expert. We will use two experts and scores [0, −1], so expert 0 wins.

Llama 4 applies sigmoid to the winning score. Sigmoid maps a number into the range 0 to 1; sigmoid(0) is 0.5. The selected expert receives **0.5x**, while the shared expert receives **x**.

| Branch | Input to expert | Contribution to the result |
| --- | --- | --- |
| Shared | x = [1, 0] | Shared expert's output |
| Routed | 0.5x = [0.5, 0] | Expert 0's output on the scaled input |
| Combination | Both branch outputs | Add the two vectors |

Writing S for the shared network and E for the selected network:

```math
\begin{aligned}
s&=\operatorname{sigmoid}(r_j)\\
y&=S(x)+E_j(sx)
\end{aligned}
```

Here r_j is the winning router score. This y is the feed-forward branch's output; a full decoder block also has normalization, attention and residual additions.

It is tempting to write the second term as sE_j(x). Would that give the same answer? For a linear expert, yes. For this SwiGLU expert, generally no: the position of that multiplication matters.

## Build the nonlinear part

A Llama 4 expert uses **SwiGLU**: make two projections of the input, apply SiLU to one, multiply their entries, then project back. In PyTorch notation that is `down(silu(gate(x)) * up(x))`.

SiLU(z) = z × sigmoid(z), applied separately to each coordinate.

For a transparent example, make the first two projections identity matrices. The expert becomes `scale * silu(x) * x`, with `scale` representing a simple output projection. For an input coordinate of 1 and output scale 1, E(0.5) = SiLU(0.5) × 0.5 ≈ 0.1556. But 0.5E(1) = 0.5 × SiLU(1) × 1 ≈ 0.3655. The shared path adds the same value to both, so it cannot remove the difference. These hand-picked weights let us examine routing; they have not learned language.

The program also adds a second token, [0, 1], so we can inspect both experts. Its printed diagonal entries are the active coordinate from each token.

```python
import torch
import torch.nn.functional as F

x = torch.tensor([[1., 0.], [0., 1.]])
router_weight = torch.tensor([[0., -1.], [-1., 0.]])
logits = x @ router_weight.T
best_score, chosen = logits.max(dim=-1)
gate = best_score.sigmoid()

def expert(tokens, scale=1.):
    return scale * F.silu(tokens) * tokens

shared = expert(x)
routed = torch.zeros_like(x)
output_scaled = torch.zeros_like(x)
for j in range(2):
    rows = torch.where(chosen == j)[0]
    s = gate[rows, None]
    routed[rows] = expert(s * x[rows], scale=j + 1)
    output_scaled[rows] = s * expert(x[rows], scale=j + 1)

print("chosen:", chosen.tolist())
print("gates:", gate.tolist())
print("input gate:", (shared + routed).diag().tolist())
print("output gate:", (shared + output_scaled).diag().tolist())
print("same:", torch.allclose(routed, output_scaled))
```

The tokens choose experts `[0, 1]`, both with gate 0.5. The active output coordinates are approximately `[0.8867, 1.0423]`. Moving the gate after the expert changes them to `[1.0966, 1.4621]`. The final check is `False`.

Now add 2 to **every router score** before selecting the winner. Predict which expert IDs change and whether the outputs change.

```answer
The expert IDs stay [0, 1]: adding the same number preserves their ordering. The selected scores become 2, so their sigmoid gates rise from 0.5 to about 0.8808. The expert inputs and outputs change. Selection depends on relative scores, but this sigmoid gate also depends on the winning score's absolute value.
```

## Put the block in the model

The released Scout model has 16 routed experts; Maverick has 128. Each MoE block selects one routed expert and also uses a shared expert. Their layer layouts differ: Scout uses MoE feed-forward sublayers throughout its decoder, while Maverick alternates dense and MoE feed-forward sublayers. A dense sublayer uses its one feed-forward network for every token. The [Meta model builders](https://github.com/meta-pytorch/torchtune/blob/bd2a0fc7c31430972728494fa01aaeeb0ebf1ba1/torchtune/models/llama4/_model_builders.py) make this distinction explicit.

Llama 4 also accepts images. A vision encoder turns image patches into vectors, which are projected and placed alongside text embeddings before the language decoder processes the sequence. This early combination is called **early fusion**. Native multimodality still involves a vision encoder; our expert program implements neither that encoder nor attention.

The [model card](https://github.com/meta-llama/llama-models/blob/main/models/llama4/MODEL_CARD.md) describes the released models and their training context. Implementing this block reproduces a mechanism, not their trained capabilities or benchmark scores.

**Inspect the implementation:** open [Meta's `MoE.forward`](https://github.com/meta-llama/llama-models/blob/0e0b8c519242d5833d8c11bffc1232b77ad7f301/models/llama4/moe.py#L175). Locate top-k selection, sigmoid, multiplication of the routed input, and addition of the shared expert. Then find `batched_swiglu` and identify the two projections. That tracing exercise is a useful check before translating a model diagram into code.

#### Quick notes

- A Llama 4 MoE branch adds a shared expert to one selected routed expert.
- The selected sigmoid gate scales the expert input: S(x) + E(sx). Moving it after SwiGLU generally changes the result.
- SwiGLU multiplies a SiLU-activated projection by a second projection, then projects back.
- Scout uses MoE feed-forward sublayers throughout; Maverick alternates dense and MoE sublayers.
- Image features join text embeddings before the decoder. Our tiny block does not reproduce trained model capabilities.

## Write Research Paper

The complete workflow from coding experiments to writing and publishing an AI research paper.

### Code, Write & Publish AI Research Paper

Video: https://fanout.sh/ai/lessons/code-write-publish-ai-research-paper

A research paper makes a claim and gives other people enough evidence to check it. Code, plots and polished writing help only when they support that claim.

The video takes a public claim that Muon beats Adam, turns it into a fair comparison, audits the original headline, then writes up and publishes the result. We can practice the same workflow with a much smaller question: **on one small regression task, after equal numbers of training steps, how do AdamW and a Muon-based optimizer compare?**

That question names the task, comparison and budget. It does not promise a new best optimizer.

## Decide what the result would mean

Our model receives two numbers and predicts their product. It has one hidden layer with eight units. The loss is mean squared error: average the squared differences between predictions and correct products. Lower is better.

AdamW adjusts parameters using moving estimates of gradients and their squared values. Muon applies a matrix operation to a momentum update before changing the weights. Momentum carries information from earlier gradients into the current update. We use the library implementation here; the [original Muon explanation](https://kellerjordan.github.io/posts/muon/) derives its matrix operation if you want to inspect it.

Muon is intended for appropriate matrix weights, with other parameters handled separately. Here, “Muon hybrid” means Muon on the hidden weight matrix and AdamW on its bias and the output layer. That distinction must appear in a methods section; calling it simply “Muon on the model” hides part of the experiment.

Before running, fix these choices:

| Choice | Our pilot |
| --- | --- |
| Data | 64 training, 32 validation and 32 test examples |
| Training budget | 80 full-batch updates per run |
| Tuning budget | Two candidate learning rates per method, two seeds each |
| Final comparison | Three new seeds, using the selected rates |
| Other settings | Same model, data and zero weight decay; hybrid's AdamW rate fixed at 0.01 |

Matching seeds makes the two methods start from the same weights within a pair. Validation data chooses learning rates. Test data is consulted only after those rates are locked. The candidate ranges below are a small demonstration, not an exhaustive or equally optimal search for each method.

## Run an experiment small enough to audit

This CPU program was checked with PyTorch 2.14. It needs a PyTorch release containing `torch.optim.Muon`; it downloads no dataset or pretrained weights.

```python
import torch
from torch import nn

torch.set_num_threads(1)
g = torch.Generator().manual_seed(123)
x = torch.randn(128, 2, generator=g)
y = (x[:, :1] * x[:, 1:2])
x_train, y_train = x[:64], y[:64]
x_val, y_val = x[64:96], y[64:96]
x_test, y_test = x[96:], y[96:]

def run(kind, lr, seed, eval_x, eval_y):
    torch.manual_seed(seed)
    model = nn.Sequential(nn.Linear(2, 8), nn.Tanh(), nn.Linear(8, 1))
    if kind == 'adamw':
        optimizers = [torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=0.)]
    else:
        optimizers = [
            torch.optim.Muon([model[0].weight], lr=lr, weight_decay=0.),
            torch.optim.AdamW([model[0].bias, *model[2].parameters()],
                              lr=0.01, weight_decay=0.),
        ]
    for _ in range(80):
        for opt in optimizers:
            opt.zero_grad()
        loss = (model(x_train) - y_train).square().mean()
        loss.backward()
        for opt in optimizers:
            opt.step()
    with torch.no_grad():
        return (model(eval_x) - eval_y).square().mean().item()

candidates = {'adamw': [0.003, 0.01], 'muon_hybrid': [0.005, 0.02]}
selected = {}
for kind, rates in candidates.items():
    scores = {lr: sum(run(kind, lr, seed, x_val, y_val) for seed in [0, 1]) / 2
              for lr in rates}
    selected[kind] = min(scores, key=scores.get)
    print(kind, 'validation:', {lr: round(v, 4) for lr, v in scores.items()})
print('locked rates:', selected)
for seed in [10, 11, 12]:
    row = {kind: run(kind, lr, seed, x_test, y_test)
           for kind, lr in selected.items()}
    print(seed, {kind: round(loss, 4) for kind, loss in row.items()})
```

In the checked run, validation selected 0.01 for AdamW and 0.02 for the Muon hybrid. The held-out results were:

| Initialization seed | AdamW test loss | Muon hybrid test loss |
| --- | ---: | ---: |
| 10 | 0.1810 | 0.2593 |
| 11 | 0.4916 | 0.4409 |
| 12 | 0.2902 | 0.3463 |

The mean losses are about 0.3209 and 0.3489. AdamW has the lower mean in this pilot, but the direction reverses for seed 11. Small numerical differences across library versions are possible; save the full values from your own run.

Which statement can these results support?

- “AdamW is better than Muon.”
- “With these data, settings and three initializations, AdamW had lower mean test error after 80 updates.”

```answer
The second statement fits the evidence. We varied initialization, but kept one small dataset split, one architecture and a limited tuning grid. We did not measure wall-clock speed, language-model quality or performance on other datasets. Three seeds do not remove those limits.
```

If you change the learning-rate grid after looking at test scores, that set has started influencing your decisions. Treat the changed run as further development and reserve a new independent test for a final claim. Save unsuccessful runs too; keeping only the winning seed makes a method look more reliable than it was.

## Turn the result into something another person can check

Start with a figure or table that answers the question. For this pilot, the three paired losses are more informative than a single bold average. A training-curve plot would need labeled axes, the comparison budget and a description of what its variation represents. Equal steps and equal wall time answer different questions.

Draft a two-sentence results paragraph that gives the observed comparison and its limits. Then compare it with this worked example:

```answer
On the fixed product-regression split, AdamW obtained mean test MSE 0.3209 versus 0.3489 for the Muon hybrid after 80 updates, using three initialization seeds and one learning rate per method selected from two candidates. The result is limited to this pilot and does not establish an optimizer ranking for language models.
```

Then write the method needed to reproduce it: data construction and split, model, parameter groups, optimizer settings, candidate rates, seeds, stopping rule and software version. Keep the executable script and complete run records alongside the figure. The introduction can now explain why the question mattered; related work explains how it fits existing experiments. An abstract should summarize th**Audit a published comparison:** open [Fantastic Pretraining Optimizers and Where to Find Them](https://arxiv.org/abs/2509.02046), the related work the video cites. Find how it gives each optimizer its own hyperparameter search, and at which point in training it compares them. Then compare its reported speedup at its smallest and largest model sizes with the scope of the pilot statement you wrote above. A paper and a public repository are useful materials to inspect; neither alone verifies a result.d document are useful materials to inspect; neither alone verifies a result.

Your pilot is practice, not yet a novel research contribution. A next research question might test whether the observed difference survives different data splits or compute budgets. Read the closest prior work before claiming that experiment is new. For a paper submission, use the chosen venue's current instructions, disclose limitations and obtain coauthor review. A public preprint shares a manuscript; it is not the same as peer-reviewed acceptance.

#### Quick notes

- Start with a narrow question, a baseline, a metric and an explicit comparison budget.
- Select settings on validation data; keep final test data out of development decisions.
- Match initializations within comparisons and report variation, not only a winning seed.
- State Muon's parameter groups and the accompanying AdamW updates; equal steps do not establish equal wall time.
- Save code, configurations, complete run records and software versions. Write claims no broader than that evidence.
- A reproducible pilot is practice; a research contribution also needs context in prior work and appropriately reviewed claims.

## Machine Learning Operations (MLOps)

Deploy and maintain ML models in production — from Git and Docker to Kubernetes, CI/CD, and monitoring with Prometheus & Grafana.

### ML Pipeline with DVC & AWS S3

Video: https://fanout.sh/ai/lessons/ml-pipeline-dvc-aws-s3

A small spam classifier has three steps: normalize training text, learn a word rule, then evaluate it. You can run three Python scripts by hand. But when one input changes, which scripts need to run again?

A **pipeline** makes that relationship explicit. DVC records each stage's command, dependencies and outputs, then uses those declarations to decide what is out of date.

## Make the files tell the story

Use a fresh directory with Python and DVC installed. The following tiny classifier is for inspecting pipeline behavior, not for filtering real mail.

```bash
mkdir dvc-pipeline-practice
cd dvc-pipeline-practice
git init -b main
dvc init
```

Save these training examples as `raw.json`:

```json
[
  {"text": "Win a prize", "spam": true},
  {"text": "claim prize", "spam": true},
  {"text": "project meeting", "spam": false}
]
```

Save separate evaluation examples as `test.json`:

```json
[
  {"text": "prize today", "spam": true},
  {"text": "project review", "spam": false},
  {"text": "win the project", "spam": false}
]
```

The preparation script, `prepare.py`, turns each text into lowercase tokens while preserving its label:

```python
import json
from pathlib import Path

rows = json.loads(Path("raw.json").read_text())
prepared = [{"tokens": row["text"].lower().split(), "spam": row["spam"]}
            for row in rows]
Path("train.json").write_text(json.dumps(prepared, indent=2))
```

The fitting script, `fit.py`, remembers words seen in spam but not in non-spam training examples. That learned set is our model:

```python
import json
from pathlib import Path

rows = json.loads(Path("train.json").read_text())
positive, negative = set(), set()
for row in rows:
    words = positive if row["spam"] else negative
    words.update(row["tokens"])
model = {"spam_words": sorted(positive - negative)}
Path("model.json").write_text(json.dumps(model, indent=2))
```

Finally, `evaluate.py` predicts spam when any learned spam word occurs and writes the fraction of correct test predictions:

```python
import json
from pathlib import Path

words = set(json.loads(Path("model.json").read_text())["spam_words"])
rows = json.loads(Path("test.json").read_text())
predictions = [bool(words.intersection(row["text"].lower().split())) for row in rows]
correct = sum(prediction == row["spam"] for prediction, row in zip(predictions, rows))
metrics = {"accuracy": correct / len(rows), "examples": len(rows)}
Path("metrics.json").write_text(json.dumps(metrics, indent=2))
print(metrics)
```

The rule misclassifies “win the project.” A word seen in spam can appear in an ordinary message. This visible error will stay in the evaluation; pipeline automation should not hide it.

## Declare what each command reads and writes

Run these commands from the directory containing the five files:

```bash
dvc stage add -n prepare -d prepare.py -d raw.json -o train.json python prepare.py
dvc stage add -n fit -d fit.py -d train.json -o model.json python fit.py
dvc stage add -n evaluate -d evaluate.py -d model.json -d test.json -M metrics.json python evaluate.py
dvc repro
dvc dag
```

`-d` declares a dependency, `-o` a cached output, and `-M` a metric file kept outside the DVC data cache. Stage definitions go into `dvc.yaml`; `dvc.lock` records the dependency/output state of the reproduced pipeline.

| Stage | Declared inputs | Output |
| --- | --- | --- |
| `prepare` | `prepare.py`, `raw.json` | `train.json` |
| `fit` | `fit.py`, `train.json` | `model.json` |
| `evaluate` | `evaluate.py`, `model.json`, `test.json` | `metrics.json` |

The first reproduction creates the outputs and reports accuracy 2/3. A second unchanged `dvc repro` skips the work. DVC compares declared inputs and output state; it does not discover every file or environment setting a script might secretly use.

Add only a comment to `prepare.py`, then run `dvc repro` again. The script is a declared dependency, so preparation is out of date. Must fitting and evaluation also run?

```answer
Not necessarily. In this example, preparation writes exactly the same train.json bytes, so fitting still has unchanged inputs and can be skipped; evaluation can be skipped too. A changed upstream script does not imply changed downstream data. Inspect DVC's output rather than assuming every later stage reran.
```

Keep the scripts, small input fixtures, `dvc.yaml`, `dvc.lock`, metric file and DVC configuration under Git. Large real inputs can themselves be tracked by DVC. The fitted model and preprocessing output are cached data artifacts, rather than files to add directly to Git.

## Where S3 fits

The pipeline runs on your machine or runner. **Amazon S3** stores objects; it does not run these Python stages.

A local remote lets you practice the storage step without a cloud account:

```bash
mkdir ../dvc-pipeline-store
dvc remote add -d backup ../dvc-pipeline-store
dvc push
```

For an existing S3 bucket, the remote URL would instead look like `s3://YOUR_BUCKET/dvc-store`. DVC's [S3 storage guide](https://doc.dvc.org/user-guide/data-management/remote-storage/amazon-s3) explains the S3 backend and authentication. Use appropriate role or temporary credentials supplied by your environment, with access to the required bucket/prefix; credentials do not belong in committed pipeline files.

**Inspect one dependency:** [DVC's repro reference](https://doc.dvc.org/command-reference/repro) explains stage selection and caching. Try this in the practice directory:

1. Back up the configuration with `cp dvc.yaml dvc.yaml.backup`.
2. In `dvc.yaml`, find `stages → prepare → deps` and remove only its `prepare.py` entry. Keep the script file and the `python prepare.py` command.
3. Run `dvc repro` once after changing the declaration. Then add another comment to `prepare.py` and run `dvc repro` again.

The second run can skip preparation: the edited script is no longer a declared dependency. DVC still runs the command when needed, but it does not infer that the command's script should be tracked. Restore the configuration with `mv dvc.yaml.backup dvc.yaml` and run `dvc repro` to restore its recorded state.

#### Quick notes

- A DVC stage declares a command, dependencies and outputs; include the script itself as a dependency.
- dvc repro runs out-of-date stages or reuses available cached results based on declared state.
- Unchanged downstream input can let later stages skip even after an upstream script reruns.
- dvc.yaml defines the pipeline; dvc.lock records reproduced dependency/output state.
- S3 stores data and model objects; it does not execute the training pipeline. Keep credentials outside committed configuration.

## Bonus Lessons

Advanced topics — training dynamics, activation functions, and cutting-edge reasoning architectures.

### Train LLM — Sequence Length vs Batch Size

Video: https://fanout.sh/ai/lessons/bonus-lessons-seq-len-vs-batch

You have 32 token positions to process. You could arrange them as four sequences of eight tokens or two sequences of sixteen. Both layouts contain 32 positions, but a token can read different context in each one.

**Batch size** counts sequences processed together. **Sequence length** counts positions in each sequence. In ordinary causal attention, a position can read earlier positions in its own row, including itself, but cannot read another batch row.

## Follow token 8

Use the numbers 0 through 31 as token IDs. Here they identify positions in an invented stream; we are not tokenizing a real sentence.

| Layout | First row | Second row | Where are tokens 7 and 8? |
| --- | --- | --- | --- |
| Four rows of length 8 | 0 through 7 | 8 through 15 | Different rows |
| Two rows of length 16 | 0 through 15 | 16 through 31 | Same row |

Can token 8 use token 7 as context in each layout?

```answer
Only in the length-16 layout. In the length-8 layout, token 8 starts a new independent row. Keeping the same total number of positions does not keep the same attention relationships.
```

Call the batch size B and the row length L. The first position can read one position, the second can read two, and so on. One row therefore permits 1 + 2 + … + L = L(L + 1)/2 pairs. Multiply by B to count all rows.

Run this with ordinary Python. It counts relationships in a causal mask; it does not train or time a model.

```python title="context_layout.py"
tokens = list(range(32))
for length in [8, 16]:
    rows = [tokens[i:i + length] for i in range(0, len(tokens), length)]
    batch = len(rows)
    allowed_pairs = batch * length * (length + 1) // 2
    same_row = 8 // length == 7 // length
    print("shape:", (batch, length))
    print("8 can read 7:", same_row)
    print("causal pairs:", allowed_pairs)
```

```text
shape: (4, 8)
8 can read 7: False
causal pairs: 144
shape: (2, 16)
8 can read 7: True
causal pairs: 272
```

The longer rows allow more pairs even though both layouts contain 32 positions. A full dense attention-score array has B × L² entries per head: 256 versus 512 here. That count is not a measurement of total GPU memory or runtime. Implementations such as [FlashAttention](https://arxiv.org/abs/2205.14135) avoid storing the whole score array in high-bandwidth memory.

Change the lengths to `[4, 32]`. Predict whether 8 can read 7 and how many causal pairs each layout permits before running it.

```answer
Length 4 gives eight rows, separates 7 and 8, and permits 80 pairs. Length 32 gives one row, keeps them together, and permits 528 pairs. More within-row context changes what can be learned from the stream.
```

## Accumulation changes the update, not the row

A **microbatch** is one batch processed in a forward/backward pass. Gradient accumulation combines several such passes before one optimizer update. With full, equally sized sequences:

```math
\text{input positions per update}=B\times L\times A\times D
```

A is the number of accumulated microbatches; D is the number of data-parallel workers. For B = 4, L = 8, A = 2 and D = 1, an update processes 64 input positions. Each sequence still has length 8. Accumulation does not let its tokens read the other microbatch.

Count actual supervised target tokens separately when padding or ignored labels are present. Equal token exposure, equal optimizer updates and equal elapsed time are different experiment budgets.

**Audit a real schedule:** Section 3.4 of [The Llama 3 Herd of Models](https://arxiv.org/abs/2407.21783) describes how Llama 3 405B changed its sequence length and tokens per step during pre-training. For each stage, divide tokens per step by sequence length to get the number of sequences per step. Note which stages change B, which change L and which change both, then decide which budget a comparison across two stages actually holds fixed.

#### Quick notes

- Batch size counts sequences; sequence length counts positions in each sequence. Ordinary causal attention stays within each batch row.
- The same 32 positions can form four length-8 rows or two length-16 rows. Token 8 can read token 7 only in the second layout.
- A causal row allows L(L + 1)/2 pairs. Count and implementation matter; pair counts alone do not measure total memory or runtime.
- Gradient accumulation accumulates gradients from microbatches before one optimizer update, without extending any sequence's context.
- B × L × accumulation × workers counts full input positions per update. Padding and ignored labels change the supervised-token count.
- Match the experiment's actual budget: tokens, optimizer updates and elapsed time are different controls.

### SwiGLU: two projections and a gate

Video: https://fanout.sh/ai/lessons/bonus-lessons-swiglu

A feed-forward block can make two different views of the same input, multiply them coordinate by coordinate, then turn the result back into an output vector. One view controls how strongly values from the other pass through.

**SwiGLU** uses this structure with a smooth function called SiLU on the controlling branch. The useful starting point is the multiplication. The word “gate” does not mean this branch contains probabilities.

## Two views of one input

For a bias-free block, use an input row x with d features and a hidden width h:

| Step | Calculation | Last dimension |
| --- | --- | --- |
| Controlling branch | SiLU(xW_gate) | h |
| Value branch | xW_up | h |
| Combine | Controlling values × value-branch values, elementwise | h |
| Project back | Combined row × W_down | d |

The two input matrices have shape d × h; the output matrix has shape h × d. Their values are learned separately. This differs from simply applying a new activation to every original input coordinate.

SiLU, also called Swish with parameter 1, is:

```math
\operatorname{SiLU}(a)=a\sigma(a),\qquad\sigma(a)=\frac{1}{1+e^{-a}}
```

At a = 1, the sigmoid is about 0.731, so SiLU is about 0.731. If the matching value-branch coordinate is 2, their product is about 1.462.

What happens to that product if the controlling input is −1 instead?

```answer
SiLU(−1) is approximately −0.269. Multiplying by 2 gives approximately −0.538. A SiLU gate can be negative; it is not constrained to the interval from zero to one.
```

## Inspect a complete tiny block

This PyTorch program uses chosen matrices so you can follow every coordinate. Install PyTorch using its [platform instructions](https://pytorch.org/get-started/locally/) if needed; the example runs on CPU.

```python title="swiglu_block.py"
import torch
from torch.nn import functional as F

x = torch.tensor([[1., 2.]])
w_gate = torch.tensor([[1., -1., 0.], [0., 0., 2.]])
w_up = torch.tensor([[2., 0., 1.], [0., 1., 0.]])
w_down = torch.tensor([[1., 0.], [0., 1.], [1., 1.]])
gate_input = x @ w_gate
up = x @ w_up
product = F.silu(gate_input) * up
output = product @ w_down
for name, value in [("gate input", gate_input), ("up", up),
                    ("product", product), ("output", output)]:
    print(name, [round(v, 4) for v in value[0].tolist()])
```

```text
gate input [1.0, -1.0, 4.0]
up [2.0, 2.0, 1.0]
product [1.4621, -0.5379, 3.9281]
output [5.3902, 3.3902]
```

The third product coordinate contributes to both output coordinates because the last row of W_down is [1, 1]. Follow that same path for a change: set the last entry of the first row of `w_up` from 1 to 0. Predict the product and output, then rerun.

```answer
The third up value becomes zero, so its product becomes zero even though its controlling input is still 4. The other products stay unchanged. The output becomes approximately [1.4621, −0.5379].
```

## What the comparison needs to control

This toy checks the mechanism, not training quality. A gated block has three projection matrices instead of the two in a simple ungated feed-forward block. At the same hidden width, their parameter counts differ.

In [GLU Variants Improve Transformer](https://arxiv.org/abs/2002.05202), read equations 5–6, then the paragraph that reduces hidden width to two-thirds for the gated comparison. Table 1 reports results for that study's settings. Those results support trying the block; they do not guarantee it beats ReLU or GELU on every task.

**Read real code:** In this pinned [SwiGLU implementation](https://github.com/SamsungSAILMontreal/TinyRecursiveModels/blob/c01103738605ba39d1430519b1ee0c62f4c707f8/models/layers.py#L151), find the split into `gate` and `up`, their multiplication, and the output projection. A combined input projection computes both branches at once; the two resulting halves still have the distinct jobs shown above.

#### Quick notes

- A bias-free SwiGLU block computes two projections, applies SiLU to one, multiplies coordinate by coordinate, then projects back.
- SiLU(a) = a × sigmoid(a). Its output can be negative or greater than one; the gate is not a probability.
- Input matrices have shape d × h, and the output matrix h × d. Zeroing a value-branch coordinate zeroes that product coordinate.
- Three projection matrices change the parameter budget. The original study reduced gated hidden width to make its comparison fairer.
- A tiny numerical block verifies the operation. Better training results require an actual controlled experiment.

### Tiny Recursive Model: repeated updates

Video: https://fanout.sh/ai/lessons/tiny-recursive-model-arc-agi

A small network can be used several times on the same problem. Each pass changes its working state, then the next pass uses that new state. The weights can stay the same throughout those passes.

The **Tiny Recursive Model**, or TRM, explores this approach for puzzle tasks. The first distinction to keep is simple: storing more learned numbers and performing more computation are different ways to enlarge a model's capacity to solve a task.

## Keep the question, revise the state

Use x for an embedded input, y for the current answer representation, and z for a working state. These are arrays of numbers. The answer representation is not yet a decoded answer, and the working state is not a readable explanation.

The same learned update network F serves both jobs:

| Operation | Update | What stays available |
| --- | --- | --- |
| Work on the current answer, repeated n times | z ← F(z + y + x) | Input x and current y |
| Revise the answer representation | y ← F(y + z) | The resulting work state z |

An output head reads y to produce answer scores. Extra rounds reuse F's parameters rather than creating new copies with independent weights. Whether the extra computation improves an answer must be measured.

## Count calls before thinking about benchmarks

Run this small Python model of the schedule. Its handpicked update halves a sum so the states remain easy to inspect. It is a scheduling example, not a trained TRM or a puzzle solver.

```python title="recursive_schedule.py"
x, y, z = 1.0, 0.0, 0.0
n = 2
rounds = 3
calls = 0
scale = 0.5

def update(value):
    global calls
    calls += 1
    return scale * value

for round_id in range(rounds):
    for _ in range(n):
        z = update(z + y + x)
    y = update(y + z)
    print("round", round_id + 1, "y:", round(y, 4), "calls:", calls)
print("stored scale values:", 1)
```

```text
round 1 y: 0.375 calls: 3
round 2 y: 0.7969 calls: 6
round 3 y: 1.2246 calls: 9
stored scale values: 1
```

The same `scale` is used in every call. It is manually set here; a real network has many learned parameters. Increasing `rounds` does not allocate another scale.

Change n from 2 to 4. Before running, predict the total calls and the number of stored scale values. Do you have enough evidence to say the answer is better?

```answer
There are 3 × (4 + 1) = 15 calls and still one scale value. Each round performs four work-state updates and one answer-state update. We have no target or quality measurement in this program, so larger y or more calls cannot establish an improvement.
```

## Read the training schedule separately

A training pass can compute a state without recording all operations for backpropagation. The published implementation does early recursion rounds under `no_grad`, records the final round, and detaches the carried states between supervision steps. A supervision step compares the predicted answer with a training target. Detaching keeps the state values but stops gradients from crossing back into the earlier computation. Repeated computation therefore does not imply one backward pass through every earlier update.

**Inspect the original method:** Read Figure 1 and Figure 3 of [Less is More: Recursive Reasoning with Tiny Networks](https://arxiv.org/abs/2510.04871). Then find `z_H`, `z_L` and `.detach()` in the pinned [inner implementation](https://github.com/SamsungSAILMontreal/TinyRecursiveModels/blob/c01103738605ba39d1430519b1ee0c62f4c707f8/models/recursive_reasoning/trm.py#L178). Map y to `z_H` and z to `z_L`. Notice that both updates call `self.L_level`.

The same file's outer wrapper has a learned early-halting branch guarded by `if self.training`. Evaluation in that implementation runs to the configured step limit. Do not assume that a training halt signal automatically saves inference steps.

## Read a result with its task attached

The paper reports strong task-specific results from small networks. Its best Sudoku result uses a 5M-parameter variant, while its 7M attention variant has different results. In the ARC comparison, some larger models score above TRM. This is not evidence that a 7M model generally beats trillion-parameter models.

**Check Table 5:** Pick one ARC column and compare TRM with the Grok-4 rows. Then read the evaluation and attempt-count labels before comparing another column. Parameter count, test-time computation, training data and the task all belong in the comparison. The interesting research question is what repeated use of a small learned update buys under a stated budget.

#### Quick notes

- TRM reuses one learned update network to change a work state z and an answer representation y while retaining the embedded input x.
- More update calls add computation without allocating independent copies of the network's parameters.
- With n work updates plus one answer update in each of T rounds, the schedule makes T(n + 1) network calls.
- Detaching keeps state values while stopping gradients from crossing into earlier computation. The training schedule records only selected rounds.
- In the cited implementation, learned early halting applies during training; evaluation runs to its configured limit.
- Results are task-specific. The strongest Sudoku variant has 5M parameters; ARC tables include larger models above TRM. Parameter count alone is not a complete comparison.

---
This representation contains public Fanout content only. Protected Pro lessons, account data, billing, checkout, and pricing are not included.

Browse the public content map: https://fanout.sh/sitemap.md
