← herq.net PL
EDUCATIONAL MATERIAL
v.2 · 2026
level: intermediate
Anatomy of a neural network

How is a
language model built?

From a single neuron, through weights and activation functions, all the way to the attention mechanism and fine-tuning with LoRA. Short, with math and interactive diagrams.

// 01

The single neuron - the building block of everything

An entire neural network is made of millions of copies of one very simple element. An artificial neuron takes a few input numbers x, multiplies each by its assigned weight w, sums the results, adds a bias b (an offset), and finally passes the result through an activation function f.

x₁ x₂ x₃ w₁ w₂ w₃ Σ + b f y weighted sum activation
Fig. 1 - Information flow in a single neuron: inputs → weights → sum → activation → output.

Mathematically, the whole neuron is a single equation. First we compute the weighted sum z, then we pass it through the function:

the neuron equation
$$ z = \sum_{i=1}^{n} w_i x_i + b \qquad\Longrightarrow\qquad y = f(z) = f\!\left(\mathbf{w}\cdot\mathbf{x} + b\right) $$

The notation w·x is the dot product - the same as the sum w₁x₁ + w₂x₂ + …, just shorter. The weight tells the neuron how important a given input is (large positive = amplifies, negative = suppresses), and the bias shifts the firing threshold.

Lab · compute a neuron yourself
1.0
0.5
0.8
-1.2
0.2
// 02

Activation functions - the source of nonlinearity

If neurons only summed and multiplied, the entire network - even with a thousand layers - would be equivalent to a single matrix multiplication, i.e. a straight line. The activation function introduces nonlinearity, which lets the network model complex, curved relationships (language, images, logic).

Interactive function plot
FunctionFormulaRangeWhere it's used
ReLUmax(0, z)[0, ∞)hidden layers (classic, fast)
Sigmoid1/(1+e⁻ᶻ)(0, 1)probability, gates
tanh(eᶻ−e⁻ᶻ)/(eᶻ+e⁻ᶻ)(−1, 1)recurrent networks
GELUz·Φ(z)≈[−0.17, ∞)modern Transformers (GPT, BERT)
Why it mattersGELU (and similar ones, like SwiGLU) dominate today's LLMs because they are "smooth" - they have a defined derivative everywhere, which makes gradient-descent training easier. ReLU is simpler and cheaper, but it has a "dead" range for z < 0.
// 03

From neuron to layer to network

A single neuron is weak. Power only comes from arranging them into layers and connecting layers into a network. The outputs of one layer become the inputs of the next. The signal flows from left (input) to right (output) - this is the so-called forward pass.

Fig. 2 - A fully connected network (hover over a neuron to highlight its connections). Each edge is one weight.

Instead of computing each neuron separately, we write the whole layer as a single matrix multiplication. If a layer has a weight matrix W and a bias vector b, then:

a layer as matrix multiplication
$$ \mathbf{h} = f\!\left(W\mathbf{x} + \mathbf{b}\right) $$

This is why LLM training happens on graphics cards (GPUs) - they are designed for lightning-fast multiplication of huge matrices. All of the model's "intelligence" sits in the numbers inside these matrices W.

IntuitionEach successive layer builds increasingly abstract concepts: the first layers catch simple patterns (e.g. word endings), deeper ones - syntax, and the deepest ones - meaning and context.
// 04

Parameters and weights - what "7 billion" means

When you hear "the model has 7B (7 billion) parameters", it refers precisely to the number of all weights and biases in the network. These are the numbers the model "learns" during training, gradually correcting them so its predictions get better and better.

parameter count of a single linear layer
$$ \#\text{param} = \underbrace{n_{\text{in}} \times n_{\text{out}}}_{\text{weights } W} \; + \; \underbrace{n_{\text{out}}}_{\text{biases } b} $$

Example: a layer taking 1000 inputs and producing 1000 outputs already has 1,000,000 + 1000 ≈ a million parameters. An LLM has hundreds of such layers - hence the billions.

Training = searching for the best numbers

Weights are not set by hand. The model starts with random numbers and improves them in a loop:

1. Prediction forward pass 2. Error loss 3. Gradient backprop 4. Weight update w ← w − η·∇ repeat billions of times
Fig. 3 - The training loop. "η" (eta) is the learning rate, "∇" is the gradient - the direction of steepest decrease in error.
The key training formulaThe weight update is w ← w − η · ∂L/∂w: we nudge each weight slightly in the direction that reduces the error L. Repeated trillions of times, this yields a model that "understands" language.

The learning curve - how loss falls over time

Every training step nudges the weights and usually lowers the loss a little. How fast (and whether) the loss falls depends on the learning rate η. Play with the slider to see three regimes: too slow, just right, and divergent.

Lab · learning rate vs convergence
0.150

How much data? The Chinchilla scaling law

Given a fixed compute budget, how many parameters versus how many training tokens should you pick? The Chinchilla paper (DeepMind, 2022) showed the sweet spot is about 20 tokens per parameter - earlier models were often undertrained.

Lab · scaling law
1 B
20
// 05

Tokens and embeddings - how text becomes numbers

The network doesn't understand letters. Text is first split into tokens (chunks of words), and each token is turned into a vector of numbers - an embedding. These are the "coordinates" of a word in a high-dimensional space of meaning.

"Cat sleeps on mat" Cat sleeps on mat each token → vector [ 0.21, −0.84, 0.07, … , 0.55 ] token embedding (e.g. 4096 numbers)
Fig. 4 - From sentence to vectors. Words with similar meaning have similar embeddings.

The beauty of embeddings is that geometry carries meaning. The words "cat" and "dog" lie close together; relationships are vectors too - the classic example:

the arithmetic of meaning
$$ \vec{\text{king}} - \vec{\text{man}} + \vec{\text{woman}} \;\approx\; \vec{\text{queen}} $$

See tokenization live

Type any text and watch how it would split into tokens. Common words stay whole; rarer and longer ones break into pieces (## marks a word continuation). This split is illustrative - real tokenizers (BPE) learn their merges from a dataset.

Lab · subword tokenizer

Meaning arithmetic - compute an analogy

Since words are vectors, you can add and subtract them. Pick three words and see which word the result lands closest to. (A toy 2D space: the horizontal axis ~ gender, the vertical axis ~ status. Real embeddings have thousands of dimensions, and such analogies can be unreliable.)

Lab · king − man + woman
+≈ ?
// 06

The attention mechanism - the heart of the Transformer

This is the breakthrough that made today's LLMs possible. Attention lets every word "look around" the entire sentence and decide which other words matter most to it. In the sentence "The cat didn't eat the fish because it was spoiled" - attention links "it" to "fish", not to "cat".

Three roles: Query, Key, Value

From each token's embedding, the model creates three vectors by multiplying it by three learned matrices:

Matching the Query against each Key (dot product) gives a score; after scaling and passing through softmax we get attention weights that sum to 1. The result is a weighted sum of the values V:

scaled dot-product attention
$$ \text{Attention}(Q,K,V) = \text{softmax}\!\left(\frac{Q K^{\top}}{\sqrt{d_k}}\right) V $$

Dividing by √dₖ (the square root of the dimension) stabilizes the values so that softmax doesn't "saturate" at large numbers. Softmax turns raw scores into attention percentages.

Attention visualization · pick a query word (Query)

↑ The values are illustrative. The darker/longer the bar, the more "attention" the selected word devotes to a given word in the sentence.

The whole attention matrix at once - a heatmap

The bars above show a single row of this matrix. Here you see all of it: each row is a query word, each column a key word, and a cell's brightness says how much attention the former pays the latter. This visualizes the matrix softmax(QKᵀ/√d) - the same one we computed above.

Attention heatmap · hover a cell

↑ The numbers are the percentage of attention (each row sums to 100%). Notice the bright cell "it/spoiled → fish" - exactly the link the attention mechanism captures.

Multiple attention heads (Multi-Head)

A single attention "head" looks at one type of relationship. The model runs dozens of them in parallel - one tracks grammar, another references, another style - and their results are combined. Hence the name multi-head attention.

input head 1 · syntax head 2 · references head 3 · … concat output
Fig. 5 - Multiple attention heads work in parallel, and their outputs are concatenated and mixed.
// 07

The Transformer block - everything together

An LLM is a stack of many identical Transformer blocks (e.g. 32, 80, or even over 100). Each block has two main parts: an attention layer and an ordinary feed-forward network (FFN). They are held together by two tricks that make training very deep networks possible:

residual connection input (embeddings) LayerNorm Multi-Head Attention softmax(QKᵀ/√d)·V + LayerNorm Feed-forward network (FFN) Linear → GELU → Linear + output → next block
Fig. 6 - One Transformer block. An LLM is dozens of such blocks stacked on top of one another.

At the very end of the stack, the final layer turns the vectors back into probabilities for the next token - and it's from these that the next word of the answer is "sampled".

How is the next word chosen? Temperature and top-p

The final layer yields a probability distribution over all tokens. How we sample from it is set by two knobs: temperature (sharpens or flattens the distribution) and top-p (cuts off the tail of unlikely words). Play with them:

Lab · next-token sampling
0.70
1.00

↑ Grey bars show the full post-temperature distribution; red ones are the tokens that survived the top-p cut and that the model actually samples from (✕ = cut).

// 08

LoRA - cheap fine-tuning of large models

Full fine-tuning of a 70B model means updating all 70 billion parameters - this requires huge graphics cards and a lot of money. LoRA (Low-Rank Adaptation) is a clever trick: we freeze the original weights and train only a tiny "add-on".

The key observation

The weight change needed to specialize a model is "low-rank" - it can be written as the product of two thin matrices. Instead of training the whole large update matrix ΔW (with dimensions d×d), we train only two skinny matrices A and B:

low-rank decomposition
$$ W' = W_0 + \Delta W = W_0 + \frac{\alpha}{r}\,B A,\qquad B\in\mathbb{R}^{d\times r},\; A\in\mathbb{R}^{r\times d},\; r \ll d $$

Where r is the rank (e.g. 8 or 16) - the bottleneck that determines the number of new parameters, and α is the scale of the adapter's influence. W₀ stays untouched.

W₀ d × d (frozen) ❄ not trained + B d × r A r × d ▲ we only train this (r ≪ d) = W′ specialized model The product B·A reconstructs the full-size update ΔW, but with drastically fewer parameters.
Fig. 7 - LoRA adds to the frozen matrix W₀ an update built from two thin matrices B and A.

How many parameters do we save?

Let's compare the full update with LoRA for a matrix d = 4096 and rank r = 8:

ApproachParameter-count formulaResult (d=4096, r=8)
Full fine-tuning (ΔW)d × d≈ 16,800,000
LoRA (B + A)d × r + r × d = 2·d·r≈ 65,500
Savingsd / (2r)~256× less
Why it's a breakthroughLoRA lets you fine-tune a large model on a single GPU, and the resulting adapter weighs megabytes instead of gigabytes. You can keep many adapters (one for a "legal style", another for "customer support") and attach them to the same base model on demand.

The flow in brief

  1. We take a ready-made base model and freeze all weights W₀.
  2. To selected layers (usually the Q and V matrices in attention) we add a pair A, B starting from zero.
  3. We train only A and B on our data - a fraction of the cost.
  4. Finally, the result B·A can be merged into W₀ (zero overhead at runtime) or kept separately as a swappable adapter.
what happens to the activation
$$ \mathbf{h} = W_0\mathbf{x} + \frac{\alpha}{r}\,B(A\mathbf{x}) $$

The token x passes through the frozen main path W₀x and through the cheap LoRA "side track" - and the results are summed. That's all.

Play with the rank r

The rank r is LoRA's one real knob: the smaller it is, the fewer new parameters (and the cheaper), but the less "capacity" for new knowledge. See how r translates into the number of trained parameters (the bar scale is logarithmic):

Lab · rank vs savings
8