Mathematical Foundations
3.1 Language as a Mathematical Problem
For a machine to process language, text must be translated into mathematical representations. Human language, with its richness of nuance, ambiguity, and complex structure, is not directly interpretable by mathematical algorithms. Therefore, one of the first tasks in building an LLM is to create suitable numerical representations.
Text is turned into numbers through a process called tokenization, in which words, subwords, or characters are mapped to integers. These integers are then converted into dense vectors of real numbers by embedding layers. Each token receives an associated vector that captures certain semantic and syntactic properties of that token.
3.2 Vector Spaces and Embeddings
A central concept in LLMs is the vector space. Each word, after being processed by the model, exists as a point — or more precisely, as a vector — in a high-dimensional space. The dimensionality of these spaces varies, but is commonly on the order of hundreds or thousands of dimensions. The dimension refers to the number of independent values that define each vector.
The magic of embeddings lies in the fact that semantic relationships between words are reflected as geometric relationships between their vectors. If you take the vector for “king”, subtract the vector for “man”, and add the vector for “woman”, you get a vector very close to the vector for “queen”. This property, known as the word2vec arithmetic analogy, shows that embeddings capture semantic relationships in a quantifiable way.
3.3 Probability and Prediction
At the heart of every language model is the principle of conditional probability. Given a sequence of preceding tokens, the model computes the probability of each possible vocabulary token being the next one. Mathematically, if we denote a sequence of tokens as , the model computes .
This probability distribution is computed through multiple layers of neural transformation, each one processing the intermediate representation of the sequence and progressively refining it. During training, the model adjusts its parameters to maximize the probability of the actual tokens that appear in the training text.
The final output of the model is typically a probability distribution over the entire vocabulary. During text generation, different sampling strategies can be used to select the next token, from the deterministic choice of the most likely token to stochastic methods that introduce creative variability.
3.4 Activation Functions and Normalization
The neural networks that make up LLMs use several mathematical functions to transform data between layers. Activation functions, such as ReLU (Rectified Linear Unit), GELU (Gaussian Error Linear Unit), and SwiGLU, introduce nonlinearities that allow the model to learn complex relationships between input and output.
Normalization is another crucial component. Techniques such as Layer Normalization and RMS Normalization stabilize training by ensuring that intermediate values keep adequate magnitudes, avoiding numerical problems that could hinder or prevent learning.
3.5 Dimensions: The Most Useful Debugging Tool
Consider a batch , where is the batch size, is the number of tokens, and is the model dimension. A linear projection with produces . Tracking these dimensions makes it possible to detect a large class of errors before even running the program.
The dot product measures compatibility: . In attention, larger products indicate that a query and a key are more aligned. The softmax, in turn, transforms a vector of scores into probabilities . Subtracting before exponentiation preserves the result and improves numerical stability.
Quick example
For the logits , the softmax assigns more probability to the first item but keeps positive probability for the others. Adding the same constant to all logits does not change this distribution. Verify this property algebraically or with
torch.softmax.
3.6 The Chain Rule and Backpropagation
A network is a composition of functions. If , , and , the influence of on the loss is obtained by the chain rule:
Backpropagation traverses the computational graph in reverse, reusing intermediate derivatives. Automatic differentiation libraries record the forward operations and compute vector-Jacobian products; they do not “discover” the mathematics, but automate its application.
import torch
w = torch.tensor(2.0, requires_grad=True)
x = torch.tensor(3.0)
y = w * x
loss = (y - 5) ** 2
loss.backward()
print(w.grad) # 2 * (w*x - 5) * x = 6
The sign of the gradient indicates the direction of local growth of the loss; the optimizer moves in the opposite direction. A zero gradient may represent a minimum, a flat point, the saturation of an activation, or a path disconnected from the graph. For this reason, inspecting the loss alone is not enough.
3.7 Cross-Entropy and Divergence Between Distributions
For a true distribution and an approximation , the cross-entropy is . When the target is a single token, only the logarithm of the probability of that token contributes. The Kullback–Leibler divergence satisfies ; if is fixed, minimizing cross-entropy also minimizes this divergence.
KL is not a distance
is not symmetric and, in general, does not obey the triangle inequality. It quantifies the information lost when using in place of , not an ordinary geometric distance.