CNSLT ACADEMY / INSIDE MODERN AI MODELS

Embeddings and Positional Encoding: Meaning, Geometry and Order

FOUNDATIONSBEGINNERFREE TEXT LESSONVIDEO 🔒 PRO

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.

Embeddings and Positional Encoding: Meaning, Geometry and Order

##

  1. 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, dmodel=4,096d_{\text{model}} = 4,096 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 approve to approved points in nearly the same geometric direction as verify to verified.

No human defines what Axis #1,492 means. Backpropagation (Lesson

  1. shapes every coordinate automatically so the model gets better at predicting text.

##

  1. Mechanics: the embedding matrix and worked cosine similarity

Inside an LLM, the token embedding layer is simply a trainable parameter matrix E∈RV×dmodelE \in \mathbb{R}^{V \times d_{\text{model}}}. For a model with V=128,000V = 128,000 tokens and dmodel=4,096d_{\text{model}} = 4,096, that lookup table alone holds 128,000×4,096≈524 million parameters128,000 \times 4,096 \approx 524\text{ million parameters}. Selecting token ID 4820 pulls row 4820—mathematically identical to multiplying a one-hot vector by EE. *(Many models also use weight tying, reusing the transpose ETE^T 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 a\mathbf{a} and b\mathbf{b} regardless of magnitude, we compute Cosine Similarity:

cos⁡(a,b)=a⋅b∥a∥ ∥b∥\cos(\mathbf{a}, \mathbf{b}) = \frac{\mathbf{a} \cdot \mathbf{b}}{\|\mathbf{a}\| \, \|\mathbf{b}\|}

Consider three illustrative 4D embeddings:

  • vbank=[0.8,−0.4,0.2,0.6]\mathbf{v}_{\text{bank}} = [0.8, -0.4, 0.2, 0.6]
  • vloan=[0.7,−0.3,0.3,0.5]\mathbf{v}_{\text{loan}} = [0.7, -0.3, 0.3, 0.5]
  • vriver=[−0.6,0.7,−0.2,0.1]\mathbf{v}_{\text{river}} = [-0.6, 0.7, -0.2, 0.1]

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.9487

Step 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!)

##

  1. 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:

  1. Absolute Sinusoidal Encoding (Original 2017 Transformer): Adds fixed sine and cosine waves of different frequencies to each token embedding:
PE(pos,2i)=sin⁡(pos100002i/d),PE(pos,2i+1)=cos⁡(pos100002i/d)PE_{(pos, 2i)} = \sin\left(\frac{pos}{10000^{2i/d}}\right), \quad PE_{(pos, 2i+1)} = \cos\left(\frac{pos}{10000^{2i/d}}\right)

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).

  1. 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 position 2,049 if it only learned rows 0..2,047.
  2. 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.
  3. 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
  4. and rotates each 2D pair by angle m⋅θim \cdot \theta_i (where mm is token position):
  • Because rotating vector q\mathbf{q} by mθm\theta and vector k\mathbf{k} by nθn\theta leaves the angle between them equal to (m−n)θ(m - n)\theta, the attention dot product qmTkn\mathbf{q}_m^T \mathbf{k}_n 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 θ\theta (NTK-aware / YaRN scaling) followed by short long-context fine-tuning.

##

  1. Clearing up the biggest terminology trap: five distinct concepts

Many articles loosely call all of these "embeddings." Keep them strictly separated:

ConceptMathematical formStatic or dynamic?Role in the system
1. Token IDSingle integer (4820)StaticVocabulary index output by the tokeniser
2. Static Token EmbeddingVector ∈Rd\in \mathbb{R}^{d}Static per token IDStarting coordinate entering Layer 1 (mixes all senses of "bank")
3. Positional SignalSinusoid or RoPE rotationFunction of index/offsetEncodes word order and relative token spacing
4. Contextual RepresentationHidden state ∈Rd\in \mathbb{R}^{d}Dynamic per promptUpdated vector inside/after Transformer layers (knows "bank" = lender)
5. Retrieval Embedding1 vector per passage/docDynamic per passageOutput of a *dedicated embedding model* trained via contrastive learning for RAG/search

##

  1. 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.

##

  1. 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,000 would 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!

##

  1. Practical exercise
  2. 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.

  1. Calculate by hand the cosine similarity between u=[1,1,0,0]\mathbf{u} = [1, 1, 0, 0] and v=[1,0,0,0]\mathbf{v} = [1, 0, 0, 0], and between u\mathbf{u} and w=[−1,−1,0,0]\mathbf{w} = [-1, -1, 0, 0].
  2. Audit a hypothetical enterprise RAG store: list four governance controls you would apply to the vector table itself.

##

  1. Knowledge check
  2. How many parameters are in a token embedding table with V=100,000V = 100,000 and dmodel=4,096d_{\text{model}} = 4,096?
  3. Why would a Transformer without positional encoding confuse "Bank sued borrower" with "Borrower sued bank"?
  4. What mathematical property makes RoPE especially effective for attention and long-context scaling?
  5. What is the difference between an LLM's static token embedding and a contextual representation?
  6. Why can two factually opposite sentences still have high cosine similarity?

Answer key:

  1. 100,000×4,096=409.6 million100,000 \times 4,096 = 409.6\text{ million} parameters.
  2. Because Transformers process all tokens in parallel, making Self-Attention permutation-invariant without position signals.
  3. Rotating Q and K by position-proportional angles makes their dot product depend naturally on relative distance (m−n)(m - n).
  4. A static embedding assigns one fixed starting vector per token ID; a contextual representation evolves across Transformer layers based on surrounding tokens.
  5. Because they occupy almost identical lexical and topical neighbourhoods in semantic space, differing mainly by a negation word.

##

  1. 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.

##

  1. Further reading
LEARNER FEEDBACK

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.

COURSE PROGRESS0/29 complete
Not yet completed
CHECK YOUR UNDERSTANDING