Cosine similarity
# grade this stage (from your course directory)
npx theinference test --stage cosine --watchCosine similarity is the angle-based comparison: cosine(a,b) = (a·b)/(‖a‖·‖b‖). It ranges from −1 (opposite) through 0 (unrelated) to 1 (identical direction). This single function is what every score in your search engine comes from.
cosine(a, b) = dot(a, b) / (‖a‖ · ‖b‖)
What to build
Implement cosine
Implement cosine(a, b) in src/vecmath.ts by composing the dot and l2norm you already wrote. Guard the zero-vector case: if either norm is 0, return 0 (no direction to compare).
export function cosine(a: Float32Array, b: Float32Array): number {
// dot / (norm·norm); return 0 if either norm is 0
}
adapter — allclose vs the reference cosine value, atol=1e-5, rtol=1e-4, on a seeded pair.
A real corpus can contain an empty or degenerate chunk whose embedding is all zeros. dot/0 = NaN, and a single NaN poisons your entire ranking (every comparison with it is NaN, and sorts go haywire). Returning 0 for a zero-norm input is the standard guard — do it before dividing.