Pidoku

Neural Networks from Scratch

Module 10 Lesson 10.d 1h 30m Difficulty 2/5

Prerequisites 10.a, 10.b, 10.c


Before you start: five words#

WordPlain meaning
LayerOne step of the network: usually a matrix multiplication followed by a simple function.
WeightA number in a layer’s matrix, chosen by training.
BiasAn extra learned number added to each output of a layer. Many current models leave it out.
Activation functionA simple function applied to every number on its own, such as “replace negatives with 0”. It is what makes the network more than one big matrix (10.e).
Hidden size (d)How many numbers represent each token inside the network — 4,096 in an 8B-class model.

1. What is it?#

A neural network is a stack of linear steps (matrix multiplications) alternating with non-linear steps (activation functions):

x → [linear] → [non-linear] → [linear] → [non-linear] → ... → y

That is the entire structure. Everything else in a transformer — attention, normalisation, mixture-of-experts — is a variation on “linear step, then non-linear step, repeated”.


2. Why does it exist?#

The linear steps do the learning; the non-linear steps make depth worth having.

Without non-linearity, stacking layers is pointless, because two matrix multiplications are just one matrix multiplication:

W₂(W₁x) = (W₂W₁)x = Wx

A hundred linear layers collapse into one. Depth buys nothing.

Put a non-linear function between them and the collapse is impossible:

W₂ · relu(W₁x)   cannot be written as a single matrix multiply

Now depth composes: each layer can build new features out of the previous layer’s features. That is the whole reason “deep” learning is deep.


3. Simple analogy#

An assembly line of specialists.

Station 1 turns raw material into simple parts (edges in a vision model; common letter patterns in a language model). Station 2 combines simple parts into sub-assemblies. Station 3 combines those into components. By the last station you have something complex built from many layers of simple combinations.

The non-linearity is each station’s “is this part worth passing on?” decision. Without it every station just rescales the raw material, and you might as well have one station.


4. Tiny example#

A complete two-layer network that computes XOR (“exactly one of the two inputs is 1”) — the classic proof that non-linearity matters:

Go
package main

import "fmt"

// XOR is not linearly separable: no single layer can compute it.
// These hand-set weights solve it with one hidden layer.
var (
	W1 = [2][2]float32{{1, 1}, {1, 1}} // (2, 2)
	b1 = [2]float32{0, -1}
	W2 = [2]float32{1, -2} // (2,)
	b2 = float32(0)
)

func forward(x [2]float32) float32 {
	var h [2]float32
	for i := range h {
		h[i] = max(0, W1[i][0]*x[0]+W1[i][1]*x[1]+b1[i]) // ReLU
	}
	return W2[0]*h[0] + W2[1]*h[1] + b2
}

func main() {
	X := [][2]float32{{0, 0}, {0, 1}, {1, 0}, {1, 1}}
	y := []float32{0, 1, 1, 0}
	for i, x := range X {
		fmt.Println(x, "→", forward(x), "target", y[i])
	}
	// [0 0] → 0   [0 1] → 1   [1 0] → 1   [1 1] → 0
}

Trace the hardest input, [1, 1], by hand:

hidden 0: relu(1·1 + 1·1 + 0)  = relu(2) = 2
hidden 1: relu(1·1 + 1·1 - 1)  = relu(1) = 1
output:   1·2 + (-2)·1 + 0     = 0          ✓ XOR(1,1) = 0

Now delete the ReLU (h = W1·x + b1) and try to find any weights that solve XOR. You cannot — it is a theorem (exercise A). That is the non-linearity earning its place.


5. Technical explanation#

The building blocks of a transformer#

You need only five:

1. Linear (fully connected)

y = x @ W.T + b        # W: (out, in), b: (out,)

Parameters: out × in (plus out if there is a bias). Almost all of a model’s parameters live here.

2. Activation — applied to each number separately, no parameters (10.e).

3. Normalisation — keeps the size of the numbers stable from layer to layer, so they neither blow up nor shrink towards zero (11.e goes deeper):

Go
// LayerNorm: normalize over the feature dimension
func layerNorm(x, gamma, beta []float32) []float32 {
	var mean, variance float32
	for _, v := range x {
		mean += v
	}
	mean /= float32(len(x))
	for _, v := range x {
		variance += (v - mean) * (v - mean)
	}
	variance /= float32(len(x))
	inv := 1 / float32(math.Sqrt(float64(variance)+1e-6))
	y := make([]float32, len(x))
	for i, v := range x {
		y[i] = (v-mean)*inv*gamma[i] + beta[i] // gamma, beta learned, shape (d,)
	}
	return y
}

// RMSNorm (used by Llama, most modern LLMs): cheaper, no mean subtraction
func rmsNorm(x, gamma []float32) []float32 {
	var sumSq float32
	for _, v := range x {
		sumSq += v * v
	}
	inv := 1 / float32(math.Sqrt(float64(sumSq/float32(len(x)))+1e-6))
	y := make([]float32, len(x))
	for i, v := range x {
		y[i] = v * inv * gamma[i] // gamma learned, no beta
	}
	return y
}

A worked RMSNorm on x = [3, 4] with gamma = [1, 1]: the mean of the squares is (9 + 16) / 2 = 12.5, its square root is about 3.54, so the output is [0.85, 1.13]. The vector keeps its direction but now has a typical size of about 1.

RMSNorm drops LayerNorm’s mean subtraction and bias: fewer operations, fewer parameters, and in practice no worse. Nearly every current open model (Llama, Qwen, DeepSeek, Mistral, Gemma) uses it. It saves passes over the data, and with two norms per layer and dozens of layers, for an operation limited by memory bandwidth, the saving is real. Some recent models (Qwen3, OLMo 2, Gemma 3) also apply an RMSNorm to the query and key vectors inside attention (“QK-norm”) for training stability.

4. Residual connection

x = x + sublayer(x)

It adds the layer’s output back onto its input. It has no parameters but an enormous effect: during training, gradients flow straight through the addition, and at inference it means a residual stream carries information through the whole network while each layer adds a correction. Thinking of a language model as “a residual stream that layers read from and write to” is a genuinely useful mental model.

5. Embedding — a lookup table from token ID to vector (10.f).

A complete feed-forward block#

The feed-forward network (FFN, also called the MLP) is the part of each layer that works on each token separately. Current models use the SwiGLU form:

Go
// SwiGLU, as used in Llama/Mistral/Qwen. x is one token's vector, shape (d,).
func mlpBlock(x []float32, Wgate, Wup, Wdown Mat) []float32 {
	gate := Wgate.Apply(x) // (d_ff,)
	up := Wup.Apply(x)     // (d_ff,)
	for i, g := range gate {
		silu := g / (1 + float32(math.Exp(float64(-g)))) // SiLU/Swish: g * sigmoid(g)
		gate[i] = silu * up[i]
	}
	return Wdown.Apply(gate) // (d,)
}

Three matrix multiplications, one elementwise multiply and one sigmoid. In a dense model this block holds about two-thirds of the parameters and does most of the FLOPs.

Why three matrices instead of the classic two? The “gate” (one projection, passed through SiLU, multiplying another projection elementwise) works better per parameter. To keep the parameter count similar to a classic two-matrix FFN with d_ff = 4d, SwiGLU models use d_ff ≈ 8d/3 or a nearby multiple of 256 (11,008 for d = 4,096 in Llama 2 7B; Llama 3 8B uses 14,336).

Mixture-of-experts (MoE) models replace this single block with many smaller copies (“experts”) and a router that sends each token to a few of them (14.g). Each expert is still a SwiGLU block like the one above.

Counting parameters#

Linear(in, out):     in × out (+ out if bias)
LayerNorm(d):        2d
RMSNorm(d):          d
Embedding(V, d):     V × d

Per transformer layer (Llama-style, with grouped-query attention — fewer K/V heads than query heads, 12.g):

q_proj: d × d
k_proj: d × d_kv          where d_kv = n_kv_heads × head_dim
v_proj: d × d_kv
o_proj: d × d
gate:   d × d_ff
up:     d × d_ff
down:   d_ff × d
2 RMSNorms: 2d

Try the formula on a model you know (exercise C). It is the fastest way to learn an architecture.


6. Under the hood#

What one layer costs at inference, for one token, using the Llama 3 8B sizes:

d = 4096, d_ff = 14336, d_kv = 1024 (8 KV heads × 128)

FLOPs (2 × parameters used):
  q_proj    2 · 4096 · 4096  =  33.6 M
  k_proj    2 · 4096 · 1024  =   8.4 M
  v_proj    2 · 4096 · 1024  =   8.4 M
  o_proj    2 · 4096 · 4096  =  33.6 M
  gate      2 · 4096 · 14336 = 117.4 M
  up        2 · 4096 · 14336 = 117.4 M
  down      2 · 14336 · 4096 = 117.4 M
  ────────────────────────────────────
  total                       436 M FLOPs per token per layer
  × 32 layers                = 14 GFLOPs      (+ ~1 GFLOP for the output layer ≈ 2 × 8B)
  attention over the KV cache + 4 · layers · S · d   (grows with context length S, 12.f)

Norms, activations, residual adds: ~0.1% of FLOPs, but each reads and writes the
whole activation tensor → a much larger share of MEMORY traffic.

That last line is why kernel fusion matters (11.h): norms and elementwise operations are trivial in FLOPs but expensive in bandwidth, so merging them into their neighbours is nearly free performance.


7. Performance implications#

  • Matmuls dominate FLOPs (over 95%), yet norms, activations and residual adds can take 10–25% of the time in an unfused implementation, because they are memory-bound.
  • RMSNorm instead of LayerNorm saves a pass over the data.
  • The residual add is a separate kernel unless fused. Fusing “add residual + RMSNorm” into one kernel is a standard optimisation (13.j).
  • The gate and up projections can be merged by concatenating their weights, turning two matmuls into one larger, more efficient one.

8. Production implications#

  • You will read model code constantly. Looking at modeling_llama.py and immediately seeing “7 linears, 2 norms, 2 residual adds per layer” is the baseline skill.
  • Architecture details change serving. GQA and MLA change the KV-cache size (12.g); SwiGLU changes FFN shapes; MoE changes memory versus compute (14.g); RoPE (10.i) changes what is cached.
  • Engines fuse weights at load time (gate + up, and q + k + v) to make the matmuls bigger and more efficient.

9. Common mistakes#

Thinking the non-linearity is a minor detail. Without it there is no network.

Confusing LayerNorm and RMSNorm. Different parameter counts and kernels; using the wrong one silently damages quality.

Assuming d_ff = 4d. SwiGLU models use about 8d/3, and MoE experts are smaller still. Getting this wrong ruins a parameter-count estimate.

Ignoring the memory cost of “cheap” operations. A residual add does 1 FLOP per element but moves 12 bytes per element at 32-bit precision (two reads, one write).

Assuming bias terms exist. Most current language models leave them out of linear layers.


10. Hands-on exercise#

A. XOR by hand. Check the network in section 4 on paper for all four inputs. Then show that no single linear layer w₁x₁ + w₂x₂ + b can match XOR. (Hint: write the four inequalities a threshold at 0.5 would need, and add the two for [0,1] and [1,0].)

B. A transformer feed-forward half-layer. Implement rmsNorm, silu, the SwiGLU block and a residual add, in any language. No attention yet. Check every shape.

C. Count Llama 3 8B. With d = 4,096, d_ff = 14,336, 32 layers, 32 query heads, 8 KV heads, head_dim 128 and V = 128,256, compute the parameter count with the formulas in section 5. Compare with the published 8.03B. (Hint: the input embedding and the output layer are separate matrices in this model.)

D. Where does the time go? Profile one transformer layer in PyTorch. What fraction of the time is matmuls, norms and elementwise operations? Compare with the FLOP fractions and explain the gap.

E. A fusion win. Implement RMSNorm as (i) separate PyTorch operations and (ii) the same code under torch.compile. Measure the difference.


11. Interview questions#

  1. Why do neural networks need non-linearities? Prove it.
  2. What is the difference between LayerNorm and RMSNorm, and why do current LLMs prefer RMSNorm?
  3. Write out a SwiGLU feed-forward block and explain why d_ff ≈ 8d/3.
  4. What fraction of a dense transformer’s parameters sit in the feed-forward blocks? Why does that matter for quantization and for MoE?
  5. Why do norms and residual adds take a larger share of time than of FLOPs?
  6. What is the residual stream, and why is it a useful mental model?

12. Further reading#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in