DEV Community

Hassan Imran
Hassan Imran

Posted on Edited on

Tokenization & Embeddings: How Stories Change into Vectors

Watch the full visual breakdown on YouTube here

This article teaches how to turn a single sentence into a concrete embedding matrix, exposing the math, the code, and the hidden failure modes.

Why Tokenization Matters

AI models cannot operate on inked sticky notes; they need numeric GPS‑style coordinates. Tokenization is the deterministic process that slices a string into atomic symbols and assigns each a stable integer ID. Those IDs become the bridge between human language and linear algebra.

From Text to Token IDs

The first transformation is a lookup in a vocabulary ledger.

sentence = "The cat chased shadows"
# 1️⃣ lower‑case & split
tokens = sentence.lower().split()               # ['the', 'cat', 'chased', 'shadows']
# 2️⃣ build a tiny vocab
vocab = {word: idx for idx, word in enumerate(tokens)}
# 3️⃣ map words → integer IDs
token_ids = np.array([vocab[w] for w in tokens])  # [0, 1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

Each integer is a one‑hot basis vector eᵢ ∈ {0,1}|V|, but we never materialise the full vector because multiplication with a zero‑filled row is wasteful.

Embedding Lookup – The Matrix Math

An embedding matrix Wₑ ∈ ℝ|V|×d stores a dense d‑dimensional vector for every token.

np.random.seed(42)
d_model = 4                                 # tiny for illustration
W_E = np.random.randn(len(vocab), d_model) * 0.1
# Direct row‑wise lookup – no explicit one‑hot multiplication
X = W_E[token_ids]                           # shape (4, 4)
print("Sentence matrix shape:", X.shape)
Enter fullscreen mode Exit fullscreen mode

The operation X = W_E[token_ids] is mathematically equivalent to eᵢᵀ·Wₑ but executes as a fast memory fetch. The result is a matrix X ∈ ℝ⁴ˣ⁴ where each row corresponds to a word’s embedding.

Architecture

Building the End‑to‑End Script

Below is the complete 20‑line script that tokenizes, looks up embeddings, and measures cosine similarity between two words. Run it verbatim to see the pipeline in action.

import numpy as np

# ----- 1️⃣ Input ---------------------------------------------------
sentence = "The cat chased shadows"

# ----- 2️⃣ Tokenization --------------------------------------------
tokens = sentence.lower().split()
vocab = {w: i for i, w in enumerate(tokens)}
ids = np.array([vocab[w] for w in tokens])

# ----- 3️⃣ Embedding matrix ----------------------------------------
np.random.seed(42)
dim = 4
W_E = np.random.randn(len(vocab), dim) * 0.1
X = W_E[ids]
print("X shape:", X.shape)

# ----- 4️⃣ Utility -------------------------------------------------
def cosine_sim(u, v):
    return np.dot(u, v) / (np.linalg.norm(u) * np.linalg.norm(v))

# ----- 5️⃣ Demo ----------------------------------------------------
print("cosine(cat, shadows):", cosine_sim(X[1], X[3]))
Enter fullscreen mode Exit fullscreen mode

Because the weights are random, the similarity score is noisy; swapping W_E for a pre‑trained matrix (e.g., from LangChain or Gemini) yields meaningful geometry.

Pitfalls of Naïve Embedding Strategies

  1. Out‑of‑vocabulary (OOV) failures – a word like moonlight raises KeyError. Modern tokenizers use sub‑word schemes (BPE, WordPiece) to guarantee coverage.
  2. Static semantics – a single row for bank cannot distinguish river bank from financial bank. Contextual models (ELMo, BERT, Gemini) generate dynamic vectors conditioned on surrounding tokens.
  3. Order blindness – the matrix X contains the same rows regardless of word order. Positional encoding must be added before self‑attention can exploit sequence structure.

Complexity Performance

Preparing for Positional Encoding (Next Step)

When the same four vectors are shuffled, the model still sees the identical set. The upcoming video will show how a sinusoidal Positional Encoding matrix PE ∈ ℝ⁴ˣ⁴ is added element‑wise (X_final = X + PE) to inject order information before the attention layers.


Companion Resources & Code

Stay tuned for the next deep‑dive: Positional Encoding – Turning Order into Vectors.

Top comments (0)