Tuesday, June 2, 2026

Embeddings — Deep Dive

1. What IS an Embedding?

An embedding is a list of numbers that represents the meaning of a token. Think of it as GPS coordinates, but instead of 2 dimensions (latitude, longitude), you have thousands of dimensions.

Code
Real GPS (2 dimensions):
  New York  → [40.71, -74.00]
  New Jersey → [40.05, -74.40]   ← nearby = geographically similar
  Tokyo     → [35.68, 139.69]   ← far away

Token Embedding (4096 dimensions):
  "cancel"    → [0.82, -0.14, 0.91, 0.03, -0.67, ... 4096 numbers]
  "terminate" → [0.79, -0.11, 0.88, 0.05, -0.64, ... ]  ← nearby = similar meaning
  "pizza"     → [-0.45, 0.72, -0.33, 0.64, 0.21, ... ]  ← far away = unrelated

Each of those 4096 numbers captures some aspect of meaning — we don't always know what each dimension means, but collectively they encode:

  • Is this a verb or noun?
  • Is it positive or negative?
  • Is it formal or casual?
  • Is it about food? technology? emotions?

2. How Are Embeddings Learned?

Start: Completely Random

Code
Before training (Day 0):
  "king"   → [0.52, 0.11, -0.83, 0.44, ...]   ← random garbage
  "queen"  → [-0.31, 0.67, 0.02, -0.91, ...]   ← random garbage
  "pizza"  → [0.19, -0.55, 0.73, 0.28, ...]    ← random garbage

  All words are equally "far apart" — no meaning yet.

Training: Learn from Context

The model reads trillions of sentences and learns:

Code
Sentence 1: "The king ruled the kingdom"
Sentence 2: "The queen ruled the kingdom"
Sentence 3: "I ordered a pizza"

Model notices:
  - "king" and "queen" appear in SAME contexts 
    (before "ruled", after "the", with "kingdom")
  - "pizza" appears in COMPLETELY DIFFERENT contexts 
    (after "ordered", with "toppings", "delivery")

So training pushes:
  - "king" vector TOWARD "queen" vector (similar contexts)
  - "pizza" vector AWAY from both (different contexts)

After Billions of Sentences:

Code
After training:
  "king"   → [0.83, -0.21, 0.67, 0.45, ...]
  "queen"  → [0.81, -0.18, 0.64, 0.42, ...]   ← very close!
  "prince" → [0.78, -0.25, 0.61, 0.39, ...]   ← also close!
  "pizza"  → [-0.44, 0.71, -0.28, 0.63, ...]  ← far away

The famous example:

Code
king - man + woman ≈ queen   (vector arithmetic actually works!)

3. How Does It Store Names, Proper Nouns, Standard Words?

Standard Words (common):

Code
"the"      → Single token, ID 279
              Embedding learned from trillions of occurrences
              Vector captures: "article, neutral, precedes nouns"

"customer" → Single token, ID 12043  
              Vector captures: "person, business context, receives service"

Names and Rare Words (get split):

Code
"Comcast"    → ["Com", "cast"] → IDs [1568, 4384]
               Each piece gets its OWN embedding vector
               The transformer layers COMBINE them to understand 
               "this refers to the company Comcast"

"Teradata"   → ["Ter", "adata"] → IDs [7321, 18294]

"John"       → ["John"] → ID [2782]  (common name = single token)

"Kuznetsov"  → ["K", "uz", "nets", "ov"] → IDs [42, 3712, 17843, 869]

Key insight: For split words, the meaning isn't in any single token's embedding — it emerges when the transformer layers process them together with attention.

Code
"Com" alone could mean: company, combination, communication, comedy...
"cast" alone could mean: throw, actors, plaster cast...

But "Com" + "cast" in context → the model figures out "it's the telecom company"
(This is the transformer's job, not the embedding's job alone)

4. Embedding Sizes Across Models

ModelVocab SizeEmbedding DimensionsTotal Parameters (embedding layer alone)
GPT-250,257768~38 million
GPT-350,25712,288~617 million
GPT-4~100,000~8,192–12,288 (estimated)~800M–1.2B
LLaMA 232,0004,096~131 million
LLaMA 3128,2564,096 (8B) / 8,192 (70B)~525M / ~1B
Mistral 7B32,0004,096~131 million
BERT (base)30,522768~23 million

Why bigger models have larger embeddings: More dimensions = more nuance. Like describing a person with 5 adjectives vs. 4,096 adjectives — the more dimensions, the more precisely you can differentiate meanings.


5. Who Prepares the Initial Vocabulary and How?

The vocabulary is built before training using an algorithm called BPE (Byte Pair Encoding). Here's how:

Step-by-Step BPE Example:

Code
Training corpus (simplified):
  "low low low low low"
  "lower lower"  
  "newest newest newest"
  "widest"

Step 1: Start with individual characters as vocab
  Vocab: {l, o, w, e, r, n, s, t, d, i, ...}

Step 2: Count which pairs of characters appear most often
  "lo" appears 7 times (5 in "low" + 2 in "lower")
  "ow" appears 7 times
  "ne" appears 3 times
  "we" appears 3 times
  ...

Step 3: Merge the most frequent pair → "lo" becomes one token
  Vocab: {l, o, w, e, r, n, s, t, d, i, ..., "lo"}

Step 4: Recount pairs with the merged token
  "lo"+"w" appears 7 times → merge!
  Vocab: {..., "lo", "low"}

Step 5: Keep merging until you reach desired vocab size
  "low" + "er" → "lower"
  "new" + "est" → "newest"
  ...

Final vocab (after 128,000 merges):
  Single characters: a, b, c, ...
  Common pieces: "ing", "tion", "un", "re", ...
  Full common words: "the", "and", "customer", ...
  

Who does this?

The model creators (Meta, OpenAI, Google) run BPE on their training corpus once before training starts. It's a preprocessing step.

Code
Meta (LLaMA 3):
  1. Collected training text (web, books, code...)
  2. Ran BPE algorithm on that text
  3. Chose 128,256 as target vocab size
  4. Output: tokenizer.model file (the vocab)
  5. THEN started training the actual LLM

6. The Big Question: "English Didn't Change, So Why Do Vocabs Differ?"

Great intuition — but here's why vocabs do change between models:

Reason 1: Different Training Data

Code
LLaMA 2 (trained 2023):
  - Mostly English text, books, web
  - Less code
  - Result: 32,000 tokens, optimized for English

LLaMA 3 (trained 2024):
  - Much more code (Python, JS, etc.)
  - More multilingual (Hindi, Chinese, etc.)
  - Result: 128,256 tokens

New tokens added for code:
  "def", "self", "import", "    " (4 spaces = 1 token for indentation!)
  
New tokens added for other languages:
  "的", "है", "это" (common Chinese/Hindi/Russian pieces)

Reason 2: Different Vocab Sizes = Different Splits

Code
Small vocab (32,000 tokens):
  "embeddings" → ["embed", "dings"]     (2 tokens)
  "transformer" → ["trans", "former"]    (2 tokens)
  
Large vocab (128,000 tokens):
  "embeddings" → ["embeddings"]          (1 token!)  
  "transformer" → ["transformer"]        (1 token!)
  
Bigger vocab = fewer tokens per sentence = faster processing
But bigger vocab = larger embedding matrix = more memory

Reason 3: Different Optimization Goals

Code
GPT-4 (OpenAI):
  - Optimized for conversation, reasoning
  - Kept common English phrases as single tokens
  - " cannot" = 1 token (note the space is included!)

Code-specific models (CodeLlama):
  - Optimized for programming
  - "function", "return", "async" = single tokens
  - "    " (indentation) = single token

Reason 4: Efficiency Tradeoffs

Code
The tradeoff:
┌─────────────────────────────────────────────────┐
│  Smaller Vocab (32K)           Larger Vocab (128K) │
│  ─────────────────            ──────────────────── │
│  ✅ Less memory                ✅ Fewer tokens/sentence │
│  ✅ Smaller embedding table    ✅ Faster inference │
│  ❌ More tokens per sentence   ❌ Huge embedding table │
│  ❌ Slower inference           ❌ More memory │
└─────────────────────────────────────────────────┘

Summary Table

QuestionAnswer
What is an embedding?A vector of numbers that encodes meaning
How is it learned?By observing which words appear in similar contexts across billions of sentences
Names/rare words?Split into subword pieces; transformer combines them for meaning
Who makes the vocab?Model creators, using BPE on training data, before training starts
Does vocab change across models?Yes — different data, different sizes, different goals
Why change if English is the same?More languages, more code, efficiency tradeoffs, and different corpus compositions

The analogy:

English alphabet hasn't changed — but dictionaries differ (Oxford vs. Webster vs. Urban Dictionary). Each is optimized for different audiences. Same idea with LLM vocabularies — same language, different "dictionaries" optimized for different jobs.

Tokenization in Plain English

 The core problem: Computers only understand numbers. Text is not numbers. Tokenization is the bridge.


What is a token?

A token is a "chunk" of text — sometimes a word, sometimes part of a word, sometimes punctuation.

Code
"I love chatbots" → ["I", " love", " chat", "bots"]

Why "chatbots" gets split: it's rarer than "chat" and "bots" individually, and the model already knows those pieces.


How similar words are grouped (Embeddings)

This is the magic part. Once each token gets an ID number, that ID maps to a vector (a list of ~4096 numbers). These vectors are positioned in space such that:

WordsRelationship
"king" and "queen"Close together (both royalty)
"cancel" and "disconnect"Close together (similar intent)
"pizza" and "disconnect"Far apart (unrelated)

So even though "cancel" (ID 12074) and "disconnect" (ID 29482) have totally different IDs, their vectors point in nearly the same direction. The model learns this during training.


What is the vocabulary?

The vocab is simply the complete list of all token pieces the model knows — like a dictionary, but of subword chunks rather than full words.

  • GPT-4's vocab: ~100,000 tokens
  • LLaMA 3's vocab: ~128,000 tokens

If a word isn't in the vocab as-is, it gets split into pieces that are:

Code
"Comcast"       → ["Com", "cast"]         ✅ both in vocab
"unforgettable" → ["un", "forget", "table"] ✅ all in vocab

Nothing is ever truly "unknown" — the model can always assemble it from smaller known pieces.


The LEGO analogy (from your doc) is perfect

  • Vocab = your box of LEGO pieces (~100K–150K pieces)
  • Tokenization = breaking a sentence into those pieces
  • Embedding = each piece has a hidden "meaning coordinate" so similar pieces sit near each other
  • The transformer = the brain that reads those coordinates and figures out what you're saying

TL;DR:
Text → split into subword chunks (tokens) → each chunk gets a number (ID) → each ID maps to a meaning-vector → similar meanings get similar vectors → the model works with those vectors.

Thursday, May 28, 2026

LLM quantization explanation

 

Simplest Possible Explanation of 4-bit Quantization

You Download a Model File (FP16)

The model has weights. Let's say one small block of 8 weights (using 8 instead of 64 for simplicity):

Code
Original FP16 weights (2 bytes each):
  [0.8, 0.3, -0.5, 1.2, -1.0, 0.1, 0.6, -0.9]

Memory: 8 weights × 2 bytes = 16 bytes

"Loading in 4-bit" = Compressing on the Fly

When you do load_in_4bit=True, this happens:

Step 1: Find the biggest value in the block

Code
absmax = 1.2 (the largest absolute value)

Step 2: Divide everything by absmax → normalize to [-1, 1]

Code
[0.8/1.2, 0.3/1.2, -0.5/1.2, 1.2/1.2, -1.0/1.2, 0.1/1.2, 0.6/1.2, -0.9/1.2]
= [0.67,   0.25,    -0.42,    1.0,     -0.83,    0.08,    0.5,     -0.75]

Step 3: Snap each to nearest of 16 allowed levels

Code
4 bits = 16 possible values. Think of it as 16 "bins":

-1.0  -0.7  -0.5  -0.4  -0.3  -0.2  -0.1  0.0  0.1  0.2  0.3  0.4  0.5  0.7  1.0
  0     1     2     3     4     5     6    7    8    9   10   11   12   13   14   15

 0.67 → snaps to  0.7 (index 13)
 0.25 → snaps to  0.3 (index 10)
-0.42 → snaps to -0.4 (index 3)
 1.0  → snaps to  1.0 (index 15)
-0.83 → snaps to -0.7 (index 1)
 0.08 → snaps to  0.1 (index 8)
 0.5  → snaps to  0.5 (index 12)
-0.75 → snaps to -0.7 (index 1)

Step 4: Store

Code
Stored in memory:
  Indices:  [13, 10, 3, 15, 1, 8, 12, 1]  ← 8 × 4 bits = 4 bytes
  Scale:    1.2                             ← 1 × 2 bytes (FP16)
                                            ─────────────
                                            Total: 6 bytes (was 16!)

When the Model Runs (Forward Pass), Decompress

Code
Retrieve index → look up NF4 level → multiply by scale:

  index 13 → 0.7  × 1.2 = 0.84    (original was 0.8)
  index 10 → 0.3  × 1.2 = 0.36    (original was 0.3) ✓ 
  index 3  → -0.4 × 1.2 = -0.48   (original was -0.5)
  index 15 → 1.0  × 1.2 = 1.2     (original was 1.2) ✓ exact!
  index 1  → -0.7 × 1.2 = -0.84   (original was -1.0) ← worst error
  index 8  → 0.1  × 1.2 = 0.12    (original was 0.1)
  index 12 → 0.5  × 1.2 = 0.6     (original was 0.6) ✓ exact!
  index 1  → -0.7 × 1.2 = -0.84   (original was -0.9)

Side by Side

Code
Original FP16:    [0.80,  0.30, -0.50,  1.20, -1.00,  0.10,  0.60, -0.90]
After 4-bit:      [0.84,  0.36, -0.48,  1.20, -0.84,  0.12,  0.60, -0.84]
Error:            [+0.04,+0.06,+0.02,  0.00, +0.16, +0.02,  0.00, +0.06]

Memory: 16 bytes → 6 bytes (3.7× smaller)

That's It. The Whole Process Is:

Code
┌─────────────────────────────────────────────┐
│                                             │
│  LOADING:                                   │
│    FP16 weights                             │
│        ↓  ÷ absmax                          │
│    Normalized [-1, 1]                       │
│        ↓  snap to nearest bin               │
│    4-bit index + scale stored in GPU        │
│                                             │
│  RUNNING (every forward pass):              │
│    4-bit index                              │
│        ↓  look up bin value                 │
│    NF4 level                                │
│        ↓  × scale                           │
│    Approximate FP16 value → used in matmul  │
│                                             │
└─────────────────────────────────────────────┘

Why It Works

Code
Original weights:  [0.80,  0.30, -0.50,  1.20, -1.00,  0.10,  0.60, -0.90]
                    ↓ matrix multiply with input
Original output:   42.5

4-bit weights:     [0.84,  0.36, -0.48,  1.20, -0.84,  0.12,  0.60, -0.84]
                    ↓ matrix multiply with same input
4-bit output:      42.3

Close enough! The model still picks the same next token.

The small errors in individual weights average out across thousands of multiplications.

Monday, August 11, 2025

Covariance



Significance of covariance & meaning of high vs low values

Covariance measures how two features vary together:

  • Positive covariance → When feature F1F_1 is above its mean, feature F2F_2 tends to also be above its mean. (They move in the same direction.)

  • Negative covariance → When F1F_1 is above its mean, F2F_2 tends to be below its mean. (They move in opposite directions.)

  • Near zero covariance → No consistent linear relationship — knowing one feature’s deviation from the mean tells you nothing about the other.

Numerically:

  • Large magnitude (positive or negative) means strong linear relationship.

  • Small magnitude means weak or no relationship.


Why covariance matters in PCA

  • The covariance matrix encodes all pairwise relationships between features.

  • If features are highly correlated (large positive or negative covariance), PCA will combine them into a principal component that captures their shared variation, so you don’t have redundancy.

  • If covariances are near zero, features are largely independent; PCA will mostly keep them separate unless variances are drastically different.


💡 Analogy
Think of the covariance matrix as a “map” of how all features move together.
The eigenvectors are “routes” through this map that maximize variance.
PCA rotates your view to look along those routes, and you project the original data (not the covariance matrix itself) into that rotated view.


Sunday, August 10, 2025

How R2 is different from RMSE, MAE

 Let’s unpack this step-by-step — because R², RMSE, and MAE all involve “difference between actual and predicted,” but they measure different things and answer different questions.


1. R² (Coefficient of Determination) — Variance Captured

  • Think of your target values (y_actual) as having some spread (variance) around their mean.

  • If you didn’t have a model and just guessed the mean for everyone, that’s your baseline.

  • R² asks:

    "How much better is my model compared to just guessing the mean every time?"


Formula

R2=1−Sum of Squared Errors of ModelSum of Squared Errors of Mean ModelR^2 = 1 - \frac{\text{Sum of Squared Errors of Model}}{\text{Sum of Squared Errors of Mean Model}}

Where:

  • SSE_model = Σ(Actual − Predicted)²

  • SSE_mean = Σ(Actual − Mean)²


Intuition

  • R² = 1.0 → Model perfectly predicts all values (100% of variance explained).

  • R² = 0.0 → Model is no better than guessing the mean.

  • R² < 0.0 → Model is worse than guessing the mean (ouch).


Example in Credit Limit Prediction

Let’s say actual limits for 5 customers are:

Actual:  10k, 12k, 15k, 20k, 25k
Mean:    16.4k

Variance is the spread around 16.4k.

Case A: Terrible Model

Predicted: 16.4k for everyone (mean model) →
SSE_model = SSE_mean → R² = 0.

Case B: Decent Model

Predicted: 9k, 13k, 14k, 21k, 26k →
SSE_model is much smaller than SSE_mean → R² ≈ 0.85.
This means the model explains 85% of the variation in limits between customers.


2. RMSE & MAE — Error Magnitude

  • These do not compare to a baseline — they tell you how far off predictions are, on average.

  • RMSE penalizes large mistakes more heavily than MAE (because it squares the errors before averaging).

  • Both are absolute accuracy metrics, not relative to variance.


Example with Same Data

If predictions are:

Actual:    10k, 12k, 15k, 20k, 25k
Predicted: 9k, 13k, 14k, 21k, 26k

Errors: 1k, 1k, 1k, 1k, 1k

  • MAE = (1k + 1k + 1k + 1k + 1k) / 5 = 1k

  • RMSE = sqrt((1² + 1² + 1² + 1² + 1²) / 5) = 1k

  • R² = very high, because variance explained is high.


Key Difference

  • R²: “How much of the pattern in the data did I capture?”

  • RMSE / MAE: “How far off am I, in the actual unit (e.g., $)?”

You can have:

  • High R² but high RMSE → You’re good at ranking & trend, but still making large dollar errors.

  • Low R² but low RMSE → Everyone gets about the same prediction, close to average, but model doesn’t capture much variation between people.