Macalinao StudioLearnAll lessons ↗

TAKE THE LONGER ROUTE

Open the complete college lesson →

Worked explanations, full local narration, and connected Signal Room, Workbench and Field Notes.

SIGNAL ROOM

CBOW + Skip-gramUnderstand the moving parts.

The methods worth knowing - the intuition still applies, and they show why context matters.

Suggested preparation: 05

WORKBENCH / CHANGE ONE THING

Build a context window

Watch CBOW gather neighbors while skip-gram reverses the prediction direction.

Computed teaching example · fixed assumptions shown below

LISTEN & FOLLOW / GUIDED RECAP

Audio starts only when you choose.

FIELD NOTES / THE COMPLETE READING

Take the longer way.

The full lesson narrative, equations and code. Switch views without losing your place.

A slower starting point

Predict a missing word from its neighbors, then reverse the question.

Where this deserves more time

Negative sampling versus full softmax; input and output tables; gradient derivation.

Open the complete high-school reading

Moment 01 / 12

Course Overview & Objectives

Welcome to representation learning. Today we set the agenda: what this course covers, and what you should be able to do by the end. Let's start with the core themes.

Our focus is pre-transformer embeddings, specifically Continuous Bag of Words and Skip-gram, the two word2vec objectives from Mikolov and colleagues in 2013. These models remain the cleanest way to see how distributional context induces semantic structure.

Throughout, we emphasize intuition over mechanics: why context determines meaning. The distributional hypothesis says words in similar contexts have similar meanings, and these models operationalize that directly as a prediction task.

The format is interactive: lectures, discussion, and hands-on implementation across the coming sessions. You will train these models yourself, because the details only become clear when you write the loss function.

Finally, we connect these static embeddings to modern contextual architectures like BERT. The move from one vector per word to one vector per occurrence is the conceptual leap behind everything since.

By the end, you will have both the theory and the implementation skills behind the embedding methods that underlie modern NLP. Let's build that foundation carefully, step by step.

Equations, code and original cards

Course Overview & Objectives

• Topic Focus: Pre-transformer Embeddings

   CBOW & Skip-gram (word2vec, Mikolov et al. 2013)

• Emphasis on Intuition: the Distributional Hypothesis

• Interactive Format: Lectures, Discussion, Implementation

• From Static Embeddings to Contextual Models (BERT)

Moment 02 / 12

Introduction to Word Embeddings

Welcome to this session on word embeddings, the dense representations that preceded transformers and still underpin much of modern natural language processing.

A word embedding maps a discrete token to a continuous vector in a low-dimensional space, chosen so that geometric proximity reflects semantic similarity rather than surface spelling.

The governing principle is the distributional hypothesis: words that co-occur with similar contexts, like king and queen, should occupy nearby points in embedding space.

Mikolov and colleagues proposed two objectives in 2013: continuous bag of words predicts the center word from its context window, while skip-gram inverts this, predicting context from the center word.

Trained by maximizing likelihood over large corpora, these shallow models dominated representation learning until attention-based architectures arrived, yet their objectives remain conceptually central.

To recap, embeddings place discrete words in a continuous space where context similarity induces semantic structure, letting downstream models generalize beyond exact string matches.

Equations, code and original cards

Introduction to Word Embeddings

• Tokens mapped to dense low-dimensional vectors

• Distributional hypothesis: context similarity implies semantic similarity

• CBOW versus Skip-gram objectives (Mikolov et al. 2013)

• Pre-transformer foundation of learned representations

Moment 03 / 12

CBOW Model: Architecture & Math

Welcome. We now dissect Continuous Bag of Words, the Mikolov et al. 2013 model that learns embeddings by predicting a held-out word from its neighbors. The point is efficiency: a shallow network with one mean-pooling operation and a large softmax.

Fix a symmetric context window. CBOW reads the surrounding words on both sides of position t, ignores their order, and predicts the center token. Each context identifier selects one row from the embedding matrix; mean pooling those rows yields a single context vector.

The averaged vector equals one over the context size times the sum of the selected embedding rows. It is a sufficient statistic only under a bag-of-words assumption; permuting the neighbors leaves it unchanged.

In matrix form, the embedding table has vocabulary rows and embedding-dimension columns, so lookup is indexing rather than computation. The output matrix is embedding dimension by vocabulary size; multiplying the averaged context by it produces one logit per vocabulary item.

Those logits are unnormalized scores, not probabilities. A high dot product means the output column for a word aligns with the averaged context; the forward pass is therefore two table lookups, one mean, and one matrix-vector product.

Softmax exponentiates the logits and normalizes by their summed exponentials, yielding a categorical distribution over the vocabulary. The naive cost is linear in vocabulary size, which motivates hierarchical softmax or sampled losses when the vocabulary is large.

Training minimizes cross-entropy, equivalently the negative log likelihood of the true center word: minus the target logit plus the log of the summed exponentials. Gradients touch only the context embedding rows and the output columns, so updates are sparse despite the dense softmax.

The pipeline is therefore deliberately simple: aggregate neighbors by mean pooling, score every word with an output matrix, normalize with softmax, and descend the cross-entropy gradient. Its inductive bias is also its limitation: order and syntax vanish, but the objective scales to corpora where richer sequence models would be prohibitively slow.

Equations, code and original cards

CBOW: Architecture, Objective & Inductive Bias

Context Window & Embeddings

• Predict center word from symmetric neighbors

• Order discarded: bag-of-context inductive bias

• m = 2 → (wₜ₋₂, wₜ₋₁, wₜ₊₁, wₜ₊₂)

Matrix Notation

• Embedding table E ∈ ℝ^{V×N}: row lookup

• u = mean of context rows; logits z = Wᵀu

• W ∈ ℝ^{N×V}; full softmax is O(V)

\text{Average embedding:}\quad \hat{v} = \frac{1}{C} \sum\limits_{j=1}^C v_{w_j}
u = \hat{v}^\top W
p(w_t|context) = \frac{e^{u_{w_t}}}{\sum\limits_{w=1}^V e^{u_w}} \quad (\text{softmax output})
\mathcal{L} = -\log p(w_t|context) = -u_{w_t} + \log \left( \sum\limits_{w=1}^V e^{u_w} \right)

Moment 04 / 12

CBOW Model: Gradient Derivations

For softmax followed by cross entropy, the derivative with respect to each logit is predicted probability minus target probability. The derivative with respect to a probability is different: negative target divided by prediction.

For a linear classifier z equals W h, the weight gradient is the outer product of the logit gradient and h. Backpropagate through the context average to the contributing embedding rows.

Clarification: p minus y is the logit gradient, not the probability gradient.

Equations, code and original cards

CBOW Model: Gradient Derivations

• Softmax error: ŷ − one-hot target

• Chain rule in matrix form; rank-one outer product

• Updates: output matrix W and input context embeddings

• Co-occurrence gradients shape the embedding space

z=Wh,\quad p=\operatorname{softmax}(z),\quad \nabla_z L=p-y
\nabla_W L = (\hat{y} - y) \cdot h^T \\ \nabla_h L = W^T \cdot (\hat{y} - y)

Moment 05 / 12

Skip-gram Model: Architecture & Math

We now examine the Skip-gram architecture, introduced by Mikolov and colleagues in 2013, and the objective that makes its embeddings work.

Skip-gram inverts the prediction direction: a single center word parameterizes a distribution over every position in its context window, factorized as conditionally independent given the center.

Structurally, the model is a shallow two-layer network with no nonlinearity; the learned embedding is simply the input weight matrix, and the number of training pairs scales with window size.

Full softmax over the vocabulary is prohibitively expensive, so negative sampling replaces it with a binary logistic objective: distinguish true context pairs from k draws of a noise distribution.

The training objective, then, is to maximize the average log probability of context words given the center word, summed over all positions in the corpus.

Formally, we maximize one over T times the sum over t of the sum over context offsets j of the log probability of word t plus j given word t.

Each conditional probability is a softmax: the exponential of the context vector dotted with the center vector, normalized by that exponential summed over the entire vocabulary.

In summary, Skip-gram predicts context from a center word, and negative sampling renders the softmax tractable, yielding embeddings whose geometry encodes distributional semantics.

Equations, code and original cards

Skip-gram Model: Architecture & Math

Center word parameterizes distribution over context window

Shallow linear network; training pairs scale with window size

Negative sampling: logistic objective vs. k noise draws

Maximize average log p(w(t+j) | w(t)) via softmax

\max \sum_{t=1}^T \sum_{-c \leq j \leq c, j \neq 0} \log p(w_{t+j} \mid w_t)
p(w_{O} \mid w_{I})= \frac{\exp({\mathbf{v}'_{w_O}}^{\top} \mathbf{v}_{w_I})}{\sum_{w=1}^V \exp({\mathbf{v}'_w}^{\top} \mathbf{v}_{w_I})}

Moment 06 / 12

Negative Sampling Optimization

Negative sampling is the word2vec trick that turns a full-vocabulary softmax into a few binary logistic decisions.

The bottleneck is the denominator: every update scores the target against all vocabulary items, so cost grows linearly with vocabulary size.

Instead, keep one observed context pair as positive, draw a small number of negatives from a smoothed unigram distribution, usually the three-fourths power, and learn to separate them.

The objective adds log sigmoid for the true context-target dot product, and log sigmoid of minus each noise dot product, attracting real pairs and repelling noise.

This is noise contrastive estimation in spirit, after Gutmann and Hyvarinen: not exact softmax, but a surrogate whose gradients still shape useful geometry.

Each step now costs a handful of dot products rather than a full vocabulary scan, with sample count controlling the speed-quality tradeoff.

So negative sampling buys scalable training: near word2vec quality at a fraction of softmax cost, which is why it became standard for large vocabularies.

Equations, code and original cards

Negative Sampling Optimization

Full Softmax Bottleneck

• Denominator scores every vocabulary logit

• Cost grows linearly with vocabulary size

• Millions of classes make each update wasteful

Sampling Context Words

• Positive: observed target-context pair

• Negatives: smoothed unigram, three-fourths power

• Update touches one positive plus a small noise set

L = -\log \sigma (v_{w_O}^\top v_{w_I}) - \sum_{i=1}^k \mathbb{E}_{w_i \sim P_n(w)} \left[ \log \sigma (-v_{w_i}^\top v_{w_I}) \right]

Adjusted Loss Function

• Maximize log sigmoid for true dot products

• Maximize log sigmoid of minus noise dot products

• Logistic gradients replace full normalization

Speed-Quality Tradeoff

• Full scan becomes a handful of dot products

• More negatives: better approximation, slower steps

• Near word2vec quality at much lower cost

Moment 07 / 12

CBOW & Skip-gram Interactive Visualization

Let's begin with the core idea behind CBOW and Skip-gram, the two architectures Mikolov and colleagues introduced in word2vec, using this interactive diagram.

Now consider the context window. The window size sets the effective receptive field of the model: how many surrounding tokens contribute to each training signal.

Next, observe the CBOW forward pass. Context embeddings are averaged into a single vector, and a softmax over the vocabulary scores the target word. Here is the code that implements it.

Following this, we examine the backward pass, where the cross-entropy error propagates through the output matrix and updates each context embedding, improving predictions over time.

Now compare this with Skip-gram, which inverts the direction: the target embedding predicts each context word independently, yielding one training pair per context position.

The backward pass here accumulates gradients from all context predictions into a single update of the target word's embedding.

Watch the embeddings evolve as both models train. Co-occurring words are pulled together in the vector space, sharpening the geometry that encodes meaning.

Finally, review the comparison. CBOW is faster and smooths frequent words; Skip-gram is slower but represents rare words better, which drives its typical use cases.

Explore different input words and window sizes to see how embeddings evolve. This hands-on interaction builds real intuition for word2vec training dynamics.

Equations, code and original cards

Moment 08 / 12

Advanced Techniques & Optimizations (2024-2026)

Let's examine advanced techniques in embedding models from recent years. We'll cover methods that have substantially improved training efficiency and representation quality at scale.

First, hierarchical softmax and adaptive sampling. The full softmax over a vocabulary of size V costs O of V per training example; hierarchical softmax reduces this to O of log V via a tree-structured classifier, while importance-sampled and adaptive variants approximate the normalization constant with a frequency-weighted proposal distribution.

Next, scaling laws. Following Kaplan et al. 2020 and Hoffmann et al. 2022, loss decreases as a power law in parameters and data, with Chinchilla-optimal training near twenty tokens per parameter. These relations tell us how to trade embedding dimension against corpus size under a fixed compute budget.

We then turn to alignment, contrasting contextual embeddings, where a token's vector depends on its surrounding context, against static embeddings, where each type has one fixed representation. The distinction matters: contextual models resolve polysemy but cost inference compute, while static tables remain preferable for low-latency retrieval.

Finally, recent research trends and efficiency benchmarks: contrastive objectives, distillation from larger teachers, and quantization-aware training, all pushing embedding quality per unit of compute.

Together these advances yield embeddings that capture richer semantics while training faster. Keep them in mind as we dissect the underlying mechanisms in detail.

Equations, code and original cards

Advanced Techniques & Optimizations (2024-2026)

State-of-the-art improvements in embedding training efficiency and representation quality.

Hierarchical Softmax &
Adaptive Sampling

• Softmax cost cut from O(V) to O(log V)
• Frequency-weighted importance sampling
• Approximates the partition function

Scaling Laws Impact

• Power-law loss vs. params and data
• Chinchilla: ~20 tokens per parameter
• Guides compute-optimal allocation

Alignment Techniques

• Contextual vs. static embeddings
• Polysemy resolution vs. fixed types
• Trade-off: expressivity vs. latency

Research Trends & Benchmarks

• Contrastive objectives & distillation
• Quantization-aware training
• Quality per FLOP as the metric

Moment 09 / 12

Implementation Details: PyTorch Walkthrough

Let's walk through a PyTorch implementation of word2vec. We'll cover the embedding layer, context window construction, and the training loop for both CBOW and Skip-gram architectures.

First, the embedding layer: an nn.Embedding table of shape vocabulary size by embedding dimension, initialized near zero. Context windows are generated by sliding over the tokenized corpus, pairing each center word with its neighbors within a fixed radius.

Next, the forward pass with negative sampling. Rather than computing the full softmax over the entire vocabulary, which costs O of V per update, we approximate it with a handful of sampled negatives drawn from a unigram distribution raised to the three-quarter power.

Here is the CBOW forward pass. Context indices index the embedding table, we average the resulting vectors, and a linear layer maps to vocabulary logits. Notice this is a bag-of-words model: word order is discarded entirely.

The loss is negative log likelihood under a binary cross-entropy formulation: maximize the log sigmoid of the target score, plus the sum of log sigmoids of negated negative scores. Gradients flow back into the embedding table.

For performance: move the embedding table to GPU, since the lookup is memory-bound and benefits from batched indexing. Debug with a small vocabulary and batch size first; verify the loss decreases before scaling up.

We covered the full pipeline: embedding initialization, context window generation, the negative-sampling forward pass, the noise-contrastive loss, and practical optimization. These implementation details transfer directly to training larger representation models in PyTorch.

Equations, code and original cards

Implementation Details: PyTorch Walkthrough

• nn.Embedding: V × d lookup table

• Sliding context window generation

• Negative sampling: avoids O(V) softmax

• Negatives ~ unigram^0.75 distribution

Sample Code Snippet: CBOW Forward Pass

def forward(self, context_words):  embeds = self.embedding(context_words).mean(dim=1)  out = self.linear(embeds)  return out

• Loss: log σ(pos) + Σ log σ(−neg)

• Backprop into embedding table

• GPU: batched embedding lookup

• Debug with small vocab and batches

Moment 10 / 12

Cutting-edge Variations & Open Research Questions

We close with frontier directions in representation learning: where static embeddings meet contextual models, and where open problems still limit language systems.

First, transformer encoders replace fixed vectors with context-dependent token states in the residual stream, so polysemy is resolved by attention rather than by a single lookup table.

Second, multilingual and domain-adaptive embeddings exploit cross-lingual transfer and continued pretraining, but low-resource languages and technical vocabularies still suffer from data scarcity and catastrophic forgetting.

Rare and out-of-vocabulary terms are mitigated by byte pair encoding, character models, and retrieval, yet morphology, names, and neologisms remain a hard generalization test.

Interpretability and alignment remain open: probing classifiers and causal interventions reveal partial concept structure, while value alignment demands evaluations that track human preferences under distribution shift.

The throughline is clear: embeddings are moving from static geometry toward contextual, multilingual, interpretable representations whose failures guide the next models.

Equations, code and original cards

Cutting-edge Variations & Open Research Questions

Frontier methods, failure modes, and research directions

• Contextualization: static vectors to residual-stream states

• Multilingual and domain-adaptive transfer under scarcity

• Rare and out-of-vocabulary robustness via subwords and retrieval

• Interpretability, alignment, and evaluation under shift

Moment 11 / 12

Conceptual & Computational Quiz

Now test whether the CBOW and skip gram objectives are clear: work independently, predict centers from context and contexts from centers, and justify when negative sampling beats full softmax.

After submission, we will audit the errors: likelihood signs, sampling distributions, window size effects, and which gradients actually move the embeddings.

Equations, code and original cards

Moment 12 / 12

Summary & Key Takeaways

Let's consolidate the core results on pre transformer word embeddings and their lasting design lessons.

First, embeddings map discrete tokens to dense vectors so semantic regularities become linear structure in a learned space.

We derived skip gram and continuous bag of words as likelihood objectives, with negative sampling replacing the costly full softmax.

Their influence persists in subword units, initialization, evaluation benchmarks, and the residual stream view of representation in modern language models.

For further study, prioritize the original word to vec and GloVe papers, plus analyses of bias, geometry, and downstream transfer.

You should now read embedding behavior through objectives, sampling noise, and vector geometry, ready to contrast these inductive biases with attention based transformers.

Equations, code and original cards

Summary & Key Takeaways

• Dense vectors encode distributional semantics

• Skip gram and continuous bag of words likelihoods; negative sampling

• Legacy: subwords, initialization, benchmarks, residual stream view

• Next: word2vec and GloVe papers; bias, geometry, transfer

MAKE IT YOURS

Explain the change.

References, scope & corrections

Research snapshots in the source material are not a claim of current state of the art. The reference review corrects identified errors; it is not exhaustive certification of every historical statement. Source code snippets are examples, not a tested production training system.

2 correction entries · expansion notes

Reset this lesson?

This removes only this lesson’s saved notes, experiments and progress.