▲ Best viewed on a desktop browser — the interactive demos rely on drag, hover, and a wide viewport.

CAIST:CENTER FOR ARTIFICIAL INTELLEGENCE AND SMART TECHNOLOGIES


Algebra for AI · A First-Principles Walkthrough

Every model you use is a small number of linear-algebra moves, applied a huge number of times.

A word embedding is a vector. A transformer layer is a matrix multiplication. PCA is an eigenvalue problem. Attention is a dot product. This page builds those moves up from the definition of a vector, so that by the end, a neural network stops looking like a diagram of boxes and starts looking like what it is: coordinates being represented, transformed, and decomposed.

§▸ · Live · the whole page in one picture
Most vectors change direction when you transform them. A few don't — they just stretch. Those are the eigenvectors, and they reappear in every section below.
1.00
preset warps the ring · slider blends it in
matrix A[[2,1],[1,2]] eigenvalues3.00, 1.00 eigen-directionsreal — gold lines below

The central claim of this page: almost everything a machine-learning system does to data can be sorted into three moves — represent it as a vector, transform it with a matrix, or decompose a matrix to find the directions that matter. Sections §1–§3 build the first two moves. Sections §4–§6 build the third. Sections §7–§8 point every one of those moves directly at a real AI system, and §9 maps the whole page onto a single diagram.

§0 · Primer: jargon decoder

Four ideas the rest of the page is built on.

If you've done linear algebra before, skim this section — it's short on purpose. Everything here is used again, by name, in a later section.

§0.1 · Vector
A list of numbers. An arrow from the origin.
A vector is an ordered list of numbers, [3, 2]. Geometrically it's an arrow starting at the origin. A word embedding with 768 numbers is a vector in a 768-dimensional space — impossible to draw, but it obeys the exact same rules as the 2-D arrow you can drag below.
↕ drag tip
coords[3.00, 2.00] length ‖x‖3.61
§0.2 · Dot Product & Cosine Similarity
How much one vector points the same way as another.
Dot product $\langle x,y\rangle = x_1y_1 + x_2y_2 = \|x\|\|y\|\cos\theta$. It's largest when the vectors point the same way, zero when perpendicular, negative when opposite. Dividing out the lengths gives cosine similarity $\cos\theta = \dfrac{\langle x,y\rangle}{\|x\|\|y\|}$, a number between −1 and 1 that ignores how long the vectors are and only asks which way they point. §7 uses exactly this number to rank meaning.
↕ drag either tip
‖x‖1.00 ‖y‖1.00 ⟨x,y⟩0.00 cosθ0.00 angle90°
§0.3 · Matrix as a Machine
A matrix eats a vector and returns a new vector.
A matrix $A$ turns an input $x$ into an output $y = Ax$. The rule: $y$ is a weighted combination of $A$'s columns, using $x$'s numbers as the weights — $y = x_1 \cdot \text{col}_1(A) + x_2 \cdot \text{col}_2(A)$. Every layer of a neural network is this operation, over and over.
A =
↕ drag input x (grey)
x[1.00, 1.00] y = Ax breakdown
§0.4 · Basis & Coordinates
The same arrow. Different numbers, depending on your ruler.
A basis is a choice of ruler — two vectors $e_1', e_2'$ used to measure everything else. The grey point below is a fixed arrow in space. Its coordinates in the standard basis (grey grid) never change. Drag the colored basis vectors and watch the same point get different coordinates in the new (violet/cyan) grid. Neither set of numbers is more correct — they describe the same arrow from two different rulers. This is exactly what changes when you swap embedding models in §7.
↕ drag e₁′ / e₂′
standard coords[3.00, 2.00] new-basis coords basis valid?yes
Takeaway · next §1

A vector is a point described by numbers relative to a basis. A matrix is a machine that turns vectors into other vectors by recombining their coordinates. Those two facts are the entire vocabulary of linear algebra — §1 asks a sharper question: what set of vectors can a given matrix, or a given basis, actually reach?

§1 · Vector spaces

What can a handful of vectors actually reach?

Every embedding table, every hidden layer, every weight matrix defines a space of vectors it can produce. Before asking what a network learns, it's worth asking what it could possibly reach in the first place — that's a vector-space question, and it has a precise answer.

Definition, briefly A vector space is a set of vectors closed under two operations: add any two members and the sum is still a member; scale any member by a number and it's still a member. $\mathbb{R}^2$, all 768-dimensional embeddings, and the set of outputs a linear layer can produce are all vector spaces in this sense — that's why "adding two embeddings" or "scaling a hidden state" always produces something valid to feed into the next layer.

Given a small set of vectors, the span is every point reachable by scaling and adding them. Two vectors in the plane usually span the whole plane. But if one is just a scaled copy of the other — they're linearly dependent — every combination lands on a single line, no matter how you scale them. The set is linearly independent exactly when this collapse doesn't happen, and dropping any vector genuinely shrinks the span.

§1 · DEMO · span & independence
Drag the two vectors. Watch what the span can and can't reach.
The gold point is the combination $c_1v_1 + c_2v_2$, built from the sliders. The shaded region is everywhere that combination can land as $c_1, c_2$ range over all numbers — the span. Drag $v_2$ until it lines up with $v_1$: the shading collapses from the whole plane down to a single line. That's a linearly dependent pair losing a dimension.
1.00
1.00
↕ drag v₁ (violet) / v₂ (cyan)
v₁[1.40, 0.40] v₂[0.20, 1.30] independent?yes rank / span dim.2 v₃ = a·v₁ + b·v₂

A basis is a linearly independent set whose span is the whole space — the smallest ruler that reaches everywhere, first met in §0.4. The dimension of a space is simply how many vectors a basis for it needs: 2 for the plane, 768 for a typical sentence embedding, and, for a neural network layer, however many independent directions its weight matrix's columns actually point in — a number that can be smaller than the layer's width. A layer with 512 output units whose columns are secretly dependent isn't using 512 dimensions of capacity; it's using fewer, and every dependent column is wasted parameters. §3 gives this a single number.

Takeaway · next §2

Span measures what a set of vectors can reach; independence measures whether every vector in the set is pulling its weight. A matrix's columns are just such a set. §2 turns this around: instead of asking what a fixed set of vectors spans, it asks what happens to every vector in the space when a matrix acts on all of them at once.

§2 · Linear transformations

A matrix is a machine for warping space — consistently.

§0.3 showed $Ax$ landing on a single output point. Slide that same matrix over every point in the plane at once, and a matrix stops looking like arithmetic and starts looking like what it is: a picture of space getting stretched, rotated, sheared, or flattened, in a way that keeps straight lines straight and the origin fixed. That picture is exactly what a neural network layer does to its input, before any nonlinearity gets involved.

§2 · DEMO · drag the basis vectors, warp the grid
A matrix is fully determined by where it sends $\hat{\imath}=(1,0)$ and $\hat{\jmath}=(0,1)$.
Every other point is a combination of $\hat\imath$ and $\hat\jmath$ (§1), so once you know where those two land, you know where everything lands — that's the warped grid. The dashed circle is the unit circle; watch it become an ellipse as you drag.
↕ drag î (violet) / ĵ (cyan) tips
A î→[1.00, 0.00] ĵ→[0.00, 1.00] basis still independent?yes

Two transformations applied back to back — first $B$, then $A$ — combine into a single matrix, their product $AB$. This is why "stack two layers" and "multiply two matrices" are the same sentence in a neural network. Matrix multiplication is not commutative: $AB \neq BA$ in general, because doing the shear first and the rotation second lands you somewhere different than doing them in the other order.

§2 · DEMO · order matters
Shear then rotate is not the same matrix as rotate then shear.
0.80
50°
both shapes start as the dashed square
gold: rotate·shear (R S) violet: shear·rotate (S R) same matrix?no
Takeaway · next §3

A matrix moves every point in space in one consistent, straight-line-preserving way, entirely determined by where it sends the basis vectors. Stacking transformations is matrix multiplication, and order matters. What none of this has asked yet: does the warp lose information? A projection visibly flattens the plane into a line — §3 gives that loss a single number.

§3 · The determinant

One number that says whether a transformation destroys information.

§2's warped grid changed the shape of a unit square. The determinant $\det(A)$ is by how much it changed the square's area — a single signed number that captures how a transformation scales space, in any number of dimensions (area in 2-D, volume in 3-D, and so on).

§3 · DEMO · the unit square, after A
Drag the basis vectors. Watch the shaded area track $|\det(A)|$.
For a $2\times2$ matrix $A = \begin{pmatrix}a & b\\ c& d\end{pmatrix}$, $\det(A) = ad - bc$. It's exactly the signed area of the parallelogram that $\hat\imath$ and $\hat\jmath$ get mapped to. Drag $\hat\jmath$ across $\hat\imath$'s line: the parallelogram flattens to a segment, its area passes through zero, and the sign of the determinant flips — the transformation has turned space inside out.
↕ drag î (violet) / ĵ (cyan) tips
A det(A) = ad−bc area = |det(A)| orientationpreserved invertible?yes

Three facts follow directly from "determinant = area-scale-factor," and all three matter for what a layer of a network can and can't do:

  • $\det(A) = 0$ means singular. The transformation flattens the plane onto a line (or the line onto a point) — a whole direction of input is thrown away. Two different inputs can now map to the exact same output, so $A$ has no inverse: there's no way to undo the operation and recover what went in. In a network, a weight matrix that becomes singular during training has permanently lost representational capacity along some direction — a hidden form of the "dead neuron" problem.
  • The sign of $\det(A)$ says whether orientation flips. Positive keeps a clockwise triangle clockwise; negative mirrors it. Magnitude and sign are independent facts about the same transformation.
  • Determinants multiply under composition: $\det(AB) = \det(A)\det(B)$. Stack a volume-preserving rotation ($\det{=}1$) with a volume-preserving shear ($\det{=}1$) from §2, and the combined transform still preserves area exactly — even though the shape it produces looks nothing like either step alone.
Takeaway · next §4

The determinant tells you how much a transformation scales space and whether it flips orientation — but it says nothing about which directions get stretched the most, or which ones don't move at all. §4 finds those directions directly.

§4 · Eigenvectors & eigenvalues

The directions a transformation doesn't rotate — only stretches.

§2 showed that most vectors change direction under a matrix. A special few don't: they come back out pointing exactly the same way (or exactly opposite), just longer or shorter. Those are eigenvectors, and the amount they stretch by is their eigenvalue: $Av = \lambda v$.

Shared matrix for this section, A =
λ² − tr(A)·λ + det(A) = 0
tr(A)5.00 det(A)6.00 discriminant1.00 λ₁3.00 λ₂2.00
§4 · DEMO · hunt for an eigen-direction
Drag v around the circle. Watch Av. Find where they line up.
The grey arrow is $v$; the colored arrow is $Av$. For almost every angle they point in different directions. Sweep $v$ all the way around — twice, it turns gold and locks onto $Av$'s direction. Those lock-on angles are the eigenvectors of $A$; the length ratio at that instant is the eigenvalue.
↔ drag v around the circle
v Av angle(v, Av) Rayleigh quotient ⟨Av,v⟩/⟨v,v⟩ eigenvector?no
§4 · DEMO · power iteration
Apply A over and over. Any starting vector drifts toward the strongest eigenvector.
Start from a random vector and repeatedly replace it with $Av$. Whichever eigenvector has the largest $|\lambda|$ dominates the sum after enough multiplications, because its component gets amplified fastest relative to the others. This is not a curiosity — it's the actual algorithm behind Google's original PageRank (see the reference in the hero) and behind §6's search for the top principal component.
0
trail fades with each step
current vector ‖Anv‖ / ‖An−1v‖ converging to |λmax|3.00

Not every real matrix has real eigenvectors — try a pure rotation (revisit the hero demo's "rotate" preset). Rotating every vector by a fixed angle never leaves any direction unchanged, so the characteristic equation's discriminant goes negative and the eigenvalues come out complex. A negative discriminant in the readout above is exactly that case.

Takeaway · next §5

Eigenvectors are the directions a transformation only stretches; eigenvalues are the stretch factors. Repeated application of $A$ is dominated by whichever eigenvalue has the largest magnitude. §5 uses exactly that fact to explain why some networks' hidden states blow up over many steps, and others quietly die out.

§5 · Diagonalization

Why applying a matrix 50 times is either boring or catastrophic.

If $A$ has a full set of independent eigenvectors, it factors as $A = PDP^{-1}$: $P$'s columns are the eigenvectors, and $D$ is diagonal with the eigenvalues down the middle. This is diagonalization, and it turns a painful question — what does $A$ applied 50 times look like? — into an easy one, because $A^n = PD^nP^{-1}$, and raising a diagonal matrix to the $n$-th power just means raising each eigenvalue to the $n$-th power.

A =
vanishing
§5 · DEMO · A applied n times
Drag n. Watch whether the arrow survives, or where it goes.
This is §4's power-iteration idea, stretched out along a slider instead of clicked step by step, with the growth curve plotted directly. A vanilla recurrent network updates its hidden state roughly as $h_t \approx Ah_{t-1}$ every timestep; backpropagating through $T$ steps multiplies by $A^T$. Watch what that means for $\|A^nv\|$ below.
0
arrow after n applications of A
Dn = diag(λ₁n, λ₂n) ‖Anv‖

The three presets above are the three futures a repeated linear update can have, and they map directly onto training pathologies with names you've likely already seen:

  • Exploding. $|\lambda_{\max}| > 1$: every application stretches the dominant direction further. Hidden states and gradients grow exponentially in the number of steps — the exploding-gradient problem.
  • Vanishing. $|\lambda_{\max}| \lt 1$: everything shrinks toward zero. Gradients from many steps back become too small to update anything — the reason plain RNNs struggle to remember long-range context, and part of the motivation for LSTMs, GRUs, and careful weight initialization (Glorot & Bengio, linked in the hero).
  • Stable. $|\lambda| = 1$ for every eigenvalue — the orthogonal case, where $A$ only rotates, never stretches. Lengths are preserved exactly, no matter how many times $A$ is applied. Keeping weight matrices close to orthogonal is a real, deliberate training technique for exactly this reason.
Takeaway · next §6

Diagonalization turns "apply $A$ many times" into "raise a few numbers to a power," and those numbers decide whether a repeated process explodes, vanishes, or holds steady. So far every eigen-example has used a matrix someone handed you. §6 builds one from data — the covariance matrix — and its eigenvectors turn out to be the most informative directions in a dataset.

§6 · Principal Component Analysis

The directions your data actually varies along are eigenvectors.

Take a cloud of data points, centre it at the origin, and build its covariance matrix $\Sigma$ — a matrix that records how much each pair of coordinates varies together. It's always symmetric ($\Sigma_{xy} = \Sigma_{yx}$ by construction), and the spectral theorem guarantees every real symmetric matrix has real eigenvalues and perpendicular eigenvectors — no complex-eigenvalue surprises like §4's pure rotation. Those perpendicular eigenvectors are the principal components: the axes the data spreads out along the most, sorted by their eigenvalues, which are exactly the variance along each axis.

§6 · DEMO · find the axes hiding in the cloud
Shape the cloud with the sliders. The gold and violet arrows are computed from the points, not from the sliders.
The sliders control how the points are generated — spread along two directions, then rotated. Everything else on the canvas is computed live from the resulting 150 points: the covariance matrix, its eigenvectors (arrow directions), and its eigenvalues (arrow lengths and the variance-explained bars). If PCA is working, the gold arrow should land right along the cloud's long axis, however you've rotated it.
2.20
0.60
30°
gold = PC1 · violet = PC2
Σ (covariance) λ₁ (PC1 variance) λ₂ (PC2 variance) variance kept by PC1 alone

With only two coordinates this is a nice picture; the payoff shows up in the dimensions you can't draw. A dataset of 768-dimensional sentence embeddings still has a $768\times768$ covariance matrix with 768 eigenvectors — but if the first two or three eigenvalues capture most of the total variance, projecting onto just those eigenvectors keeps most of what the data was actually saying while throwing away the rest. That's how a 768-dimensional embedding space gets compressed down to the 2-D scatter plot on a slide, and it's the same operation — on a much larger scale — behind whitening layers and dimensionality reduction in real training pipelines.

Takeaway · next §7

PCA finds the axes a dataset naturally spreads out along by diagonalizing its covariance matrix — a direct application of §5 to a matrix built from data rather than handed to you. §7 looks at what those axes, and the vectors sitting in the space they define, are actually made to mean.

§7 · Embeddings & cosine similarity

Meaning, encoded as a direction in space.

An embedding is a vector a model has learned to assign to a word, sentence, or image, chosen so that things with similar meaning end up as vectors that point similar ways. "Similar way" is not a metaphor here — it's §0.2's cosine similarity, computed directly on the embedding vectors, and it's how every semantic search, recommendation system, and retrieval-augmented model on the market ranks results.

§7 · DEMO · a toy 2-D embedding space
Drag the query point. Cosine similarity and Euclidean distance don't always agree on what's "closest."
feline sits exactly twice as far from the origin as the query point, in precisely the same direction — a stand-in for how a rarer synonym often gets a larger-magnitude embedding for the same meaning. dog is physically nearer to the query but points a noticeably different way. Drag the query near the cat/dog cluster and compare the two rankings below.
↕ drag the gold "?" query point
wordcosθ with queryEuclidean distance
top match by cosine top match by distance agree?

Because embeddings are ordinary vectors, they inherit ordinary vector arithmetic (§1's closure again). The most-quoted demonstration of this, from the original word2vec work linked in the hero, is analogy-by-subtraction: the offset from "man" to "woman" is, roughly, the same offset as "king" to "queen" — because both offsets point in the direction a model has learned to associate with gender, independent of the royalty concept riding along with it.

§7 · DEMO · king − man + woman ≈ queen
Slide t to carry the man→woman offset over to king, and watch where it lands.
(Toy coordinates, chosen to make the picture exact — a real embedding model's version of this is approximate, not exact, but the mechanism is identical: vector subtraction, then addition.)
0.00
gold path: king + t·(woman − man)
king + t·(woman−man) cosθ with true "queen"
Takeaway · next §8

Embeddings turn "similar meaning" into "similar direction," and cosine similarity from §0.2 is how that similarity gets measured and ranked. None of this addresses where the embedding vectors come from in the first place — §8 builds the machine that learns them.

§8 · Neural networks as stacked matrix transforms

A layer is $Wx+b$. Depth is what happens when you interleave a bend.

A single neural-network layer computes $y = \phi(Wx + b)$: a linear transformation (§2) with a bias offset, followed by a nonlinearity $\phi$ like $\tanh$ or ReLU applied number-by-number. The matrix part alone can rotate, scale, and shear. It can never bend a straight decision boundary into a curved one — composing linear maps just gives another linear map, $W_2(W_1x) = (W_2W_1)x$, one matrix again, exactly as in §2. The nonlinearity is the only thing standing between "one big matrix" and "deep network."

Why depth needs a nonlinearity Stack ten linear layers with no $\phi$ between them and $y = W_{10}W_9\cdots W_1 x$ — by §2's composition rule, that product is just some single matrix $M$. Ten layers of pure linear algebra have exactly the representational power of one. Every extra bit of power a deep network has over a shallow one comes from the nonlinearities bending space between the matrix multiplications.
§8 · DEMO · train a 2-hidden-unit network on a problem no line can solve
Same-sign quadrants are one class, opposite-sign quadrants are the other. No straight line separates them — yet.
Left: the raw input space, colored by the network's current prediction. Right: what the input points look like after the hidden layer's matrix-plus-$\tanh$ — the same points, bent by the network. The output layer only ever draws a straight line (it's linear), so training has to warp the right-hand picture until a straight line works. Click train and watch it happen.
0
input space (x₁, x₂)
hidden space (h₁, h₂) — after W₁, b₁, tanh
loss (binary cross-entropy) accuracy W₁ w₂

Scale this picture up and you have the recipe for everything from a small classifier to a large language model: alternating linear transforms and nonlinearities, with attention layers adding one more linear-algebra primitive on top — each token's relevance to every other token, computed as a scaled dot product $QK^\top$ between query and key vectors, exactly the inner product from §0.2, just computed for every pair of tokens in the sequence at once via one matrix multiplication.

Takeaway · next §9

A neural network is matrix multiplications separated by nonlinear bends, chosen and adjusted so that a linear readout at the very end can finally draw a straight line through the bent space. §9 zooms back out and lays every section of this page onto one map.

§9 · Putting it together

Represent. Transform. Decompose. That's the whole page.

Back in the hero: almost anything a machine-learning system does to data sorts into one of three moves. Here is every section of this page, filed under the move it belongs to, next to the real system that leans on it.

MoveConceptSectionShows up directly in
Represent Vector spaces, span, independence §1 Embedding-space capacity; whether a layer's columns waste width on dependent directions
Transform Linear transformations & composition §2 Every dense layer, convolution, and attention projection; stacking layers = matrix product
Transform The determinant §3 Invertibility; log-determinant terms in normalizing flows; rank collapse / dead units
Decompose Eigenvectors & eigenvalues §4 Power iteration behind PageRank; stability analysis of any repeated linear update
Decompose Diagonalization §5 Exploding / vanishing gradients in RNNs; why orthogonal weight init helps
Decompose PCA / covariance eigenvectors §6 Dimensionality reduction, whitening, 2-D visualization of high-dimensional embeddings
Represent Embeddings & cosine similarity §7 Semantic search, recommendation systems, retrieval-augmented generation
Transform Stacked linear layers + nonlinearity §8 Every deep network; attention's $QK^\top$ is §0.2's inner product at sequence scale
▣ CHEAT SHEET · nine ideas, one sentence each
Vector: ordered list of numbers, or an arrow from the origin. Dot product & cosine similarity: how much two vectors point the same way, with or without caring about their length. Vector space, span, independence: the set a group of vectors can reach by scaling and adding them, and whether every vector in the group is actually needed to reach it. Linear transformation: a matrix, warping all of space at once, consistently, fixing the origin and keeping lines straight. Determinant: the signed factor by which a transformation scales area or volume; zero means information is being thrown away. Eigenvector / eigenvalue: a direction a transformation only stretches, and the factor it stretches by. Diagonalization: rewriting a matrix in its own eigenvector basis, so raising it to a power is just raising a few numbers to that power. PCA: diagonalizing a dataset's covariance matrix to find the directions it actually varies along. Neural network layer: a matrix transform plus a nonlinear bend, repeated, so a straight line at the very end can separate what a straight line couldn't separate at the start.

None of the individual ideas on this page are exotic — every one of them is standard, decades- or centuries-old linear algebra. What's changed is scale: instead of a $2\times2$ matrix, a transformer layer's weight matrix might be thousands of rows and columns wide, and instead of one matrix multiplication, a modern model runs hundreds of them per token, per layer, per forward pass. The mathematics underneath does not change. Only the size of the arrows does.