Compute the cosine similarity between two equal-length vectors A and B. This is the cosine of the angle between them: their dot product divided by the product of their L2 norms.
sim(A,B)=∑i=0N−1A[i]2∑i=0N−1B[i]2∑i=0N−1A[i]B[i]The result is a single scalar in [−1,1] written to a 1-element device buffer. Computing it needs three reductions over the array: the dot product and both squared norms.
Input: N = 3, A = [1, 2, 3], B = [4, 5, 6]
Output: 0.9746
Dot product 32 over norms 1477≈32.83.
Input: N = 3, A = [1, 0, 0], B = [0, 1, 0]
Output: 0.0
Orthogonal vectors have zero cosine similarity.
All three reductions can share one pass: each thread accumulates A[i]B[i], A[i]2, and B[i]2 at once.
Use shared-memory partial sums plus atomicAdd into three scratch accumulators, then a tiny finalize step combines them.
Accepts: array
Accepts: array
Submit a correct solution to see your kernel performance.
Compute the cosine similarity between two equal-length vectors A and B. This is the cosine of the angle between them: their dot product divided by the product of their L2 norms.
sim(A,B)=∑i=0N−1A[i]2∑i=0N−1B[i]2∑i=0N−1A[i]B[i]The result is a single scalar in [−1,1] written to a 1-element device buffer. Computing it needs three reductions over the array: the dot product and both squared norms.
Input: N = 3, A = [1, 2, 3], B = [4, 5, 6]
Output: 0.9746
Dot product 32 over norms 1477≈32.83.
Input: N = 3, A = [1, 0, 0], B = [0, 1, 0]
Output: 0.0
Orthogonal vectors have zero cosine similarity.
All three reductions can share one pass: each thread accumulates A[i]B[i], A[i]2, and B[i]2 at once.
Use shared-memory partial sums plus atomicAdd into three scratch accumulators, then a tiny finalize step combines them.
Accepts: array
Accepts: array
Submit a correct solution to see your kernel performance.