cosineSimilarityGPU function

GPUTensor<Scalar> cosineSimilarityGPU(
  1. GPUTensor<Vector> a,
  2. GPUTensor<Vector> b,
  3. CommandBuffer tape
)

Computes the cosine similarity between two vectors, measuring their directional alignment. Calculates the dot product of a and b and divides it by the product of their individual L2 norms. Returns a scalar between -1.0 (opposite) and 1.0 (identical direction). The operations are appended to tape for execution.

Implementation

GPUTensor<Scalar> cosineSimilarityGPU(
    GPUTensor<Vector> a, GPUTensor<Vector> b, CommandBuffer tape) {
  GPUTensor<Scalar> dot = dotProductGPU(a, b, tape);
  GPUTensor<Scalar> normA = l2NormGPU(a, tape);
  GPUTensor<Scalar> normB = l2NormGPU(b, tape);
  GPUTensor<Scalar> denominator = multiplyGPU<Scalar>(normA, normB, tape);
  GPUTensor<Scalar> out = divideGPU<Scalar>(dot, denominator, tape);
  out.subMap["dot"] = dot;
  out.subMap["normA"] = normA;
  out.subMap["normB"] = normB;
  out.subMap["denominator"] = denominator;
  return out;
}