Project Icon

SimSIMD

快速高效的向量相似度计算库

SimSIMD是一个高性能向量相似度计算库,为机器学习和科学计算提供快速的距离和相似度计算。支持欧几里得、余弦等多种距离函数,可处理浮点和整型数据。通过SIMD优化,性能显著优于NumPy和SciPy。提供Python、Rust等语言绑定,并具有广泛的平台兼容性。

SimSIMD 📏

SimSIMD banner

Computing dot-products, similarity measures, and distances between low- and high-dimensional vectors is ubiquitous in Machine Learning, Scientific Computing, Geo-Spatial Analysis, and Information Retrieval. These algorithms generally have linear complexity in time, constant complexity in space, and are data-parallel. In other words, it is easily parallelizable and vectorizable and often available in packages like BLAS and LAPACK, as well as higher-level numpy and scipy Python libraries. Ironically, even with decades of evolution in compilers and numerical computing, most libraries can be 3-200x slower than hardware potential even on the most popular hardware, like 64-bit x86 and Arm CPUs. SimSIMD attempts to fill that gap. 1️⃣ SimSIMD functions are practically as fast as memcpy. 2️⃣ SimSIMD compiles to more platforms than NumPy (105 vs 35) and has more backends than most BLAS implementations.

Features

SimSIMD provides over 100 SIMD-optimized kernels for various distance and similarity measures, accelerating search in USearch and several DBMS products. Implemented distance functions include:

  • Euclidean (L2) and Cosine (Angular) spatial distances for Vector Search.
  • Dot-Products for real & complex vectors for DSP & Quantum computing.
  • Hamming (~ Manhattan) and Jaccard (~ Tanimoto) bit-level distances.
  • Kullback-Leibler and Jensen–Shannon divergences for probability distributions.
  • Haversine and Vincenty's formulae for Geospatial Analysis.
  • For Levenshtein, Needleman–Wunsch and other text metrics, check StringZilla.

Moreover, SimSIMD...

  • handles f64, f32, and f16 real & complex vectors.
  • handles i8 integral and b8 binary vectors.
  • is a zero-dependency header-only C 99 library.
  • has bindings for Python, Rust and JavaScript.
  • has Arm backends for NEON and Scalable Vector Extensions (SVE).
  • has x86 backends for Haswell, Skylake, Ice Lake, and Sapphire Rapids.

Due to the high-level of fragmentation of SIMD support in different x86 CPUs, SimSIMD uses the names of select Intel CPU generations for its backends. They, however, also work on AMD CPUs. Intel Haswell is compatible with AMD Zen 1/2/3, while AMD Genoa Zen 4 covers AVX-512 instructions added to Intel Skylake and Ice Lake. You can learn more about the technical implementation details in the following blog-posts:

Benchmarks

Against NumPy and SciPy

Given 1000 embeddings from OpenAI Ada API with 1536 dimensions, running on the Apple M2 Pro Arm CPU with NEON support, here's how SimSIMD performs against conventional methods:

Kindf32 improvementf16 improvementi8 improvementConventional methodSimSIMD
Inner Product2 x9 x18 xnumpy.innerinner
Cosine Distance32 x79 x133 xscipy.spatial.distance.cosinecosine
Euclidean Distance ²5 x26 x17 xscipy.spatial.distance.sqeuclideansqeuclidean
Jensen-Shannon Divergence31 x53 xscipy.spatial.distance.jensenshannonjensenshannon

Against GCC Auto-Vectorization

On the Intel Sapphire Rapids platform, SimSIMD was benchmarked against auto-vectorized code using GCC 12. GCC handles single-precision float but might not be the best choice for int8 and _Float16 arrays, which have been part of the C language since 2011.

KindGCC 12 f32GCC 12 f16SimSIMD f16f16 improvement
Inner Product3,810 K/s192 K/s5,990 K/s31 x
Cosine Distance3,280 K/s336 K/s6,880 K/s20 x
Euclidean Distance ²4,620 K/s147 K/s5,320 K/s36 x
Jensen-Shannon Divergence1,180 K/s18 K/s2,140 K/s118 x

Broader Benchmarking Results:

Using SimSIMD in Python

The package is intended to replace the usage of numpy.inner, numpy.dot, and scipy.spatial.distance. Aside from drastic performance improvements, SimSIMD significantly improves accuracy in mixed precision setups. NumPy and SciPy, processing i8 or f16 vectors, will use the same types for accumulators, while SimSIMD can combine i8 enumeration, i16 multiplication, and i32 accumulation to avoid overflows entirely. The same applies to processing f16 values with f32 precision.

Installation

Use the following snippet to install SimSIMD and list available hardware acceleration options available on your machine:

pip install simsimd
python -c "import simsimd; print(simsimd.get_capabilities())"

One-to-One Distance

import simsimd
import numpy as np

vec1 = np.random.randn(1536).astype(np.float32)
vec2 = np.random.randn(1536).astype(np.float32)
dist = simsimd.cosine(vec1, vec2)

Supported functions include cosine, inner, sqeuclidean, hamming, and jaccard. Dot products are supported for both real and complex numbers:

vec1 = np.random.randn(768).astype(np.float64) + 1j * np.random.randn(768).astype(np.float64)
vec2 = np.random.randn(768).astype(np.float64) + 1j * np.random.randn(768).astype(np.float64)

dist = simsimd.dot(vec1.astype(np.complex128), vec2.astype(np.complex128))
dist = simsimd.dot(vec1.astype(np.complex64), vec2.astype(np.complex64))
dist = simsimd.vdot(vec1.astype(np.complex64), vec2.astype(np.complex64)) # conjugate, same as `np.vdot`

Unlike SciPy, SimSIMD allows explicitly stating the precision of the input vectors, which is especially useful for mixed-precision setups.

dist = simsimd.cosine(vec1, vec2, "i8")
dist = simsimd.cosine(vec1, vec2, "f16")
dist = simsimd.cosine(vec1, vec2, "f32")
dist = simsimd.cosine(vec1, vec2, "f64")

It also allows using SimSIMD for half-precision complex numbers, which NumPy does not support. For that, view data as continuous even-length np.float16 vectors and override type-resolution with complex32 string.

vec1 = np.random.randn(1536).astype(np.float16)
vec2 = np.random.randn(1536).astype(np.float16)
simd.dot(vec1, vec2, "complex32")
simd.vdot(vec1, vec2, "complex32")

One-to-Many Distances

Every distance function can be used not only for one-to-one but also one-to-many and many-to-many distance calculations. For one-to-many:

vec1 = np.random.randn(1536).astype(np.float32) # rank 1 tensor
batch1 = np.random.randn(1, 1536).astype(np.float32) # rank 2 tensor
batch2 = np.random.randn(100, 1536).astype(np.float32)

dist_rank1 = simsimd.cosine(vec1, batch2)
dist_rank2 = simsimd.cosine(batch1, batch2)

Many-to-Many Distances

All distance functions in SimSIMD can be used to compute many-to-many distances. For two batches of 100 vectors to compute 100 distances, one would call it like this:

batch1 = np.random.randn(100, 1536).astype(np.float32)
batch2 = np.random.randn(100, 1536).astype(np.float32)
dist = simsimd.cosine(batch1, batch2)

Input matrices must have identical shapes. This functionality isn't natively present in NumPy or SciPy, and generally requires creating intermediate arrays, which is inefficient and memory-consuming.

Many-to-Many All-Pairs Distances

One can use SimSIMD to compute distances between all possible pairs of rows across two matrices (akin to scipy.spatial.distance.cdist). The resulting object will have a type DistancesTensor, zero-copy compatible with NumPy and other libraries. For two arrays of 10 and 1,000 entries, the resulting tensor will have 10,000 cells:

import numpy as np
from simsimd import cdist, DistancesTensor

matrix1 = np.random.randn(1000, 1536).astype(np.float32)
matrix2 = np.random.randn(10, 1536).astype(np.float32)
distances: DistancesTensor = simsimd.cdist(matrix1, matrix2, metric="cosine") # zero-copy
distances_array: np.ndarray = np.array(distances, copy=True) # now managed by NumPy

Multithreading

By default, computations use a single CPU core. To optimize and utilize all CPU cores on Linux systems, add the threads=0 argument. Alternatively, specify a custom number of threads:

distances = simsimd.cdist(matrix1, matrix2, metric="cosine", threads=0)

Using Python API with USearch

Want to use it in Python with USearch? You can wrap the raw C function pointers SimSIMD backends into a CompiledMetric and pass it to USearch, similar to how it handles Numba's JIT-compiled code.

from usearch.index import Index, CompiledMetric, MetricKind, MetricSignature
from simsimd import pointer_to_sqeuclidean, pointer_to_cosine, pointer_to_inner

metric = CompiledMetric(
    pointer=pointer_to_cosine("f16"),
    kind=MetricKind.Cos,
    signature=MetricSignature.ArrayArraySize,
)

index = Index(256, metric=metric)

Using SimSIMD in Rust

To install, add the following to your Cargo.toml:

[dependencies]
simsimd = "..."

Before using the SimSIMD library, ensure you have imported the necessary traits and types into your Rust source file. The library provides several traits for different distance/similarity kinds - SpatialSimilarity, BinarySimilarity, and ProbabilitySimilarity.

Spatial Similarity: Cosine and Euclidean Distances

use simsimd::SpatialSimilarity;

fn main() {
    let vector_a: Vec<f32> = vec![1.0, 2.0, 3.0];
    let vector_b: Vec<f32> = vec![4.0, 5.0, 6.0];

    // Compute the cosine similarity between vector_a and vector_b
    let cosine_similarity = f32::cosine(&vector_a, &vector_b)
        .expect("Vectors must be of the same length");

    println!("Cosine Similarity: {}", cosine_similarity);

    // Compute the squared Euclidean distance between vector_a and vector_b
    let sq_euclidean_distance = f32::sqeuclidean(&vector_a, &vector_b)
        .expect("Vectors must be of the same length");

    println!("Squared Euclidean Distance: {}", sq_euclidean_distance);
}

Spatial similarity functions are available for f64, f32, f16, and i8 types.

Dot-Products: Inner and Complex Inner Products

use simsimd::SpatialSimilarity;
use simsimd::ComplexProducts;

fn main() {
    let vector_a: Vec<f32> = vec![1.0, 2.0, 3.0, 4.0];
    let vector_b: Vec<f32> = vec![5.0, 6.0, 7.0, 8.0];

    // Compute the inner product between vector_a and vector_b
    let inner_product = SpatialSimilarity::dot(&vector_a, &vector_b)
        .expect("Vectors must be of the same length");

    println!("Inner Product: {}", inner_product);

    // Compute the complex inner product between complex_vector_a and complex_vector_b
    let complex_inner_product = ComplexProducts::dot(&vector_a, &vector_b)
        .expect("Vectors must be of the same length");

    let complex_conjugate_inner_product = ComplexProducts::vdot(&vector_a,
项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

吐司

探索Tensor.Art平台的独特AI模型,免费访问各种图像生成与AI训练工具,从Stable Diffusion等基础模型开始,轻松实现创新图像生成。体验前沿的AI技术,推动个人和企业的创新发展。

Project Cover

SubCat字幕猫

SubCat字幕猫APP是一款创新的视频播放器,它将改变您观看视频的方式!SubCat结合了先进的人工智能技术,为您提供即时视频字幕翻译,无论是本地视频还是网络流媒体,让您轻松享受各种语言的内容。

Project Cover

美间AI

美间AI创意设计平台,利用前沿AI技术,为设计师和营销人员提供一站式设计解决方案。从智能海报到3D效果图,再到文案生成,美间让创意设计更简单、更高效。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号