Representation Learning & Embedding Geometry

How models turn inputs into vectors whose geometry can expose useful factors, contextual meaning, and similarity structure.

Intermediate · Undergraduate mathematics · about 18 minutes

Reading map and next steps

Intuition

The idea in plain words, before the symbols.

A neural network turns each input into vectors: lists of numbers that later layers compute with. A vector produced this way is called a representation or an embedding. Representation learning is the study of how training shapes these vectors so that useful properties of the input become easy to read off (Bengio et al., 2013).

Ideally:

  • inputs that mean similar things get nearby vectors,
  • unrelated inputs point in different directions,
  • and simple operations on the vectors, such as dot products, distances and averages, answer useful questions: which documents match a query, which images form a cluster, which label a small classifier should predict.

When this works, embeddings can be reused: for similarity search, as inputs to small classifiers, or to study which directions carry which information. It can also go wrong. Contextual embeddings from language models are often anisotropic: they share a common direction, so even unrelated words have high cosine similarity (Ethayarajh, 2019), which makes raw similarity scores less informative.

Context matters too. A static word vector gives the word "bank" one vector everywhere. A contextual representation gives the token a different vector depending on whether the sentence is about rivers or money. ELMo made this practical by building token vectors from the layers of a bidirectional language model (Peters et al., 2018).

Study prompts for this section: Intuition
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Mathematics

Definitions, assumptions and the derivation.

Let an encoder fθf_\theta map each input xx to a vector zz. If a simple predictor gψg_\psi can recover a useful factor from zz, the representation has made that factor easy to extract. For contextual word representations, the vector for token kk can depend on the whole sentence t1,…,tNt_1,\ldots,t_N:

z=fθ(x)∈Rd,a^=gψ(z),ELMo⁡ktask=γtask∑j=0Lsjtask hk,jLM(t1,…,tN).\begin{aligned} z &= f_\theta(x)\in\mathbb R^d,\qquad \hat a = g_\psi(z),\\ \operatorname{ELMo}^{\mathrm{task}}_k &= \gamma^{\mathrm{task}}\sum_{j=0}^{L}s^{\mathrm{task}}_j\, h^{\mathrm{LM}}_{k,j}(t_1,\ldots,t_N). \end{aligned}

Here a^\hat a is the predicted value of a factor or label aa, gψg_\psi is a simple extractor such as a linear classifier (a "probe"), and hk,jLMh^{\mathrm{LM}}_{k,j} is the bidirectional language model's state for token kk at layer jj, with j=0j=0 the context-free token embedding. Peters et al. combine the L+1L+1 layers with task-specific softmax weights sjtasks_j^{\mathrm{task}} and a scale γtask\gamma^{\mathrm{task}}. Because every hk,jLMh^{\mathrm{LM}}_{k,j} with j≥1j\ge1 depends on the whole sentence, the same word receives different vectors in different sentences.

Similarity as a dot product (often cosine)

A common choice is cosine similarity, which is just a dot product of normalized vectors:

sim(z,z′)=z⊤z′∥z∥2 ∥z′∥2=z^⊤z^′.\mathrm{sim}(z, z') = \frac{z^\top z'}{\lVert z\rVert_2\,\lVert z'\rVert_2} = \hat z^\top \hat z'.

Normalization matters because it makes similarity depend on direction instead of length.

Contrastive learning (InfoNCE)

Suppose we have positive pairs (xi,yi)(x_i, y_i): two views of the same thing, such as two crops of one image or an image and its caption. Encode them with the same encoder (θ′=θ\theta'=\theta) or with two separate encoders:

zi=fθ(xi),ui=fθ′(yi).z_i = f_\theta(x_i), \qquad u_i = f_{\theta'}(y_i).

InfoNCE treats (zi,ui)(z_i, u_i) as the correct match among a batch of candidates:

L=−1N∑i=1Nlog⁡exp⁡(sim(zi,ui)/τ)∑j=1Nexp⁡(sim(zi,uj)/τ).\mathcal L = -\frac{1}{N} \sum_{i=1}^N \log \frac{\exp\big(\mathrm{sim}(z_i, u_i)/\tau\big)}{\sum_{j=1}^N \exp\big(\mathrm{sim}(z_i, u_j)/\tau\big)}.
  • Each term is a cross-entropy loss for picking the true partner uiu_i out of the NN candidates in the batch; the other N−1N-1 are the negatives.
  • τ>0\tau > 0 is the temperature. Smaller τ\tau sharpens the softmax, so most of the gradient comes from the negatives most similar to ziz_i.
  • For independent pairs drawn from the joint distribution, with negatives drawn from the marginal distribution, van den Oord et al. (2018) bound the mutual information between the views by I≥log⁡N−E[L]I \ge \log N - \mathbb E[\mathcal L]. The expectation is over sampled batches; the bound does not apply to every individual batch loss.

Checking for anisotropy

Two quick checks on a set of NN normalized embeddings z^i\hat z_i with mean zˉ=1N∑iz^i\bar z=\frac1N\sum_i\hat z_i. First, the length ∥zˉ∥\lVert\bar z\rVert: near 00 when directions are spread out, near 11 when all vectors point roughly the same way. Second, the covariance

C=1N∑i=1N(z^i−zˉ)(z^i−zˉ)⊤.C = \frac{1}{N}\sum_{i=1}^N (\hat z_i - \bar z)(\hat z_i - \bar z)^\top.

If a few of its eigenvalues dominate, the vectors vary mainly along a few directions, which can dominate cosine comparisons. Subtracting the mean, or whitening with C−1/2C^{-1/2}, changes this geometry.

Study prompts for this section: Mathematics
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Code

The same calculation as runnable code, in the notation of the derivation.

import numpy as np

def unit(v):
    return v / (np.linalg.norm(v) + 1e-9)

# Toy handcrafted features: axis 0 = water-vs-finance context,
# axis 1 = the token identity "bank", axis 2 = filler.
feat = {
    "river": np.array([1.0, 0.0, 0.0]),
    "shore": np.array([1.0, 0.0, 0.0]),
    "money": np.array([-1.0, 0.0, 0.0]),
    "loan": np.array([-1.0, 0.0, 0.0]),
    "bank": np.array([0.0, 1.0, 0.0]),
}

def contextual(left, token, right):
    return unit(0.55 * feat[token] + 0.35 * (feat[left] + feat[right]))

static_bank = unit(feat["bank"])
river_bank = contextual("river", "bank", "shore")
money_bank = contextual("money", "bank", "loan")

water_probe = unit(np.array([1.0, 0.0, 0.0]))
def water_score(z):
    return float(z @ water_probe)

print("static bank:", round(water_score(static_bank), 3))
print("river bank: ", round(water_score(river_bank), 3))
print("money bank: ", round(water_score(money_bank), 3))

assert water_score(river_bank) > water_score(static_bank) > water_score(money_bank)
assert np.linalg.norm(river_bank - money_bank) > 1.4

The code builds a contextual vector for "bank" by mixing its own hand-chosen feature with those of its two neighbors, then reads the water-versus-finance axis with a fixed linear probe. The static vector scores 00, "river bank" about 0.7860.786 and "money bank" about −0.786-0.786: the same token, two different representations.

Study prompts for this section: Code
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Demo

Change an input, predict the result, and see which quantities respond.

ExploreChange one control at a time and name what responds.An optional observation guide follows the demo.

Explore Representation Learning & Embedding Geometry

Loading the interactive demo…

Observation guide

Optional and ungraded. Opening a guide saves nothing.

Choose what to inspect in Representation Learning & Embedding Geometry, then open its guide.

The demo has four tabs:

  • Normalization: LayerNorm and RMSNorm both remove a vector's overall scale, so only its direction is left to compare. LayerNorm also subtracts the mean first, which can change that direction; the demo measures the change with cosine similarity.
  • Directions: task vectors, which are differences in weight space, not representation space: the weights of a fine-tuned model minus the pretrained weights. Adding or subtracting them edits behavior (Ilharco et al., 2023).
  • Equivariance: feature maps that change predictably when the input is transformed. Rotate the input, and an equivariant output rotates with it, while an invariant output does not change.
  • Geometry: moving a direction along a curved surface without twisting it (parallel transport).
Study prompts for this section: Demo
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

In focus

Concept: Representation Learning & Embedding Geometry

What is the smallest example of Representation Learning & Embedding Geometry you can work through by hand, and what does it show?

BeforeScaled Dot-Product Attention & Transformer LayersNextTokenization & Vocabulary Design
DetailsRepresentation Learning

After the first pass

Go deeper

Optional material for a second reading. Sources are always shown; the other panels open from their headings or from these links, and closing one keeps what you wrote or revealed.
What to look for in each sectionChoose a section and what you expect to see in it, then read short advice.

Section by section

Choose what to look for in each section

How models turn inputs into vectors whose geometry can expose useful factors, contextual meaning, and similarity structure.

Choose what to look for (no demo yet)01 / Intuition
Illustration of embedding clusters, geometric neighborhoods, and feature directions.
What to look for

Start with the picture, metaphor, or geometric mechanism.

Choose first

Choose what you expect to see in this section of Representation Learning & Embedding Geometry.

Questions to ask of the pictureChoose a part of the picture and what you expect, then read short advice.

Looking at the picture

Questions to ask of the picture

How models turn inputs into vectors whose geometry can expose useful factors, contextual meaning, and similarity structure.

4 of 4 sections writtenNo live demo yet
Question

Which part of the picture should you look at first?

Choose first

Pick the part of the picture you expect to explain Representation Learning & Embedding Geometry.

Sources

References for this page

A reference shows where an idea comes from; it does not vouch for every step on this page.
paper · 2013Representation Learning: A Review and New PerspectivesBengio, Courville, and Vincent
Why it is cited

Reviews representation learning as learning transformations of the data that make useful explanatory factors easier to extract (IEEE TPAMI).

Open source
paper · 2018Deep contextualized word representationsPeters et al.
Why it is cited

Introduces ELMo, contextual word vectors computed from all layers of a bidirectional language model, so a word's vector depends on its sentence (NAACL 2018).

Open source
paper · 2018Representation Learning with Contrastive Predictive Codingvan den Oord, Li, and Vinyals
Why it is cited

Introduces contrastive predictive coding and the InfoNCE loss, which scores a positive pair against negative samples, and shows that minimizing it maximizes a lower bound on mutual information.

Open source
paper · 2019How Contextual are Contextualized Word Representations? Comparing the Geometry of BERT, ELMo, and GPT-2 EmbeddingsEthayarajh
Why it is cited

Finds that contextual word representations are anisotropic in every layer of ELMo, BERT and GPT-2, and that upper layers produce more context-specific representations (EMNLP-IJCNLP 2019).

Open source
paper · 2023Editing Models with Task ArithmeticIlharco et al.
Why it is cited

Defines a task vector as the weights of a fine-tuned model minus the pretrained weights, and edits behavior by adding, negating or combining task vectors (ICLR 2023).

Open source
What each claim rests on1 claim, each with its sources, where it appears on this page, and its caveats.

Claims and sources

How models turn inputs into vectors whose geometry can expose useful factors, contextual meaning, and similarity structure.

Checked against the cited passages

The checks were made by this site, not by an independent reviewer.

Representation learning trains encoders to transform raw inputs into internal features that make useful factors easier to extract; ELMo-style contextual embeddings make token representations depend on sentence context.
What the sources support

Bengio et al. frame representation learning as learning transformations that expose useful explanatory factors and make useful information easier to extract. Peters et al. introduce ELMo contextual word repr...

Where to see it on this page
Equation 1
z=fθ(x)∈Rd,a^=gψ(z),ELMo⁡ktask=γtask∑j=0Lsjtask hk,jLM(t1,…,tN).\begin{aligned} z &= f_\theta(x)\in\mathbb R^d,\qquad \hat a = g_\psi(z),\\ \operatorname{ELMo}^{\mathrm{task}}_k &= \gamma^{\mathrm{task}}\sum_{j=0}^{L}s^{\mathrm{task}}_j\, h^{\mathrm{LM}}_{k,j}(t_1,\ldots,t_N). \end{aligned}
Caveat

Covers only useful-factor extraction and ELMo-style contextual token vectors. It does not cover InfoNCE, retrieval quality, task vectors, anisotropy fixes, equivariance, parallel transport, or all representa...

StatusChecked against the cited passages.

Bengio et al. support representation learning as learned features that make useful information or explanatory factors easier for predictors to extract. Peters et al. support ELMo as sentence-contextual token representations from biLM layer states, including task-specific layer weighting and polysemy disambiguation. The equations and the code on this page illustrate this claim; the geometry demos are not covered.

Explain it without the pageWrite your own explanation before asking for feedback. Your draft and any hints stay while this page is open.

Practice · Representation Learning & Embedding Geometry

Try the idea in your own words

How models turn inputs into vectors whose geometry can expose useful factors, contextual meaning, and similarity structure.

Concept · Selected for practice

Representation Learning & Embedding Geometry

What it rests on: Sources: Representation Learning: A Review and New Perspectives; Deep contextualized word representations; Representation Learning with Contrastive...

Context and links
Choose a task

Explain the mechanism

For Representation Learning & Embedding Geometry: What is the smallest example of Representation Learning & Embedding Geometry you can work through by hand, and what does it show? Explain your answer, including what changes, why, and which assumption matters.

No answer yet

A rough first thought is enough. Your draft stays when you change tasks.

Your draft stays on this page and is cleared when you leave or reload.

A little help · Explain

Open one hint at a time. These are suggestions, not your answer or a grade.

0 of 3 hints shown for this question.

    Clearing your answer keeps this help record. Outside help is your own report; this page cannot check it.

    Where am I stuck? (optional)
    Your own description, not an automatic diagnosis

    Choose one, or leave this unspecified. Select it again to clear it.

    Take your draft to a feedback conversation

    No AI feedback runs here. You can copy a prompt to use elsewhere; nothing is sent automatically. Review the text before sharing, and leave out private information.

    Write an attempt before copying a feedback prompt.

    A draft, or an AI reply to it, is not a test of what you have learned. To check that, try a different case later without help.

    Ask about this pagePick one item on this page and copy a prompt about it into an AI assistant you already use. Notes you write here stay in this browser.
    Ask about this pageClose
    ConceptRepresentation Learning & Embedding GeometrySources: Representation Learning: A Review and New Perspectives; Deep contextualized word representations; Representation Learning with Contrastive...assert water_score(river_bank) > water_score(static_bank) > water_score(money_bank)

    Your question

    Choose what your question is about

    Pick the idea, equation, source, code, claim, misconception or demo state you want to ask about. The prompt you copy includes it, so the answer can stay on that item.
    Next local actionNo local draft saved yet

    Open the draft below to save one note and next action in this browser.

    conceptRepresentation Learning

    Representation Learning & Embedding Geometry

    Starting question

    What is the smallest example of Representation Learning & Embedding Geometry you can work through by hand, and what does it show?

    SourcesCheck the 5 cited sources listed under Sources.Notes can be saved for this item
    Points of view on this item

    Fixed prompts generated from this item. They are not comments from people or independent reviews.

    Learner’s first stepAsk what would make "Representation Learning & Embedding Geometry" feel predictable rather than familiar.
    Assumption

    The 5 cited sources must support this exact item, not just the surrounding topic.

    Source-checking summary

    Connect the definition to one equation, piece of code or demo before widening the discussion.

    Proposed experiment

    Change one input, then check that the same relationship holds in the mathematics, the code and the demo.

    Next action

    You can state the mechanism in your own words

    Evidence4 checks
    ObservationChecking for a saved observation
    ActionReady for one action
    PromptLearner prompt ready to copy
    Go to this item
    01ObservationChecking what this browser has saved
    02EvidenceChecking for a saved observation
    03SourcesCheck the 5 cited sources listed under Sources.
    04Next stepSave one next action
    Local action draftNo local draft saved yetOpen when you are ready to write one next action
    Local action draft

    This draft stays in this browser and is attached to this item only.

    No local draft saved.
    Evidence to inspect
    • What the 5 cited sources say about this exact item
    • The definition, its prerequisites, and a contrasting concept
    • The equation or code that makes the concept concrete
    • One demo state that shows what stays the same as the inputs change
    What would resolve this
    • You can state the mechanism in your own words
    • You can name the prerequisite that would clear up the confusion
    • You can predict how the result changes when one input changes
    Reference idconcept/concept-notebook/representation-learning/representations concept:representation-learning/representations