Retrieve top-k
# grade this stage (from your course directory)
npx theinference test --stage retrieve-topk --watchThe core retrieval operation: given a query vector and the chunk index, return the top-k chunks by cosine similarity. Because every vector is a unit vector, cosine is just the dot product — fast and exact.
What to build
Implement cosine + retrieve
Implement cosine(a, b) (dot product on unit vectors) and retrieve(queryVec, index, k): score every chunk, sort by descending score with ties broken by ascending chunk id, and return the top-k {chunkId, score}. The retrieve <questionIndex> <k> command prints the result for one question.
export function cosine(a: number[], b: number[]): number {
// sum of a[i] * b[i]
}
export function retrieve(queryVec: number[], index: Index, k: number): Scored[] {
// score each id; sort by score desc, then chunkId asc; slice(0, k)
}
./your_program.sh retrieve 0 10
# -> top-10 [{chunkId, score}] for question 0
process mode, stdout_json_match. The chunk id order must match the reference exactly; scores are compared within atol 1e-4. The deterministic tie-break (ascending chunk id) is what makes the order reproducible.
Two chunks with identical cosine would otherwise sort non-deterministically. Always break ties by ascending chunkId so the ordering — and every metric built on it — is reproducible.