Foundations, 1 of 5, about 7 h 50 min of reading
Mathematical Literacy for AI Security
About 7 h 50 min left
Concept. Every attack and defense in the next 25 weeks rests on one of three pieces of mathematics. The first is the geometry of vector spaces, which decides what a retrieval-augmented generation (RAG) system retrieves and how it can be poisoned. The second is the probability distribution over tokens, which an adversarial suffix bends toward an unsafe answer. The third is gradient descent, which is how a model learns and how poisoned data corrupts that learning. You do not need to become a mathematician. You need enough fluency that when RAG Poisoning & Knowledge CorruptionRAG security, 2 of 2, about 3.6 h says "embedding poisoning" or Adversarial Machine LearningModels and supply chain, 1 of 3, about 12.3 h says "gradient-based jailbreak", the attack is obvious instead of mysterious. Building that fluency is the whole job of this unit.
🎯 Objectives
By the end of this unit you can:
- Compute cosine similarity and a dot product by hand on small vectors, and explain why they, and not raw distance, decide what a retrieval system returns.
- Read a row of logits, turn it into a probability distribution with softmax, and explain what temperature does to that distribution.
- Explain gradient descent and backpropagation well enough to see how a single poisoned training example nudges a model's weights.
- Name the later-week attack that exploits each primitive: embedding poisoning, adversarial suffixes and data poisoning.
- Recognize where probability distributions appear on the defensive side: confidence, uncertainty and out-of-distribution (OOD) detection.
Why a security course opens with linear algebra
Consider an attacker who wants a crafted document to appear whenever a victim asks a particular question. A modern AI system represents meaning as a position in a high-dimensional space, so the attacker places the document at the coordinates the victim's query will reach for. That is embedding poisoning. To anyone who cannot do the geometry, it looks like ordinary retrieval. "Position" is a mathematical object, so it has mathematical weaknesses.
Two specializations cover this material, and both are organized the same way: Imperial College's Mathematics for Machine Learning (Coursera) and DeepLearning.AI's Mathematics for ML and Data Science (Coursera). Each teaches linear algebra to represent data as vectors and matrices, calculus to optimize, and probability to quantify uncertainty. That order is the anatomy of every model you will attack.
Vectors, dot products and the geometry of meaning
An embedding is a list of numbers, called a vector, that a model assigns to a piece of text so that similar meanings land near each other. Nearly every system measures "near" with cosine similarity: the cosine of the angle between two vectors, computed as their dot product divided by the product of their lengths.
💡 Cosine similarity by hand. Take
a = [1, 0, 1]andb = [1, 1, 0]. The dot product is1·1 + 0·1 + 1·0 = 1, and each length is√2, socos = 1 / (√2·√2) = 0.5. A cosine of1.0means identical direction,0means orthogonal (unrelated), and-1means opposite. Do this by hand a few times, because the intuition is what makes RAG Poisoning & Knowledge CorruptionRAG security, 2 of 2, about 3.6 h legible.
Retrieval uses cosine instead of plain distance because cosine ignores magnitude and keeps only direction, so two documents on the same topic count as similar even when one is far longer. An attacker works exactly that seam. To poison a retrieval index, the malicious document does not need to be close in every dimension. It only needs to point in the same direction as the target query. The three common metrics differ in what they cannot see:
| Metric | Formula (intuition) | Blind to | Where it bites in security |
|---|---|---|---|
| Dot product | Σ aᵢbᵢ |
nothing: magnitude and direction both count | rewards long, keyword-stuffed poison documents |
| Cosine similarity | dot product divided by both lengths | magnitude | the default RAG metric, and the target of embedding poisoning (RAG Poisoning & Knowledge CorruptionRAG security, 2 of 2, about 3.6 h) |
| Euclidean distance | √Σ(aᵢ−bᵢ)² |
which gap it measures (length and angle mix into one number) | clustering and anomaly detection on the defense side |
3Blue1Brown's Essence of Linear Algebra (3Blue1Brown) teaches the visual intuition for all of this: vectors as arrows, the dot product as projection, and matrices as transformations of space. Khan Academy's exercises (Khan Academy) let you drill it.
🔑 Rule to carry forward. In a vector store, similarity is a weapon. Anything that can write to the index can choose coordinates, and choosing coordinates near a victim query is the entire mechanism of RAG poisoning.
Softmax and logits: the distribution attackers steer
A language model does not emit a word. It emits a vector of raw scores called logits, one per token in its vocabulary. Softmax turns those scores into a probability distribution: it exponentiates each logit and divides by the sum of all the exponentials, so the outputs are positive and sum to exactly 1.0 (Machine Learning Mastery). For logits [1, 3, 2], softmax gives [0.090, 0.665, 0.245]. The largest logit dominates, but the others keep a share.
The exponential is the step that does the work, because it amplifies differences: a small lead in logit space becomes a large lead in probability space. Softmax is a "soft" argmax. Where argmax would return a hard [0, 1, 0], softmax spreads probability to reflect uncertainty (Machine Learning Mastery). Temperature rescales the logits before the exponential. A low temperature sharpens the distribution toward the top token, which makes the output more deterministic, and a high temperature flattens it, which makes the output more random. StatQuest's Softmax (StatQuest) is a clear walkthrough from logits to probabilities.
💡 Why this is a security concept. An adversarial suffix (Prompt Hacking MasterclassInjection and guardrails, 1 of 5, about 7.8 h to Adversarial Machine LearningModels and supply chain, 1 of 3, about 12.3 h) is a string of tokens chosen so that, after softmax, the probability mass shifts onto a harmful continuation the model would normally refuse. The attacker is not tricking the model in some loose sense. They are editing the logits that feed softmax. If you can read a softmax output, you can read the objective an attacker is optimizing.
Gradient descent and backpropagation: how learning is corrupted
A model learns by minimizing a loss, a single number that measures how wrong it is. Gradient descent repeatedly nudges every weight a little in the direction that most reduces the loss, and the gradient is the vector of those directions. Backpropagation computes the gradient efficiently. The network is a computational graph, and the chain rule lets you flow the gradient backward from the loss to every weight, multiplying local gradients along the way (Stanford CS231n).
Attacks live inside these mechanics, so they are worth learning well. Each operation in the graph, called a gate, has a simple local rule (Stanford CS231n):
- The add gate passes the incoming gradient through unchanged to both inputs.
- The multiply gate sends each input a gradient scaled by the other input's value, so mismatched magnitudes create outsized and non-obvious effects.
- The max gate sends the entire gradient to the input that won the forward pass, and the losers get zero.
Karpathy's micrograd walkthrough is the best from-scratch build of this intuition: it implements an autograd engine and trains a neuron line by line (Andrej Karpathy). The visual companion is 3Blue1Brown's Neural Networks series (3Blue1Brown, with an extended version as a Manning liveVideo). The 10-hour hands-on version is freeCodeCamp's Linear Algebra for ML.
🔑 The security payoff. Training follows the gradient, so whoever influences the training data influences the gradient. Data poisoning (Adversarial Machine LearningModels and supply chain, 1 of 3, about 12.3 h and RAG Poisoning & Knowledge CorruptionRAG security, 2 of 2, about 3.6 h) works by contributing examples whose gradient tugs the weights toward the attacker's goal. A gradient-based jailbreak such as GCG takes the gradient with respect to the input tokens instead of the weights and uses it to pick which suffix tokens to swap, a greedy search guided by gradients. The math is the same, and it is aimed at the prompt.
The loop below shows where the two attacks enter it:
flowchart TD
D["Training data"] --> F["Forward pass through the graph:<br/>add, multiply, max gates"]
F --> L["Loss: one number for how wrong"]
L --> G["Gradient by backpropagation:<br/>chain rule, gate by gate"]
G --> U["Nudge every weight<br/>against the gradient"]
U -->|"repeat"| F
P["Poisoned example (weeks 11 to 12):<br/>its gradient tugs the weights<br/>toward the attacker's goal"] -.-> D
G -.->|"the same gradient, aimed at<br/>an input suffix, not the weights"| J["Gradient-based jailbreak (GCG)"]
Probability and statistics: the defender's language
The distributions above are an attack surface, and they are also the defender's main instrument. Confidence scores, anomaly detection, out-of-distribution flags and the statistical tests behind red-team evaluations all rest on the same foundations: random variables, expectation and variance, conditional probability, and Bayes' theorem. Brown University's interactive Seeing Theory covers this spine with visual, manipulable widgets: basic and compound probability, distributions and the central limit theorem, then frequentist and Bayesian inference and regression (Seeing Theory). StatQuest's Statistics Fundamentals playlist is the video counterpart (StatQuest). When Guardrails & Semantic FirewallsInjection and guardrails, 4 of 5, about 19.8 h builds a semantic firewall that flags "unusual" inputs, "unusual" will mean low probability under a distribution, and you will already know what that sentence means.
Building the fluency: watch to understand, then drill to retain
Mathematical intuition does not survive a single viewing. It comes from alternating between seeing the geometry and doing it. Split your week's resources by the job each does, instead of working from top to bottom:
- Watch to understand. 3Blue1Brown's visuals-first series build the mental picture of vectors as arrows and gradient descent as rolling downhill, and everything else hangs on that picture. The Neural Networks set is also free as a Manning liveVideo (1h 2m) with 22 graded exercises, if you want the checkpointed version.
- Drill to retain. Passive video is where intuition decays, so cement it against immediate feedback. Khan Academy's Linear Algebra unit moves from vectors to matrix transformations to eigenvalues in interactive, auto-graded exercises. freeCodeCamp's 33-chapter Linear Algebra for ML (10h 48m) is the code-along counterpart that turns each concept into runnable Python. For the probability spine of random variables, distributions and Bayes, StatQuest's Statistics Fundamentals playlist is the drill track behind the defender's-language section above.
- Do by hand. The most useful exercise of the week is not on a screen. On paper, compute a dot product, two lengths and a cosine similarity (see the callout above), then perturb one vector and watch the cosine move. You will reuse that reasoning for embedding poisoning in RAG Poisoning & Knowledge CorruptionRAG security, 2 of 2, about 3.6 h, and it takes five minutes.
🔑 Watch, then drill. A concept you have only seen animated is one you will recognize but cannot use. Every primitive in this week reappears as an attack in the attack weeks, so pay the drill cost now and the offensive weeks will read as applications of what you know.
✅ Check yourself
📇 Reference: each primitive and its attack surface
Finish Mathematical Literacy for AI Security
About 7 h 50 min left in this unit.
From memory first
Write the main points of this unit, in your own words.
What you set out to be able to do
Check each one against what you can do now.
- Compute cosine similarity and a dot product by hand on small vectors, and explain why they, and not raw distance, decide what a retrieval system returns.
- Read a row of logits, turn it into a probability distribution with softmax, and explain what temperature does to that distribution.
- Explain gradient descent and backpropagation well enough to see how a single poisoned training example nudges a model's weights.
- Name the later-week attack that exploits each primitive: embedding poisoning, adversarial suffixes and data poisoning.
- Recognize where probability distributions appear on the defensive side: confidence, uncertainty and out-of-distribution (OOD) detection.
The unit is done when you have answered the check and marked the required sources.
1 Check yourself
Do the check2 Required sources
Go to the sources
Sources in this unit
- 3Blue1Brown: Essence of Linear Algebra
- 3Blue1Brown: Neural Networks
- Andrej Karpathy: The spelled-out intro to neural networks and backpropagation
- Stanford CS231n: Backpropagation notes
- StatQuest: Softmax
- DeepLearning.AI: Mathematics for ML and Data Science (Coursera)
- Khan Academy: Linear Algebra
- freeCodeCamp: Linear Algebra for Machine Learning
- Imperial College London: Mathematics for ML (Coursera)
- Practice: compute cosine similarity by hand on vectors of 3-5 dimensions. This geometry is the foundation for understanding embedding poisoning (RAG Poisoning & Knowledge Corruption).
- StatQuest: Statistics Fundamentals
- Seeing Theory (Brown University)
- 3Blue1Brown: Neural Networks (Manning liveVideo)
- The Softmax Function: Neural Net Outputs as Probabilities
Checklist
It does not count toward done.
- Compute cosine similarity and the dot product by hand on two vectors of 3-5 dimensions, and write down both results.
- Explain in a few sentences why cosine similarity, not Euclidean distance, drives retrieval in retrieval-augmented generation (RAG), and how that lets an attacker poison embeddings (RAG Poisoning & Knowledge CorruptionRAG security, 2 of 2, about 3.6 h).
- Turn a row of logits into a probability distribution with softmax, check that it sums to 1, and explain what temperature does to it.
- Describe how steering the softmax output relates to adversarial suffixes (Prompt Hacking MasterclassInjection and guardrails, 1 of 5, about 7.8 h-11), in a short note you could hand to a colleague.
- Work through gradient descent and backpropagation on a small example, applying the chain rule and the add, multiply and max gate rules, and write out each local gradient.
- Connect gradient flow to data poisoning and gradient-based jailbreaks (Adversarial Machine LearningModels and supply chain, 1 of 3, about 12.3 h-12) by naming where the attacker's input enters the gradient.
- Finish a linear algebra refresher on vectors, matrices and dot products, and solve its exercises.
- Explain where probability shows up in defense, such as confidence scores and anomaly or out-of-distribution (OOD) detection as low probability under a distribution (Guardrails & Semantic FirewallsInjection and guardrails, 4 of 5, about 19.8 h), using one example.
- Follow the watch-then-drill path (3Blue1Brown visuals, then Khan Academy, freeCodeCamp and StatQuest drills) and finish with a cosine similarity computed by hand.
The poison that wins on direction
Attack: Win a cosine ranking with a long vector that sits farthest away by Euclidean distance Defend: Rank one set by cosine, dot and Euclidean and say which metric the poison cannot win
Nothing to do here yet; the unit is complete without it.
Practise this in the lab, One document, one question.15 to 25 min estimate
Practise this in the lab, Keep planted documents out of a retrieval pipeline.1 h 10 min to 1 h 40 min estimate
Practise this in the lab, Capstone: one engagement, replayable findings and a scope log.1 h 40 min estimate
Study notes
None yet
Sign in to take notes.
Your additions
None yet
More for this unit
1 reading
Readings no section cites. They do not count toward the unit.
Linear algebra and vector spaces1 reading
Practice: compute cosine similarity by hand on vectors of 3-5 dimensions. This geometry is the foundation for understanding embedding poisoning (RAG Poisoning & Knowledge Corruption).
labSign in to mark it done, keep it for later and open its questions.