Leonardo Castro

9 math concepts to understand how LLMs really work

Vectors, matrices, embeddings, attention, probability, softmax, loss, gradients and optimization: the path from a prompt to the next word, worked out by hand.

By Leonardo CastroPublished on 25 min read
  • LLMs
  • Math
  • Transformers
  • Deep Learning
  • Probability

You type “The patient was referred to the” and the model completes it with “doctor”. In between, the text was split into tokens, each token became a list of numbers, those lists went through a long sequence of matrix multiplications, got mixed with one another through attention and, at the end, turned into a probability distribution over the entire vocabulary. One token was sampled from that distribution, and the whole process started again for the next word.

These are nine concepts from introductory courses, and they matter even if you only use LLMs through an API: decisions such as using the probability as a score, trusting an attention map, choosing the temperature or understanding why a model that did well on a benchmark does poorly on your data all depend on them. The patient sentence comes back in Part II, when the model picks the next word, and in Part III, in training, when “doctor” was the expected answer and the model got it wrong.

Animated grid of the nine concepts: vectors, matrices, embeddings, dot product, probability, softmax, loss function, gradients and optimization, each with a mini chart, a formula and a short caption.
The map of the article: the three rows of the grid are the three parts of the text, from representation to answer to training.

The numbers in the examples and figures are illustrative, chosen so the arithmetic fits on one line. The real-model numbers cited throughout the text come from the references.

Part I: how the model represents text

1. Vectors

A vector is a sequence of dd numbers, x=(x1,x2,…,xd)∈Rdx = (x_1, x_2, \dots, x_d) \in \mathbb{R}^d. In an LLM, every input token becomes a vector like this, and everything else operates on these vectors. The value of dd is an architectural choice: in the original Transformer, all sub-layers and embeddings produce vectors of dimension dmodel=512d_{\text{model}} = 512 in the base model and 1024 in the big model (Vaswani et al., 2017).

The simplest operation between vectors is addition, coordinate by coordinate. With v=(1.9, 0.9)v = (1.9,\ 0.9) and w=(0.6, 2.4)w = (0.6,\ 2.4), we get v+w=(2.5, 3.3)v + w = (2.5,\ 3.3). The length of that vector, its norm, comes from the Pythagorean theorem:

∥v+w∥=2.52+3.32=6.25+10.89=17.14≈4.14\lVert v + w \rVert = \sqrt{2.5^2 + 3.3^2} = \sqrt{6.25 + 10.89} = \sqrt{17.14} \approx 4.14

Vectors v (blue) and w (pink) start at the origin and form a parallelogram; the black diagonal v + w has norm 4.14. Below, the formula x = (x₁, …, x_d) ∈ ℝ^d.
Two dimensions so we can see addition and the norm. An LLM has hundreds or thousands, and the same operations apply.

In 512 dimensions, it is tempting to imagine that coordinate 37 stores “gender” and coordinate 211 stores “verb tense”. A single dimension does not have to correspond to any interpretable feature; meaning lies in the set of values as a whole and in where the vector sits relative to the others. Word embeddings already captured many syntactic and semantic relationships between words without any coordinate carrying a label (Mikolov et al., 2013).

2. Matrices

Vectors hold the representation; matrices transform it. A linear layer takes a vector xx and returns another one:

y=Wx+b,W∈Rm×ny = Wx + b, \qquad W \in \mathbb{R}^{m \times n}

WW is a matrix of learned parameters, bb a bias vector and yy the new representation, which may have a different dimension. Almost all of a Transformer’s heavy lifting is of this kind: the query, key and value projections in attention are matrix multiplications, and the feed-forward block in each layer is made of two linear transformations with a nonlinearity in between. In the original base model, the inner layer of that block has dimension 2048 (four times dmodeld_{\text{model}}) and the nonlinearity is ReLU (Vaswani et al., 2017).

The figure shows what a matrix does to the plane. In the first frame, it is a 40° rotation:

W=(0.77−0.640.640.77),det⁡W=0.77⋅0.77−(−0.64)⋅0.64≈1.00W = \begin{pmatrix} 0.77 & -0.64 \\ 0.64 & 0.77 \end{pmatrix}, \qquad \det W = 0.77 \cdot 0.77 - (-0.64) \cdot 0.64 \approx 1.00

The determinant tells you how much the transformation scales areas. With a determinant of 1, area doesn’t change: in the first frame the matrix only rotates the circle; as the animation runs, it also stretches one axis and squeezes the other, and the circle becomes an ellipse with the same area.

A unit circle with vector x is transformed by matrix W: it rotates and stretches into an ellipse with the same area, and x becomes Wx. The matrix W is shown alongside and det W = 1.00 throughout.
A matrix rotates, stretches and squeezes space. Stack several of them with nothing in between and you still get a single transformation of this kind.

The nonlinearity is what keeps the model from collapsing. Applying W1W_1 and then W2W_2 gives W2(W1x+b1)+b2W_2(W_1 x + b_1) + b_2, which is still a single transformation of the same kind, W′x+b′W'x + b'. ReLU or GELU, applied element-wise between layers, break that equivalence and let the network learn relationships that no linear transformation can represent (Goodfellow, Bengio & Courville, 2016). GELU is defined as xΦ(x)x\Phi(x), where Φ\Phi is the cumulative distribution function of the standard normal (Hendrycks & Gimpel, 2016); LLaMA replaces ReLU with SwiGLU (Touvron et al., 2023).

3. Embeddings

We still need to say where each token’s first vector comes from. The model’s vocabulary VV is a fixed list of tokens, and each token has an index. The embedding matrix EE has one row per token, and the initial vector is just the corresponding row:

ei=E[i],E∈R∣V∣×de_i = E[i], \qquad E \in \mathbb{R}^{|V| \times d}
eie_i
Initial vector of the token with index i
EE
Embedding matrix, learned during training
∣V∣|V|
Vocabulary size
dd
Dimension of the model's vectors
The input embedding is a table lookup.

That lookup ignores context: “cancellation” always gets the same initial vector. Context comes in layer by layer, as attention mixes each token’s vector with those of its neighbors. In a toy example, by the last layer “cancellation” in “subscription cancellation” sits close to vectors related to customer churn, and in “payment cancellation”, close to vectors for financial transactions.

Two point clouds, “customer churn” (pink) and “financial transaction” (blue). A star starts at the initial vector E[i] for “cancellation” and moves to the churn cloud (“subscription cancellation”) and then to the transaction cloud (“payment cancellation”).
Illustrative 2D projection: the same token starts from the same vector and ends up in different regions depending on context.

The table also leaves out order. Attention scores depend only on the content of the vectors; with nothing else, “the customer cancelled the payment” and “the payment cancelled the customer” would have the same input vectors, just shuffled. The original Transformer handles this by adding to the embeddings a positional encoding in which each dimension is a sinusoid of a different frequency; learned positions gave nearly identical results, and the authors kept the sinusoidal version because it may allow extrapolation to sequences longer than those seen in training (Vaswani et al., 2017). LLaMA replaces the absolute positional embedding with RoPE at every layer (Touvron et al., 2023), which encodes position with a rotation matrix and makes the relative position between two tokens show up directly in the attention computation (Su et al., 2021).

Part II: how the model answers

4. Dot product and attention

Now the vectors need to talk to each other. To decide how much “referred” should influence the next position, the model measures the compatibility between two vectors, and the simplest measure is the dot product:

q⋅k=q1k1+q2k2+⋯+qdkkdk=∥q∥ ∥k∥cos⁡θq \cdot k = q_1 k_1 + q_2 k_2 + \dots + q_{d_k} k_{d_k} = \lVert q \rVert \, \lVert k \rVert \cos\theta

The second form shows what it measures: the length of both vectors and the angle between them. In the figure, ∥q∥=3.20\lVert q \rVert = 3.20, ∥k∥=2.15\lVert k \rVert = 2.15 and θ=60°\theta = 60°. Since cos⁡60°=0.50\cos 60° = 0.50, the dot product is 3.20×2.15×0.50=3.443.20 \times 2.15 \times 0.50 = 3.44. Vectors pointing the same way give a large positive product; perpendicular ones give zero; opposite ones give a negative value.

Query q (orange) and key k (blue) vectors with angle θ between them. In the first frame q·k = +3.44 and cos θ = +0.50; as k rotates, the values and a −1 to +1 gauge change. Below, score = q·k / √d_k.
The dot product grows when q and k point in the same direction. Attention uses this number as its score.

Dividing the dot product by both norms leaves the cosine, between −1 and +1. That is cosine similarity, the most common measure for comparing query and document embeddings in semantic search, as in RAG architectures.

In attention, each token produces three vectors, each through a learned matrix: a query qq (“what I’m looking for”), a key kk (“what I offer”) and a value vv (“what I pass along”). The score between positions ii and jj is the dot product qi⋅kjq_i \cdot k_j, divided by dk\sqrt{d_k}. Softmax (concept 6) turns the scores in each row into weights that sum to 1, and the output at each position is the average of the value vectors weighted by those weights. In matrix form:

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right) V
Q,K,VQ, K, V
Matrices of queries, keys and values, one row per token
dkd_k
Dimension of the query and key vectors
QK⊤QK^\top
All the scores q_i · k_j at once
Scaled dot-product attention (Vaswani et al., 2017, Eq. 1).

Why dk\sqrt{d_k}? The original paper explains it with an assumption: if the components of qq and kk are independent random variables with mean 0 and variance 1, their dot product has mean 0 and variance dkd_k, and typical values grow with the dimension. Large scores saturate softmax (one weight close to 1, the others close to 0) and leave the gradients very small. Dividing by dk\sqrt{d_k}, the standard deviation, brings the variance back to around 1 (Vaswani et al., 2017).

Multi-head attention runs several attentions in parallel, each with its own projections, and concatenates the results; each head can attend to different relationships between tokens. The code below implements a single head with a causal mask, in NumPy. The mask (which comes back in concept 5) puts −∞-\infty in the scores of future positions, and softmax turns those −∞-\infty into zero weight.

attention.py
import numpy as np
def softmax(s, axis=-1):
s = s - s.max(axis=axis, keepdims=True) # numerical stability
e = np.exp(s)
return e / e.sum(axis=axis, keepdims=True)
def causal_attention(Q, K, V):
n, d_k = Q.shape
scores = Q @ K.T / np.sqrt(d_k) # (n, n): q_i · k_j / √d_k
future = np.triu(np.ones((n, n), dtype=bool), k=1)
scores = np.where(future, -np.inf, scores) # position i can't see j > i
weights = softmax(scores) # each row sums to 1
return weights @ V, weights
rng = np.random.default_rng(0)
n, d_model, d_k = 4, 8, 4 # 4 tokens, toy sizes
X = rng.normal(size=(n, d_model)) # token vectors
W_q, W_k, W_v = (rng.normal(size=(d_model, d_k)) for _ in range(3))
out, w = causal_attention(X @ W_q, X @ W_k, X @ W_v)
print(w.round(2)) # lower triangular
print(out.shape) # (4, 4)

The printed matrix w is lower triangular: the first row puts weight 1 on the token itself, and each following row spreads its weight over the previous positions and the current one. Subtracting the maximum before exponentiating leaves the softmax output unchanged and avoids numerical overflow.

These weights easily become a heatmap, hence the temptation to treat them as an explanation. The literature is split. Jain & Wallace (2019) showed that attention weights often correlate poorly with gradient-based measures of importance and that very different attention distributions can produce the same prediction; they concluded that standard attention should not be treated as explanation. Wiegreffe & Pinter (2019) replied that this depends on what one means by explanation and that the test has to consider the whole model, and they showed cases where attention does carry useful information. Both study recurrent networks with attention on classification and question answering; carrying their conclusions over to Transformer LLMs is itself an extrapolation. The safest reading is to treat an attention map as partial evidence about information flow; the reason behind the answer takes other tests.

5. Probability

After the last layer, the vector at the last position is turned into one score per vocabulary token, and those scores become probabilities. For every possible token, the model computes P(xt∣x<t)P(x_t \mid x_{<t}): the probability that it comes next, given the previous ones. The probability of a whole sentence follows from the chain rule, as the product of the conditional probabilities of each token, the same factorization used since n-gram models (Jurafsky & Martin, 2026):

P(x1,…,xT)=∏t=1TP(xt∣x<t)P(x_1, \dots, x_T) = \prod_{t=1}^{T} P(x_t \mid x_{<t})
xtx_t
Token at position t
x<tx_{<t}
All tokens before t
Autoregressive factorization: generating text means predicting one token at a time.

The causal mask keeps this honest during training, when the model sees the whole sentence and makes all its predictions in parallel: without it, the position that has to predict “doctor” could look at “doctor” right ahead of it. In the Transformer decoder, self-attention is modified so that the prediction at position ii depends only on positions before ii (Vaswani et al., 2017). In practice, position ii sees the tokens up to ii and predicts token i+1i + 1, which is why the code above lets each position see itself.

For “The patient was referred to the ___”, the figure shows an illustrative distribution: doctor 0.22, ICU 0.20, ward 0.18, clinic 0.16, ER 0.14. These five add up to 0.90. The remaining 0.10 is spread across the rest of the vocabulary, which in a real model is much larger, and everything together sums to 1.

Next-token probability bars for “The patient was referred to the ___”: doctor 0.22, ICU 0.20, ward 0.18, clinic 0.16, ER 0.14 and others 0.10. A stacked column beside them adds up to 1.00.
The five most likely tokens and the rest of the vocabulary under “others”: the full distribution sums to 1.

The 0.22 for “doctor” is the probability of one token, given the context. The probability that the whole answer is correct is a different calculation, and the model doesn’t compute it. A long answer chains dozens of choices like this one, and a distribution this flat only says that, at that point, several continuations were plausible. Whether these numbers match how often the model is actually right is the calibration question, which comes back in the next concept.

6. Softmax and temperature

The scores that come out of the last layer, the logits, can be any real number. Softmax turns a vector of logits zz into probabilities: it exponentiates each one, which makes everything positive, and divides by the sum, which makes the total equal 1. Temperature TT comes in by dividing the logits before the exponential, as described in Holtzman et al. (2020):

σ(z)i=ezi/T∑jezj/T\sigma(z)_i = \frac{e^{z_i / T}}{\sum_{j} e^{z_j / T}}
ziz_i
Logit (score) of option i
TT
Temperature; T = 1 is the standard softmax
σ(z)i\sigma(z)_i
Final probability of option i
Softmax with temperature. The same function, without T, normalizes the attention scores.

Here is the arithmetic with four illustrative logits, z=(2, 1, 0.4, −0.5)z = (2,\ 1,\ 0.4,\ -0.5). With T=1T = 1, the exponentials are e2≈7.39e^2 \approx 7.39, e1≈2.72e^1 \approx 2.72, e0.4≈1.49e^{0.4} \approx 1.49 and e−0.5≈0.61e^{-0.5} \approx 0.61. They sum to 12.2112.21, and the probabilities are:

7.3912.21≈0.612.7212.21≈0.221.4912.21≈0.120.6112.21≈0.05\frac{7.39}{12.21} \approx 0.61 \qquad \frac{2.72}{12.21} \approx 0.22 \qquad \frac{1.49}{12.21} \approx 0.12 \qquad \frac{0.61}{12.21} \approx 0.05

With T=0.35T = 0.35, the divided logits become (5.71, 2.86, 1.14, −1.43)(5.71,\ 2.86,\ 1.14,\ -1.43), and the gaps between them nearly triple. The exponentials come out around 303303, 17.417.4, 3.13.1 and 0.240.24, summing to ≈324\approx 324, and the result is (0.94, 0.05, 0.01, 0.00)(0.94,\ 0.05,\ 0.01,\ 0.00): almost all the mass went to the first option. With T=3T = 3, the distribution flattens to (0.37, 0.26, 0.21, 0.16)(0.37,\ 0.26,\ 0.21,\ 0.16). The ranking of the options never changes; temperature just sets how concentrated the distribution is at the top.

Softmax of logits 2, 1, 0.4, −0.5. At T = 0.35 the bars are 0.94, 0.05, 0.01 and 0.00; as the temperature slider rises to 3 the bars even out (0.37, 0.26, 0.21, 0.16) and then return.
Same logits, different temperatures: low T concentrates probability, high T spreads it out. The order of the bars doesn't change.

Temperature, then, only redistributes probability among options the model has already ranked. If the right answer was in third place, lowering the temperature makes a wrong answer more likely. A study with nine LLMs on multiple-choice benchmark problems found no statistically significant effect of temperatures between 0.0 and 1.0 on accuracy (Renze & Guven, 2024). Open-ended generation and extreme temperatures were outside its scope, but it points the same way: temperature controls diversity and style; truthfulness depends on other things.

That leaves the question from the previous concept. Summing to 1 makes the output a probability distribution; being calibrated is a separate requirement: across all the times the model says 0.8, it should be right about 80% of the time. Guo et al. (2017) showed that modern classification networks tend to be poorly calibrated and that a single temperature parameter, fitted on a validation set, fixes much of the problem without changing accuracy. For LLMs, the picture is mixed. Kadavath et al. (2022) found large models to be well calibrated on multiple-choice and true/false questions in the right format, but replacing one option with “none of the above” was enough to hurt calibration; RLHF-trained policies looked poorly calibrated, yet became reasonably calibrated with a simple temperature adjustment. The GPT-4 report shows that post-training worsened the pre-trained model’s calibration on MMLU (ECE from 0.007 to 0.074) (OpenAI, 2023). For your model, the practical conclusion is the same either way: calibration has to be measured on your task, with your data.

Part III: how the model learned

7. Loss function

Back to training. The sentence in the data read “The patient was referred to the doctor”, and the model, still early on, gave “doctor” a probability of only 0.04. How bad is that? Cross-entropy answers with a number:

L=−log⁡y^expected\mathcal{L} = -\log \hat{y}_{\text{expected}}
y^expected\hat{y}_{\text{expected}}
Probability the model assigned to the token that actually appeared in the data
log⁡\log
Natural logarithm
Cross-entropy for one token: the loss looks at the probability of the correct token and nothing else.

With y^expected=0.04\hat{y}_{\text{expected}} = 0.04, the loss is −log⁡0.04≈3.22-\log 0.04 \approx 3.22; had the model given it 0.95, it would be −log⁡0.95≈0.05-\log 0.95 \approx 0.05. Near 1 the loss is almost zero, and near 0 it grows without bound: giving near-zero probability to the right token is very expensive.

Curve of the loss −log ŷ (natural logarithm), high near zero and falling to 0 at ŷ = 1. A point at ŷ = 0.04 marks a loss of 3.22, then slides to ŷ = 0.95, loss 0.05.
The loss grows fast as the probability of the correct token goes to zero. At 0.04, it is 3.22.

During training, this loss is computed at every position of every sequence, and what gets minimized is the average. Perplexity is the exponential of that average, and minimizing perplexity is equivalent to maximizing the probability the model assigns to the test text (Jurafsky & Martin, 2026). An average loss of 3.22 corresponds to a perplexity of about 25, as if, on average, the model were hesitating between 25 equally likely options.

Two caveats. First, a modern LLM goes through more than one training stage. Ouyang et al. (2022) describe the language modeling objective as misaligned with what we want from an assistant, which is to follow instructions helpfully and safely, and so they add two stages: supervised fine-tuning, which uses the same loss on demonstrations written by people, and reinforcement learning from human feedback, which optimizes the score of a reward model trained on labelers’ comparisons between responses.

Second, low loss does not guarantee a model fit for your application. The loss measures fit to the distribution of the training and validation data; on text from another period, industry or population, you have to measure the model’s performance directly. Kadavath et al. (2022) themselves note that the model’s ability to predict whether it knows the answer generalizes only partially across tasks.

8. Derivatives and gradients

The loss tells you how wrong the model was. To fix it, you need to know which way to move each parameter, and the derivative tells you that: how much a function changes when its input changes a little. The partial derivatives of the loss with respect to each parameter form a vector, the gradient ∇L\nabla \mathcal{L}, which points in the direction in which the loss increases fastest. Backpropagation computes this vector layer by layer, back to front, by applying the chain rule (Goodfellow, Bengio & Courville, 2016).

The figure uses a toy loss with two parameters, L(θ)=12(θ12+4θ22)\mathcal{L}(\theta) = \tfrac{1}{2}(\theta_1^2 + 4\theta_2^2), whose gradient is ∇L=(θ1, 4θ2)\nabla \mathcal{L} = (\theta_1,\ 4\theta_2). The contour lines are ellipses, and the gradient is always perpendicular to them, pointing outward. Its norm varies along the same contour: 1.40 on the elongated side, 2.80 on the steep side, because the factor of 4 makes the loss more sensitive to θ2\theta_2.

Elliptical contour lines of L = ½(θ₁² + 4θ₂²) around the minimum. A point travels along one contour while the ∇L arrow always points outward, perpendicular to it; ‖∇L‖ ranges from 1.40 to 2.80.
The gradient points where the loss rises fastest, and it is longer where the loss is steeper. Training moves the opposite way.

In deep networks, the gradient can explode, and a single huge update undoes what training has built. Gradient clipping rescales the gradient to a fixed norm whenever it exceeds a threshold. The technique was proposed for recurrent networks (Pascanu, Mikolov & Bengio, 2013) and is still in use: LLaMA clips the gradient norm at 1.0 (Touvron et al., 2023).

When the batch you want doesn’t fit on the GPU, gradient accumulation processes smaller batches, sums their gradients and only then updates the parameters, as if the batch were larger; with sequences of different lengths, the loss should be divided by the total number of valid tokens in the effective batch, instead of averaging the averages (Hugging Face, n.d.).

Two pieces of the architecture exist largely to keep the training of deep networks stable. Residual connections add a block’s input to its output, x+F(x)x + F(x), creating a direct path for information and gradients to flow through the network. They were proposed to train much deeper vision networks, where adding layers without them hurt accuracy, a degradation that didn’t come from overfitting (He et al., 2016). Layer normalization (LayerNorm) keeps the scale of activations under control: it re-centers and rescales them using the mean and variance of the inputs to a layer, for a single example, and was proposed to speed up training (Ba, Kiros & Hinton, 2016). The order of the two varies: the original Transformer normalizes after the residual sum, LayerNorm(x+Sublayer(x))\text{LayerNorm}(x + \text{Sublayer}(x)) (Vaswani et al., 2017); LLaMA normalizes the input of each sub-layer, using RMSNorm (Touvron et al., 2023).

9. Optimization

With the gradient in hand, all that’s left is to take the step. Gradient descent moves a little in the direction opposite to the gradient:

θt+1=θt−η ∇L(θt)\theta_{t+1} = \theta_t - \eta \, \nabla \mathcal{L}(\theta_t)
θt\theta_t
Parameters at step t
η\eta
Learning rate, the step size
∇L(θt)\nabla \mathcal{L}(\theta_t)
Gradient of the loss at the current parameters
Gradient descent: the simplest update rule.

The learning rate η\eta is the most sensitive knob in training. Too small and training crawls; too large and the parameters overshoot and oscillate. On the elongated bowl in the figure, L(θ)=12(θ12+8θ22)\mathcal{L}(\theta) = \tfrac{1}{2}(\theta_1^2 + 8\theta_2^2), gradient descent zigzags from wall to wall, because a step that suits the flat direction is too large for the steep one. The problem is that η\eta is a single number for all parameters, and each parameter lives on a different scale.

Adam addresses this. For each parameter, it keeps two exponential moving averages: one of the gradient (the first moment, which acts like momentum) and one of the squared gradient (the second moment, that gradient’s typical scale). The step is the first average divided by the square root of the second, with a bias correction for the first iterations, and each parameter gets an adaptive rate: where the gradient tends to be large, the step shrinks; where it tends to be small, it grows (Kingma & Ba, 2015).

On an elongated bowl, gradient descent (pink) zigzags toward the minimum while Adam (blue) follows a smoother curve; a counter shows steps 0 to 40.
Two update rules on the same problem: Adam normalizes the step per parameter and takes a more direct path, while gradient descent zigzags.

On this toy quadratic problem, the figure is about behavior, and the final score can mislead: after 40 steps, gradient descent with a well-tuned rate ends up closer to the minimum than Adam, which heads more directly toward the minimum at first and then oscillates near the bottom. Adam’s advantage is per-parameter adaptation, which matters when different parts of the network have gradients on different scales. LLaMA is trained with the AdamW variant, which decouples weight decay from the gradient update (Loshchilov & Hutter, 2019), with β1=0.9\beta_1 = 0.9, β2=0.95\beta_2 = 0.95 and a weight decay of 0.1 (Touvron et al., 2023).

The rate also changes over the course of training. During warmup, it starts small and grows over the first steps: the original Transformer increased it linearly over 4,000 steps and then decreased it with the inverse square root of the step number (Vaswani et al., 2017); LLaMA uses 2,000 warmup steps and a cosine decay down to 10% of the peak rate (Touvron et al., 2023). The original paper doesn’t justify warmup; the most common explanation is that, with the parameters still random, small steps avoid overly large updates before training settles down.

What this changes in practice

The nine concepts boil down to four decisions that come up in any project with LLMs.

The first is using a token’s probability (the “yes” in a classification, for example) as a confidence score, with a threshold on top. Before you do, measure calibration with a reliability diagram or ECE on a validation set from your task, and recalibrate if needed; the temperature scaling of Guo et al. (2017) is the simplest starting point. I’ve built credit-granting engines with decision trees and random forests, and the lesson there is the same: a score that ranks customers well can be far from a trustworthy probability of default (I discuss this in Beyond the Credit Score). With LLMs, changing the prompt format can also change calibration.

The second is about explanation. An attention map helps with an investigation, but on its own it can’t justify a decision to an auditor or a customer. Combine it with input perturbation tests, comparison against known cases and a record of what went into the context.

The third is about evaluation. Benchmarks and validation loss measure the model on a distribution that probably differs from yours. Build an evaluation set with examples from your domain, from the period and population the system will run on, and rerun the evaluation when that data changes.

The fourth is about temperature. Use a low temperature when you want more stable answers, as in field extraction and classification, and a higher one when you want variety, as in generating alternatives. It does little against factual errors; for those you need other tools, such as retrieving the right content into the context and verifying the answer.

Conclusion

The whole article can be told through the path of a single word. During generation, “doctor” came out with 0.22 from a distribution built by vectors, matrices and dot products and shaped by softmax. In training, the same word had received 0.04; the loss of 3.22 became a gradient, and the optimizer adjusted the parameters to make it more likely. Knowing what each piece computes also shows what it doesn’t guarantee, and that matters when deciding whether an answer can feed into a decision.

References

  1. Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L. & Polosukhin, I. (2017). Attention Is All You Need. Advances in Neural Information Processing Systems 30 (NeurIPS 2017); arXiv:1706.03762. Link
  2. Mikolov, T., Sutskever, I., Chen, K., Corrado, G. S. & Dean, J. (2013). Distributed Representations of Words and Phrases and their Compositionality. Advances in Neural Information Processing Systems 26 (NIPS 2013); arXiv:1310.4546. Link
  3. Goodfellow, I., Bengio, Y. & Courville, A. (2016). Deep Learning. MIT Press. Link
  4. Hendrycks, D. & Gimpel, K. (2016). Gaussian Error Linear Units (GELUs). arXiv:1606.08415. Link
  5. Touvron, H., Lavril, T., Izacard, G., Martinet, X., Lachaux, M.-A., Lacroix, T., Rozière, B., Goyal, N., Hambro, E., Azhar, F., Rodriguez, A., Joulin, A., Grave, E. & Lample, G. (2023). LLaMA: Open and Efficient Foundation Language Models. arXiv:2302.13971. Link
  6. Su, J., Lu, Y., Pan, S., Murtadha, A., Wen, B. & Liu, Y. (2021). RoFormer: Enhanced Transformer with Rotary Position Embedding. arXiv:2104.09864. Link
  7. Jain, S. & Wallace, B. C. (2019). Attention is not Explanation. Proceedings of NAACL-HLT 2019, pp. 3543–3556. DOI 10.18653/v1/N19-1357. Link
  8. Wiegreffe, S. & Pinter, Y. (2019). Attention is not not Explanation. Proceedings of EMNLP-IJCNLP 2019, pp. 11–20. DOI 10.18653/v1/D19-1002. Link
  9. Jurafsky, D. & Martin, J. H. (2026, draft of August 19, 2026, 3rd ed.). Speech and Language Processing, ch. 3, “N-gram Language Models”. Link
  10. Holtzman, A., Buys, J., Du, L., Forbes, M. & Choi, Y. (2020). The Curious Case of Neural Text Degeneration. International Conference on Learning Representations (ICLR 2020); arXiv:1904.09751. Link
  11. Renze, M. & Guven, E. (2024). The Effect of Sampling Temperature on Problem Solving in Large Language Models. Findings of the Association for Computational Linguistics: EMNLP 2024, pp. 7346–7356. DOI 10.18653/v1/2024.findings-emnlp.432. Link
  12. Guo, C., Pleiss, G., Sun, Y. & Weinberger, K. Q. (2017). On Calibration of Modern Neural Networks. Proceedings of the 34th International Conference on Machine Learning (ICML 2017), PMLR 70:1321–1330. Link
  13. Kadavath, S., Conerly, T., Askell, A., Henighan, T., Drain, D., Perez, E., et al. (2022). Language Models (Mostly) Know What They Know. arXiv:2207.05221. Link
  14. OpenAI (2023). GPT-4 Technical Report. arXiv:2303.08774. Link
  15. Ouyang, L., Wu, J., Jiang, X., Almeida, D., Wainwright, C., Mishkin, P., et al. (2022). Training language models to follow instructions with human feedback. Advances in Neural Information Processing Systems 35 (NeurIPS 2022); arXiv:2203.02155. Link
  16. Pascanu, R., Mikolov, T. & Bengio, Y. (2013). On the difficulty of training recurrent neural networks. Proceedings of the 30th International Conference on Machine Learning (ICML 2013), PMLR 28(3):1310–1318. Link
  17. Hugging Face (n.d.). Performing gradient accumulation with Accelerate (Accelerate documentation). Link
  18. He, K., Zhang, X., Ren, S. & Sun, J. (2016). Deep Residual Learning for Image Recognition. IEEE Conference on Computer Vision and Pattern Recognition (CVPR 2016); arXiv:1512.03385. Link
  19. Ba, J. L., Kiros, J. R. & Hinton, G. E. (2016). Layer Normalization. arXiv:1607.06450. Link
  20. Kingma, D. P. & Ba, J. (2015). Adam: A Method for Stochastic Optimization. International Conference on Learning Representations (ICLR 2015); arXiv:1412.6980. Link
  21. Loshchilov, I. & Hutter, F. (2019). Decoupled Weight Decay Regularization. International Conference on Learning Representations (ICLR 2019); arXiv:1711.05101. Link