NLP & Transformers
Word and text embeddings, the Transformer encoder/decoder, self-attention and positional encoding, and BERT for embeddings and question answering.
18 questions
JuniorTheoryVery commonWhy is cosine similarity preferred over Euclidean distance for text embeddings?
Why is cosine similarity preferred over Euclidean distance for text embeddings?
Cosine compares only the angle between two vectors and ignores magnitude, so it captures the direction of meaning. Euclidean distance grows with the norm, and the norm tracks text length and word frequency, so two texts on one topic can look far apart merely because one is longer.
Common mistakes
- ✗Treating cosine and Euclidean as interchangeable rankings
- ✗Forgetting the vector norm encodes length or frequency, not topic
- ✗Assuming cosine needs shared surface words to score highly
Follow-up questions
- →When do cosine and Euclidean give the same ranking?
- →Why can a high cosine still mean the two texts are unrelated?
JuniorTheoryVery commonWhat is positional encoding and why is it needed?
What is positional encoding and why is it needed?
It adds position information to each token's embedding so the same token at different positions differs. It is needed because self-attention is permutation-invariant — order-blind by itself. Variants: original sinusoidal, learned embeddings, and RoPE (rotary positional embeddings).
Common mistakes
- ✗Thinking self-attention is order-aware without positional encoding
- ✗Believing positional encoding replaces rather than augments token embeddings
- ✗Not knowing any variant beyond the original sinusoidal scheme
Follow-up questions
- →How do learned position embeddings differ from sinusoidal ones?
- →What advantage does RoPE offer over absolute positional encoding?
JuniorTheoryVery commonHow does self-attention work in the Transformer?
How does self-attention work in the Transformer?
Each token attends to every other token to mix context. A token is projected into Query, Key, and Value vectors. The attention weight between two tokens is softmax(Q·Kᵀ / √dₖ) — a normalized Query–Key similarity. Each token's output is the weighted sum of all Value vectors.
Common mistakes
- ✗Treating attention like an RNN with a single sequential hidden state
- ✗Forgetting the √dₖ scaling inside the softmax
- ✗Confusing the roles of Query, Key, and Value
Follow-up questions
- →Why divide the dot product by √dₖ before the softmax?
- →What does multi-head attention add over a single attention?
SeniorTheoryVery commonHow do the encoder and decoder blocks of the original Transformer differ structurally?
How do the encoder and decoder blocks of the original Transformer differ structurally?
An encoder block has two sub-layers: self-attention and a feed-forward network. A decoder block adds a THIRD — encoder-decoder cross-attention over the encoder outputs — and its self-attention is causally masked, unlike the encoder's bidirectional one. The decoder ends in Linear + Softmax.
Common mistakes
- ✗Forgetting the decoder's extra cross-attention sub-layer
- ✗Thinking the decoder's self-attention is unmasked like the encoder's
- ✗Missing that only the decoder ends in Linear + Softmax over the vocabulary
Follow-up questions
- →What does the decoder's cross-attention attend over, and why?
- →Why must the decoder's self-attention be causally masked?
JuniorTheoryCommonWhat problem with word-level vocabularies does subword tokenization solve?
What problem with word-level vocabularies does subword tokenization solve?
A word-level vocabulary is finite, so unseen words collapse to a single [UNK] token and lose all meaning. Subword schemes keep frequent fragments instead and split any unknown word into known pieces, so OOV vanishes. BPE learns its merges by greedily joining the most frequent adjacent pair.
Common mistakes
- ✗Thinking subword models still emit [UNK] for any unseen word
- ✗Believing BPE merges are hand-written rules rather than frequency-learned
- ✗Confusing subword splitting with stemming or affix stripping
Follow-up questions
- →How does WordPiece pick a split differently from BPE?
- →What happens to sequence length when a text is heavily fragmented?
JuniorTheoryCommonWhat methods for building word and text embeddings do you know?
What methods for building word and text embeddings do you know?
Sparse/count-based: Bag-of-Words and TF-IDF. Dense static: word2vec and GloVe (one vector per word), FastText (word2vec plus subword n-grams, handling rare/OOV words). Contextual: ELMo and BERT, where a word's vector depends on its context, so the same word varies.
Common mistakes
- ✗Calling BoW/TF-IDF dense learned embeddings instead of sparse counts
- ✗Thinking word2vec/GloVe vectors are contextual rather than static
- ✗Missing that FastText adds subword n-grams over word2vec
Follow-up questions
- →How is word2vec trained, and how does FastText differ from it?
- →Why do contextual embeddings beat static ones for polysemous words?
MiddleTheoryCommonStemming or lemmatization — which do you apply, and when is neither worth it?
Stemming or lemmatization — which do you apply, and when is neither worth it?
Stemming chops affixes by rules and may emit non-words, but it is cheap; lemmatization uses a dictionary and part of speech to return a real base form at a higher cost. Both mainly help sparse count models by collapsing forms; with subword contextual models they add little.
Common mistakes
- ✗Swapping which method returns a real dictionary form
- ✗Applying aggressive normalisation before a subword transformer
- ✗Assuming normalisation never changes the vocabulary size
Follow-up questions
- →Why does lemmatization need the part of speech to be correct?
- →Where does over-stemming visibly hurt a search ranking?
MiddleTheoryCommonIn TF-IDF, what exactly does the IDF factor downweight relative to bag-of-words?
In TF-IDF, what exactly does the IDF factor downweight relative to bag-of-words?
Bag-of-words counts terms inside one document. IDF scales each count by a factor that falls as the number of documents containing the term rises, so corpus-wide terms are damped. A word repeated often in one document still scores high; only spread across documents is penalised.
Common mistakes
- ✗Reading IDF as a penalty on within-document repetition
- ✗Confusing IDF term weighting with L2 document normalisation
- ✗Inverting the direction and thinking common terms get boosted
Follow-up questions
- →Why is the IDF formula smoothed with a plus one in the denominator?
- →When does TF-IDF lose to a plain count model?
MiddleTheoryCommonHow do skip-gram and CBOW differ in what word2vec predicts, and when is each better?
How do skip-gram and CBOW differ in what word2vec predicts, and when is each better?
CBOW predicts the centre word from its averaged context, which trains fast and favours frequent words. Skip-gram reverses it and predicts each context word from the centre one, creating one pair per neighbour, so rare words get more updates and small corpora fare better.
Common mistakes
- ✗Swapping the prediction direction of the two objectives
- ✗Assuming the choice affects only training speed
- ✗Thinking one trained model can serve both objectives
Follow-up questions
- →Why does negative sampling make either objective tractable?
- →How does the window size change what the vectors encode?
SeniorTheoryCommonUsing a trained BERT, how do you get an embedding for a whole text?
Using a trained BERT, how do you get an embedding for a whole text?
Training-free: pool all token embeddings (mean/max), or take the [CLS] embedding — though raw [CLS] is a weak similarity vector. For a strong text embedding, fine-tune SentenceBERT-style: add pooling plus a feed-forward head and train with metric learning (siamese/triplet loss).
Common mistakes
- ✗Trusting the raw [CLS] vector as a good similarity embedding
- ✗Thinking you must retrain BERT from scratch for text vectors
- ✗Forgetting metric learning is what makes similar texts close
Follow-up questions
- →Why is the raw [CLS] embedding poor for similarity without fine-tuning?
- →How does a triplet loss shape the embedding space?
SeniorTheoryCommonWhat is special about self-attention in an autoregressive Transformer decoder compared to a plain attention?
What is special about self-attention in an autoregressive Transformer decoder compared to a plain attention?
A triangular causal mask is applied: before the softmax, scores for future positions (j > i) are set to −∞, so position i attends only to itself and earlier tokens. This enforces autoregression — the model can't peek at the token it must predict. An encoder (e.g. BERT) uses no such mask.
Common mistakes
- ✗Masking past instead of future positions
- ✗Applying the mask after softmax rather than as −∞ before it
- ✗Thinking BERT's encoder also uses a causal mask
Follow-up questions
- →Why set masked scores to −∞ rather than zero before the softmax?
- →How does the absence of this mask let BERT be bidirectional?
JuniorTheoryOccasionalWhy does a static embedding table struggle with a word that has several meanings?
Why does a static embedding table struggle with a word that has several meanings?
A static model such as word2vec stores one vector per word type, so every sense of a word is averaged into a single point that fits none of them well. Contextual models compute the vector from the surrounding sentence, so each occurrence gets its own representation.
Common mistakes
- ✗Believing word2vec resolves the sense at lookup time from context
- ✗Thinking one averaged vector represents each sense adequately
- ✗Confusing subword splitting with sense disambiguation
Follow-up questions
- →How would you detect that polysemy is hurting a production model?
- →Where do static embeddings still beat contextual ones in practice?
MiddleTheoryOccasionalWill BERT's token embeddings change if you permute the words in a sentence?
Will BERT's token embeddings change if you permute the words in a sentence?
Yes. BERT adds positional embeddings, so the same token at a different position starts from a different input vector. Also, self-attention mixes each token with its context, which reordering changes. Both effects make the contextual embeddings differ after a permutation.
Common mistakes
- ✗Treating BERT embeddings as static lookups independent of position
- ✗Thinking positional info attaches only to [CLS], not every token
- ✗Forgetting self-attention re-mixes context after reordering
Follow-up questions
- →Which two ingredients make BERT sensitive to word order?
- →How would removing positional embeddings change this answer?
MiddleTheoryOccasionalCan a pretrained BERT give a reasonable embedding for a rare word it never saw in training?
Can a pretrained BERT give a reasonable embedding for a rare word it never saw in training?
Yes, for two reasons. First, WordPiece tokenization splits the rare word into frequent subword tokens, so there is no out-of-vocabulary failure. Second, BERT is contextual, so surrounding words inform it. To get a single word vector, mean- or max-pool its subword embeddings.
Common mistakes
- ✗Assuming rare words always collapse to a single [UNK] token
- ✗Forgetting WordPiece subword splitting prevents OOV
- ✗Ignoring that context shapes the contextual embedding
Follow-up questions
- →How does WordPiece decide where to split an unseen word?
- →When would subword pooling give a misleading word vector?
MiddleTheoryOccasionalHow do word-level entity labels line up with subword tokens in named-entity recognition?
How do word-level entity labels line up with subword tokens in named-entity recognition?
One word becomes several pieces, so the word tag under the BIO scheme goes on its first piece; the remaining pieces are marked as continuations and masked out of the loss. At inference you map predictions back to words by reading the tag of each word first piece.
Common mistakes
- ✗Letting every subword piece contribute a duplicated label to the loss
- ✗Forgetting to map subword predictions back onto whole words
- ✗Assuming subword models cannot do per-token classification
Follow-up questions
- →What breaks when an entity boundary falls inside one subword piece?
- →How would you evaluate this tagger — per token or per span?
MiddlePerformanceOccasionalAdding word bigrams and trigrams exploded your text feature matrix — what is the cost and fix?
Adding word bigrams and trigrams exploded your text feature matrix — what is the cost and fix?
Each distinct n-gram becomes its own column, so the vocabulary grows far faster than the corpus and most columns fire in a few documents. Prune with a minimum document frequency, cap the vocabulary size, or hash into a fixed width; the matrix is sparse, so cost tracks nonzeros.
Common mistakes
- ✗Assuming the count matrix is stored densely with all zero cells
- ✗Believing the n-gram vocabulary is bounded by the unigram one
- ✗Thinking feature hashing is collision-free
Follow-up questions
- →How do you pick the width for feature hashing?
- →When do character n-grams beat word n-grams on the same text?
SeniorTheoryOccasionalHow do you train BERT for extractive question answering, where the answer is a span in a reference text?
How do you train BERT for extractive question answering, where the answer is a span in a reference text?
Frame the answer as two numbers — the start and end token positions. Feed the question and text together and add two output heads over the tokens: one predicting P(start), one P(end), each a feed-forward layer plus softmax. The span runs from the argmax start to the argmax end (SQuAD-style).
Common mistakes
- ✗Treating extractive QA as free-form text generation
- ✗Using one head instead of separate start and end heads
- ✗Forgetting the span is decoded as argmax start to argmax end
Follow-up questions
- →How do you ensure the predicted end position is not before the start?
- →What loss is used to train the start and end heads?
MiddleDebuggingRareDomain terms were added to the tokenizer and fine-tuning now fails — what is wrong?
Domain terms were added to the tokenizer and fine-tuning now fails — what is wrong?
Adding tokens grows the tokenizer vocabulary but not the model embedding matrix, so the new ids index past its rows and training crashes. Call resize_token_embeddings after add_tokens; the appended rows start random, so budget continued pretraining or the new terms carry no meaning.
Open full question →Common mistakes
- ✗Calling add_tokens without resizing the model embedding matrix
- ✗Expecting new token rows to be meaningful without further training
- ✗Blaming the optimizer or learning rate for an index-range crash
Follow-up questions
- →How would you initialise the new rows better than at random?
- →When is it cheaper to leave the terms fragmented instead?