Charan | AI Journey › 01 · Vectors › Vector Dimensions
⚡ 3D Simulator
AI Journey · Understand Language

Vector Dimensions

A dimension is one coordinate slot in a vector. 768D means each token gets 768 numbers. More dimensions give a model more representational freedom — but at a linear cost in memory and compute.

🔴 MUST 15 Study Phases Vectors Prerequisite: Sparse vs Dense → Why Text Becomes Numbers
🧙‍♂️ The Wise Scholar's Metaphor The Mental Coordinate Axes ($d$)
⏮️ 00 · Math & Foundations Hub →

Dimensions: The Nuance Sliders in the Scholar's Imagination

If the scholar only had 2 dimensions (e.g. X = Size, Y = Animacy), "whale" and "elephant" would land in the exact same spot! By giving the scholar 4,096 dimensions ($d_{\text{model}}$ in LLaMA 3), each concept gets 4,096 subtle property dials (aquatic, extinct, mechanical, sentiment, tense, honorific) avoiding overcrowding and allowing fine-grained distinction.

01

IntroductionWhat is a dimension?

Visual lesson: See dimensions as rows and columns, with two sliders and the token-ID-to-vector flow. Open "Rows. Dimensions. Vectors." →
#charan #dimension #vector
Infographic: What does Dimension (1,536) mean? Complete visual explanation with person analogy, 1,536D vectors, and matrix stacking
Infographic: What does Dimension (1,536) mean? Person analogy → 1,536D token vector → 3D vector space → 50,000×1,536 embedding matrix → Transformer. Click to open full size.
Infographic: from your question to the LLM — tokens, token IDs, embedding matrix rows and columns, input matrix, and the Transformer
Rows = vocabulary tokens, columns = dimensions; the input matrix keeps only the rows your question selects. Click to open full size. Numbers are illustrative.

A dimension is a single coordinate slot in a vector. A 3D vector has three slots: [x, y, z]. A 768-dimensional embedding has 768 slots: [d₀, d₁, …, d₇₆₇]. Every slot holds one floating-point number.

2D  →  [ 0.2,  0.8 ]
3D  →  [ 0.2,  0.8, -0.4 ]
5D  →  [ 0.2,  0.8, -0.4,  0.1,  0.6 ]
768D→  [ 0.21, -0.07, 0.54, 0.11, …, 0.33 ]   (768 values)

Dimension = width

Dimension tells you how wide a single vector is — how many numbers are needed to describe one item (one token, one sentence, one document).

Not sequence length

A sequence of 128 tokens, each embedded into 768D, produces a matrix of shape [128, 768]. 128 is length; 768 is dimension. They are completely separate axes.

Key idea: dimension = number of coordinate slots in one vector — not the number of tokens, not the number of words, not a measure of "intelligence". More dimensions = more representational capacity and proportionally more storage and compute.
Token ID→ Embedding lookup→ Vector [d₀…d₇₆₇]→ Hidden state [768]→ Next layer

Concrete example: the vector for “cat”

Suppose the token ID for cat is 1. Its row in the embedding matrix is (illustrative values):

Token ID = 1   → which row to read
Vector for cat = [  0.80,  −0.30,   0.40,   0.15 ]
                   dim 1   dim 2   dim 3   dim 4

4 numbers = a 4-dimensional vector

Each dimension is one position in the vector. Together, the numbers form the token's learned numerical representation. The token ID is not this vector; it only tells the model which vector to retrieve.

Try it: vector dimension explorer

Drag the slider to change how many numbers describe one token. Bars above the line are positive values, bars below are negative.

16D

This is a simulated vector for learning, not a real model embedding.

Three words, three jobs: the token ID says which row to retrieve; the dimension says how many numbers are in that row; the vector is the complete row of numbers. For a matrix with 50,000 tokens and 4,096 dimensions, the shape is 50,000 × 4,096: 50,000 rows, each containing 4,096 numbers.
02

Why It MattersThe cost–capacity tradeoff

Every extra dimension added to your embedding is an extra degree of freedom — the model can encode one more independent aspect of meaning. But that freedom comes at a price paid in every operation that touches the vector.

d
Width per vector
∝ d
Memory per vector
∝ d
Dot product cost

If you double d from 384 to 768, you double the memory for every stored embedding, and every dot product in every attention head takes twice as many multiply-accumulate operations. The embedding matrix itself grows by a factor of two as well.

Why designers choose d carefully:
  • Too small → the model cannot distinguish subtly different concepts; information bottleneck.
  • Too large → training slows, inference is expensive, and the model may overfit on small datasets.
  • Common sweet spots: 128 (tiny/mobile), 384 (sentence transformers), 768 (BERT-base), 1024 (BERT-large), 4096 (large generative models).
Tip: The best d is the smallest one that doesn't bottleneck your task. Start with a pre-trained checkpoint and only tune if you're training from scratch.

How big are vectors in real models?

Example embedding dimensionNumbers per token
4 (toy example)4
128128
768768
4,0964,096
12,28812,288

These are example sizes; actual models vary. With 4,096-dimensional embeddings, each token ID retrieves a vector containing 4,096 numbers.

03

IntuitionAxes, not labels

Imagine plotting words on a 2D graph where one axis loosely captures "animal-ness" and another captures "size". You could put cat at (0.8, 0.3) and elephant at (0.7, 0.95). That works for two features. But real language has thousands of interacting properties.

Real embeddings don't assign clean human-readable labels to their dimensions. They are learned: gradient descent arranges the numbers so that vectors which should behave similarly in downstream tasks end up geometrically close. What ends up encoded in dimension 237 is an entangled mixture of many features — not a single interpretable concept.

Toy 2D (interpretable)

You can draw it. Axis 0 ≈ animal-ness, Axis 1 ≈ size. Clean, but far too simple for real language.

Real 768D (learned)

No axis has a label. The representation as a whole is meaningful; individual coordinates are typically entangled mixtures of syntax, semantics, and task-specific signals.

A human analogy

Describe a person to someone who has never seen them, using 4 measurements:

The person

  • Height: 175 cm
  • Age: 30 years
  • Weight: 70 kg
  • Shoe size: 9

[175, 30, 70, 9] → 4 values = 4 dimensions.

The token “cat”

  • Dim 1: 0.21
  • Dim 2: −0.43
  • Dim 3: 0.87
  • Dim 4: 0.16

[0.21, −0.43, 0.87, 0.16] → 4 learned values = 4 dimensions. Illustrative; token ID 3797 is also illustrative.

  • Person → the thing being represented (here, the token).
  • Measurements → individual dimensions.
  • List of measurements → the vector.
  • Number of measurements → the dimensionality.

Describing a person with hundreds of measurements captures more detail than four, and in the same way a model may use 4,096 dimensions per token. More dimensions alone do not guarantee a better model; architecture, training and the learned parameters matter too.

Where the analogy stops: height and age are human-readable, but a token's dimensions usually are not. Dimension 1 does not necessarily mean “animal-ness” and dimension 2 does not necessarily mean “size”. Information is distributed across the whole learned vector, and the values are learned in training rather than assigned by hand.
Note: Some probing experiments suggest rough structure in individual dimensions of certain models, but this is an active research question, not a reliable design principle.
04

TheoryDimension vs sequence length vs batch size

Three numbers appear together constantly when reading NLP papers and tensor shapes. They describe different axes of the same tensor and must not be confused.

Axis nameSymbolTypical valueWhat it counts
Batch sizeB8 – 64Number of independent sequences processed together
Sequence lengthT or L128 – 4096Number of tokens in one sequence
Embedding dimensiond or H128 – 4096Width of each vector (number of coordinates)
Hidden-state tensor shape in BERT-base:
  [B=8,  T=128,  H=768]
   ^      ^       ^
   batch  seq     embedding dim
   (how   (how    (how wide
   many   long)   each vector is)
Common confusion: Sequence length and embedding dimension both appear as numbers in a tensor shape. Always check which axis is which before reasoning about memory or computation.
05

How It WorksEmbedding lookup and layer propagation

The embedding layer is a matrix E of shape [V, d] where V is vocabulary size and d is embedding dimension. Given a token ID i, the embedding for that token is simply row i of E: a vector of length d.

Token ID i→ E[i] = vector of length d→ Add positional encoding [d]→ Transformer layer (preserves d)→ Hidden state [d]

Notice that every Transformer layer preserves the hidden dimension d. Attention projects queries, keys, and values to subspaces of size d_k (often d / num_heads), then projects back to d before adding the residual. The width of the representation stays constant through the stack.

Embedding matrix

Shape [V, d]. Each row is the learned vector for one vocabulary item. Queried by index (token ID). This is where dimension is set.

Sequence length ⊥ dimension

Sequence length (how many tokens) and embedding dimension (how wide each token's vector is) are orthogonal axes. Changing one does not change the other.

06

MathematicsFormal notation and parameter count

01
Vector space: \(\mathbf{x} \in \mathbb{R}^d\) — a column of \(d\) real numbers.
02
Embedding matrix: \(E \in \mathbb{R}^{V \times d}\) — \(V\) rows (one per vocab item), each of width \(d\).
03
Dot product: \(\mathbf{x} \cdot \mathbf{y} = \sum_{i=1}^{d} x_i \, y_i\) — exactly \(d\) multiplications plus \(d{-}1\) additions.
04
Parameter count in embedding layer: \(V \times d\). For BERT-base: \(30\,522 \times 768 = 23.4\text{M}\) parameters — just the embedding table.
Note: The dot product cost is \(O(d)\), which is why doubling the dimension doubles the cost of every similarity computation in attention and retrieval systems.
07

Worked ExampleSame algebra at every dimensionality

The rules of vector algebra are identical whether you have 2 dimensions or 768. Here are concrete vectors at four different widths, all using the same dot-product formula.

2D — easy to plot

a = [0.6, 0.8]
b = [0.8, 0.6]
dot = 0.6×0.8 + 0.8×0.6 = 0.96

3D — still visualizable

a = [0.6, 0.8, 0.0]
b = [0.8, 0.6, 0.0]
dot = 0.48 + 0.48 + 0 = 0.96

5D — compute directly

a = [1, 0, 1, 0, 1]
b = [0, 1, 1, 0, 1]
dot = 0+0+1+0+1 = 2

768D — rely on math

Can't visualize it, but the formula is exactly the same: sum of element-wise products over 768 terms. Algebra doesn't care about dimensionality.

Key insight: The difficulty with high dimensions is not mathematical — the formulas stay the same. The difficulty is that human intuition about distance and angles breaks down in high-dimensional spaces.
08

VisualizeProjecting high dimensions to 2D/3D

To visualize a set of 768D embeddings, researchers project them down to 2D or 3D using dimensionality reduction techniques. The most common are PCA, t-SNE, and UMAP.

flowchart LR A["768D embeddings\n(tokens / sentences)"] --> B["Dimensionality\nReduction"] B --> C["PCA\n(linear, fast)"] B --> D["t-SNE\n(local structure)"] B --> E["UMAP\n(topology-preserving)"] C --> F["2D / 3D scatter plot"] D --> F E --> F
Important: A 2D projection of 768D data discards or distorts most of the structure. Clusters that look close in a t-SNE plot may be far apart in the original space. Use projections to build intuition, never as a reliable measure of actual similarity.

What projections are good for

  • Visual sanity check that similar items cluster
  • Detecting obvious errors in embeddings
  • Communicating qualitative results to stakeholders

What projections cannot do

  • Give accurate distances between points
  • Preserve all structure from the original space
  • Replace actual nearest-neighbour search
09

CodeShape inspection in Python

The most common first step when working with embeddings is simply inspecting shapes to confirm that dimension, sequence length, and batch size are in the right places.

python
# ── Plain Python ───────────────────────────────────────────
tokens = 4          # sequence length (4 tokens)
embedding_dim = 6   # dimension (6 coordinates per token)

# A manual embedding table: list-of-lists
embedding_table = [
    [ 0.21, -0.07,  0.54,  0.11, -0.33,  0.08],   # token 0
    [-0.15,  0.42,  0.03, -0.28,  0.67,  0.21],   # token 1
    [ 0.88, -0.11, -0.09,  0.55,  0.04, -0.19],   # token 2
    [ 0.10,  0.30, -0.74,  0.02,  0.51,  0.44],   # token 3
]

num_tokens = len(embedding_table)      # → 4  (sequence length)
dim_per_token = len(embedding_table[0])  # → 6  (embedding dim)
print(f"Tokens: {num_tokens}, Dim: {dim_per_token}")

# ── NumPy ───────────────────────────────────────────────────
import numpy as np

E = np.array(embedding_table)
print(E.shape)       # (4, 6)  →  [seq_len, embedding_dim]
print(E[0].shape)    # (6,)    →  one token vector

# Batch of sequences
batch = np.random.randn(8, 128, 768)   # [batch, seq, dim]
print(batch.shape)   # (8, 128, 768)

# ── PyTorch ────────────────────────────────────────────────
import torch
import torch.nn as nn

vocab_size = 30522
d_model = 768

emb = nn.Embedding(vocab_size, d_model)
print(emb.weight.shape)   # torch.Size([30522, 768])

token_ids = torch.tensor([[101, 2054, 2003, 102]])  # shape [1, 4]
out = emb(token_ids)
print(out.shape)     # torch.Size([1, 4, 768])
#                                  ^  ^    ^
#                               batch seq  dim

What this reveals

.shape instantly tells you [batch, seq, dim]. Always inspect shapes first when debugging embedding-related bugs — the wrong axis is the #1 source of shape errors.

What NumPy / PyTorch add

Broadcasting, batched matrix multiply (@), and CUDA acceleration — all of which are critical when working with 768D vectors at scale.

10

Hands-onExperiments to run yourself

Experiment A — memory vs dimension

Fix sequence length at 16, vary embedding dimension, measure tensor memory.

▶dim=32: torch.zeros(8, 16, 32).element_size() * 8*16*32 = 16 KB
▶dim=64: 32 KB (2×)
▶dim=128: 64 KB (4×)
✓Memory scales linearly with d — doubling d doubles memory.

Experiment B — sequence length is independent

Fix dim=128, vary sequence length. Confirm it scales independently.

▶seq=16, dim=128: shape (8, 16, 128)
▶seq=64, dim=128: shape (8, 64, 128) — 4× more rows, same width
▶seq=128, dim=128: shape (8, 128, 128) — 8× more rows, same width
✓Changing sequence length doesn't change embedding dim — orthogonal axes.

Experiment C — projection to 2D

Create a small embedding set, project to 2D with PCA, compare nearest neighbours before and after.

▶points = np.random.randn(20, 768) # 20 random 768D points
▶from sklearn.decomposition import PCA
▶proj = PCA(n_components=2).fit_transform(points) # (20, 2)
▶Compare nearest-neighbour rank in 768D vs 2D.
✓Neighbours change — projection is lossy. Never trust 2D plots as ground truth.
11

CompareDimension sizes and their trade-offs

Dimension (d)Model exampleMemory per vector (float32)CapacityTypical use
128DistilBERT-tiny, small sentence models512 BLowMobile, edge, fast retrieval
384MiniLM, all-MiniLM-L61.5 KBMediumSemantic search, lightweight NLP
768BERT-base, RoBERTa-base, DistilBERT3 KBHighMost production NLP tasks
1024BERT-large, RoBERTa-large4 KBVery highHigh-accuracy fine-tuned models
4096LLaMA-2, GPT-class large models16 KBVery highLarge generative models
2D / 3D projectiont-SNE / PCA output8–12 BNot the original spaceVisualization only — not for similarity
Note: Smaller d can be perfectly adequate. MiniLM at 384D outperforms some 768D models on sentence similarity tasks because it was trained specifically for that task.
12

ApplyWhere dimension shows up in real systems

Embeddings

Each token in the vocabulary maps to a vector of width d. The embedding layer's parameter count is V × d. Choosing d is one of the first decisions when training a model from scratch.

Attention heads

Multi-head attention projects queries, keys, and values to head-specific subspaces of dimension d_k = d / num_heads. Total compute per attention layer is proportional to d regardless of how heads split it.

RAG and vector search

In retrieval-augmented generation, queries and documents must use embeddings from the same model — identical d. Mixing models with different d silently corrupts similarity scores.

Vector index storage

Vector databases (FAISS, Pinecone, Weaviate) store and index vectors of a fixed dimension. Memory for an index with N vectors is N × d × 4 bytes (float32). At 1 M documents, 768D = ~3 GB just for raw vectors.

13

LimitationsWhat high dimensions don't give you

  • More dimensions ≠ better representations. A poorly-trained 768D model will underperform a well-trained 128D model. Quality of training data and objectives matters far more than dimension count.
  • Individual dimensions are not interpretable. You cannot read "dimension 237 = formality". Each dimension is a learned mixture. Probing classifiers can sometimes find linear directions, but the raw coordinates are not meaningful.
  • Visualization requires lossy projection. PCA, t-SNE, and UMAP all discard or distort structure. A 2D plot of 768D data should be treated as a rough sketch, not ground truth.
  • Curse of dimensionality. In very high-dimensional spaces, all pairwise distances tend to become similar, which can make nearest-neighbour search less discriminative. Approximate nearest-neighbour methods (HNSW, IVF) are needed at scale.
Common mistake: Choosing the largest dimension "to be safe". Unnecessarily large d inflates the embedding matrix, slows attention, and can hurt generalization on small datasets through overfitting.
14

Feynman ChallengeExplain it simply

The Coordinate-Slot Analogy

Imagine a filing system where every word gets a card with d numbered slots. Each slot holds one decimal number. If two cards have similar numbers in most slots, the words they represent are used similarly in language. The filing system doesn't tell you what each slot measures — it just learns the numbers that make the system work best for predicting language.

768D means every word's card has 768 slots. A sentence of 128 words produces 128 cards, each with 768 numbers — not one card with 768 × 128 numbers. Width and length are separate things.

Common Misconceptions

  • ❌ "768 dimensions means the model understands 768 concepts." — Dimensions are not labeled concepts. They are coordinates in a learned geometric space.
  • ❌ "Bigger d is always better." — More capacity only helps if you have enough data and compute to fill it. Underfitting from too-small d is rare; overfitting and cost from too-large d is common.
  • ❌ "I can read what dimension 237 means." — The values in individual dimensions are not human-interpretable without dedicated probing experiments.
  • ❌ "Embedding dimension = sequence length." — These are orthogonal axes. A 768D embedding can represent a sequence of 4 tokens or 4096 tokens equally well.
  • ❌ "More dimensions = more tokens the model can process." — Sequence length and embedding dimension are independent. Context window size is controlled by architecture (positional encoding range, attention window), not by d.
10-second summary: Dimension = how many numbers describe one item. More numbers = more capacity = more cost. It is completely separate from how many items are in a sequence.
15

BuildHands-on mini-projects

🔵 Capstone Mini-Projects

1 · Dimension shape inspector

Use numpy.zeros to create tensors of shape [batch, seq, d] with different values of d. Print shapes and confirm which axis is which. Try [8, 128, 768], [1, 4, 6], and [32, 512, 1024].

2 · Dot product vs dimension benchmark

Create random vectors of size 32, 256, and 1024. Compute 10,000 dot products at each size with timeit. Plot cost vs d and confirm the linear relationship.

3 · Projection fidelity demo

Generate 20 random 3D points, record their true nearest neighbours by Euclidean distance. Project to 2D with PCA. Re-compute nearest neighbours in 2D. Measure how many neighbours changed — visualize the mismatch.

✓

SummaryEverything in one place

Dimension is the width of a single vector — the number of coordinate slots. It determines representational capacity and is directly proportional to memory and compute cost.

Dimension
Number of coordinates in one vector (768 in BERT-base)
Sequence length
Number of tokens in one sequence — independent of dimension
Embedding width
The same thing as dimension — set once in the embedding layer, preserved through all Transformer layers
Trade-off
Larger d → more capacity, higher cost; smaller d → faster and cheaper, potential bottleneck
  • A vector in \(\mathbb{R}^d\) has exactly \(d\) coordinates — each is one dimension.
  • Embedding matrix shape: [V, d]. Hidden-state tensor shape: [B, T, d].
  • Dot product and cosine similarity both require vectors of the same dimension — mixing models with different d silently breaks retrieval.
  • Individual dimensions are not interpretable — only the vector as a whole is meaningful.
  • Use dimensionality reduction (PCA / t-SNE / UMAP) only for visualization; never for measuring actual similarity.
  • Common real-world sizes: 128 (tiny) → 384 (compact) → 768 (standard) → 1024 (large) → 4096 (generative LLMs).
This page 0:00
This session 0:00
Total (all pages) 0:00
Today 0:00
▶ Running
📊 View all study stats →
0:00 studying