Contextual embeddings and BERT
Contextual embeddings let models assign vector meanings that change with context; BERT is a powerful Transformer-based way to learn such embeddings by self-attention and masked-language pretraining.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Engineers use contextual embeddings when any downstream NLP task (classification, NER, parsing, QA, etc.) must represent the meaning of a word differently depending on the words around it. BERT is a widely-used method to produce such contextual vectors that can be fine-tuned for many tasks with very little task-specific data.
Key ideas
Static embedding: an embedding that is the same for a word type regardless of sentence context (example: word2vec, GloVe). Static means no dependence on surrounding tokens.
Contextual embedding: an embedding that depends on the token's surrounding words. The same word type in different sentences gives different vectors.
Transformer: a neural-network architecture built from repeated blocks of self-attention and position-wise feed-forward layers. Transformers avoid recurrence (no RNNs) and process tokens in parallel.
Self-attention: a mechanism that computes a weighted sum of values where weights are computed from pairwise similarity between tokens. For a sequence of tokens, each token computes a query vector and compares it to the keys of every token; similarities (after a softmax) weight the values.
Scaled dot-product attention (definition): Given matrices Q (queries), K (keys), V (values) with compatible sizes, the output is softmax(QK^T / sqrt(d_k)) V. Assumptions: Q, K, V are real-valued; each row corresponds to one token's vector; d_k is the dimensionality of key vectors.
Multi-head attention: run several independent self-attention computations (heads) in parallel, then concatenate their outputs and linearly project to the model dimension. This lets the model focus on different relational patterns simultaneously.
Positional encoding: because Transformer blocks have no recurrence or convolution, we inject token position information into token embeddings. Two common approaches: learned position embeddings, or fixed sinusoidal positional encodings defined by sine and cosine functions of position and dimension index.
BERT (Bidirectional Encoder Representations from Transformers): a model built from stacked Transformer encoder layers trained with two unsupervised objectives (original paper): Masked Language Modeling (MLM) and Next Sentence Prediction (NSP). BERT is bidirectional in the sense that MLM conditions on both left and right context simultaneously. BERT uses only the Transformer encoder; inputs are formed by prepending a [CLS] token and separating segments with [SEP], with token type (segment) embeddings marking sentence A as 0 and sentence B as 1.
Masked Language Modeling (MLM): randomly select some input token positions and train the model to predict the original token identity only at those selected positions. This forces the model to use context from both left and right.
Next Sentence Prediction (NSP): given a pair of text segments A and B, the model predicts whether B immediately follows A in the original text (binary classification). BERT used NSP with balanced examples to teach sentence relationships; later work found NSP may be unnecessary for some tasks.
Assumptions behind BERT-style pretraining: large unlabeled corpora exist; subword tokenisation (WordPiece) is used to handle rare words; model capacity and compute allow learning deep contextual patterns.
How it fits into a pipeline: train BERT (pretraining) once; for a downstream task, add a small task-specific head (classification, token tagging, etc.) and fine-tune the entire model on labeled task data.
Diagrams to draw (exam):
- Draw a single Transformer encoder block: label input embedding -> multi-head self-attention (show Q,K,V inside) -> add & norm -> feed-forward -> add & norm. Indicate residual connections.
- Draw attention weight matrix for 4 tokens: a 4×4 grid with darker cells where attention weight is high. Label rows as queries and columns as keys.
Formulas
Attention(Q,K,V) = softmax(Q·K^T / sqrt(d_k)) · V — Q: queries (n×d_k), K: keys (n×d_k), V: values (n×d_v). Dimensionless. Applies to scaled dot-product self-attention.
softmax(z_i) = exp(z_i) / sum_j exp(z_j) — for vector z across the axis; dimensionless; applies when converting scores to probabilities.
MultiHead(Q,K,V) = Concat(head_1,...,head_h) · W^O, head_i = Attention(QW_i^Q, KW_i^K, VW_i^V) — W matrices are learned linear projections; dimensions match model design. Dimensionless.
PE(pos,2i) = sin(pos / 10000^{2i/d_model}) — pos: token position (0-based), i: dimension index. Dimensionless. Applies to sinusoidal positional encodings.
PE(pos,2i+1) = cos(pos / 10000^{2i/d_model}) — same symbols as above.
Embedding_input = TokenEmbedding + SegmentEmbedding + PositionalEmbedding — sum of three vectors per token. Dimensionless.
L_MLM = - sum_{t in masked} log p_theta(original_token_t | context) — MLM loss: negative log-likelihood summed over masked positions. Units: nats (if natural log) or bits (if log base 2); dimensionless probability.
L_total = L_MLM + lambda * L_NSP — combined pretraining loss; lambda is weighting constant (often 1 in BERT's original setup). Dimensionless.
Worked examples
Example 1 — compute scaled dot-product self-attention for 3 tokens (numerical)
Given tokens T1,T2,T3 with d_k=2 and matrices (each row is a token vector):
Q = K = [[1,0], [0,1], [1,1]]
V = [[1,0], [0,1], [1,1]]
Step 1 — compute raw scores S = Q·K^T (3×3):
Row1 (1,0)·K rows = [1,0,1]
Row2 (0,1)·K rows = [0,1,1]
Row3 (1,1)·K rows = [1,1,2]
So S = [[1,0,1],[0,1,1],[1,1,2]].
Step 2 — scale by sqrt(d_k) = sqrt(2) ≈ 1.4142: S_scaled = S / 1.4142 ≈ [[0.7071,0,0.7071],[0,0.7071,0.7071],[0.7071,0.7071,1.4142]].
Step 3 — apply softmax row-wise to get attention weights A.
Row1 softmax([0.7071,0,0.7071]) -> exps ≈ [2.028,1,2.028], sum ≈ 5.056 -> probs ≈ [0.401,0.198,0.401].
Row2 softmax([0,0.7071,0.7071]) -> exps ≈ [1,2.028,2.028], sum ≈ 5.056 -> probs ≈ [0.198,0.401,0.401].
Row3 softmax([0.7071,0.7071,1.4142]) -> exps ≈ [2.028,2.028,4.113], sum ≈ 8.169 -> probs ≈ [0.248,0.248,0.504].
Step 4 — output = A · V (matrix multiply). Compute per row:
Output1 = 0.401*[1,0] + 0.198*[0,1] + 0.401*[1,1] = [0.802, 0.599].
Output2 = 0.198*[1,0] + 0.401*[0,1] + 0.401*[1,1] = [0.599, 0.802].
Output3 = 0.248*[1,0] + 0.248*[0,1] + 0.504*[1,1] = [0.752, 0.752].
These 3 output vectors are the self-attention results and are the contextualised representations for the tokens after one attention step.
Example 2 — model-answer: "Explain BERT pretraining and fine-tuning with the MLM loss derivation"
Model answer (exam style):
BERT pretraining uses two objectives: Masked Language Modeling (MLM) and Next Sentence Prediction (NSP). For MLM, select a subset M of token positions (original paper: 15% of tokens) and replace each selected token as follows: 80% of time by special token [MASK], 10% by a random token, 10% left unchanged. Let theta be model parameters and let x be the original sequence with masked input x_masked. The model computes p_theta(x_t | x_masked) for each token position t as a softmax over the vocabulary from the final transformer output at that position. The MLM loss is the negative log-likelihood over masked positions:
L_MLM(theta) = - sum_{i in M} log p_theta(x_i | x_masked).
This loss trains the model to predict original tokens only at masked locations, forcing the use of bidirectional context. NSP adds a binary cross-entropy loss where pairs (A,B) are labeled IsNext=1 if B follows A in corpus, else 0. Final pretraining loss is L_total = L_MLM + L_NSP. After pretraining, fine-tuning: add a task-specific head (e.g., classification head on [CLS] token), initialise with pretrained weights, and update all parameters on small labeled task data. This transfer yields strong performance because pretrained contextual embeddings capture language patterns useful across tasks.
(End of model answer.)
Common mistakes
Mixing up attention weight and attention output: the softmaxed scores multiply V to produce the output — high weight on a token does not mean its key vector is copied, it influences the weighted sum of values.
Softmax axis error: apply softmax over keys for each query (row-wise), not over the entire matrix.
During MLM training, replacing 80/10/10 incorrectly (the original BERT policy matters if reimplementing paper experiments).
Confusing pretraining and fine-tuning objectives and datasets.
For your exam
Question types you will see: definitions (e.g., define self-attention), short notes (e.g., compare static vs contextual embeddings), derivations (derive attention formula and show scaling), numericals (compute attention for small matrices), diagrams (draw Transformer encoder block, attention heatmap), and long answers (explain BERT pretraining/fine-tuning, pros and cons).
What a full-marks answer includes:
- Clear definitions of key terms (embedding, attention, Transformer, BERT).
- Exact attention formula with symbol meanings and the reason for the 1/sqrt(d_k) scaling (to stabilise gradients / keep dot products in a suitable range before softmax).
- A small worked numerical example or a correct diagram as required.
- For BERT questions: description of MLM and NSP, the 80/10/10 masking policy, and the fine-tuning step. Also know typical configurations: BERT-Base (12 layers, 12 attention heads, hidden size 768, ~110M parameters) and BERT-Large (24 layers, 16 attention heads, hidden size 1024, ~340M parameters).
- Mention assumptions (large unlabeled corpora, WordPiece tokenisation) and limitations (compute cost, large models need many resources).
Quick check
- What is the purpose of positional encoding in Transformers?
- Write the scaled dot-product attention formula and explain what d_k does.
- In BERT's MLM, what fraction of selected tokens are replaced with [MASK] in the original paper?
Answers: 1) To give the model information about token order since attention alone is permutation-invariant. 2) Attention(Q,K,V)=softmax(Q·K^T / sqrt(d_k))·V; d_k scales dot-products to avoid tiny gradients and extreme softmax values. 3) 80% of the selected tokens are replaced by [MASK].
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?