Build your own semantic search
Cosine similarity·12 min

Score one query against the corpus

0 / 1
# grade this stage (from your course directory)
npx theinference test --stage score-one-query --watch

Now scale up from "two vectors" to "one query vs the whole library." scoreAll(query, corpus, dim) computes the cosine of the query against every document vector and returns a Float32Array of scores — one per doc, in corpus order.

What to build

Your task

Implement scoreAll

Implement scoreAll(query, corpus, dim) in src/index.ts. corpus is a flat Float32Array of numDocs × dim (row-major); query is length dim. Return a Float32Array of length numDocs where entry i is cosine(query, doc_i).

src/index.ts
export function scoreAll(query: Float32Array, corpus: Float32Array, dim: number): Float32Array {
  // numDocs = corpus.length / dim
  // for each row i: out[i] = cosine(query, corpus.subarray(i*dim, (i+1)*dim))
}
How it's graded

adapter — the harness feeds a fixed query and the full corpus inline, calls scoreAll, and compares the whole score array with allclose, atol=1e-5, rtol=1e-4.

Slice rows without copying

Use corpus.subarray(i*dim, (i+1)*dim) to view each document row — it's a zero-copy window into the same buffer, not a new allocation. Over a big corpus that matters.