PJ's Guide to Large Language Models

Chapter 1: Tokenization, Embedding Spaces & Rotary Position Geometry

1.1 Discrete Text to Subword Codes: BPE & Unigram LM

An autoregressive Large Language Model defines a probability distribution over finite sequences of discrete symbols drawn from a vocabulary V of cardinality |V| (typically 32,768 to 256,000 in frontier models). Character-level vocabularies produce prohibitively long sequences under quadratic self-attention O(S2), whereas word-level vocabularies suffer from open-vocabulary out-of-distribution (OOV) failures and Zipfian tail sparsity.

Modern LLMs resolve this rate-distortion trade-off via deterministic subword compression, predominantly Byte-Level Byte-Pair Encoding (BBPE). Starting from the 256 raw UTF-8 byte primitives (guaranteeing zero <UNK> tokens for any arbitrary Unicode string), BBPE iteratively merges the adjacent symbol pair (a, b) maximizing corpus co-occurrence frequency:

Puppy PJ inspecting byte-level subword entropy
Fig 1.1 — Entropy Floor
H(X) = −∑ p(x) log2 p(x)

Even as a 2-pound puppy, Ms. PJ understood that unmerged UTF-8 bytes inflate sequence length by ~4×.

(a*, b*) = arg max(a,b) ∈ Vt×Vt Count&calig;(a, b),    Vt+1 = Vt ∪ {a* ⊕ b*}
(1.1)

In contrast, Unigram Language Model tokenization (Kudo, 2018; SentencePiece) initializes an oversized seed vocabulary and prunes tokens via Expectation-Maximization to minimize negative marginal log-likelihood over all valid segmentations S(x) of a string x, where the Viterbi algorithm decodes the maximum-probability segmentation x* = arg maxs∈S(x) ∏i p(si).

Larger vocabularies (e.g., 128k–256k tokens) improve compression ratio (bytes/token) and multilingual fertility, directly reducing both pre-training FLOPs per gigabyte and inference decode latency. However, they inflate the embedding and language-modeling head parameter footprint WE ∈ ℝ|V|×d and softmax normalization cost per step.

1.2 Embedding Geometry & Weight Tying

Given token indices t = (t1, …, tS), the initial residual stream state is formed by table lookup hi(0) = etiTWE ∈ ℝd. At the output of the final Transformer block L, logits over V are projected via zi = WU Norm(hi(L)). Smaller models frequently enforce weight tying (WU = WE), whereas frontier models (>7B parameters) typically untie WE and WU so input representations and output probability geometry can decouple without rank interference.

1.3 Permutation Invariance & Rotary Position Embeddings (RoPE)

Self-attention without positional injection is strictly permutation-equivariant: permuting input rows by any permutation matrix P yields Attn(PX) = P Attn(X). Early Transformers added absolute sinusoidal vectors pm directly to hm(0), contaminating semantic residual subspaces and degrading beyond training length.

Rotary Position Embedding (RoPE) (Su et al., 2021) instead injects relative positional information directly into the query and key inner product by applying a position-dependent orthogonal rotation matrix RΘ,md ∈ SO(d) composed of d/2 independent 2×2 planar rotations with geometric frequency schedule θi = b−2(i−1)/d (standard base b = 10,000, scaled to 500,000–10,000,000 for 128k–1M contexts):

RΘ,md = diagi=1..d/2 [ cos(mθi)   −sin(mθi) ;   sin(mθi)   cos(mθi) ]
(1.2)

Because planar rotation matrices form a commutative Abelian subgroup satisfying (RΘ,m)TRΘ,n = RΘ,n−m, the dot product between a rotated query at position m and a rotated key at position n depends strictly on the relative displacement (n − m), while preserving vector Euclidean norms ||Rmq||2 = ||q||2:

⟨ RΘ,md qm,   RΘ,nd kn ⟩ = qmT (RΘ,md)T RΘ,nd kn = qmT RΘ,n−md kn
(1.3)
R(mθ₁)q R(nθ₁)k (n−m)θ₁ Subspace i=1 (High Freq / Local) RoPE Wavelength Spectrum & Context Extension Low dim i: short wavelength (captures syntax & adjacent tokens) High dim i: long wavelength (scaled by NTK / YaRN for 128k–1M ctx)

Fig 1.2 — Orthogonal complex-plane rotation in RoPE preserves Euclidean inner-product geometry as a pure function of relative offset (n − m).

1.4 Long-Context Extrapolation: NTK-Aware Scaling & YaRN

Naïvely extending context length L' = sL via linear Position Interpolation (m → m/s) compresses high-frequency dimensions, blurring local token order. NTK-Aware RoPE increases the base b → b′ = b·sd/(d−2) so high frequencies remain unstretched while low frequencies interpolate smoothly. YaRN (Yet another RoPE extensioN) partitions dimensions by wavelength ratio r(i) = L / λi, interpolating low-frequency bands, leaving high-frequency bands untouched, and applying an attention-temperature correction t = (0.1 ln s + 1)2 to stabilize softmax entropy.

Prof. PJ's Bench Note: Think of RoPE wavelengths like my acoustic surveillance from the windowsill. High-frequency dimensions resolve the exact millimeter between two crumbs on the carpet; low-frequency dimensions track the UPS truck turning onto the avenue three blocks away.
« Previous: Guide Portal [ Table of Contents ] Next: Ch. 2 — Attention & FlashAttention »