Embeddings and Positional Encoding: Meaning, Geometry and Order
By the end of this lesson, you should be able to explain how an embedding matrix converts token IDs into semantic vectors, compute cosine similarity by hand, cleanly separate five frequently confused concepts (token ID, static embedding, positional signal, contextual state, retrieval embedding), explain why parallel Transformers require positional encoding and how RoPE encodes relative distance, and identify privacy and long-context risks tied to embeddings.
##
- Intuition first: GPS coordinates in meaning space
At the end of Lesson 23, "The bank approved the loan" became arbitrary integer IDs [791, 4820, 9142, 279, 8954]. Numbers like 4820 have no semantic geometry—4820 is not mathematically "near" 8954.
An embedding solves this by placing every token at a learned coordinate in a high-dimensional geometric space (for example, dimensions). Think of a 3D map upgraded to 4,096 axes:
- Financial concepts (
bank,loan,collateral,mortgage) cluster in one region. - Action/approval verbs (
approved,verified,authorised) share geometric directions. - Relationships themselves become directions (vectors): the offset from
approvetoapprovedpoints in nearly the same geometric direction asverifytoverified.
No human defines what Axis #1,492 means. Backpropagation (Lesson
- shapes every coordinate automatically so the model gets better at predicting text.
##
- Mechanics: the embedding matrix and worked cosine similarity
Inside an LLM, the token embedding layer is simply a trainable parameter matrix . For a model with tokens and , that lookup table alone holds . Selecting token ID 4820 pulls row 4820—mathematically identical to multiplying a one-hot vector by . *(Many models also use weight tying, reusing the transpose as the final output projection layer to save hundreds of millions of parameters.)*
### Worked example: measuring semantic proximity with Cosine Similarity To compare two vectors and regardless of magnitude, we compute Cosine Similarity:
Consider three illustrative 4D embeddings:
Step 1: Compute magnitudes (L2 norms)
||bank|| = sqrt(0.8^2 + (-0.4)^2 + 0.2^2 + 0.6^2) = sqrt(1.20) = 1.0954
||loan|| = sqrt(0.7^2 + (-0.3)^2 + 0.3^2 + 0.5^2) = sqrt(0.92) = 0.9592
||river|| = sqrt((-0.6)^2 + 0.7^2 + (-0.2)^2 + 0.1^2) = sqrt(0.90) = 0.9487Step 2: Compute dot products and cosine similarities
bank · loan = (0.8)(0.7) + (-0.4)(-0.3) + (0.2)(0.3) + (0.6)(0.5) = 0.56 + 0.12 + 0.06 + 0.30 = 1.04
cos(bank, loan) = 1.04 / (1.0954 * 0.9592) = +0.9898 (tightly aligned!)
bank · river = (0.8)(-0.6) + (-0.4)(0.7) + (0.2)(-0.2) + (0.6)(0.1) = -0.48 - 0.28 - 0.04 + 0.06 = -0.74
cos(bank, river) = -0.74 / (1.0954 * 0.9487) = -0.7121 (pointing apart!)##
- Why Transformers need Positional Encoding — and how RoPE works
Older Recurrent Neural Networks processed text sequentially (t = 1, then t = 2, then t = 3), so word order was baked into time steps. Transformers process every token in the prompt in parallel. Without positional information, Self-Attention is permutation-invariant—it sees a sentence as an unordered bag of vectors where "The bank sued the borrower" and "The borrower sued the bank" produce identical inputs!
Four major families of positional encoding evolved to solve this:
- Absolute Sinusoidal Encoding (Original 2017 Transformer): Adds fixed sine and cosine waves of different frequencies to each token embedding:
Think of it like a multi-hand binary clock: fast-spinning hands distinguish adjacent words (pos 4 vs. pos 5), while slow-spinning hands distinguish distant paragraphs (pos 50 vs. pos 500).
- Learned Absolute Positional Embeddings (GPT-2, BERT): Trains a second lookup table for positions
0 .. max_len - 1. Simple, but imposes a rigid ceiling: the model cannot easily read position2,049if it only learned rows0..2,047. - ALiBi (Attention with Linear Biases): Adds no vector to the input at all; instead subtracts a head-specific linear distance penalty directly from attention scores so distant tokens naturally receive slightly lower bias.
- RoPE — Rotary Positional Embeddings (Llama, Qwen, Gemma, Mistral): The dominant modern standard. Instead of *adding* a position vector at Layer 1, RoPE pairs up dimensions inside the Query and Key vectors (Lesson
- and rotates each 2D pair by angle (where is token position):
- Because rotating vector by and vector by leaves the angle between them equal to , the attention dot product naturally depends purely on their relative distance $(m - n)$!
- Even better, engineers can extend context windows (e.g., 8K → 128K) by smoothly rescaling RoPE's base frequency (NTK-aware / YaRN scaling) followed by short long-context fine-tuning.
##
- Clearing up the biggest terminology trap: five distinct concepts
Many articles loosely call all of these "embeddings." Keep them strictly separated:
| Concept | Mathematical form | Static or dynamic? | Role in the system |
|---|---|---|---|
| 1. Token ID | Single integer (4820) | Static | Vocabulary index output by the tokeniser |
| 2. Static Token Embedding | Vector | Static per token ID | Starting coordinate entering Layer 1 (mixes all senses of "bank") |
| 3. Positional Signal | Sinusoid or RoPE rotation | Function of index/offset | Encodes word order and relative token spacing |
| 4. Contextual Representation | Hidden state | Dynamic per prompt | Updated vector inside/after Transformer layers (knows "bank" = lender) |
| 5. Retrieval Embedding | 1 vector per passage/doc | Dynamic per passage | Output of a *dedicated embedding model* trained via contrastive learning for RAG/search |
##
- AI GRC and security implications
- Embeddings are not encryption (Inversion Risk): Research (such as *Vec2Text*) demonstrates that original text—including names, medical terms, and confidential clauses—can often be iteratively reconstructed from dense embedding vectors. Vector databases require the exact same encryption, RBAC, tenant isolation, and retention policies as source databases.
- Long-context degradation (“Lost in the Middle”): Even when RoPE scaling allows a 128K-token context window, models frequently attend strongly to the beginning and end of prompts while overlooking facts buried in the middle. Never rely on a giant context window alone for mandatory compliance rules without task-specific retrieval and evaluation.
- Model lock-in on vector indices: Vectors from Embedding Model A live in a totally different coordinate system from Embedding Model B. Switching embedding models requires re-indexing every document in your vector database—plan for re-embedding pipelines in your architecture and TCO budget.
##
- Common misconceptions
- “Static embeddings already know which sense of ‘bank’ a sentence means.” False. In the lookup table,
"bank"has only one vector. Disambiguation happens inside Self-Attention (Lesson 25). - “Positional encoding just appends the integer position 1, 2, 3 to the vector.” False. Unbounded integers like
50,000would overwhelm small floating-point embedding weights and ruin numerical stability. - “Storing vectors instead of raw text removes PII risk.” False. Vectors can leak sensitive attributes and be partially inverted back to text.
- “Cosine similarity of 0.85 proves two statements agree factually.” False.
"The bank approved the loan"and"The bank rejected the loan"share nearly identical words and context, so they often score high cosine similarity despite opposite meanings!
##
- Practical exercise
- Take two opposing compliance statements:
- A:
"Customer payment data must NOT be exported outside India." - B:
"Customer payment data may be exported outside India."
Explain why a retrieval embedding model may give A and B very high cosine similarity—and what downstream risk that creates in a policy Q&A assistant.
- Calculate by hand the cosine similarity between and , and between and .
- Audit a hypothetical enterprise RAG store: list four governance controls you would apply to the vector table itself.
##
- Knowledge check
- How many parameters are in a token embedding table with and ?
- Why would a Transformer without positional encoding confuse
"Bank sued borrower"with"Borrower sued bank"? - What mathematical property makes RoPE especially effective for attention and long-context scaling?
- What is the difference between an LLM's static token embedding and a contextual representation?
- Why can two factually opposite sentences still have high cosine similarity?
Answer key:
- parameters.
- Because Transformers process all tokens in parallel, making Self-Attention permutation-invariant without position signals.
- Rotating Q and K by position-proportional angles makes their dot product depend naturally on relative distance .
- A static embedding assigns one fixed starting vector per token ID; a contextual representation evolves across Transformer layers based on surrounding tokens.
- Because they occupy almost identical lexical and topical neighbourhoods in semantic space, differing mainly by a negation word.
##
- Checklist
- [ ] Distinguish Token IDs, Static Embeddings, Positional Signals, Contextual States, and Retrieval Embeddings.
- [ ] Verify whether your target LLM uses RoPE and test real retrieval accuracy in the middle of long prompts.
- [ ] Classify and protect vector databases at the same sensitivity tier as the source documents they embed.
- [ ] Budget for full corpus re-indexing whenever upgrading retrieval embedding models.
- [ ] Test negation-sensitive queries during semantic search evaluation.
- [ ] Pair semantic similarity with reranking or structured verification for high-stakes compliance checks.
##
- Further reading
- Vaswani et al. (2017): Attention Is All You Need (Sinusoidal Positional Encoding)
- Su et al. (2021): RoFormer — Enhanced Transformer with Rotary Position Embedding (RoPE)
- Liu et al. (2023): Lost in the Middle — How Language Models Use Long Contexts
- Morris et al. (2023): Text Embeddings Reveal (Almost) As Much As Text (Vec2Text)
- Jay Alammar: The Illustrated Word2vec
Help improve this learning path.
Suggest a concept we should teach, or tell us what is unclear. No account is required. Email is optional and only for a reply. Do not include confidential or sensitive information.