Exercises

Agentic AI · L-Embed

Calculations and conceptual questions on vector similarity, word embeddings and text embeddings. Four tutorials on semantic search (semantic tool selection, the limits of nearest-neighbour search, English and multilingual embedding models, truncated embeddings) are in the lab notebook lecture-Embed-lab.ipynb. Solutions are in skip cells (tag solution), stripped for the handout.

Part A — Vector-Math Calculations

Exercise 1 — Cosine & Euclidean by Hand (calculation)

Given $\mathbf{a}=(1,2,2)$ and $\mathbf{b}=(2,0,0)$, compute: (i) $\mathbf{a}\cdot\mathbf{b}$; (ii) $\|\mathbf{a}\|_2$ and $\|\mathbf{b}\|_2$; (iii) the cosine similarity $S_C(\mathbf{a},\mathbf{b})$; (iv) the Euclidean distance $\|\mathbf{a}-\mathbf{b}\|_2$.

Exercise 2 — Cosine of Unit Vectors (theory)

Show that if $\mathbf{u},\mathbf{v}$ are unit vectors then $S_C(\mathbf{u},\mathbf{v})=\mathbf{u}\cdot\mathbf{v}$. Why does this make normalizing embeddings convenient for search?

Exercise 3 — Distance vs. Cosine (theory)

Prove $\|\mathbf{u}-\mathbf{v}\|_2^2 = \|\mathbf{u}\|_2^2+\|\mathbf{v}\|_2^2-2\,\mathbf{u}\cdot\mathbf{v}$. Deduce that for unit vectors $\|\mathbf{u}-\mathbf{v}\|_2^2 = 2-2\cos\theta$, and explain why Euclidean and cosine then give the same ranking.

Exercise 4 — Cosine or Euclidean? (conceptual)

Give a case where cosine similarity is preferable to raw Euclidean distance, and why.

Exercise 5 — Inner Product vs. Cosine (calculation)

DPR, the retrieval bi-encoder of Karpukhin et al. (2020), scores a pair by the plain inner product $\mathbf{q}^\top\mathbf{p}$ and not by the cosine. Take the query vector $\mathbf{q}=(1,0)$ and the two passage vectors $\mathbf{p}_1=(0.8,\,0.6)$ and $\mathbf{p}_2=(2,\,3)$.

(i) Compute $\mathbf{q}^\top\mathbf{p}_j$ and $S_C(\mathbf{q},\mathbf{p}_j)$ for both passages, and rank the passages under each of the two scores.

(ii) Write the inner product as the product of two norms and a cosine, and use the product to explain why the two rankings differ.

(iii) Every passage vector is divided by its norm before it is stored. Which ranking does the inner product then produce, and why?

Exercise 6 — BM25 by Hand (calculation)

BM25 scores a document $d$ against a query $q$ by one weight per query term (Robertson & Zaragoza, 2009):

$$\mathrm{BM25}(q,d)=\sum_{t\in q}\mathrm{idf}^{\mathrm{RSJ}}_t\cdot \frac{\operatorname{count}(t,d)\,(k_1+1)}{\operatorname{count}(t,d)+k_1\!\left(1-b+b\,\dfrac{|d|}{|d_{\text{avg}}|}\right)}, \qquad \mathrm{idf}^{\mathrm{RSJ}}_t=\ln\frac{N-\mathrm{df}_t+0.5}{\mathrm{df}_t+0.5}$$

where $\operatorname{count}(t,d)$ is the number of occurrences of term $t$ in $d$, $|d|$ the length of $d$ in terms, $|d_{\text{avg}}|$ the average document length, $N$ the number of documents, $\mathrm{df}_t$ the number of documents containing $t$, and $k_1$, $b$ the two parameters.

The formula differs from the BM25 of the lecture in two places (Robertson & Zaragoza, 2009, §3.3 and §3.5.1). The idf is the Robertson–Spärck Jones weight without relevance information (Eq. 3.3) in place of $\log(N/\mathrm{df}_t)$; it is negative when $\mathrm{df}_t > (N-0.5)/2$. The numerator carries the factor $k_1+1$, a common variant that multiplies every term by the same constant: the fraction tends to $k_1+1$ instead of 1, and the ranking does not change.

A corpus holds $N=10$ documents with average length $|d_{\text{avg}}|=20$ terms. The query is "cache eviction"; cache occurs in 3 documents, eviction in 2. Three of the documents:

Document $\lvert d\rvert$ $\operatorname{count}(\text{cache},d)$ $\operatorname{count}(\text{eviction},d)$
$d_1$ 10 1 1
$d_2$ 10 6 0
$d_3$ 40 2 1

Use $k_1=1.2$ throughout.

(a) Compute $\mathrm{idf}^{\mathrm{RSJ}}_{\text{cache}}$ and $\mathrm{idf}^{\mathrm{RSJ}}_{\text{eviction}}$.

(b) Replace the fraction by the raw count $\operatorname{count}(t,d)$ — a score linear in the raw count, with the same idf — and rank the three documents.

(c) Now use the fraction with $b=0$. Compute it for counts of 1, 2 and 6, score and rank the three documents, and state the value the fraction approaches as $\operatorname{count}(t,d)\to\infty$.

(d) Repeat (c) with $b=0.75$. Which pair of documents changes places, and which term of the formula causes it?

(e) A third query term, the, occurs in 8 of the 10 documents. Compute its idf. What does a document gain by containing it, and why is the case more frequent in a corpus of chunks cut from a single technical manual?

Part B — Word Embeddings

Exercise 7 — Analogy by Vector Offset (calculation)

The vector-offset method of Mikolov, Yih & Zweig (2013) answers the question man is to woman as king is to ? by computing $\mathbf{x} = \mathbf{v}_{\text{king}} - \mathbf{v}_{\text{man}} + \mathbf{v}_{\text{woman}}$ and returning the word whose vector is nearest to $\mathbf{x}$ by cosine similarity. The evaluation of Mikolov et al. (2013a) excludes the three question words from that search. Take the two-dimensional toy vectors

Word man woman king queen apple
Vector $(2,\,0)$ $(2,\,2)$ $(5,\,1)$ $(5,\,4)$ $(-1,\,2)$

(i) Compute $\mathbf{x}$.

(ii) Compute $S_C(\mathbf{x},\mathbf{v}_w)$ for $w \in \{\textit{queen}, \textit{woman}, \textit{king}, \textit{apple}\}$.

(iii) Which word does the method return? Which word would it return if the question words were not excluded? Under which condition on the offset $\mathbf{v}_{\text{woman}} - \mathbf{v}_{\text{man}}$ is a question word nearest to $\mathbf{x}$?

Exercise 8 — Training Pairs of CBOW and Skip-gram (calculation)

Take the sentence "the cat sat on the mat" (six words, positions $t = 1,\dots,6$) and a window of $C = 2$ words on each side, as in the lecture's CBOW and Skip-gram (Mikolov et al. 2013a, §3.1–3.2).

(a) Skip-gram: list the training pairs (centre word, context word) that the centre word sat produces. How many pairs does the whole sentence produce? A word near the start or the end of the sentence has fewer than $2C$ context words.

(b) CBOW: write the input $\mathbf{h}_t$ for the centre word sat as an average of input vectors. Compute it for the 2-dimensional input vectors $\mathbf{v}_{\textit{the}} = (1, 0)$, $\mathbf{v}_{\textit{cat}} = (0, 2)$ and $\mathbf{v}_{\textit{on}} = (2, 2)$.

(c) Skip-gram with $C = 10$ draws for every centre word a radius $R$ uniformly from $\{1,\dots,10\}$ and predicts only the $R$ words on each side. Compute the probability that a context word at distance $j$ is predicted, for $j = 1$, $5$ and $10$, and the expected number of predictions per centre word. Compare it with a fixed window of 10 words on each side.

(d) One Skip-gram training step for the pair (sat, cat) maximises $\log p(\textit{cat} \mid \textit{sat})$ with the softmax of the lecture (Mikolov et al. 2013b, §2, Eq. 2). Which vectors does the step change? Which vectors are kept as the word vectors after training?

Part C — Text Embeddings

Exercise 9 — Bi-Encoder vs. Cross-Encoder Cost (calculation)

Reimers & Gurevych (2019) report that finding the most similar pair among $n = 10{,}000$ sentences takes about 65 hours with a BERT cross-encoder, and about 5 seconds for the 10,000 encodings of a bi-encoder.

(i) Verify the number of cross-encoder forward passes, 49,995,000. Derive the time of one cross-encoder forward pass and of one bi-encoder encoding.

(ii) A retrieval corpus holds $N = 10^6$ passages, and the vectors have $d = 768$ dimensions. With the times of (i), compute the time per query of a cross-encoder that scores every passage. For a bi-encoder, state what is computed once, before any query arrives, and compute the time per query, assuming a machine that performs $10^{10}$ multiply-adds per second for the vector comparisons.

(iii) A system retrieves $k = 100$ candidates with the bi-encoder and scores only these with the cross-encoder. Compute the cross-encoder time per query.

(iv) Which property of the score does the bi-encoder give up in exchange for its speed?

Exercise 10 — Pooled Vectors and Trained Geometry (conceptual)

Reimers & Gurevych (2019) measure the Spearman rank correlation ($\times 100$) between the cosine similarity of two sentence vectors and human similarity judgements, averaged over seven semantic-textual-similarity sets:

Representation Correlation
BERT [CLS] vector 29.19
Mean of BERT token vectors 54.81
Mean of GloVe word vectors 61.32
Sentence-BERT 74.89

(i) Why is a rank correlation compared with the human judgements, and not the cosine values themselves?

(ii) A linear classifier fitted on the mean of BERT token vectors performs well on supervised sentence-classification tasks. Explain why this result does not contradict the correlation of 54.81.

(iii) The second and the fourth row both reduce the token vectors to their mean. What differs between the two, and why does that difference change the correlation?

(iv) Why is the [CLS] vector of an untuned BERT the weakest row?

References

Peer-reviewed papers

  • Devlin, Jacob, et al. "BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding." Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long and Short Papers). 2019, pp. 4171–4186. arXiv:1810.04805. — the footnote stating that the [CLS] vector is not a sentence representation without fine-tuning.
  • Karpukhin, Vladimir, et al. "Dense Passage Retrieval for Open-Domain Question Answering." Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing. 2020. arXiv:2004.04906. — DPR, a bi-encoder that scores by the plain inner product.
  • Mikolov, Tomas, et al. "Distributed Representations of Words and Phrases and their Compositionality." Advances in Neural Information Processing Systems. Vol. 26. 2013b. arXiv:1310.4546. — negative sampling and the subsampling of frequent words; the objective every later embedder builds on.
  • Mikolov, Tomas, et al. "Linguistic Regularities in Continuous Space Word Representations." Proceedings of the 2013 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies. 2013, pp. 746–751. ACL Anthology N13-1090. — the vector-offset method.
  • Reimers, Nils, and Iryna Gurevych. "Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks." Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Language Processing (EMNLP-IJCNLP). 2019, pp. 3982–3992. arXiv:1908.10084. — the cross-encoder and bi-encoder timings, and the correlations of pooled and trained sentence vectors with human judgements.
  • Robertson, Stephen, and Hugo Zaragoza. "The Probabilistic Relevance Framework: BM25 and Beyond." Foundations and Trends in Information Retrieval, vol. 3, no. 4, 2009, pp. 333–389. doi:10.1561/1500000019. — BM25, the sparse half of hybrid search.

Preprints & other non-peer-reviewed papers

  • Mikolov, Tomas, et al. "Efficient Estimation of Word Representations in Vector Space." arXiv preprint arXiv:1301.3781 (2013a). — the cost count $Q$ of the feed-forward model, CBOW and skip-gram, and the analogy evaluation that excludes the question words.