Welcome to this module on embedding techniques in modern machine learning. Today we outline the core topics, establishing the mathematical and engineering foundations you will need throughout.
We begin with an overview of embedding concepts: how learned vector representations map discrete tokens into a continuous space where semantic similarity becomes geometric proximity.
Core topics include token and byte-level embeddings, positional encoding strategies from sinusoids to rotary embeddings, semantic structure in embedding space, and how scale affects representation quality.
To connect theory with practice, we will work through implementation snippets in Python and PyTorch, so you can construct and train these embedding layers directly in code.
We will also develop the mathematical foundations, including the sinusoidal positional encoding formulas from Vaswani et al., to see precisely how positional information enters the residual stream.
By the end, you will understand both the mathematics and the implementation of efficient embedding layers, giving you the theoretical insight and practical skill to use them in modern architectures.
Equations, code and original cards
Course Introduction and Learning Goals
• Overview of embedding concepts: learned vector representations of discrete tokens
Embedding Basics: Tokenization and Byte-Pair Encoding (BPE)
Welcome. This lecture covers tokenization and Byte-Pair Encoding, BPE, the subword segmentation algorithm underlying essentially every modern language model, from the GPT family to LLaMA. These choices determine the input representation the entire residual stream is built on.
Tokenization maps raw text to a sequence of discrete symbols drawn from a fixed vocabulary. Operating on bytes rather than Unicode characters guarantees full coverage of any language or symbol, while subword units keep rare words compositional instead of collapsing them into an unknown token.
Here is the core BPE merge loop in Python. We initialize with character-level tokens, count all adjacent pairs, and greedily merge the most frequent one. Repeating this builds a vocabulary of subword units that interpolates between character-level granularity and word-level efficiency.
Formally, the merge set M is an ordered list of token pairs, each selected by argmax over corpus pair frequencies at that iteration. The order matters: at inference, merges are applied in exactly the learned priority sequence, which makes the segmentation deterministic and reproducible.
The vocabulary size is a hyperparameter set by the number of merge operations, typically thirty-two thousand to one hundred thousand. Larger vocabularies shorten sequences, reducing attention's quadratic cost, but inflate the embedding matrix and the softmax over the output logits.
To summarize: tokenization discretizes text, BPE greedily constructs a frequency-optimal subword vocabulary, and the vocabulary size trades sequence length against embedding and softmax cost. This representation is the foundation on which embeddings, and everything downstream, are defined.
Equations, code and original cards
Embedding Basics: Tokenization and Byte-Pair Encoding (BPE)
• Tokenization: text → discrete token sequence; byte-level fallback for full coverage
• BPE: greedy frequency-based merge of adjacent token pairs
We formalize token embeddings: the interface between discrete symbols and the continuous residual stream consumed by modern language models. The slide states the object precisely; the mechanism is indexing, not magic.
Define the embedding matrix as a real matrix with vocabulary-size rows and model-width columns. Row i is the dense vector assigned to token i, its initial representation in the residual stream before position and context are added.
The lookup extracts token i's vector by selecting row i of the embedding matrix. Computationally this is indexing; algebraically it is a one-hot row vector transposed and multiplied by that matrix, placing a single one at position i.
Formally, the embedding of token i equals the one-hot vector for token i transposed times the embedding matrix. Because the one-hot vector has a single one, the product copies row i and never mixes rows.
For updates, backpropagation accumulates the loss gradient into the embedding matrix only at active rows: the gradient with respect to that matrix is a sparse scatter of upstream vectors, summed over every occurrence of each token.
The PyTorch fragment wraps this in torch dot nn dot Embedding: integer indices in, dense vectors out, and autograd populates the embedding weight's grad field after loss dot backward, ready for the optimizer.
Summary: embeddings are a learned table, lookup is one-hot selection, and learning is sparse gradient accumulation into touched rows. This simple parameterization anchors representations before attention and position encode context.
Equations, code and original cards
Token Embeddings: Discrete Indices to Continuous Vectors
• Embedding matrix: E ∈ ℝV×d
• V: vocabulary size, often 50k–256k
• d: model width / residual-stream dimension
• Lookup: select row i from E for token i
• Equivalent views: integer indexing or one-hot product:
x_i^T E = e_i, a row copy with no mixing
\mathbf{e}_i = \mathbf{x}_i \times \mathbf{E}
• Gradient: ∂L/∂E is row-sparse
• Backprop through lookup scatters upstream gradients:
∂L/∂E = Σ occurrences g_t x_iᵀ; only active rows update
import torchE = torch.nn.Embedding(V, d) # learned tableidx = torch.LongTensor([token_indices])h = E(idx) # gather rows to [batch, time, d]loss = compute_loss(h)loss.backward() # E.weight.grad touched at active rows
Moment 04 / 14
Interactive Visualization: Token Byte Breakdown
Let's explore the token byte breakdown through this interactive diagram. Click each token node to reveal how raw text transforms into subword tokens and their underlying UTF-8 byte representation.
Notice how tokens decompose into UTF-8 bytes, each byte influencing model cost. Sequence length drives the quadratic attention term, so tokenization granularity directly shapes compute.
Larger vocabularies reduce average token length, but increase embedding matrix size. The vocabulary scales the embedding parameters linearly while shrinking the sequence length, so weigh this trade-off as you explore.
Finally, see how tokens map to embedding indices, implemented in PyTorch as an embedding lookup table taking vocabulary size and embedding dimension. This ties tokenization directly to the model's input representation.
Equations, code and original cards
Moment 05 / 14
Positional Encoding Fundamentals
Positional encoding addresses a structural limitation of the transformer: the self-attention operator is permutation-equivariant, so the residual stream carries no information about token order. Absent positional signals, the model reduces a sequence to a bag of embeddings.
Concretely, shuffling the input tokens merely shuffles the output rows; attention scores depend only on content, not position. Positional encoding breaks this symmetry by injecting order information, which the causal mask alone cannot supply for absolute location.
The original scheme of Vaswani et al. 2017 uses fixed sinusoids: the even dimension two-i of the vector at position pos is sine of pos over ten-thousand raised to two-i over d, and the odd dimension uses cosine. Because offsets appear as phase shifts, relative position is encoded linearly across frequencies.
Being parameter-free, sinusoidal encodings impose a useful inductive bias and extrapolate, at least in principle, to sequence lengths beyond those seen in training.
Learned absolute embeddings instead train one vector per position, offering flexibility at the cost of a hard cap at the maximum training length and weaker length extrapolation.
Rotary Position Embeddings, introduced by Su et al., take a different route: query and key vectors are rotated in two-dimensional subspaces by an angle proportional to position, so the attention dot product depends only on relative offset. RoPE is now standard in modern large language models.
Here is the sinusoidal construction in PyTorch. Note the geometric spacing of frequencies via the exponential of the log-ten-thousand term, and the interleaving of sine and cosine across even and odd channels.
To summarize: positional encoding restores order sensitivity to a permutation-equivariant architecture. Fixed sinusoids, learned embeddings, and rotary schemes differ in parameterization, extrapolation behavior, and whether they encode absolute or relative position.
Equations, code and original cards
Positional Encoding Fundamentals
• Self-attention is permutation-equivariant: no intrinsic order signal
• Sinusoidal encoding (Vaswani et al. 2017):
– PE(pos, 2i) = sin \bigl(\frac{pos}{10000^{2i/d}}\bigr)
– PE(pos, 2i+1) = cos \bigl(\frac{pos}{10000^{2i/d}}\bigr)
• Learned absolute embeddings vs. parameter-free functions
• Variants: RoPE (Su et al.), ALiBi (linear attention bias)
\text{For position } pos \in \{0,...,L-1\} \text{ and embedding dimension } d:
We now derive positional embeddings from first principles: the mechanism that injects sequence order into a transformer whose self-attention is otherwise permutation-equivariant and therefore blind to token position.
Define the positional encoding matrix P with shape L by d, where L is the maximum sequence length and d the model dimension. Row pos of P is a deterministic code for absolute position, added directly into the residual stream.
Vaswani et al. build that code from sinusoids: even channels take sine of pos over ten thousand raised to two i over d, odd channels take cosine, so wavelength grows geometrically across the embedding dimensions.
The PyTorch implementation broadcasts position indices against dimension indices to form angles, applies sine to even columns and cosine to odd columns, and returns an L by d tensor that is continuous, differentiable, and fixed.
Because this code is added element-wise to token embeddings, attention logits become sensitive to relative offsets: the inner product between two sinusoidal codes varies smoothly with their distance, without introducing a single trainable parameter.
Learned positional embeddings instead treat P as a parameter updated by backpropagation. That buys expressiveness and task-specific structure, but costs L times d parameters and typically extrapolates poorly beyond the training length.
The takeaway: sinusoidal encodings give an extrapolatable, parameter-free inductive bias for order, while learned encodings trade that bias for flexibility; rotary variants such as RoPE refine the same relative-position idea.
Equations, code and original cards
Mathematical Derivation of Positional Embeddings
• Define \( P \in \mathbb{R}^{L\times d} \): row \( pos \) encodes absolute position, added to the residual stream
• Sinusoidal codes (Vaswani et al. 2017), wavelength geometric in dimension \( i \):
Let's begin with semantic word maps and embedding space geometry, where lexical meaning is encoded as points in a continuous high-dimensional vector space.
First, consider vector space representations: each word maps to a dense vector in, say, 768 dimensions, letting us capture semantic relationships as geometric structure rather than symbolic rules.
To quantify semantic similarity between word vectors, we use cosine similarity, which measures the cosine of the angle between two vectors and is invariant to their magnitude.
Formally, cosine similarity is the dot product of u and v divided by the product of their Euclidean norms, yielding a value between minus one and one, with one indicating identical direction.
Next, a PyTorch implementation: this computes cosine similarity between two tensors directly, showing how the mathematical definition translates into a few lines of efficient code.
The snippet normalizes via the dot product over the norms; in practice you'd use torch dot n n functional cosine similarity, which batches over dimensions and stabilizes gradients.
Finally, consider scale and dimensionality: in high dimensions, embeddings concentrate on a manifold, distances concentrate, and clustering behavior shifts, which shapes how semantic structure is captured.
In summary, semantic word maps arise from vector space models, are measured through cosine similarity, and are implemented efficiently in PyTorch. These foundations underpin modern representation learning.
Here we visualize word embeddings projected into three dimensions. Watch how the vectors cluster by semantic relatedness, since proximity in this space encodes meaning.
The rotation speed slider controls the camera orbit. Continuous rotation exploits motion parallax, helping you perceive depth and spatial relationships within the projection.
The vector scale slider compares normalized against raw embeddings. Because cosine similarity ignores magnitude, rescaling exposes how vector norms distort semantic distances.
Zoom in to inspect individual clusters. Nearest neighbors under cosine distance are the operational definition of semantic similarity in embedding space.
The reset button restores the default camera and parameters, returning you to the canonical view whenever you want a clean baseline.
Equations, code and original cards
Moment 09 / 14
Scale Comparison in Embeddings
Let's examine scale in embedding spaces—a property that determines whether two vectors are close because they share direction or merely because one has larger norm.
Distinguish normalized from raw embeddings. Unit-normalized vectors live on the hypersphere, retaining only direction; raw embeddings preserve magnitude, which conflates scale with semantic content.
Scale directly determines your similarity metric's behavior. The dot product grows linearly with vector norms, whereas cosine similarity divides by them, isolating pure angular agreement.
Cosine similarity is the dot product divided by the product of the two norms. Dividing out the magnitudes leaves only the cosine of the angle between the vectors.
The raw dot product, by contrast, scales multiplicatively with both norms—so a high-magnitude embedding dominates the score regardless of directional alignment.
Downstream, attention logits are query-key dot products, so embedding scale directly shifts logit magnitude, sharpening or flattening the softmax distribution over keys.
Formally, write any vector as a scalar alpha times a unit direction. Then the dot product factors into alpha times beta times the directional agreement—scale decouples cleanly.
Here is a PyTorch snippet constructing a raw embedding and its normalized counterpart, letting you probe scale effects on dot products directly.
The takeaway: scale is not noise—it is a design choice. Whether you normalize determines what your similarity scores and attention weights actually measure.
Welcome to advanced PyTorch implementations for transformer input pipelines: token embeddings, sinusoidal positional encodings, and their junction with the residual stream. We will read the code as architecture, not boilerplate.
Begin with the embedding layer: torch dot n n dot Embedding allocates a learned matrix whose rows are indexed by token ids and whose columns form the dense features entering the residual stream.
A typical call passes vocabulary size and model width, for example ten thousand by five hundred twelve; Xavier uniform initialization keeps early logits and gradient norms from exploding.
For position, the naive intuition is that attention sees order automatically; it does not. Vaswani and colleagues added fixed sinusoids so relative offsets become linear structure in attention space.
The implementation builds wavelengths geometrically: even channels take sine of position times a frequency, odd channels take cosine, with frequency falling as dimension index rises across the width.
In the forward pass, token embeddings and the positional slice are summed before layer normalization; autograd then backpropagates cross entropy through that sum into the embedding matrix.
Integrated this way, the same residual stream carries identity and order into causal self attention, letting heads compute content based and position aware logits under masking.
The takeaway is control: initialize embeddings deliberately, choose sinusoidal, learned, or rotary position encodings by inductive bias, and ablate them under fixed seeds; small input side choices move perplexity, optimization stability, and downstream transfer more than most students expect.
Equations, code and original cards
Advanced Implementations: Transformer Inputs in PyTorch
Embeddings, Sinusoidal Positional Encodings & the Residual Stream
Embedding Layer Creation
• Learned lookup table: token id to row vector at model width
• Init: pretrained, Xavier uniform, or scaled normal; freeze vs fine-tune
• Example: embedding = nn.Embedding(50000, 768)
# Embedding Layer Setupembedding = nn.Embedding(50000, 768) # vocabulary x model widthnn.init.xavier_uniform_(embedding.weight) # stable early logits
Sinusoidal Positional Encoding
• Fixed order signal; attention alone is permutation equivariant
Forward & Backward Pass Snippets• Forward: sum token embedding with positional slice before blocks• Autograd routes cross-entropy gradients into the lookup matrixdef forward(self, x): x_embed = self.embedding(x) # token identity features x_pos = self.pos_encoding[:, :x.size(1), :] # order features return self.drop(x_embed + x_pos) # residual-stream input
Integration into Transformer Architecture
• Embedding sum is the residual-stream input to causal masked self-attention
• Order context lets heads form position-aware logits without recurrence
• Ablate sinusoidal vs learned vs rotary: measure perplexity and stability
Moment 11 / 14
State-of-the-Art Techniques and Optimizations (2024-2026)
This scene covers recent advances in embedding design, roughly 2024 through 2026. The thrust is memory and compute efficiency at scale: as vocabularies and hidden dimensions grow, the embedding matrix becomes a first-order bottleneck in large language models.
We begin with the embedding table itself, targeting size and sparsity. Structured pruning, low-rank factorization, and quantization compress the matrix substantially while preserving downstream accuracy.
Sparsity trades capacity for efficiency. A sparse embedding constrains most entries toward zero, cutting both the memory footprint and the effective parameter count the optimizer must update.
Formally, sparsity is defined as the fraction of zero entries in the embedding matrix. This scalar lets you compare compression schemes and reason about the accuracy-efficiency tradeoff quantitatively.
In practice, PyTorch exposes this through torch dot n n dot Embedding. Here we allocate ten thousand rows of dimension two hundred fifty-six, and the sparse flag restricts gradient updates to the rows actually indexed.
On the research frontier, alignment and calibration methods fine-tune pretrained embeddings so that geometric proximity tracks semantic similarity, improving retrieval quality and downstream task performance.
Scaling laws, embedding compression, and modern tokenization jointly determine model quality per parameter. These are not peripheral optimizations; they underpin retrieval-augmented systems and efficient deployment at scale.
Clarification: The nonzero fraction is density, not sparsity.
Equations, code and original cards
State-of-the-Art Techniques and Optimizations (2024-2026)
Definition: sparsity equals the fraction of zero entries in the embedding matrix
Embedding Alignment & Calibration (2026)
Moment 12 / 14
Open Research and Cutting-Edge Variations
We now turn to open problems in embedding research: context dependence, cross-lingual alignment, multimodal grounding, and interpretability, where representation learning remains unsettled.
Contextual embeddings replace a fixed type vector with a function of the sequence; ELMo and BERT made the hidden state, not the lookup table, the representation.
This PyTorch sketch adds a context-conditioned residual to a static embedding, a minimal analogue of adapter or prompt-tuning updates learned during optimization.
The class subclasses torch dot nn dot Module, registers an embedding table as a parameter, and composes it with context inside forward, so autograd reaches every weight.
Mathematically, the output is the base embedding plus a broadcast context vector; gradients flow through both terms, so the residual stream is shaped by sequence state.
Current work extends this to XLM-style cross-lingual alignment, CLIP-style image-text contrastive spaces, probing and sparse-autoencoder interpretability, and retrieval-augmented architectures that treat embeddings as addressable memory, with open questions in bias, geometry, and evaluation.
The takeaway is that embeddings are learned interfaces between symbols, context, and modality; progress now depends on alignment, diagnostics, and architectures that expose them.
Equations, code and original cards
Open Problems in Modern Embedding Research
• Contextual embeddings: hidden states as functions of the sequence
• Cross-lingual and multimodal alignment in shared contrastive spaces
• Interpretability: probing, geometry, causality, and feature disentanglement
• Retrieval, adapters, and sparse memory as embedding-centric architectures
Now test whether the embedding mechanics have taken hold: subword tokenization, nearest-neighbor geometry, and the training objective. Work independently; derive each answer rather than guessing.
After submission, we will audit the errors: inspect logits, cosine similarities, and gradient norms, then isolate which assumption failed. Answer precisely.
Equations, code and original cards
Moment 14 / 14
Summary and Key Takeaways
Let's close by consolidating the core results. These four pillars—tokenization, positional structure, embedding geometry, and implementation—underpin every modern transformer.
First, tokenization and byte pair encoding: greedy merge operations compress raw text into a subword vocabulary, trading sequence length against vocabulary size and shaping the effective token distribution.
Second, positional encoding injects order into otherwise permutation-equivariant self-attention; without it, attention is blind to arrangement, so position must be supplied explicitly to the residual stream.
The sinusoidal scheme of Vaswani et al. 2017 encodes position as sines and cosines across geometrically spaced frequencies, yielding fixed vectors whose relative offsets remain linearly decodable.
We then analyzed embedding geometry: semantic similarity concentrates along directions, anisotropy and norm imbalance distort cosine metrics, and dimensionality governs capacity and downstream generalization.
Finally, we connected theory to practice—rotary embeddings, normalization choices, and PyTorch modules—showing how registering positional constants as buffers keeps them persistent, device-consistent, and excluded from gradient updates.
Master these mechanisms and the residual stream, causal masking, and scaled dot-product attention become natural next steps rather than black boxes.
import torch
import torch.nn as nn
class PositionalEncoding(nn.Module):
def __init__(self, d_model, max_len=5000):
super().__init__()
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2) * (-\log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
self.register_buffer('pe', pe.unsqueeze(0))
def forward(self, x):
x = x + self.pe[:, :x.size(1), :]
return x
MAKE IT YOURS
Explain the change.
References, scope & corrections
Research snapshots in the source material are not a claim of current state of the art. The reference review corrects identified errors; it is not exhaustive certification of every historical statement. Source code snippets are examples, not a tested production training system.