SimSIMD

SimSIMD

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

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

SimSIMD向量计算SIMD优化距离度量跨平台Github开源项目

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.

<div> <a href="https://pepy.tech/project/simsimd"> <img alt="PyPI" src="https://static.pepy.tech/personalized-badge/simsimd?period=total&units=abbreviation&left_color=black&right_color=blue&left_text=SimSIMD%20Python%20installs" /> </a> <a href="https://www.npmjs.com/package/simsimd"> <img alt="npm" src="https://img.shields.io/npm/dy/simsimd?label=JavaScript%20NPM%20installs" /> </a> <a href="https://crates.io/crates/simsimd"> <img alt="rust" src="https://img.shields.io/crates/d/simsimd?label=Rust%20Crate%20installs" /> </a> <img alt="GitHub code size in bytes" src="https://img.shields.io/github/languages/code-size/ashvardanian/simsimd"> <a href="https://github.com/ashvardanian/SimSIMD/actions/workflows/release.yml"> <img alt="GitHub Actions Ubuntu" src="https://img.shields.io/github/actions/workflow/status/ashvardanian/SimSIMD/release.yml?branch=main&label=Ubuntu&logo=github&color=blue"> </a> <a href="https://github.com/ashvardanian/SimSIMD/actions/workflows/release.yml"> <img alt="GitHub Actions Windows" src="https://img.shields.io/github/actions/workflow/status/ashvardanian/SimSIMD/release.yml?branch=main&label=Windows&logo=windows&color=blue"> </a> <a href="https://github.com/ashvardanian/SimSIMD/actions/workflows/release.yml"> <img alt="GitHub Actions MacOS" src="https://img.shields.io/github/actions/workflow/status/ashvardanian/SimSIMD/release.yml?branch=main&label=MacOS&logo=apple&color=blue"> </a> <a href="https://github.com/ashvardanian/SimSIMD/actions/workflows/release.yml"> <img alt="GitHub Actions CentOS Linux" src="https://img.shields.io/github/actions/workflow/status/ashvardanian/SimSIMD/release.yml?branch=main&label=CentOS&logo=centos&color=blue"> </a> </div>

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,

编辑推荐精选

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

Trae

Trae

字节跳动发布的AI编程神器IDE

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

热门AI辅助写作AI工具讯飞绘文内容运营AI创作个性化文章多平台分发AI助手
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

openai-agents-python

openai-agents-python

OpenAI Agents SDK,助力开发者便捷使用 OpenAI 相关功能。

openai-agents-python 是 OpenAI 推出的一款强大 Python SDK,它为开发者提供了与 OpenAI 模型交互的高效工具,支持工具调用、结果处理、追踪等功能,涵盖多种应用场景,如研究助手、财务研究等,能显著提升开发效率,让开发者更轻松地利用 OpenAI 的技术优势。

Hunyuan3D-2

Hunyuan3D-2

高分辨率纹理 3D 资产生成

Hunyuan3D-2 是腾讯开发的用于 3D 资产生成的强大工具,支持从文本描述、单张图片或多视角图片生成 3D 模型,具备快速形状生成能力,可生成带纹理的高质量 3D 模型,适用于多个领域,为 3D 创作提供了高效解决方案。

3FS

3FS

一个具备存储、管理和客户端操作等多种功能的分布式文件系统相关项目。

3FS 是一个功能强大的分布式文件系统项目,涵盖了存储引擎、元数据管理、客户端工具等多个模块。它支持多种文件操作,如创建文件和目录、设置布局等,同时具备高效的事件循环、节点选择和协程池管理等特性。适用于需要大规模数据存储和管理的场景,能够提高系统的性能和可靠性,是分布式存储领域的优质解决方案。

下拉加载更多