I've been digging into the MiniMind open-source project. It trains a 64M-parameter model from 0 to 1 for 3 yuan in 2 hours.

That sounds approachable, but once I actually looked into it, I realized every step is math and Python.

I record what I learn in the stickers and articles for "Learn AI by Coding" (码上学 AI), hoping to help people who want to understand how AI works but keep getting stopped by math and Python.

  • Posts numbered 001: 600 to 800 words each, notes from daily learning, simple but not systematic.
  • Posts numbered 101: 3,000 to 5,000 words each, periodic long reads, systematic but time-consuming.

1. Starting With a Photo-Editing Relay: Why Normalization?

Start with an example. Imagine a line of people passing a photo along. Each person brightens it a little before handing it off. By the end, it's easy to end up with an overexposed, washed-out image that's unusable.

A common fix: after each person edits, pull the exposure back to a normal range, then pass it on. The next person does the same when they finish. Round after round, you still end up with a usable photo.

Large neural networks work the same way. They stack hundreds or thousands of layers, and every time data passes through a layer, its scale and distribution can shift: some values become huge, some become tiny. Once they leave the usable range, further training gets hard.

So after each layer, a large model also needs a step like "pull the exposure back to normal." That's normalization.


2. Normalization: Putting Different "Rulers" on the Same Scale

Normalization does one simple thing: take data at different scales and rescale it into a suitable range using the same rule.

How exactly? Two common methods: LayerNorm and RMSNorm.

The earliest Transformers used LayerNorm. Today's large models mostly use RMSNorm because it's cheaper and simpler to compute. MiniMind, LLaMA, DeepSeek, and Qwen all use RMSNorm.

This article only covers RMSNorm. How LayerNorm was gradually replaced is a separate story.


3. Root Mean Square: How Do You Measure the Overall Size of a Set of Numbers?

RMS stands for root mean square. Before the math, let's look at the problem it solves.

The question is this: given a set of numbers, how do you measure how big they are overall?

The most direct answer is the average. For 3, 4, 5, the average is 4.

But that assumes the values point in the same direction. Otherwise the average loses its meaning.

Take another set: -3, 0, 3. The average is 0. That 0 makes it look like there's nothing in the set. It only says the set is balanced; it says nothing about the swing from -3 to 3.

Physics makes the awkwardness obvious.

Take the AC power in your home. Voltage swings between positive and negative. Its true average is 0. Yet we all know voltage carries energy and can hurt you. (By the way, the "220 volts" we quote is the RMS voltage, not the average.)

So ask a different question: if you want to measure how much "energy" a set of numbers carries, what tool do you use?

The answer is root mean square.

Run -3, 0, 3 through it:

  1. Square: square each number. -3 becomes 9, 0 stays 0, 3 becomes 9.
  2. Average: add the squares and divide by the count, .
  3. Square root: take the square root of 6, which is about 2.45.

Why square first? In physics, energy tends to scale with the square. Power, for example, is proportional to voltage squared.

Why take the square root at the end? Squaring changes the unit: volts become volts squared. To return to the original scale, we undo the square.

For -3, 0, 3, the average is 0 and the RMS is 2.45. The average says "it's balanced." The RMS says "it carries energy."

Try 3, 4, 5:

  1. Squares: 9, 16, 25.
  2. Average: .
  3. Square root: .

The result is 4.08, close to the set's average of 4, because all values are positive and point the same way. That 4.08 is the RMS.

As a formula:

Read the formula from the inside out:

  • square each ;
  • sum them from 1 to with ;
  • divide by , which is the average;
  • take the square root to return to the original scale.

4. From RMS to RMSNorm: Scaling and a Learnable Parameter

Once you have RMS, you can use it as a "standard ruler": divide every number by the set's RMS, and the overall scale lands near 1.

This is the photo relay from the beginning: pull brightness back into a standard range, and the image won't be overexposed or too dark to use.

Scaling alone isn't enough. Dividing by RMS applies a fixed ratio; the model can't adjust it. So multiply by a learnable parameter (Gamma) and let the model learn the right amount of scaling during training. That's RMSNorm.

In practice, add a tiny positive number (for example, ) inside the square root to prevent division by zero:

Putting it together, for the -th element:

Where:

  • : the -th element of the input vector;
  • : the vector dimension (the from the previous section);
  • : a tiny positive number that prevents division by zero;
  • : a learnable scaling parameter, learned during training.

In plain English:

Each number is divided by the group's overall level (RMS), then multiplied by a coefficient the model learned.

Dividing by RMS evens out the scale. Multiplying by hands the decision of whether to scale, and by how much, back to the model.


5. Code Walkthrough: MiniMind's First Function

That's the theory. Here's the code that actually runs. This is the full RMSNorm implementation in MiniMind:

class RMSNorm(torch.nn.Module):
    def __init__(self, dim: int, eps: float = 1e-5):
        super().__init__()
        self.eps = eps
        self.weight = nn.Parameter(torch.ones(dim))

    def norm(self, x):
        return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)

    def forward(self, x):
        return (self.weight * self.norm(x.float())).type_as(x)

We'll take it in three parts.

1. Initialization: __init__

Initialization does three things:

  • take the dimension of the input vector, dim;
  • store a tiny number, eps, to prevent division by zero during computation; this is the in the formula;
  • create a learnable parameter, weight, initialized to a vector of all ones; this is the in the formula.

weight has the same dimension as the last dimension of the input vector. Starting from all ones means "output as-is at first, with no extra scaling." Training keeps updating it.

2. Normalization: norm()

This is the core of RMSNorm:

x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)

Read it from the inside out:

  • x.pow(2): square each element;
  • .mean(-1, keepdim=True): average along the last dimension to get the mean square;
  • + self.eps: add a tiny number to avoid a zero denominator;
  • torch.rsqrt(...): the reciprocal square root, that is, ;
  • x * ...: multiplication performs "divide by the RMS."

The corresponding math is:

Two details that are easy to miss:

  • Why use rsqrt instead of taking a square root and then dividing? Dividing by a number is the same as multiplying by its reciprocal. One rsqrt plus one multiplication saves compute compared with a square root and a division. It's a small engineering optimization.
  • What is keepdim=True for? After averaging, if the dimension is dropped, the result can no longer align elementwise with the original tensor. Keeping it (the shape goes from [B, T, D] to [B, T, 1]) lets each position divide by the RMS of its own segment. That's what broadcasting is for.

3. Forward Pass: forward()

return (self.weight * self.norm(x.float())).type_as(x)

forward() is the actual entry point when the model calls RMSNorm. It does four things in order:

  1. Cast the input to float32: improve numerical precision. Training often uses bf16 or fp16, whose range is small; squaring can lose precision or overflow. Raising precision first and computing in float32 is more stable.
  2. Call self.norm(...): perform the normalization.
  3. Multiply by the learnable weight self.weight: let the model adjust the normalized result.
  4. .type_as(x): cast the result back to the input's dtype, so later layers don't have to change type. This balances precision and speed.

6. Summary

RMSNorm in one sentence: convert numbers at different scales onto the same ruler, then let the model fine-tune them.

Next up is RoPE (rotary position embedding): the intuition, the formula, and the code.