Vectors
Representing words and sentences as vectors for fast, parallel computation.
By the end of this chapter, you'll be able to:
- Represent a token's embedding as a NumPy vector
- Perform element-wise vector arithmetic
- Explain why NumPy operations replace explicit Python loops
Every embedding from the previous chapter — that list of numbers like [0.12, -0.87, 0.33, 0.05] — is a vector. Everything from here through the
Transformers section is built out of a small set of
operations on vectors and the matrices that stack them together.
Vectors, without the loops
Plain Python would represent a vector as a list, and any arithmetic on it would mean writing a loop. NumPy replaces that loop with a single expression:
import numpy as np
cat = np.array([1, 2, 3])
dog = np.array([2, 3, 4])
print(cat + dog)
# [3 5 7]
print(cat * dog)
# [2 6 12]
print(cat - dog)
# [-1 -1 -1]Each operation happens element-wise — position 0 with position 0, position 1 with position 1, and so on — across the entire vector at once, computed in optimized C rather than interpreted Python.
Why this matters at model scale
A real embedding isn't 3 numbers, it's often 768, 1536, or more — and a model processes thousands of them per batch. Looping through each dimension in plain Python would make training orders of magnitude slower. NumPy (and the GPU tensor libraries built on the same idea) is what makes the arithmetic in the rest of this handbook computationally feasible at all.
From one vector to a sentence
Stack several vectors together — one per token — and you get a matrix: a sentence represented as rows of numbers.
sentence = np.array([
[1, 2], # I
[3, 4], # love
[5, 6] # AI
])
# Normally we'd need nested loops. NumPy does it in one line.
scores = sentence @ sentence.T
print(scores)
# [[ 5 11 17]
# [11 25 39]
# [17 39 61]]| I | love | AI | |
|---|---|---|---|
| I | 5 | 11 | 17 |
| love | 11 | 25 | 39 |
| AI | 17 | 39 | 61 |
scores = sentence @ sentence.T — one dot product per pair of tokens.
The @ operator is matrix multiplication. sentence @ sentence.T compares every
token's vector against every other token's vector in one operation, producing a
3×3 grid of scores — one score per pair of tokens. That grid isn't just a curiosity:
it's the exact shape of the attention matrix, covered in the
Attention chapter. Everything there is this same
operation, applied to real embeddings instead of [1, 2] and [3, 4].
Check your understanding
1. What does cat + dog compute for cat = [1, 2, 3] and dog = [2, 3, 4]?
2. In sentence @ sentence.T, what does the resulting 3×3 matrix represent?