FullStack AI Hub
Studio
AI & LLM Systems · 01. Transformer Architecture
10 min
6 steps
Beginner

Tokenization, Embeddings & RoPE

Slice text into BPE subwords, inspect dense semantic embeddings, and rotate vectors with RoPE vs Sinusoidal waves.

AI & LLM Systems01. Transformer ArchitectureLesson 1 of 4
10 minBeginner6 steps

Tokenization, Embeddings & RoPE

Slice text into BPE subwords, inspect dense semantic embeddings, and rotate vectors with RoPE vs Sinusoidal waves.

SEQ TOKENS
12 tok
COMPRESSION
4.7 ch/tok
POS ENCODING
RoPE Rotary
RELATIVE Δ(m−n)
+4 pos
Tokenization · Embeddings · RoPE Lab
1. Subword Tokenization & IDs
2. Embedding Vector · “it”id #340 · d=8 preview
d0 anim
0.84
d1 loc
0.32
d2 verb
0.18
d3 mod
0.36
d4 pron
0.96
d5 open
0.24
d6 close
0.34
d7 code
0.08
Nearest Cosine Neighbors in Prompt
3. Positional Encoding
Q(m)K(n)
Q angle m·θ2.52 rad
K angle n·θ0.84 rad
Δ angle (m−n)θ1.68 rad
Shift Invariance Proof
dot(m=6, n=2) = -0.8972
dot(m+5, n+5) = -0.8972
In This LessonStep 1 of 6
What You Will Master
  • ✓Explain why Byte-Pair Encoding (BPE) balances vocabulary size against O(N²) sequence length
  • ✓Inspect how discrete token IDs project into dense semantic vectors measurable via cosine similarity
  • ✓Understand why self-attention is permutation-invariant without explicit positional encodings
  • ✓Verify how Rotary Positional Embeddings (RoPE) encode exact relative distance (m − n) via 2D rotation

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
BPE Subword TokenizationGeneral-purpose multilingual & code LLMs (GPT-4, Llama 3)Compresses ~4 chars/token without unknown <UNK> tokens, but struggles with character-level spelling
Sinusoidal PE (2017)Classic Encoder-Decoder Transformers with fixed training sequence lengthsAdded once to input embeddings; degrades rapidly when extrapolating past training context length
Learned Absolute PEFixed-window encoders like BERT (512 tokens) and early GPT-2Hard ceiling at max trained position — cannot attend beyond learned embedding table
RoPE (Rotary Position)Modern long-context LLMs (Llama 3, Mistral, Gemma, Qwen)Rotates Q/K pairs at every layer so dot product depends strictly on relative offset (m − n)

Step-by-Step Architectural Breakdown (6 Steps)

Full architectural walkthrough transcript and state transitions for Tokenization, Embeddings & RoPE.

STEP 01 · SETUPJump to step →

Why LLMs Never Read Characters or Whole Words

Transformers only operate on fixed-size numeric tensors, so raw strings must first be sliced into integer **Token IDs**. Splitting by single characters explodes sequence length (`N`) and makes $O(N^2)$ attention impossibly slow; splitting by whole words creates millions of rare out-of-vocabulary words.

**Byte-Pair Encoding (BPE)** repeatedly merges the most frequent adjacent byte pairs to build a vocabulary of ~50K–128K subwords. Notice how `"didn't"` splits cleanly into `didn` + `'t`, achieving ~4.7 characters per token.

idea:Click any token chip on the stage or switch between BPE Subword, Word, and Character granularity to watch token count explode.

BPE TokenizationSubword VocabularyCompression Ratio
STEP 02 · TECHNIQUEJump to step →

Embedding Lookup: From Token IDs to Semantic Geometry

Each integer token ID indexes a row in the learned **Embedding Matrix** $W_E \in \mathbb{R}^{V \times d_{\text{model}}}$. In an 8B model, every token becomes a 4,096-dimensional floating-point vector encoding semantic and syntactic features.

Click `"animal"`, `"it"`, and `"tired"` on the stage to compare their embedding barcodes and **Nearest Cosine Neighbors**—words that play related semantic roles point in similar directions in embedding space.

good:Embeddings are just lookup tables at layer 0: the word "bank" starts with the exact same static vector whether it means river bank or money bank. Self-attention contextualizes it next.

Embedding MatrixCosine Similarityd_model
STEP 03 · PROBLEMJump to step →

The Order Blindness Problem of Self-Attention

Unlike RNNs that process one word after another, a Transformer processes **all tokens in parallel**. Pure self-attention treats a sentence as an unordered bag of vectors: `"Dog bites man"` and `"Man bites dog"` would produce identical attention sets!

To preserve word order without reintroducing slow sequential recurrence, the original 2017 Transformer added deterministic **Sinusoidal Positional Encodings** directly onto each token embedding before layer 1.

watch:Without positional information, attention weights depend only on token content—completely ignoring whether a word appeared 2 tokens ago or 2,000 tokens ago.

Permutation InvarianceSinusoidal PEMulti-Frequency Clock
STEP 04 · SOLUTIONJump to step →

RoPE: Encoding Relative Distance as 2D Phase Rotation

Additive sinusoidal encodings mix position into the semantic vector once at the input, and fade across deep layers. Modern LLMs (Llama 3, Mistral, Gemma) instead use **Rotary Positional Embeddings (RoPE)** inside every attention layer.

RoPE groups each Query and Key vector into 2D coordinate pairs and **rotates** them by angle $m\theta_i$ and $n\theta_i$ on the unit circle. Because rotating two vectors by $m\theta$ and $n\theta$ leaves the angle between them equal to $(m - n)\theta$, their dot product depends **only on relative distance**!

good:Watch the green Shift Invariance Proof box on the stage: shifting both m and n forward by +5 changes absolute angles, yet dot(m, n) and dot(m+5, n+5) match to 4 decimal places.

RoPE2D Rotation MatrixRelative Position Invariance
STEP 05 · TRADE-OFFJump to step →

Long-Context Scaling & RoPE Base Frequency (YaRN / NTK)

Modern LLMs extend context windows from 8K to 128K+ tokens by scaling RoPE’s base wavelength (for example raising base $\theta$ from `10,000` to `500,000` in Llama 3 or applying **YaRN** frequency interpolation) so distant tokens don’t alias into unseen phase collisions.

At the same time, tokenizer efficiency directly multiplies effective context: a well-trained 128K BPE vocabulary fits ~20% more code and multilingual text into the same KV-cache budget than a 32K vocabulary.

idea:Larger vocabularies shorten sequences (faster attention), but increase the size of the embedding and final LM-head logit projection matrices.

RoPE Base ScalingYaRNVocabulary Trade-off
STEP 06 · RECAPJump to step →

Recap: From Raw Text to Position-Aware Tensors

Before a single attention score is computed, every prompt completes three steps: **BPE subword tokenization** compresses text into IDs, **embedding lookup** maps IDs into dense semantic vectors, and **RoPE** prepares 2D phase rotations so relative distance survives every attention dot product.

Next, we take these position-aware vectors directly into the heart of the Transformer: **Scaled Dot-Product Self-Attention (Q, K, V)**.

good:Tensor shape leaving this stage: [Batch, SeqLen, d_model]. Every token is now a rich geometric vector ready to query the entire context.

Input PipelineTensor ShapesRelative Phase

Related Production Deep-Dives & Simulators

Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.