Transformers from the Ground Up · Part 1

Tokens, Embeddings, and the Linear Algebra Behind Them

Whenever you hear people talk about LLMs and transformers, it feels like they throw a hundred buzzwords at you at once: tokenizers, embeddings, projections, self-attention, and high-dimensional spaces. It sounds intimidating, but when you peel back the layers, computers don't understand words or feelings. They only understand numbers.

Most of my day-to-day background is in automation and DevOps, where the best way to understand anything is to take the machine apart piece by piece until you see how the gears actually turn. So in this post, I want to explain this to you the way I would explain it over coffee to a friend: how we turn plain English into lists of numbers, and the simple school math—vectors, matrices, addition, scaling, and dot products—that makes everything work under the hood.


1. The Terms You Need to Know First

Token

A token is just a small chunk of text that the computer reads. It does not have to be an entire word. Sometimes it is a full word like "cat", sometimes it is a piece of a word like "play" and "ing", or even just punctuation. For example, if you feed the sentence "Transformers are fast" to a model, it might break it into 4 pieces: ["Transform", "ers", " are", " fast"].

Tokenizer

The tokenizer is the translator tool. It takes the text you type, chops it into tokens, and hands each token a unique ID number from its dictionary. If you type the word "cat", the tokenizer looks up its catalog number and says: "That's ID 5421."

"cat" → [Tokenizer] → ID: 5421

Vocabulary & Vocab Size

The vocabulary is simply the entire list of words and subwords the tokenizer knows about. The total count in that dictionary is the vocab size (often called V). For example, GPT-2 knows 50,257 tokens. That means every token ID is just a whole number between 0 and 50,256.

Embedding

Here is the problem: computers can't do anything smart with ID numbers alone. ID 5421 is not "closer in meaning" to ID 5420 than ID 100. They are just arbitrary labels, like roll numbers in a classroom.

We need a way for words with similar meanings to live close to each other. An embedding is a lookup table that trades that ID number for a list of decimal numbers (a vector). If our model uses 4 numbers per word, the word "cat" turns into a list of 4 numbers:

ID: 5421 → [Embedding Table] → [0.5, 0.2, -0.3, 0.8]

Embedding Dimension (d_model)

The embedding dimension (written as d_model or just d) is how many numbers we give to each word. In our simple examples, we will use d = 4 so it fits on a single line. In big production models like LLaMA, that list is 4,096 numbers long. Each number tracks a tiny aspect of the word's meaning, style, or grammar.

Sequence Length (T)

The sequence length (called T) is simply how many tokens are in the sentence or paragraph you passed in. If you pass a 4-word sentence, your sequence length is 4.


2. Vectors & How We Do Math on Words

A vector is just an ordered list of numbers representing one token. In Python, we use NumPy to create and play with them:

import numpy as np

# A word vector representing 'cat' with 4 numbers
cat = np.array([0.5, 0.2, -0.3, 0.8])
print("Shape:", cat.shape)      # (4,)
print("Dimensions:", cat.ndim)  # 1

Now, what kind of math do we actually do with these lists of numbers?

A. Vector Addition: Combining Two Pieces of Info

Adding two vectors is easy: you just add the numbers in matching positions. In language models, we use this to blend two things together—like taking the base meaning of a word and adding its position in the sentence so the model knows where it sits:

combined = [0.5 + 0.1,   0.2 + (-0.1),   -0.3 + 0.2,   0.8 + (-0.1)]
cat = np.array([0.5, 0.2, -0.3, 0.8])
context = np.array([0.1, -0.1, 0.2, -0.1])

combined = cat + context
print("Combined vector:", combined)
# [0.6, 0.1, -0.1, 0.7]

B. Scaling: Turning the Volume Up or Down

Scaling just means multiplying every number in your list by a single number (a scalar). Think of it like turning a volume knob up or down on that word's importance:

word_vector = np.array([0.5, 0.3, -0.2, 0.8])
weight = 0.7  # say we only want 70% of this word's strength

scaled_vector = weight * word_vector
print("Scaled vector:", scaled_vector)
# [0.35, 0.21, -0.14, 0.56]

C. The Dot Product: How Similar Are Two Words?

This is the single most important math operation in modern AI. If you take two word vectors, multiply each matching pair of numbers, and sum them all up, you get one single number called the dot product.

a · b = (a1 × b1) + (a2 × b2) + ... + (an × bn)

What does that number mean? It tells you how closely aligned two words are. If the words point in similar directions, the score is high and positive. If they have nothing to do with each other, it's near zero. If they are opposites, it turns negative.

cat = np.array([0.5, 0.3, -0.2, 0.8])
dog = np.array([0.6, 0.2, -0.1, 0.7])
car = np.array([-0.2, 0.8, 0.5, -0.3])

cat_dog_similarity = np.dot(cat, dog)
cat_car_similarity = np.dot(cat, car)

print("cat · dog similarity:", cat_dog_similarity)  # 0.94 -> strong match!
print("cat · car similarity:", cat_car_similarity)  # -0.20 -> low / unrelated

D. Putting It Together: "Money in the Bank"

Words change meaning based on the words around them. Take the word "bank". Does it mean a river bank, or a place where you keep cash?

If you see the phrase "Money in the bank", you instantly know it's a financial bank because of the word "money". How does the math do that? We build what is called a context-aware composite vector:

  1. Check similarity (Dot Product): Compare bank against every surrounding word (money, in, the).
  2. Convert to percentages (Normalize weights): Divide each score by the total so they add up to 100% (1.0). money gets the highest percentage by far.
  3. Blend them (Scale + Add): Multiply each word by its percentage and add them all together. The new vector for "bank" is now colored by "money".
# 4-number vectors for each word in "Money in the bank"
money    = np.array([0.85, 0.10, 0.05, 0.75])  # finance-heavy vector
in_word  = np.array([0.15, 0.40, 0.35, 0.10])  # little helper preposition
the_word = np.array([0.10, 0.30, 0.40, 0.05])  # article
bank     = np.array([0.70, 0.25, 0.15, 0.60])  # our target word

# Step 1: Check similarity between 'bank' and each neighbor
score_money = np.dot(bank, money)
score_in    = np.dot(bank, in_word)
score_the   = np.dot(bank, the_word)

print(f"Similarity with 'money': {score_money:.3f}")  # 1.080 (highest!)
print(f"Similarity with 'in':    {score_in:.3f}")     # 0.318
print(f"Similarity with 'the':   {score_the:.3f}")    # 0.235

# Step 2: Turn scores into percentages that sum to 1.0
total = score_money + score_in + score_the
weight_money = score_money / total
weight_in    = score_in / total
weight_the   = score_the / total

print(f"\nWeights:")
print(f"  money : {weight_money:.3f} ({(weight_money * 100):.1f}%)")
print(f"  in    : {weight_in:.3f} ({(weight_in * 100):.1f}%)")
print(f"  the   : {weight_the:.3f} ({(weight_the * 100):.1f}%)")

# Step 3: Blend them together
context_aware_bank = (weight_money * money + 
                      weight_in * in_word + 
                      weight_the * the_word)

print("\nFinal context-aware vector for 'bank':")
print(context_aware_bank)
# Notice how the numbers are strongly pulled toward 'money'!

3. Matrices: Stacking Words Together

A matrix is simply a 2D table of numbers with rows and columns. When you take a 4-word sentence like "Money in the bank" and stack each word's 4 numbers as a row, you get a 4 × 4 matrix:

# Stacking our 4 words into one table: shape (4, 4)
sentence_matrix = np.array([
    [0.85, 0.10, 0.05, 0.75],  # Row 0: money
    [0.15, 0.40, 0.35, 0.10],  # Row 1: in
    [0.10, 0.30, 0.40, 0.05],  # Row 2: the
    [0.70, 0.25, 0.15, 0.60]   # Row 3: bank
])
print("Sentence Matrix shape:", sentence_matrix.shape)  # (4, 4)

Matrix Multiplication: The One Big Rule

When multiplying two matrices (using Python's @ operator), there is one strict rule you cannot break:

Matrix A of shape (M, K) × Matrix B of shape (K, N) → Output Matrix of shape (M, N)

The inside numbers must match! The number of columns in the first matrix must equal the number of rows in the second matrix. Why? Because the computer is taking each row from matrix A and calculating a dot product with each column in matrix B. If row A has 4 numbers, column B must also have 4 numbers, or the pairs don't line up.

A Real Example: Compressing / Reducing Dimensions

Why do we multiply matrices in practice? One common reason is to compress or project features into a smaller size. Suppose each word currently has 4 numbers, but we want to squeeze them down to just 2 numbers to save compute and keep only the most important signals.

We take our (4, 4) sentence matrix and multiply it by a projection matrix W of shape (4, 2):

(4 tokens, 4 features) × (4 features, 2 new features) → (4 tokens, 2 new features)
# A projection matrix with shape (4, 2)
# Notice: the 4 rows match our 4 token features!
W_reduce = np.array([
    [ 0.6, -0.2],
    [-0.1,  0.5],
    [ 0.0,  0.4],
    [ 0.8, -0.1]
])

print("Sentence shape:", sentence_matrix.shape)  # (4, 4)
print("Weight shape:  ", W_reduce.shape)        # (4, 2)

# Matrix multiplication compresses the words down to 2 dimensions:
reduced_tokens = sentence_matrix @ W_reduce

print("\nCompressed words (shape:", reduced_tokens.shape, "):")
print(reduced_tokens)
# All 4 words are now represented by just 2 numbers each!

Checking Every Word Against Every Other Word at Once

Remember how we used dot products to compare "bank" with its neighbors? Instead of writing loops, matrix multiplication lets us check every single word against every other word in the sentence in a single step using the transpose (X @ X.T):

# sentence_matrix: (4, 4)
# sentence_matrix.T (flipped rows & columns): (4, 4)
similarity_table = sentence_matrix @ sentence_matrix.T

print("All pairwise similarities at once:\n", np.round(similarity_table, 3))
# Row 3, Column 0 gives the exact dot product between 'bank' and 'money': 1.08!

Quick Recap

  1. Tokens & Vocabulary: Text is sliced into tokens, and the tokenizer looks up their integer ID from its vocabulary dictionary.
  2. Embeddings: We swap arbitrary IDs for continuous lists of numbers (vectors) where similar words live close together.
  3. Vectors: Addition blends concepts, scaling adjusts volume/importance, and dot products give a similarity score.
  4. Context-Aware Blending: By weighting surrounding words based on dot product similarity, a word like "bank" absorbs context from "money".
  5. Matrices: Stacking vectors into tables lets us run operations across the entire sentence simultaneously and compress dimensions using matrix multiplication.