https://github.com/ashvardanian/simsimd

Up to 200x Faster Dot Products & Similarity Metrics — for Python, Rust, C, JS, and Swift, supporting f64, f32, f16 real & complex, i8, and bit vectors using SIMD for both AVX2, AVX-512, NEON, SVE, & SVE2 📐

https://github.com/ashvardanian/simsimd

Science Score: 26.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
    Found .zenodo.json file
  • DOI references
  • Academic publication links
  • Committers with academic emails
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (14.6%) to scientific vocabulary

Keywords

arm-neon arm-sve assembly avx2 avx512 bfloat16 blas blas-libraries distance-calculation float16 information-retrieval metrics neon numpy scipy simd simd-instructions similarity-measures similarity-search vector-search

Keywords from Contributors

search-engine recommender-system image-search nearest-neighbor-search approximate-nearest-neighbor-search fuzzy-search semantic-search webassembly full-text-search faiss
Last synced: 5 months ago · JSON representation

Repository

Up to 200x Faster Dot Products & Similarity Metrics — for Python, Rust, C, JS, and Swift, supporting f64, f32, f16 real & complex, i8, and bit vectors using SIMD for both AVX2, AVX-512, NEON, SVE, & SVE2 📐

Basic Info
Statistics
  • Stars: 1,468
  • Watchers: 21
  • Forks: 84
  • Open Issues: 23
  • Releases: 148
Topics
arm-neon arm-sve assembly avx2 avx512 bfloat16 blas blas-libraries distance-calculation float16 information-retrieval metrics neon numpy scipy simd simd-instructions similarity-measures similarity-search vector-search
Created almost 3 years ago · Last pushed 6 months ago
Metadata Files
Readme Contributing License Code of conduct

README.md

SimSIMD banner

Computing dot-products, similarity measures, and distances between low- and high-dimensional vectors is ubiquitous in Machine Learning, Scientific Computing, Geospatial Analysis, and Information Retrieval. These algorithms generally have linear complexity in time, constant or linear complexity in space, and are data-parallel. In other words, it is easily parallelizable and vectorizable and often available in packages like BLAS (level 1) 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. Moreover, most lack mixed-precision support, which is crucial for modern AI! The rare few that support minimal mixed precision, run only on one platform, and are vendor-locked, by companies like Intel and Nvidia. SimSIMD provides an alternative. 1️⃣ SimSIMD functions are practically as fast as memcpy. 2️⃣ Unlike BLAS, most kernels are designed for mixed-precision and bit-level operations. 3️⃣ SimSIMD often ships more binaries than NumPy and has more backends than most BLAS implementations, and more high-level interfaces than most libraries.

PyPI npm rust GitHub code size in bytes GitHub Actions Ubuntu GitHub Actions Windows GitHub Actions macOS GitHub Actions CentOS Linux

Features

SimSIMD (Arabic: "سيمسيم دي") is a mixed-precision math library of over 350 SIMD-optimized kernels extensively used in AI, Search, and DBMS workloads. Named after the iconic "Open Sesame" command that opened doors to treasure in Ali Baba and the Forty Thieves, SimSIMD can help you 10x the cost-efficiency of your computational pipelines. Implemented distance functions include:

  • Euclidean (L2) and Cosine (Angular) spatial distances for Vector Search. docs
  • Dot-Products for real & complex vectors for DSP & Quantum computing. docs
  • Hamming (~ Manhattan) and Jaccard (~ Tanimoto) bit-level distances. docs
  • Set Intersections for Sparse Vectors and Text Analysis. docs
  • Mahalanobis distance and Quadratic forms for Scientific Computing. docs
  • Kullback-Leibler and Jensen–Shannon divergences for probability distributions. docs
  • Fused-Multiply-Add (FMA) and Weighted Sums to replace BLAS level 1 functions. docs
  • For Levenshtein, Needleman–Wunsch, and Smith-Waterman, check StringZilla.
  • 🔜 Haversine and Vincenty's formulae for Geospatial Analysis.

Moreover, SimSIMD...

  • handles float64, float32, float16, and bfloat16 real & complex vectors.
  • handles int8 integral, int4 sub-byte, and b8 binary vectors.
  • handles sparse uint32 and uint16 sets, and weighted sparse vectors.
  • is a zero-dependency header-only C 99 library.
  • has Python, Rust, JS, and Swift bindings.
  • has Arm backends for NEON, Scalable Vector Extensions (SVE), and SVE2.
  • has x86 backends for Haswell, Skylake, Ice Lake, Genoa, and Sapphire Rapids.
  • with both compile-time and runtime CPU feature detection easily integrates anywhere!

Due to the high-level of fragmentation of SIMD support in different x86 CPUs, SimSIMD generally 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

NumPy C 99 SimSIMD
cosine distances between 1536d vectors in int8
🚧 overflows
x86: 10,548,600 ops/s
arm: 11,379,300 ops/s
x86: 16,151,800 ops/s
arm: 13,524,000 ops/s
cosine distances between 1536d vectors in bfloat16
🚧 not supported
x86: 119,835 ops/s
arm: 403,909 ops/s
x86: 9,738,540 ops/s
arm: 4,881,900 ops/s
cosine distances between 1536d vectors in float16
x86: 40,481 ops/s
arm: 21,451 ops/s
x86: 501,310 ops/s
arm: 871,963 ops/s
x86: 7,627,600 ops/s
arm: 3,316,810 ops/s
cosine distances between 1536d vectors in float32
x86: 253,902 ops/s
arm: 46,394 ops/s
x86: 882,484 ops/s
arm: 399,661 ops/s
x86: 8,202,910 ops/s
arm: 3,400,620 ops/s
cosine distances between 1536d vectors in float64
x86: 212,421 ops/s
arm: 52,904 ops/s
x86: 839,301 ops/s
arm: 837,126 ops/s
x86: 1,538,530 ops/s
arm: 1,678,920 ops/s
euclidean distance between 1536d vectors in int8
x86: 252,113 ops/s
arm: 177,443 ops/s
x86: 6,690,110 ops/s
arm: 4,114,160 ops/s
x86: 18,989,000 ops/s
arm: 18,878,200 ops/s
euclidean distance between 1536d vectors in bfloat16
🚧 not supported
x86: 119,842 ops/s
arm: 1,049,230 ops/s
x86: 9,727,210 ops/s
arm: 4,233,420 ops/s
euclidean distance between 1536d vectors in float16
x86: 54,621 ops/s
arm: 71,793 ops/s
x86: 196,413 ops/s
arm: 911,370 ops/s
x86: 19,466,800 ops/s
arm: 3,522,760 ops/s
euclidean distance between 1536d vectors in float32
x86: 424,944 ops/s
arm: 292,629 ops/s
x86: 1,295,210 ops/s
arm: 1,055,940 ops/s
x86: 8,924,100 ops/s
arm: 3,602,650 ops/s
euclidean distance between 1536d vectors in float64
x86: 334,929 ops/s
arm: 237,505 ops/s
x86: 1,215,190 ops/s
arm: 905,782 ops/s
x86: 1,701,740 ops/s
arm: 1,735,840 ops/s

For benchmarks we mostly use 1536-dimensional vectors, like the embeddings produced by the OpenAI Ada API. The code was compiled with GCC 12, using glibc v2.35. The benchmarks performed on Arm-based Graviton3 AWS c7g instances and r7iz Intel Sapphire Rapids. Most modern Arm-based 64-bit CPUs will have similar relative speedups. Variance withing x86 CPUs will be larger.

Similar speedups are often observed even when compared to BLAS and LAPACK libraries underlying most numerical computing libraries, including NumPy and SciPy in Python. 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 int8, uint8 or float16 vectors, will use the same types for accumulators, while SimSIMD can combine int8 enumeration, int16 multiplication, and int32 accumulation to avoid overflows entirely. The same applies to processing float16 and bfloat16 values with float32 precision.

Installation

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

sh pip install simsimd python -c "import simsimd; print(simsimd.get_capabilities())" # for hardware introspection python -c "import simsimd; help(simsimd)" # for documentation

With precompiled binaries, SimSIMD ships .pyi interface files for type hinting and static analysis. You can check all the available functions in python/annotations/__init__.pyi.

One-to-One Distance

```py 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, jaccard, kulbackleibler, jensenshannon, and intersect. Dot products are supported for both real and complex numbers:

```py 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. The dtype argument can be passed both by name and as a positional argument:

py dist = simsimd.cosine(vec1, vec2, "int8") dist = simsimd.cosine(vec1, vec2, "float16") dist = simsimd.cosine(vec1, vec2, "float32") dist = simsimd.cosine(vec1, vec2, "float64") dist = simsimd.hamming(vec1, vec2, "bin8")

Binary distance functions are computed at a bit-level. Meaning a vector of 10x 8-bit integers will be treated as a sequence of 80 individual bits or dimensions. This differs from NumPy, that can't handle smaller-than-byte types, but you can still avoid the bin8 argument by reinterpreting the vector as booleans:

py vec1 = np.random.randint(2, size=80).astype(np.uint8).packbits().view(np.bool_) vec2 = np.random.randint(2, size=80).astype(np.uint8).packbits().view(np.bool_) hamming_distance = simsimd.hamming(vec1, vec2) jaccard_distance = simsimd.jaccard(vec1, vec2)

With other frameworks, like PyTorch, one can get a richer type-system than NumPy, but the lack of good CPython interoperability makes it hard to pass data without copies. Here is an example of using SimSIMD with PyTorch to compute the cosine similarity between two bfloat16 vectors:

```py import numpy as np buf1 = np.empty(8, dtype=np.uint16) buf2 = np.empty(8, dtype=np.uint16)

View the same memory region with PyTorch and randomize it

import torch vec1 = torch.asarray(memoryview(buf1), copy=False).view(torch.bfloat16) vec2 = torch.asarray(memoryview(buf2), copy=False).view(torch.bfloat16) torch.randn(8, out=vec1) torch.randn(8, out=vec2)

Both libs will look into the same memory buffers and report the same results

distslow = 1 - torch.nn.functional.cosinesimilarity(vec1, vec2, dim=0) dist_fast = simsimd.cosine(buf1, buf2, "bfloat16") ```

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.

py 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")

When dealing with sparse representations and integer sets, you can apply the intersect function to two 1-dimensional arrays of uint16 or uint32 integers:

```py from random import randint import numpy as np import simsimd as simd

length1, length2 = randint(1, 100), randint(1, 100) vec1 = np.sort(np.random.randint(0, 1000, length1).astype(np.uint16)) vec2 = np.sort(np.random.randint(0, 1000, length2).astype(np.uint16))

slowresult = len(np.intersect1d(vec1, vec2)) fastresult = simd.intersect(vec1, vec2) assert slowresult == fastresult ```

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:

```py 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)

distrank1 = simsimd.cosine(vec1, batch2) distrank2 = 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:

py 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:

```py 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, managed by SimSIMD distances_array: np.ndarray = np.array(distances, copy=True) # now managed by NumPy ```

Element-wise Kernels

SimSIMD also provides mixed-precision element-wise kernels, where the input vectors and the output have the same numeric type, but the intermediate accumulators are of a higher precision.

```py import numpy as np from simsimd import fma, wsum

Let's take two FullHD video frames

firstframe = np.random.randn(1920 * 1024).astype(np.uint8) secondframe = np.random.randn(1920 * 1024).astype(np.uint8) averageframe = np.emptylike(firstframe) wsum(firstframe, secondframe, alpha=0.5, beta=0.5, out=averageframe)

Slow analog with NumPy:

slowaverageframe = (0.5 * firstframe + 0.5 * secondframe).astype(np.uint8) ```

Similarly, the fma takes three arguments and computes the fused multiply-add operation. In applications like Machine Learning you may also benefit from using the "brain-float" format not natively supported by NumPy. In 3D Graphics, for example, we can use FMA to compute the Phong shading model:

```py

Assume a FullHD frame with random values for simplicity

lightintensity = np.random.rand(1920 * 1080).astype(np.float16) # Intensity of light on each pixel diffusecomponent = np.random.rand(1920 * 1080).astype(np.float16) # Diffuse reflectance on the surface specularcomponent = np.random.rand(1920 * 1080).astype(np.float16) # Specular reflectance for highlights outputcolor = np.emptylike(lightintensity) # Array to store the resulting color intensity

Define the scaling factors for diffuse and specular contributions

alpha = 0.7 # Weight for the diffuse component beta = 0.3 # Weight for the specular component

Formula: color = alpha * lightintensity * diffusecomponent + beta * specular_component

fma(lightintensity, diffusecomponent, specularcomponent, dtype="float16", # Optional, unless it can't be inferred from the input alpha=alpha, beta=beta, out=outputcolor)

Slow analog with NumPy for comparison

slowoutputcolor = (alpha * lightintensity * diffusecomponent + beta * specular_component).astype(np.float16) ```

Multithreading and Memory Usage

By default, computations use a single CPU core. To override this behavior, use the threads argument. Set it to 0 to use all available CPU cores and let the underlying C library manage the thread pool. Here is an example of dealing with large sets of binary vectors:

```py ndim = 1536 # OpenAI Ada embeddings matrix1 = np.packbits(np.random.randint(2, size=(10000, ndim)).astype(np.uint8)) matrix2 = np.packbits(np.random.randint(2, size=(1000, ndim)).astype(np.uint8))

distances = simsimd.cdist(matrix1, matrix2, metric="hamming", # Unlike SciPy, SimSIMD doesn't divide by the number of dimensions out_dtype="uint8", # so we can use uint8 instead of float64 to save memory. threads=0, # Use all CPU cores with OpenMP. dtype="bin8", # Override input argument type to bin8 eight-bit words. ) ```

Alternatively, when using free-threading Python 3.13t builds, one can combine single-threaded SimSIMD operations with Python's concurrent.futures.ThreadPoolExecutor to parallelize the computations. By default, the output distances will be stored in double-precision float64 floating-point numbers. That behavior may not be space-efficient, especially if you are computing the hamming distance between short binary vectors, that will generally fit into 8x smaller uint8 or uint16 types. To override this behavior, use the out_dtype argument, or consider pre-allocating the output array and passing it to the out argument. A more complete example may look like this:

```py from multiprocessing import cpu_count from concurrent.futures import ThreadPoolExecutor from simsimd import cosine import numpy as np

Generate large dataset

vectorsa = np.random.rand(100000, 1536).astype(np.float32) vectorsb = np.random.rand(100000, 1536).astype(np.float32) distances = np.zeros((100_000,), dtype=np.float32)

def computebatch(startidx, endidx): batcha = vectorsa[startidx:endidx] batchb = vectorsb[startidx:endidx] cosine(batcha, batchb, out=distances[startidx:end_idx])

Use all CPU cores with true parallelism (no GIL!)

numthreads = cpucount() chunksize = len(vectorsa) // num_threads

with ThreadPoolExecutor(maxworkers=numthreads) as executor: futures = [] for i in range(numthreads): startidx = i * chunksize endidx = (i + 1) * chunksize if i < numthreads - 1 else len(vectorsa) futures.append(executor.submit(computebatch, startidx, endidx))

# Collect results from all threads
results = [future.result() for future in futures]

```

Half-Precision Brain-Float Numbers

The "brain-float-16" is a popular machine learning format. It's broadly supported in hardware and is very machine-friendly, but software support is still lagging behind. Unlike NumPy, you can already use bf16 datatype in SimSIMD. Luckily, to downcast f32 to bf16 you only have to drop the last 16 bits:

```py import numpy as np import simsimd as simd

a = np.random.randn(ndim).astype(np.float32) b = np.random.randn(ndim).astype(np.float32)

NumPy doesn't natively support brain-float, so we need a trick!

Luckily, it's very easy to reduce the representation accuracy

by simply masking the low 16-bits of our 32-bit single-precision

numbers. We can also add 0x8000 to round the numbers.

af32rounded = ((a.view(np.uint32) + 0x8000) & 0xFFFF0000).view(np.float32) bf32rounded = ((b.view(np.uint32) + 0x8000) & 0xFFFF0000).view(np.float32)

To represent them as brain-floats, we need to drop the second half

abf16 = np.rightshift(af32rounded.view(np.uint32), 16).astype(np.uint16) bbf16 = np.rightshift(bf32rounded.view(np.uint32), 16).astype(np.uint16)

Now we can compare the results

expected = np.inner(af32rounded, bf32rounded) result = simd.inner(abf16, bbf16, "bf16") ```

Helper Functions

You can turn specific backends on or off depending on the exact environment. A common case may be avoiding AVX-512 on older AMD CPUs and Intel Ice Lake CPUs to ensure the CPU doesn't change the frequency license and throttle performance.

```py $ simsimd.get_capabilities()

{'serial': True, 'neon': False, 'sve': False, 'neonf16': False, 'svef16': False, 'neonbf16': False, 'svebf16': False, 'neoni8': False, 'svei8': False, 'haswell': True, 'skylake': True, 'ice': True, 'genoa': True, 'sapphire': True, 'turin': True} $ simsimd.disablecapability("sapphire") $ simsimd.enablecapability("sapphire") ```

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.

```py from usearch.index import Index, CompiledMetric, MetricKind, MetricSignature from simsimd import pointertosqeuclidean, pointertocosine, pointertoinner

metric = CompiledMetric( pointer=pointertocosine("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:

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

```rust use simsimd::SpatialSimilarity;

fn main() { let vectora: Vec = vec![1.0, 2.0, 3.0]; let vectorb: Vec = vec![4.0, 5.0, 6.0];

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

println!("Cosine Distance: {}", cosine_distance);

// Compute the squared Euclidean distance between vectors
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

```rust use simsimd::SpatialSimilarity; use simsimd::ComplexProducts;

fn main() { // Complex vectors have interleaved real & imaginary components let vectora: Vec = vec![1.0, 2.0, 3.0, 4.0]; let vectorb: Vec = vec![5.0, 6.0, 7.0, 8.0];

// Compute the inner product between vectors
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 vectors
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, &vector_b)
    .expect("Vectors must be of the same length");

println!("Complex Inner Product: {:?}", complex_inner_product); // -18, 69
println!("Complex C. Inner Product: {:?}", complex_conjugate_inner_product); // 70, -8

} ```

Complex inner products are available for f64, f32, and f16 types.

Probability Distributions: Jensen-Shannon and Kullback-Leibler Divergences

```rust use simsimd::ProbabilitySimilarity;

fn main() { let vectora: Vec = vec![1.0, 2.0, 3.0]; let vectorb: Vec = vec![4.0, 5.0, 6.0];

let jensen_shannon = f32::jensenshannon(&vector_a, &vector_b)
    .expect("Vectors must be of the same length");

println!("Jensen-Shannon Divergence: {}", jensen_shannon);

let kullback_leibler = f32::kullbackleibler(&vector_a, &vector_b)
    .expect("Vectors must be of the same length");

println!("Kullback-Leibler Divergence: {}", kullback_leibler);

} ```

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

Binary Similarity: Hamming and Jaccard Distances

Similar to spatial distances, one can compute bit-level distance functions between slices of unsigned integers:

```rust use simsimd::BinarySimilarity;

fn main() { let vectora = &[0b11110000, 0b00001111, 0b10101010]; let vectorb = &[0b11110000, 0b00001111, 0b01010101];

// Compute the Hamming distance between vectors
let hamming_distance = u8::hamming(&vector_a, &vector_b)
    .expect("Vectors must be of the same length");

println!("Hamming Distance: {}", hamming_distance);

// Compute the Jaccard distance between vectors
let jaccard_distance = u8::jaccard(&vector_a, &vector_b)
    .expect("Vectors must be of the same length");

println!("Jaccard Distance: {}", jaccard_distance);

} ```

Binary similarity functions are available only for u8 types.

Half-Precision Floating-Point Numbers

Rust has no native support for half-precision floating-point numbers, but SimSIMD provides a f16 type with built-in conversion methods. The underlying u16 representation is publicly accessible for direct bit manipulation.

```rust use simsimd::{SpatialSimilarity, f16};

fn main() { // Create f16 vectors using built-in conversion methods let vectora: Vec = vec![1.0, 2.0, 3.0].iter().map(|&x| f16::fromf32(x)).collect(); let vectorb: Vec = vec![4.0, 5.0, 6.0].iter().map(|&x| f16::fromf32(x)).collect();

// Compute the cosine distance
let cosine_distance = f16::cosine(&vector_a, &vector_b)
    .expect("Vectors must be of the same length");

println!("Cosine Distance: {}", cosine_distance);

// Direct bit manipulation
let half = f16::from_f32(3.14159);
let bits = half.0; // Access raw u16 representation
let reconstructed = f16(bits);

// Convert back to f32
let float_value = half.to_f32();

} ```

For interoperability with the half crate:

```rust use simsimd::{SpatialSimilarity, f16 as SimF16}; use half::f16 as HalfF16;

fn main() { let vectora: Vec = vec![1.0, 2.0, 3.0].iter().map(|&x| HalfF16::fromf32(x)).collect(); let vectorb: Vec = vec![4.0, 5.0, 6.0].iter().map(|&x| HalfF16::fromf32(x)).collect();

// Safe reinterpret cast due to identical memory layout
let buffer_a: &[SimF16] = unsafe { std::slice::from_raw_parts(vector_a.as_ptr() as *const SimF16, vector_a.len()) };
let buffer_b: &[SimF16] = unsafe { std::slice::from_raw_parts(vector_b.as_ptr() as *const SimF16, vector_b.len()) };

let cosine_distance = SimF16::cosine(buffer_a, buffer_b)
    .expect("Vectors must be of the same length");

println!("Cosine Distance: {}", cosine_distance);

} ```

Half-Precision Brain-Float Numbers

The "brain-float-16" is a popular machine learning format. It's broadly supported in hardware and is very machine-friendly, but software support is still lagging behind. Unlike NumPy, you can already use bf16 datatype in SimSIMD. SimSIMD provides a bf16 type with built-in conversion methods and direct bit access.

```rust use simsimd::{SpatialSimilarity, bf16};

fn main() { // Create bf16 vectors using built-in conversion methods let vectora: Vec = vec![1.0, 2.0, 3.0].iter().map(|&x| bf16::fromf32(x)).collect(); let vectorb: Vec = vec![4.0, 5.0, 6.0].iter().map(|&x| bf16::fromf32(x)).collect();

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

println!("Cosine Distance: {}", cosine_distance);

// Direct bit manipulation
let brain_half = bf16::from_f32(3.14159);
let bits = brain_half.0; // Access raw u16 representation
let reconstructed = bf16(bits);

// Convert back to f32
let float_value = brain_half.to_f32();

// Compare precision differences
let original = 3.14159_f32;
let f16_roundtrip = f16::from_f32(original).to_f32();
let bf16_roundtrip = bf16::from_f32(original).to_f32();

println!("Original: {}", original);
println!("f16 roundtrip: {}", f16_roundtrip);
println!("bf16 roundtrip: {}", bf16_roundtrip);

} ```

Dynamic Dispatch in Rust

SimSIMD provides a dynamic dispatch mechanism to select the most advanced micro-kernel for the current CPU. You can query supported backends and use the SimSIMD::capabilities function to select the best one.

rust println!("uses neon: {}", capabilities::uses_neon()); println!("uses sve: {}", capabilities::uses_sve()); println!("uses haswell: {}", capabilities::uses_haswell()); println!("uses skylake: {}", capabilities::uses_skylake()); println!("uses ice: {}", capabilities::uses_ice()); println!("uses genoa: {}", capabilities::uses_genoa()); println!("uses sapphire: {}", capabilities::uses_sapphire()); println!("uses turin: {}", capabilities::uses_turin()); println!("uses sierra: {}", capabilities::uses_sierra());

Using SimSIMD in JavaScript

To install, choose one of the following options depending on your environment:

  • npm install --save simsimd
  • yarn add simsimd
  • pnpm add simsimd
  • bun install simsimd

The package is distributed with prebuilt binaries, but if your platform is not supported, you can build the package from the source via npm run build. This will automatically happen unless you install the package with the --ignore-scripts flag or use Bun. After you install it, you will be able to call the SimSIMD functions on various TypedArray variants:

```js const { sqeuclidean, cosine, inner, hamming, jaccard } = require("simsimd");

const vectorA = new Float32Array([1.0, 2.0, 3.0]); const vectorB = new Float32Array([4.0, 5.0, 6.0]);

const distance = sqeuclidean(vectorA, vectorB); console.log("Squared Euclidean Distance:", distance); ```

Other numeric types and precision levels are supported as well. For double-precision floating-point numbers, use Float64Array:

js const vectorA = new Float64Array([1.0, 2.0, 3.0]); const vectorB = new Float64Array([4.0, 5.0, 6.0]); const distance = cosine(vectorA, vectorB);

When doing machine learning and vector search with high-dimensional vectors you may want to quantize them to 8-bit integers. You may want to project values from the $[-1, 1]$ range to the $[-127, 127]$ range and then cast them to Int8Array:

js const quantizedVectorA = new Int8Array(vectorA.map((v) => v * 127)); const quantizedVectorB = new Int8Array(vectorB.map((v) => v * 127)); const distance = cosine(quantizedVectorA, quantizedVectorB);

A more extreme quantization case would be to use binary vectors. You can map all positive values to 1 and all negative values and zero to 0, packing eight values into a single byte. After that, Hamming and Jaccard distances can be computed.

```js const { toBinary, hamming } = require("simsimd");

const binaryVectorA = toBinary(vectorA); const binaryVectorB = toBinary(vectorB); const distance = hamming(binaryVectorA, binaryVectorB); ```

Using SimSIMD in Swift

To install, simply add the following dependency to your Package.swift:

swift dependencies: [ .package(url: "https://github.com/ashvardanian/simsimd") ]

The package provides the most common spatial metrics for Int8, Float16, Float32, and Float64 vectors.

```swift import SimSIMD

let vectorA: [Int8] = [1, 2, 3] let vectorB: [Int8] = [4, 5, 6]

let dotProduct = vectorA.dot(vectorB) // Computes the dot product let cosineDistance = vectorA.cosine(vectorB) // Computes the cosine distance let sqEuclidean = vectorA.sqeuclidean(vectorB) // Computes the squared Euclidean distance ```

Using SimSIMD in C

For integration within a CMake-based project, add the following segment to your CMakeLists.txt:

cmake FetchContent_Declare( simsimd GIT_REPOSITORY https://github.com/ashvardanian/simsimd.git GIT_SHALLOW TRUE ) FetchContent_MakeAvailable(simsimd)

After that, you can use the SimSIMD library in your C code in several ways. Simplest of all, you can include the headers, and the compiler will automatically select the most recent CPU extensions that SimSIMD will use.

```c

include

int main() { simsimdflushdenormals(); // Optional, to avoid performance penalties on denormal numbers

simsimd_f32_t vector_a[1536];
simsimd_f32_t vector_b[1536];
simsimd_kernel_punned_t metric_punned = simsimd_metric_punned(
    simsimd_metric_cos_k,   // Metric kind, like the angular cosine distance
    simsimd_datatype_f32_k, // Data type, like: f16, f32, f64, i8, b8, and complex variants
    simsimd_cap_any_k);     // Which CPU capabilities are we allowed to use
simsimd_distance_t distance;
simsimd_metric_dense_punned_t metric = (simsimd_metric_dense_punned_t)metric_punned;
metric(vector_a, vector_b, 1536, &distance);
return 0;

} ```

Dynamic Dispatch in C

To avoid hard-coding the backend, you can rely on c/lib.c to prepackage all possible backends in one binary, and select the most recent CPU features at runtime. That feature of the C library is called dynamic dispatch and is extensively used in the Python, JavaScript, and Rust bindings. To test which CPU features are available on the machine at runtime, use the following APIs:

```c int usesdynamicdispatch = simsimdusesdynamicdispatch(); // Check if dynamic dispatch was enabled simsimdcapabilityt capabilities = simsimdcapabilities(); // Returns a bitmask

int usesneon = simsimdusesneon(); int usessve = simsimdusessve(); int useshaswell = simsimduseshaswell(); int usesskylake = simsimdusesskylake(); int usesice = simsimdusesice(); int usesgenoa = simsimdusesgenoa(); int usessapphire = simsimduses_sapphire(); ```

To override compilation settings and switch between runtime and compile-time dispatch, define the following macro:

```c

define SIMSIMDDYNAMICDISPATCH 1 // or 0

```

Spatial Distances: Cosine and Euclidean Distances

```c

include

int main() { simsimdi8t i8[1536]; simsimdi8t u8[1536]; simsimdf64t f64s[1536]; simsimdf32t f32s[1536]; simsimdf16t f16s[1536]; simsimdbf16t bf16s[1536]; simsimddistancet distance;

// Cosine distance between two vectors
simsimd_cos_i8(i8s, i8s, 1536, &distance);
simsimd_cos_u8(u8s, u8s, 1536, &distance);
simsimd_cos_f16(f16s, f16s, 1536, &distance);
simsimd_cos_f32(f32s, f32s, 1536, &distance);
simsimd_cos_f64(f64s, f64s, 1536, &distance);
simsimd_cos_bf16(bf16s, bf16s, 1536, &distance);

// Euclidean distance between two vectors
simsimd_l2sq_i8(i8s, i8s, 1536, &distance);
simsimd_l2sq_u8(u8s, u8s, 1536, &distance);
simsimd_l2sq_f16(f16s, f16s, 1536, &distance);
simsimd_l2sq_f32(f32s, f32s, 1536, &distance);
simsimd_l2sq_f64(f64s, f64s, 1536, &distance);
simsimd_l2sq_bf16(bf16s, bf16s, 1536, &distance);

return 0;

} ```

Dot-Products: Inner and Complex Inner Products

```c

include

int main() { // SimSIMD provides "sized" type-aliases without relying on stdint.h simsimdi8t i8[1536]; simsimdi8t u8[1536]; simsimdf16t f16s[1536]; simsimdf32t f32s[1536]; simsimdf64t f64s[1536]; simsimdbf16t bf16s[1536]; simsimddistancet product;

// Inner product between two real vectors
simsimd_dot_i8(i8s, i8s, 1536, &product);
simsimd_dot_u8(u8s, u8s, 1536, &product);
simsimd_dot_f16(f16s, f16s, 1536, &product);
simsimd_dot_f32(f32s, f32s, 1536, &product);
simsimd_dot_f64(f64s, f64s, 1536, &product);
simsimd_dot_bf16(bf16s, bf16s, 1536, &product);

// SimSIMD provides complex types with `real` and `imag` fields
simsimd_f64c_t f64s[768];
simsimd_f32c_t f32s[768];
simsimd_f16c_t f16s[768];
simsimd_bf16c_t bf16s[768];
simsimd_distance_t products[2]; // real and imaginary parts

// Complex inner product between two vectors
simsimd_dot_f16c(f16cs, f16cs, 768, &products[0]);
simsimd_dot_f32c(f32cs, f32cs, 768, &products[0]);
simsimd_dot_f64c(f64cs, f64cs, 768, &products[0]);
simsimd_dot_bf16c(bf16cs, bf16cs, 768, &products[0]);

// Complex conjugate inner product between two vectors
simsimd_vdot_f16c(f16cs, f16cs, 768, &products[0]);
simsimd_vdot_f32c(f32cs, f32cs, 768, &products[0]);
simsimd_vdot_f64c(f64cs, f64cs, 768, &products[0]);
simsimd_vdot_bf16c(bf16cs, bf16cs, 768, &products[0]);
return 0;

} ```

Binary Distances: Hamming and Jaccard Distances

```c

include

int main() { simsimdb8t b8s[1536 / 8]; // 8 bits per word simsimddistancet distance; simsimdhammingb8(b8s, b8s, 1536 / 8, &distance); simsimdjaccardb8(b8s, b8s, 1536 / 8, &distance); return 0; } ```

Probability Distributions: Jensen-Shannon and Kullback-Leibler Divergences

```c

include

int main() { simsimdf64t f64s[1536]; simsimdf32t f32s[1536]; simsimdf16t f16s[1536]; simsimddistancet divergence;

// Jensen-Shannon divergence between two vectors
simsimd_js_f16(f16s, f16s, 1536, &divergence);
simsimd_js_f32(f32s, f32s, 1536, &divergence);
simsimd_js_f64(f64s, f64s, 1536, &divergence);

// Kullback-Leibler divergence between two vectors
simsimd_kl_f16(f16s, f16s, 1536, &divergence);
simsimd_kl_f32(f32s, f32s, 1536, &divergence);
simsimd_kl_f64(f64s, f64s, 1536, &divergence);
return 0;

} ```

Half-Precision Floating-Point Numbers

If you aim to utilize the _Float16 functionality with SimSIMD, ensure your development environment is compatible with C 11. For other SimSIMD functionalities, C 99 compatibility will suffice. To explicitly disable half-precision support, define the following macro before imports:

```c

define SIMSIMDNATIVEF16 0 // or 1

define SIMSIMDNATIVEBF16 0 // or 1

include

```

Compilation Settings and Debugging

SIMSIMD_DYNAMIC_DISPATCH:

By default, SimSIMD is a header-only library. But if you are running on different generations of devices, it makes sense to pre-compile the library for all supported generations at once, and dispatch at runtime. This flag does just that and is used to produce the simsimd.so shared library, as well as the Python and other bindings.

For Arm: SIMSIMD_TARGET_NEON, SIMSIMD_TARGET_SVE, SIMSIMD_TARGET_SVE2, SIMSIMD_TARGET_NEON_F16, SIMSIMD_TARGET_SVE_F16, SIMSIMD_TARGET_NEON_BF16, SIMSIMD_TARGET_SVE_BF16. For x86: (SIMSIMD_TARGET_HASWELL, SIMSIMD_TARGET_SKYLAKE, SIMSIMD_TARGET_ICE, SIMSIMD_TARGET_GENOA, SIMSIMD_TARGET_SAPPHIRE, SIMSIMD_TARGET_TURIN, SIMSIMD_TARGET_SIERRA.

By default, SimSIMD automatically infers the target architecture and pre-compiles as many kernels as possible. In some cases, you may want to explicitly disable some of the kernels. Most often it's due to compiler support issues, like the lack of some recent intrinsics or low-precision numeric types. In other cases, you may want to disable some kernels to speed up the compilation process and trim the binary size.

SIMSIMD_SQRT, SIMSIMD_RSQRT, SIMSIMD_LOG:

By default, for non-SIMD backends, SimSIMD may use libc functions like sqrt and log. Those are generally very accurate, but slow, and introduce a dependency on the C standard library. To avoid that you can override those definitions with your custom implementations, like: #define SIMSIMD_RSQRT(x) (1 / sqrt(x)).

Algorithms & Design Decisions 📚

In general there are a few principles that SimSIMD follows:

  • Avoid loop unrolling.
  • Never allocate memory.
  • Never throw exceptions or set errno.
  • Keep all function arguments the size of the pointer.
  • Avoid returning from public interfaces, use out-arguments instead.
  • Don't over-optimize for old CPUs and single- and double-precision floating-point numbers.
  • Prioritize mixed-precision and integer operations, and new ISA extensions.
  • Prefer saturated arithmetic and avoid overflows.

Possibly, in the future:

  • Best effort computation silencing NaN components in low-precision inputs.
  • Detect overflows and report the distance with a "signaling" NaN.

Last, but not the least - don't build unless there is a demand for it. So if you have a specific use-case, please open an issue or a pull request, and ideally, bring in more users with similar needs.

Cosine Similarity, Reciprocal Square Root, and Newton-Raphson Iteration

The cosine similarity is the most common and straightforward metric used in machine learning and information retrieval. Interestingly, there are multiple ways to shoot yourself in the foot when computing it. The cosine similarity is the inverse of the cosine distance, which is the cosine of the angle between two vectors.

math \text{CosineSimilarity}(a, b) = \frac{a \cdot b}{\|a\| \cdot \|b\|}

math \text{CosineDistance}(a, b) = 1 - \frac{a \cdot b}{\|a\| \cdot \|b\|}

In NumPy terms, SimSIMD implementation is similar to:

```python import numpy as np

def cos_numpy(a: np.ndarray, b: np.ndarray) -> float: ab, a2, b2 = np.dot(a, b), np.dot(a, a), np.dot(b, b) # Fused in SimSIMD if a2 == 0 and b2 == 0: result = 0 # Same in SciPy elif ab == 0: result = 1 # Division by zero error in SciPy else: result = 1 - ab / (sqrt(a2) * sqrt(b2)) # Bigger rounding error in SciPy return result ```

In SciPy, however, the cosine distance is computed as 1 - ab / np.sqrt(a2 * b2). It handles the edge case of a zero and non-zero argument pair differently, resulting in a division by zero error. It's not only less efficient, but also less accurate, given how the reciprocal square roots are computed. The C standard library provides the sqrt function, which is generally very accurate, but slow. The rsqrt in-hardware implementations are faster, but have different accuracy characteristics.

  • SSE rsqrtps and AVX vrsqrtps: $1.5 \times 2^{-12}$ maximal relative error.
  • AVX-512 vrsqrt14pd instruction: $2^{-14}$ maximal relative error.
  • NEON frsqrte instruction has no documented error bounds, but can be $2^{-3}$.

To overcome the limitations of the rsqrt instruction, SimSIMD uses the Newton-Raphson iteration to refine the initial estimate for high-precision floating-point numbers. It can be defined as:

math x_{n+1} = x_n \cdot (3 - x_n \cdot x_n) / 2

On 1536-dimensional inputs on Intel Sapphire Rapids CPU a single such iteration can result in a 2-3 orders of magnitude relative error reduction:

| Datatype | NumPy Error | SimSIMD w/out Iteration | SimSIMD | | :--------- | ------------------: | ----------------------: | ------------------: | | bfloat16 | 1.89e-08 ± 1.59e-08 | 3.07e-07 ± 3.09e-07 | 3.53e-09 ± 2.70e-09 | | float16 | 1.67e-02 ± 1.44e-02 | 2.68e-05 ± 1.95e-05 | 2.02e-05 ± 1.39e-05 | | float32 | 2.21e-08 ± 1.65e-08 | 3.47e-07 ± 3.49e-07 | 3.77e-09 ± 2.84e-09 | | float64 | 0.00e+00 ± 0.00e+00 | 3.80e-07 ± 4.50e-07 | 1.35e-11 ± 1.85e-11 |

Curved Spaces, Mahalanobis Distance, and Bilinear Quadratic Forms

The Mahalanobis distance is a generalization of the Euclidean distance, which takes into account the covariance of the data. It's very similar in its form to the bilinear form, which is a generalization of the dot product.

math \text{BilinearForm}(a, b, M) = a^T M b

math \text{Mahalanobis}(a, b, M) = \sqrt{(a - b)^T M^{-1} (a - b)}

Bilinear Forms can be seen as one of the most important linear algebraic operations, surprisingly missing in BLAS and LAPACK. They are versatile and appear in various domains:

  • In Quantum Mechanics, the expectation value of an observable $A$ in a state $\psi$ is given by $\langle \psi | A | \psi \rangle$, which is a bilinear form.
  • In Machine Learning, in Support Vector Machines (SVMs), bilinear forms define kernel functions that measure similarity between data points.
  • In Differential Geometry, the metric tensor, which defines distances and angles on a manifold, is a bilinear form on the tangent space.
  • In Economics, payoff functions in certain Game Theoretic problems can be modeled as bilinear forms of players' strategies.
  • In Physics, interactions between electric and magnetic fields can be expressed using bilinear forms.

Broad applications aside, the lack of a specialized primitive for bilinear forms in BLAS and LAPACK means significant performance overhead. A $vector * matrix * vector$ product is a scalar, whereas its constituent parts ($vector * matrix$ and $matrix * vector$) are vectors:

  • They need memory to be stored in: $O(n)$ allocation.
  • The data will be written to memory and read back, wasting CPU cycles.

SimSIMD doesn't produce intermediate vector results, like a @ M @ b, but computes the bilinear form directly.

Set Intersection, Galloping, and Binary Search

The set intersection operation is generally defined as the number of elements that are common between two sets, represented as sorted arrays of integers. The most common way to compute it is a linear scan:

c size_t intersection_size(int *a, int *b, size_t n, size_t m) { size_t i = 0, j = 0, count = 0; while (i < n && j < m) { if (a[i] < b[j]) i++; else if (a[i] > b[j]) j++; else i++, j++, count++; } return count; }

Alternatively, one can use the binary search to find the elements in the second array that are present in the first one. On every step the checked region of the second array is halved, which is called the galloping search. It's faster, but only when large arrays of very different sizes are intersected. Third approach is to use the SIMD instructions to compare multiple elements at once:

  • Using string-intersection instructions on x86, like pcmpestrm.
  • Using integer-intersection instructions in AVX-512, like vp2intersectd.
  • Using vanilla equality checks present in all SIMD instruction sets.

After benchmarking, the last approach was chosen, as it's the most flexible and often the fastest.

Complex Dot Products, Conjugate Dot Products, and Complex Numbers

Complex dot products are a generalization of the dot product to complex numbers. They are supported by most BLAS packages, but almost never in mixed precision. SimSIMD defines dot and vdot kernels as:

math \text{dot}(a, b) = \sum_{i=0}^{n-1} a_i \cdot b_i

math \text{vdot}(a, b) = \sum_{i=0}^{n-1} a_i \cdot \bar{b_i}

Where $\bar{bi}$ is the complex conjugate of $bi$. Putting that into Python code for scalar arrays:

```python def dot(a: List[number], b: List[number]) -> number: areal, aimaginary = a[0::2], a[1::2] breal, bimaginary = b[0::2], b[1::2] abreal, abimaginary = 0, 0 for ar, ai, br, bi in zip(areal, aimaginary, breal, bimaginary): abreal += ar * br - ai * bi abimaginary += ar * bi + ai * br return abreal, abimaginary

def vdot(a: List[number], b: List[number]) -> number: areal, aimaginary = a[0::2], a[1::2] breal, bimaginary = b[0::2], b[1::2] abreal, abimaginary = 0, 0 for ar, ai, br, bi in zip(areal, aimaginary, breal, bimaginary): abreal += ar * br + ai * bi abimaginary += ar * bi - ai * br return abreal, abimaginary ```

Logarithms in Kullback-Leibler & Jensen–Shannon Divergences

The Kullback-Leibler divergence is a measure of how one probability distribution diverges from a second, expected probability distribution. Jensen-Shannon divergence is a symmetrized and smoothed version of the Kullback-Leibler divergence, which can be used as a distance metric between probability distributions.

math \text{KL}(P || Q) = \sum_{i} P(i) \log \frac{P(i)}{Q(i)}

math \text{JS}(P, Q) = \frac{1}{2} \text{KL}(P || M) + \frac{1}{2} \text{KL}(Q || M), M = \frac{P + Q}{2}

Both functions are defined for non-negative numbers, and the logarithm is a key part of their computation.

Mixed Precision in Fused-Multiply-Add and Weighted Sums

The Fused-Multiply-Add (FMA) operation is a single operation that combines element-wise multiplication and addition with different scaling factors. The Weighted Sum is it's simplified variant without element-wise multiplication.

math \text{FMA}_i(A, B, C, \alpha, \beta) = \alpha \cdot A_i \cdot B_i + \beta \cdot C_i

math \text{WSum}_i(A, B, \alpha, \beta) = \alpha \cdot A_i + \beta \cdot B_i

In NumPy terms, the implementation may look like:

py import numpy as np def wsum(A: np.ndarray, B: np.ndarray, /, Alpha: float, Beta: float) -> np.ndarray: assert A.dtype == B.dtype, "Input types must match and affect the output style" return (Alpha * A + Beta * B).astype(A.dtype) def fma(A: np.ndarray, B: np.ndarray, C: np.ndarray, /, Alpha: float, Beta: float) -> np.ndarray: assert A.dtype == B.dtype and A.dtype == C.dtype, "Input types must match and affect the output style" return (Alpha * A * B + Beta * C).astype(A.dtype)

The tricky part is implementing those operations in mixed precision, where the scaling factors are of different precision than the input and output vectors. SimSIMD uses double-precision floating-point scaling factors for any input and output precision, including i8 and u8 integers and f16 and bf16 floats. Depending on the generation of the CPU, given native support for f16 addition and multiplication, the f16 temporaries are used for i8 and u8 multiplication, scaling, and addition. For bf16, native support is generally limited to dot-products with subsequent partial accumulation, which is not enough for the FMA and WSum operations, so f32 is used as a temporary.

Auto-Vectorization & Loop Unrolling

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.

| Kind | GCC 12 f32 | GCC 12 f16 | SimSIMD f16 | f16 improvement | | :------------------------ | -----------: | -----------: | ------------: | ----------------: | | Inner Product | 3,810 K/s | 192 K/s | 5,990 K/s | 31 x | | Cosine Distance | 3,280 K/s | 336 K/s | 6,880 K/s | 20 x | | Euclidean Distance ² | 4,620 K/s | 147 K/s | 5,320 K/s | 36 x | | Jensen-Shannon Divergence | 1,180 K/s | 18 K/s | 2,140 K/s | 118 x |

Dynamic Dispatch

Most popular software is precompiled and distributed with fairly conservative CPU optimizations, to ensure compatibility with older hardware. Database Management platforms, like ClickHouse, and Web Browsers, like Google Chrome,need to run on billions of devices, and they can't afford to be picky about the CPU features. For such users SimSIMD provides a dynamic dispatch mechanism, which selects the most advanced micro-kernel for the current CPU at runtime.

Subset F CD ER PF 4FMAPS 4VNNIW VPOPCNTDQ VL DQ BW IFMA VBMI VNNI BF16 VBMI2 BITALG VPCLMULQDQ GFNI VAES VP2INTERSECT FP16
Knights Landing (Xeon Phi x200, 2016) Yes Yes No
Knights Mill (Xeon Phi x205, 2017) Yes No
Skylake-SP, Skylake-X (2017) No No Yes No
Cannon Lake (2018) Yes No
Cascade Lake (2019) No Yes No
Cooper Lake (2020) Yes No
Ice Lake (2019) Yes No Yes No
Tiger Lake (2020) Yes No
Rocket Lake (2021) No
Alder Lake (2021) Partial Partial
Zen 4 (2022) Yes Yes No
Sapphire Rapids (2023) No Yes
Zen 5 (2024) Yes No

You can compile SimSIMD on an old CPU, like Intel Haswell, and run it on a new one, like AMD Genoa, and it will automatically use the most advanced instructions available. Reverse is also true, you can compile on a new CPU and run on an old one, and it will automatically fall back to the most basic instructions. Moreover, the very first time you prove for CPU capabilities with simsimd_capabilities(), it initializes the dynamic dispatch mechanism, and all subsequent calls will be faster and won't face race conditions in multi-threaded environments.

Target Specific Backends

SimSIMD exposes all kernels for all backends, and you can select the most advanced one for the current CPU without relying on built-in dispatch mechanisms. That's handy for testing and benchmarking, but also in case you want to dispatch a very specific kernel for a very specific CPU, bypassing SimSIMD assignment logic. All of the function names follow the same pattern: simsimd_{function}_{type}_{backend}.

  • The backend can be serial, haswell, skylake, ice, genoa, sapphire, turin, neon, or sve.
  • The type can be f64, f32, f16, bf16, f64c, f32c, f16c, bf16c, i8, or b8.
  • The function can be dot, vdot, cos, l2sq, hamming, jaccard, kl, js, or intersect.

To avoid hard-coding the backend, you can use the simsimd_kernel_punned_t to pun the function pointer and the simsimd_capabilities function to get the available backends at runtime. To match all the function names, consider a RegEx:

regex SIMSIMD_PUBLIC void simsimd_\w+_\w+_\w+\(

On Linux, you can use the following command to list all unique functions:

```sh $ grep -oP 'SIMSIMDPUBLIC void simsimd\w+\w+\w+(' include/simsimd/*.h | sort | uniq

include/simsimd/binary.h:SIMSIMDPUBLIC void simsimdhammingb8haswell( include/simsimd/binary.h:SIMSIMDPUBLIC void simsimdhammingb8ice( include/simsimd/binary.h:SIMSIMDPUBLIC void simsimdhammingb8neon( include/simsimd/binary.h:SIMSIMDPUBLIC void simsimdhammingb8serial( include/simsimd/binary.h:SIMSIMDPUBLIC void simsimdhammingb8sve( include/simsimd/binary.h:SIMSIMDPUBLIC void simsimdjaccardb8haswell( include/simsimd/binary.h:SIMSIMDPUBLIC void simsimdjaccardb8ice( include/simsimd/binary.h:SIMSIMDPUBLIC void simsimdjaccardb8neon( include/simsimd/binary.h:SIMSIMDPUBLIC void simsimdjaccardb8serial( include/simsimd/binary.h:SIMSIMDPUBLIC void simsimdjaccardb8sve( ```

License

Feel free to use the project under Apache 2.0 or the Three-clause BSD license at your preference.

Owner

  • Name: Ash Vardanian
  • Login: ashvardanian
  • Kind: user
  • Location: London, San Francisco, Yerevan
  • Company: BDFL @ Unum

Converting outrageous amounts of coffee into modest amounts of Assembly for Intel, Arm, and Nvidia chips. @unum-cloud, @cpp-armenia

GitHub Events

Total
  • Fork event: 34
  • Create event: 80
  • Commit comment event: 3
  • Release event: 44
  • Issues event: 47
  • Watch event: 486
  • Delete event: 37
  • Member event: 1
  • Issue comment event: 150
  • Push event: 261
  • Pull request review event: 25
  • Pull request review comment event: 26
  • Pull request event: 72
Last Year
  • Fork event: 34
  • Create event: 80
  • Commit comment event: 3
  • Release event: 44
  • Issues event: 47
  • Watch event: 486
  • Delete event: 37
  • Member event: 1
  • Issue comment event: 150
  • Push event: 261
  • Pull request review event: 25
  • Pull request review comment event: 26
  • Pull request event: 72

Committers

Last synced: 9 months ago

All Time
  • Total Commits: 1,009
  • Total Committers: 35
  • Avg Commits per committer: 28.829
  • Development Distribution Score (DDS): 0.211
Past Year
  • Commits: 539
  • Committers: 19
  • Avg Commits per committer: 28.368
  • Development Distribution Score (DDS): 0.174
Top Committers
Name Email Commits
Ash Vardanian 1****n 796
semantic-release-bot s****t@m****t 74
TinySemVer t****r@a****m 63
Gurgen Yegoryan 2****n 16
Arman Ghazaryan 9****n 9
Mark Reed m****9@g****m 8
Steven Roussey s****y@g****m 6
Govind p****d@g****m 4
Eren K. 9****n 3
Jim Thompson j****2@g****m 2
Michał Górny m****y@g****g 2
Pedro Gabriel Planel p****l 2
Wyctus u****n@g****m 2
Everett Knag 6****g 1
Christophe Bornet c****t@h****m 1
Conrad Kramer c****d@c****m 1
Daniel Bos c****i@g****m 1
Evan Anderson I****s@g****m 1
tom denton s****4@g****m 1
marthadev 7****v 1
lkuffo l****r@c****l 1
dependabot[bot] 4****] 1
alexanderchang1 3****1 1
Valery Mironov v****w@g****m 1
Trevor McCulloch m****t@g****m 1
Sutou Kouhei k****u@c****m 1
Robert Schulze r****t@c****m 1
Narek Galstyan n****4@g****m 1
Nairi Harutyunyan n****n@g****m 1
Michael Chetin m****9@g****m 1
and 5 more...
Committer Domains (Top 20 + Academic)

Issues and Pull Requests

Last synced: 6 months ago

All Time
  • Total issues: 106
  • Total pull requests: 259
  • Average time to close issues: 24 days
  • Average time to close pull requests: 5 days
  • Total issue authors: 51
  • Total pull request authors: 38
  • Average comments per issue: 1.91
  • Average comments per pull request: 0.92
  • Merged pull requests: 224
  • Bot issues: 0
  • Bot pull requests: 2
Past Year
  • Issues: 48
  • Pull requests: 107
  • Average time to close issues: 15 days
  • Average time to close pull requests: 2 days
  • Issue authors: 31
  • Pull request authors: 17
  • Average comments per issue: 1.13
  • Average comments per pull request: 0.76
  • Merged pull requests: 91
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
  • ashvardanian (29)
  • MarkReedZ (8)
  • MBkkt (5)
  • guyrosin (4)
  • sroussey (3)
  • mgorny (3)
  • Charlyo (2)
  • Spixmaster (2)
  • EricZequan (2)
  • pauldintel (2)
  • fancidev (2)
  • rschu1ze (2)
  • cbornet (2)
  • ogencoglu (2)
  • ternaus (2)
Pull Request Authors
  • ashvardanian (136)
  • sroussey (17)
  • MarkReedZ (16)
  • GoWind (9)
  • mgorny (5)
  • gurgenyegoryan (5)
  • real-eren (5)
  • Spixmaster (4)
  • jimthompson5802 (4)
  • amirzia (4)
  • pplanel (4)
  • corani (4)
  • dependabot[bot] (2)
  • lkuffo (2)
  • cbornet (2)
Top Labels
Issue Labels
enhancement (25) bug (24) good first issue (16) help wanted (13) low priority (2) question (2) invalid (2) semantic-release (2) documentation (1)
Pull Request Labels
released (61) dependencies (2) help wanted (1)

Packages

  • Total packages: 6
  • Total downloads:
    • npm 837 last-month
    • cargo 162,174 total
    • pypi 2,392,549 last-month
  • Total dependent packages: 6
    (may contain duplicates)
  • Total dependent repositories: 1
    (may contain duplicates)
  • Total versions: 375
  • Total maintainers: 4
proxy.golang.org: github.com/ashvardanian/simsimd
  • Versions: 32
  • Dependent Packages: 0
  • Dependent Repositories: 0
Rankings
Stargazers count: 4.4%
Average: 8.1%
Dependent packages count: 8.4%
Forks count: 8.9%
Dependent repos count: 10.6%
Last synced: 6 months ago
proxy.golang.org: github.com/ashvardanian/SimSIMD
  • Versions: 32
  • Dependent Packages: 0
  • Dependent Repositories: 0
Rankings
Dependent packages count: 9.0%
Average: 9.6%
Dependent repos count: 10.2%
Last synced: 6 months ago
pypi.org: simsimd

Portable mixed-precision BLAS-like vector math library for x86 and ARM

  • Versions: 101
  • Dependent Packages: 5
  • Dependent Repositories: 1
  • Downloads: 2,392,549 Last month
Rankings
Downloads: 2.2%
Stargazers count: 5.5%
Dependent packages count: 10.1%
Average: 10.5%
Forks count: 13.3%
Dependent repos count: 21.5%
Maintainers (1)
Last synced: 6 months ago
npmjs.org: simsimd

Portable mixed-precision BLAS-like vector math library for x86 and ARM

  • Versions: 95
  • Dependent Packages: 0
  • Dependent Repositories: 0
  • Downloads: 818 Last month
Rankings
Stargazers count: 4.9%
Forks count: 8.4%
Average: 25.8%
Dependent repos count: 37.1%
Dependent packages count: 52.6%
Maintainers (1)
Last synced: 6 months ago
npmjs.org: @sroussey/simsimd

Fastest SIMD-Accelerated Vector Similarity Functions for x86 and Arm

  • Versions: 23
  • Dependent Packages: 0
  • Dependent Repositories: 0
  • Downloads: 19 Last month
Rankings
Dependent repos count: 33.9%
Average: 41.1%
Dependent packages count: 48.3%
Maintainers (1)
Last synced: 6 months ago
crates.io: simsimd

Portable mixed-precision BLAS-like vector math library for x86 and ARM

  • Versions: 92
  • Dependent Packages: 1
  • Dependent Repositories: 0
  • Downloads: 162,174 Total
Rankings
Dependent repos count: 29.7%
Dependent packages count: 35.0%
Average: 53.7%
Downloads: 96.5%
Maintainers (2)
Last synced: 6 months ago

Dependencies

.github/workflows/prerelease.yml actions
  • actions/checkout v3 composite
  • actions/setup-python v4 composite
  • egor-tensin/setup-mingw v2 composite
.github/workflows/release.yml actions
  • CasperWA/push-protected v2 composite
  • actions/checkout v3 composite
  • actions/download-artifact v3.0.2 composite
  • actions/setup-node v3 composite
  • actions/setup-python v3 composite
  • actions/upload-artifact v3 composite
  • docker-practice/actions-setup-docker master composite
  • docker/setup-qemu-action v2.1.0 composite
  • pypa/gh-action-pypi-publish release/v1 composite
package.json npm
  • @semantic-release/exec ^6.0.3 development
  • @semantic-release/git ^10.0.1 development
  • conventional-changelog-eslint ^4.0.0 development
  • semantic-release ^21.1.1 development
pyproject.toml pypi
setup.py pypi