在.NET中,高效计算一个向量与多个向量的余弦相似性的最快方法是什么?

xvw2m8pv  于 2022-11-19  发布在  .NET
关注(0)|答案(1)|浏览(138)

下面是我目前正在使用的代码。我正在比较由768个浮点数组成的向量和由50 k个浮点数组成的向量,这大约需要800 ms。我假设有一个更快的实现,无论是在C#中还是在我可以使用的一些包中,它可以在本地进行计算,但我很难找到它。谢谢!

// USAGE:
// vectors is IEnumerable<float[768]>
// vector is float[768]

    vectors.DotProductSum(vector) * 100)

public static float DotProductSum(this IEnumerable<float> values, IEnumerable<float> other)
{
    return values.Zip(other, (d1, d2) => d1 * d2).Sum();
}
huwehgph

huwehgph1#

我发现了一个非常快的解决方案,Faiss,在我的测试中,它能够在不到5ms的时间内查询成千上万个2048浮点向量。我从.NET使用它,所以使用了FaissMask Package 器库。您需要一些本机依赖项来完成此操作,您可以通过构建faiss repo来获得这些依赖项。我还没有找到包含这些依赖项的包。具体来说,我需要:

cublasLt64_11.dll
cudart64_110.dll
faiss.dll
faiss_c.dll
libgcc_s_seh-1.dll
libgfortran-3.dll
libopenblas.dll
libquadmath-0.dll
cublas64_11.dll

之后的代码非常简单:

using var index = new FaissMask.IndexFlat((int)embeddingSize, MetricType.MetricInnerProduct);
index.Add(vectors);
var queryResults = index.Search(queryVector, 10);

相关问题