The maths you need to start understanding LLMs
TL;DR Highlight
High-school vectors and matrices are enough to follow the maths of LLM inference
Who Should Read
A backend developer who uses embeddings and RAG but finds logits, dot products and matrix projections vague
Core Mechanics
- LLM inference maths is high-school level
- The author says understanding inference needs only the vectors and matrices taught in high school.
- Training is not covered; the post is about using an existing model.
- Logits are as long as the vocabulary
- GPT-2's tokeniser has 50,257 tokens, so each logits vector has 50,257 slots.
- Each slot is how likely that token is to come next, and token 464 is "The".
- Softmax tidies equivalent scores into one
- (1,2,3) and (-9,-8,-7) both softmax to about (0.09, 0.24, 0.66).
- (1,2,5) has the same ranking but a bigger gap and gives about (0.02, 0.05, 0.94).
- Embeddings put meaning into coordinates
- Similar concepts cluster together, and different purposes call for different embedding spaces.
- Direction matters more than length, so (1,2) and (8,16) are treated as essentially the same.
- Dot product is a quick similarity measure
- Multiply matching elements and sum them.
- For vectors of similar length it measures how aligned they are, and at length 1 it equals cosine similarity exactly.
- Matrix multiplication projects between spaces
- With row-major vectors, a d1×d2 matrix maps a d1-dimensional space to a d2-dimensional one.
- A 50257×768 matrix projects 50,257 dimensions down to 768, and the lost information can't be recovered.
- A linear layer is basically a matrix multiply
- Without the activation function and bias, a neural-net layer is just XWᵀ.
- So a layer with no activation is an easy way to change dimensionality.
Community Reactions
- Opinion that RAG uses the same maths
- A commenter said RAG embeds chunks and the user query, then finds the closest documents by cosine distance.
- Reranking the top N is just an extra step on top.
- Experience that agent chains accumulate uncertainty
- A commenter argued that because LLMs emit logits, each model in a chain adds its own uncertainty.
- They said they had seen a complete collapse after just 3 chained LLM calls.
- They suggested human in the loop or a single orchestrator workflow.
- Pushback that embedding maths isn't all of an LLM
- Commenters said the post covers word vectors and token embeddings, which are only the input to a huge transformer.
- Some called the title misleading since maths that rigorously explains why LLMs work is not fully developed.
- Experience of working through Karpathy's videos
- Several commenters said coding along rather than just watching gave them a real grasp of LLMs.
- One suggested the post should explicitly say softmax exponentiates values and normalises them to sum to 1.
How to Apply
- Hand-code your RAG similarity with dot product
- Today, take two embeddings and compute dot product and cosine similarity in numpy, then compare the rankings.
- Normalise to length 1 and check that the two values match.
- Check your vector DB metric against normalisation
- Look up whether your embedding model outputs normalised vectors.
- If it doesn't, switch the index setting from dot product to cosine.
- Shorten agent chains and add checks between steps
- Find pipelines with 3 or more chained LLM calls and see if one orchestrator can replace them.
- Put rule-based checks or human review between the remaining steps.
Try It
# Run in a terminal (checks the post's concepts with numpy)
# pip install numpy
import numpy as np
def softmax(x):
e = np.exp(x - np.max(x))
return e / e.sum()
print(softmax(np.array([1, 2, 3])))
print(softmax(np.array([-9, -8, -7])))
print(softmax(np.array([1, 2, 5])))
a = np.array([1.0, 2.0])
b = np.array([8.0, 16.0])
print("dot:", a @ b)
print("cosine:", a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))
X = np.random.randn(4, 50257)
W = np.random.randn(50257, 768)
print((X @ W).shape)Terminology
Related Papers
FutureBench: A Renewable Framework for Evaluating Knowledge-Context Conflict in LLMs
Adding 'verify and prioritize the passage' to RAG prompts raised false-passage adoption; a knowledge-priority warning fixed it.
Faster Retrieval for Better, More Efficient RAG
Small neural nets learned query routing, hitting the same recall up to 8x faster in IVF search
Memorilla: Latent Semantic Memory for LLMs
Compressing documents into 16 memory tokens beat full-context accuracy on FactKG.
What the Author Wrote, What the Agent Reads: Silent Cue Loss in Enterprise Document Ingestion
Preserving red text and highlights in docx ingestion lifted marked-requirement F1 from 0.150 to 0.690.
Multimodal Reranking Is a System One Decision
One multiple-choice question to a VLM over 16 candidates reranks them, beating a dedicated 2B reranker.
You could have invented transformers from memory
Viewing linear, MLP and attention layers as memory stores: capacity goes ~64 to ~2,700 to over a million
Pointing AI at archives found a forgotten meteorite, lost rhinos, and more
Embedding search plus a cheap filter model surfaced unrecorded events in 400 years of archives
EmbeddingGemma 2: An open, lightweight multimodal embedding model
One open 740M model embeds text, images, audio and video into a single shared vector space
Related Resources
- https://www.gilesthomas.com/2025/09/maths-for-llms
- https://www.manning.com/books/build-a-large-language-model-from-scratch
- https://www.youtube.com/watch?v=7xTGNNLPyMI
- https://github.com/stared/thinking-in-tensors-writing-in-pytorch
- https://sgnt.ai/p/embeddings-explainer/
- https://www.manning.com/books/deep-learning-with-python