simd

package
v0.2.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: Unlicense Imports: 20 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package simd provides SIMD-accelerated distance functions, batch operations, and utility kernels for vector search.

Implementations are selected at runtime via dispatch tables based on CPU capabilities (AVX-512, AVX2, NEON). See docs/simd-architecture.md for detailed architecture documentation.

Index

Constants

View Source
const (
	OpSIMDPrefix = 0xfd

	OpV128Load         = 0x00
	OpF32x4Add         = 0xe4
	OpF32x4Sub         = 0xe5
	OpF32x4Mul         = 0xe6
	OpF32x4ExtractLane = 0x1f

	OpBlock    = 0x02
	OpLoop     = 0x03
	OpBrIf     = 0x0d
	OpBr       = 0x0c
	OpEnd      = 0x0b
	OpLocalGet = 0x20
	OpLocalSet = 0x21
	OpLocalTee = 0x22
	OpF32Load  = 0x2a
	OpF32Store = 0x38
	OpI32Const = 0x41
	OpF32Const = 0x43
	OpI32Add   = 0x6a
	OpI32Mul   = 0x6c
	OpI32Shl   = 0x74
	OpI32GeU   = 0x4f
	OpI32GtU   = 0x4b
	OpF32Add   = 0x92
	OpF32Sub   = 0x93
	OpF32Mul   = 0x94
	OpF32Sqrt  = 0x91
)

WASM OpCodes

Variables

View Source
var (
	// ErrDimensionMismatch is returned when input vectors have different lengths.
	ErrDimensionMismatch = errors.New("simd: vector dimension mismatch")
	// ErrInitializationFailed is returned when SIMD dispatch or JIT fails to initialize.
	ErrInitializationFailed = errors.New("simd: initialization failed")
)
View Source
var (

	// DistFunc is the best available Euclidean distance implementation
	DistFunc distanceFunc
)
View Source
var Registry = &KernelRegistry{
	kernels: make(map[KernelKey]any),
}

Registry is the global KernelRegistry used for polymorphic kernel selection.

Functions

func ADCDistanceBatch

func ADCDistanceBatch(table []float32, flatCodes []byte, m int, results []float32) error

ADCDistanceBatch computes Asymmetric Distance Computation distances. Uses pre-computed distance tables for PQ code lookups.

func AccumulateWeightedScatter

func AccumulateWeightedScatter(dst []float32, targets []uint32, weights []float32, factor float32)

AccumulateWeightedScatter adds weighted values to a destination slice using scatter indices.

func AccumulateWeightedScatterFloat32

func AccumulateWeightedScatterFloat32(dst []float32, targets []uint32, weights []float32, factor float32)

AccumulateWeightedScatterFloat32 adds weighted values to a destination slice using scatter indices. dst[targets[i]] += weights[i] * factor

func AndBitVectors

func AndBitVectors(dst, src []uint64)

AndBitVectors applies bitwise AND: dst &= src

func AndBitVectorsGeneric

func AndBitVectorsGeneric(dst, src []uint64)

AndBitVectorsGeneric is the pure-Go implementation.

func AndBytes

func AndBytes(dst, src []byte) error

AndBytes performs bitwise AND: dst[i] &= src[i]. Assumes len(dst) == len(src).

func ArgMax

func ArgMax(src []float32) int

ArgMax returns the index of the maximum value in a float32 slice.

func ArgMin

func ArgMin(src []float32) int

ArgMin returns the index of the minimum value in a float32 slice.

func Atan2Float32

func Atan2Float32(y, x, dst []float32)

Atan2Float32 calculates the arc tangent of y/x for each pair of elements.

func Atan2Float32AVX2Kernel

func Atan2Float32AVX2Kernel(y, x, dst uintptr, n int)

func BM25ScoreBatch

func BM25ScoreBatch(tfs []int, docLengths []int, avgDL float32, idf float32, k1 float32, b float32) []float32

BM25ScoreBatch computes the BM25 score for a batch of documents. It delegates to architecture-specific SIMD implementations when available.

func BrayCurtisDistance

func BrayCurtisDistance(a, b []float32) (float32, error)

BrayCurtisDistance calculates the Bray-Curtis distance between two vectors.

func BrayCurtisDistanceF16

func BrayCurtisDistanceF16(a, b []float16.Num) (float32, error)

BrayCurtisDistanceF16 calculates the Bray-Curtis distance between two float16 vectors.

func BrayCurtisDistanceFloat32

func BrayCurtisDistanceFloat32(a, b []float32) (float32, error)

BrayCurtisDistanceFloat32 calculates the Bray-Curtis distance between two float32 vectors.

func BrayCurtisDistanceFloat32AVX2

func BrayCurtisDistanceFloat32AVX2(a, b []float32) (float32, error)

BrayCurtisDistanceFloat32AVX2 is an AVX2 optimized implementation of Bray-Curtis distance.

func ChebyshevDistance

func ChebyshevDistance(a, b []float32) (float32, error)

ChebyshevDistance calculates the L-infinity distance between two vectors.

func ChebyshevDistanceF16

func ChebyshevDistanceF16(a, b []float16.Num) (float32, error)

ChebyshevDistanceF16 calculates the L-infinity distance between two float16 vectors.

func ChebyshevDistanceFloat32

func ChebyshevDistanceFloat32(a, b []float32) (float32, error)

ChebyshevDistanceFloat32 calculates the L-infinity distance between two float32 vectors.

func ChebyshevDistanceFloat32AVX2

func ChebyshevDistanceFloat32AVX2(a, b []float32) (float32, error)

ChebyshevDistanceFloat32AVX2 is an AVX2 optimized implementation of Chebyshev distance.

func ComputeBounds

func ComputeBounds(vec []float32) (minVal, maxVal float32)

ComputeBounds calculates min and max values of a vector.

func CosFloat32

func CosFloat32(src, dst []float32)

CosFloat32 calculates the cosine of each element in src.

func CosFloat32AVX2Kernel

func CosFloat32AVX2Kernel(src, dst uintptr, n int)

func CosineDistance

func CosineDistance(a, b []float32) (float32, error)

CosineDistance calculates the cosine distance (1 - similarity) between two vectors. Uses unified dispatch table for optimal cache locality and reduced dispatch overhead.

func CosineDistanceBatch

func CosineDistanceBatch(query []float32, vectors [][]float32, results []float32) error

CosineDistanceBatch computes cosine distances between query and multiple vectors. Uses pre-selected implementation via function pointer (no switch overhead).

func CosineDistanceComplex64

func CosineDistanceComplex64(a, b []complex64) (float32, error)

CosineDistanceComplex64 calculates the cosine distance for Complex64 vectors. Uses unsafe cast to float32 to reuse SIMD-accelerated float32 cosine. Cosine for complex is: 1 - Re(sum(a[i]*conj(b[i]))) / (|a| * |b|) When treating complex64[] as float32[] (interleaved real/imag), this is exactly the float32 cosine distance on the 2N-length float32 array.

func CosineDistanceComplex64Batch

func CosineDistanceComplex64Batch(query []complex64, vectors [][]complex64, results []float32, f32Vecs [][]float32) error

CosineDistanceComplex64Batch computes cosine distances between one complex64 query and multiple complex64 vectors.

func CosineDistanceComplex128

func CosineDistanceComplex128(a, b []complex128) (float32, error)

CosineDistanceComplex128 calculates the cosine distance for Complex128 vectors. Uses unsafe cast to float64 to reuse SIMD-accelerated float64 cosine.

func CosineDistanceComplex128Batch

func CosineDistanceComplex128Batch(query []complex128, vectors [][]complex128, results []float32, f64Vecs [][]float64) error

CosineDistanceComplex128Batch computes cosine distances between one complex128 query and multiple complex128 vectors. f64Vecs is a pre-allocated scratch buffer of at least len(vectors) elements; it is reused to avoid allocation.

func CosineDistanceF16

func CosineDistanceF16(a, b []float16.Num) (float32, error)

CosineDistanceF16 calculates the cosine distance between two FP16 vectors.

func CosineDistanceFMA

func CosineDistanceFMA(a, b []float32) (float32, error)

CosineDistanceFMA dispatches to AVX512 or fallback implementation

func CosineDistanceFMA_AVX512

func CosineDistanceFMA_AVX512(a, b []float32) (float32, error)

CosineDistanceFMA_AVX512 computes cosine distance (1 - similarity) using AVX-512 FMA

func CosineDistanceFloat64

func CosineDistanceFloat64(a, b []float64) (float32, error)

CosineDistanceFloat64 calculates the cosine distance (1 - similarity) for Float64 vectors. Returns float32 distance for consistency with other metrics.

func CosineDistanceFloat64Batch

func CosineDistanceFloat64Batch(query []float64, vectors [][]float64, results []float32) error

CosineDistanceFloat64Batch computes cosine distances between one float64 query and multiple float64 vectors.

func CosineDistanceInt8

func CosineDistanceInt8(a, b []int8) (float32, error)

CosineDistanceInt8 calculates the cosine distance for Int8 vectors.

func CosineDistanceInt16

func CosineDistanceInt16(a, b []int16) (float32, error)

CosineDistanceInt16 calculates the cosine distance for Int16 vectors.

func CosineDistanceInt32

func CosineDistanceInt32(a, b []int32) (float32, error)

CosineDistanceInt32 calculates the cosine distance for Int32 vectors.

func CosineDistanceInt64

func CosineDistanceInt64(a, b []int64) (float32, error)

CosineDistanceInt64 calculates the cosine distance for Int64 vectors.

func CosineDistanceUint8

func CosineDistanceUint8(a, b []uint8) (float32, error)

CosineDistanceUint8 calculates the cosine distance for Uint8 vectors.

func CosineDistanceUint16

func CosineDistanceUint16(a, b []uint16) (float32, error)

CosineDistanceUint16 calculates the cosine distance for Uint16 vectors.

func CosineDistanceUint32

func CosineDistanceUint32(a, b []uint32) (float32, error)

CosineDistanceUint32 calculates the cosine distance for Uint32 vectors.

func CosineDistanceUint64

func CosineDistanceUint64(a, b []uint64) (float32, error)

CosineDistanceUint64 calculates the cosine distance for Uint64 vectors.

func CountBitVector

func CountBitVector(src []uint64) int

CountBitVector returns the number of set bits in the vector

func CountBitVectorGeneric

func CountBitVectorGeneric(src []uint64) int

CountBitVectorGeneric is the pure-Go implementation.

func DequantizeL2Float32Int8

func DequantizeL2Float32Int8(q []float32, v []int8, minV, scale float32) float32

DequantizeL2Float32Int8 computes the Euclidean (L2) distance between a float32 query and an SQ8-quantized int8 vector.

func DequantizeL2Float32Uint8

func DequantizeL2Float32Uint8(q []float32, v []uint8, minV, scale float32) float32

DequantizeL2Float32Uint8 computes the Euclidean (L2) distance between a float32 query and an SQ8-quantized uint8 vector: sqrt(sum((q[i] - (minV + float32(v[i])*scale))^2)).

func DequantizeL2Uint8Uint8

func DequantizeL2Uint8Uint8(q8, v8 []uint8, scale float32) float32

DequantizeL2Uint8Uint8 computes the Euclidean distance between two SQ8-quantized vectors: sqrt(sum((deqQ[i] - deqV[i])^2)) = scale * sqrt(sum((q8[i] - v8[i])^2)).

func DequantizeSQ8Adaptive

func DequantizeSQ8Adaptive(src []byte, dst []float32, calib *SQ8ChannelCalibration)

DequantizeSQ8Adaptive reconstructs a float32 vector from uint8 using per-channel calibration.

func DispatchDistance

func DispatchDistance[T any](metric MetricType, a, b []T) (float32, error)

DispatchDistance computes the distance between two vectors using the best available kernel.

func DistanceDirectADC

func DistanceDirectADC(table []float32, codes []byte, m int) float32

DistanceDirectADC computes Euclidean distance between query and a single vector's PQ codes directly from precomputed distance table without allocating an intermediate distance slice.

func Dot128Uint32

func Dot128Uint32(a, b []uint32) (float32, error)

func Dot384Float16

func Dot384Float16(a, b []float16.Num) (float32, error)

Dot384Float16 calculates dot product for 384-dim float16 vectors.

func Dot384Float64

func Dot384Float64(a, b []float64) (float32, error)

Dot384Float64 calculates dot product for 384-dim float64 vectors.

func Dot384Int8

func Dot384Int8(a, b []int8) (float32, error)

Dot384Int8 calculates dot product for 384-dim int8 vectors.

func Dot384Uint8

func Dot384Uint8(a, b []uint8) (float32, error)

func Dot384Uint16

func Dot384Uint16(a, b []uint16) (float32, error)

func Dot384Uint32

func Dot384Uint32(a, b []uint32) (float32, error)

func Dot384Uint64

func Dot384Uint64(a, b []uint64) (float32, error)

func Dot768Float16

func Dot768Float16(a, b []float16.Num) (float32, error)

Dot768Float16 calculates dot product for 768-dim float16 vectors.

func Dot768Float64

func Dot768Float64(a, b []float64) (float32, error)

Dot768Float64 calculates dot product for 768-dim float64 vectors.

func Dot768Int8

func Dot768Int8(a, b []int8) (float32, error)

Dot768Int8 calculates dot product for 768-dim int8 vectors.

func Dot768Uint8

func Dot768Uint8(a, b []uint8) (float32, error)

func Dot768Uint16

func Dot768Uint16(a, b []uint16) (float32, error)

func Dot768Uint32

func Dot768Uint32(a, b []uint32) (float32, error)

func Dot768Uint64

func Dot768Uint64(a, b []uint64) (float32, error)

func Dot1024Uint8

func Dot1024Uint8(a, b []uint8) (float32, error)

func Dot1024Uint16

func Dot1024Uint16(a, b []uint16) (float32, error)

func Dot1024Uint32

func Dot1024Uint32(a, b []uint32) (float32, error)

func Dot1024Uint64

func Dot1024Uint64(a, b []uint64) (float32, error)

func DotDistanceSQ8

func DotDistanceSQ8(a, b []byte) (int32, error)

DotDistanceSQ8 computes the dot product between two uint8 vectors.

func DotProduct

func DotProduct(a, b []float32) (float32, error)

DotProduct calculates the dot product of two vectors. Uses unified dispatch table for optimal cache locality and reduced dispatch overhead.

func DotProductBatch

func DotProductBatch(query []float32, vectors [][]float32, results []float32) error

DotProductBatch calculates dot product between query and multiple vectors. Uses parallel sum reduction with multiple accumulators for ILP optimization.

func DotProductComplex64

func DotProductComplex64(a, b []complex64) (float32, error)

DotProductComplex64 calculates the real part of the dot product of two Complex64 vectors. Uses unsafe cast to float32 to reuse SIMD-accelerated float32 dot product. Complex dot product Re(sum(a[i] * conj(b[i]))) = sum(ar*br + ai*bi), which is exactly the float32 dot product on the interleaved [real, imag] float32 array.

func DotProductComplex64Batch

func DotProductComplex64Batch(query []complex64, vectors [][]complex64, results []float32, f32Vecs [][]float32) error

DotProductComplex64Batch computes dot products between one complex64 query and multiple complex64 vectors.

func DotProductComplex128

func DotProductComplex128(a, b []complex128) (float32, error)

DotProductComplex128 calculates the real part of the dot product of two Complex128 vectors. Uses unsafe cast to float64 to reuse SIMD-accelerated float64 dot product.

func DotProductComplex128Batch

func DotProductComplex128Batch(query []complex128, vectors [][]complex128, results []float32, f64Vecs [][]float64) error

DotProductComplex128Batch computes dot products between one complex128 query and multiple complex128 vectors. f64Vecs is a pre-allocated scratch buffer of at least len(vectors) elements; it is reused to avoid allocation.

func DotProductF16

func DotProductF16(a, b []float16.Num) (float32, error)

DotProductF16 calculates the dot product between two FP16 vectors.

func DotProductF64

func DotProductF64(a, b []float64) (float32, error)

DotProductF64 calculates the dot product of two Float64 vectors.

func DotProductFMA

func DotProductFMA(a, b []float32) (float32, error)

DotProductFMA dispatches to AVX512 or fallback implementation

func DotProductFMA_AVX512

func DotProductFMA_AVX512(a, b []float32) (float32, error)

DotProductFMA_AVX512 computes dot product using AVX-512 FMA instructions Processes 64 elements per iteration for maximum throughput

func DotProductFloat32Blocked

func DotProductFloat32Blocked(a, b []float32) (float32, error)

DotProductFloat32Blocked calculates dot product using blocked loop processing optimized for vectors larger than L1 cache lines or for specific instruction pipeelining. It iterates in chunks to ensure data fits in L1 cache and to potentially allow better prefetching efficiency.

func DotProductFloat32BlockedPrefetch

func DotProductFloat32BlockedPrefetch(a, b []float32) (float32, error)

DotProductFloat32BlockedPrefetch calculates dot product using blocked processing with prefetch hints for very high dimensions (1536+). This improves cache utilization by prefetching the next block while computing the current block.

func DotProductFloat64Batch

func DotProductFloat64Batch(query []float64, vectors [][]float64, results []float32) error

DotProductFloat64Batch computes dot products between one float64 query and multiple float64 vectors.

func DotProductFloat64Blocked

func DotProductFloat64Blocked(a, b []float64) (float32, error)

DotProductFloat64Blocked calculates dot product for float64 vectors using blocked processing. Optimized for high dimensions (768+) by processing in cache-friendly blocks.

func DotProductInt2

func DotProductInt2(a, b []byte) (float32, error)

DotProductInt2 calculates the dot product for 2-bit packed integer vectors.

func DotProductInt4

func DotProductInt4(a, b []byte) (float32, error)

DotProductInt4 calculates the dot product for 4-bit packed integer vectors.

func DotProductInt8

func DotProductInt8(a, b []int8) (float32, error)

DotProductInt8 calculates the dot product of two Int8 vectors.

func DotProductInt8Blocked

func DotProductInt8Blocked(a, b []int8) (float32, error)

DotProductInt8Blocked calculates dot product for int8 vectors using blocked processing.

func DotProductInt16

func DotProductInt16(a, b []int16) (float32, error)

DotProductInt16 calculates the dot product of two Int16 vectors.

func DotProductInt16Blocked

func DotProductInt16Blocked(a, b []int16) (float32, error)

DotProductInt16Blocked calculates dot product for int16 vectors using blocked processing.

func DotProductInt32

func DotProductInt32(a, b []int32) (float32, error)

DotProductInt32 calculates the dot product of two Int32 vectors.

func DotProductInt32Blocked

func DotProductInt32Blocked(a, b []int32) (float32, error)

DotProductInt32Blocked calculates dot product for int32 vectors using blocked processing.

func DotProductInt64

func DotProductInt64(a, b []int64) (float32, error)

DotProductInt64 calculates the dot product of two Int64 vectors.

func DotProductInt64Blocked

func DotProductInt64Blocked(a, b []int64) (float32, error)

DotProductInt64Blocked calculates dot product for int64 vectors using blocked processing.

func DotProductTiledBatch

func DotProductTiledBatch(query []float32, vectors [][]float32, results []float32) error

DotProductTiledBatch calculates dot products for multiple vectors by tiling the dimension loop.

func DotProductUint8

func DotProductUint8(a, b []uint8) (float32, error)

DotProductUint8 calculates the dot product of two Uint8 vectors.

func DotProductUint16

func DotProductUint16(a, b []uint16) (float32, error)

DotProductUint16 calculates the dot product of two Uint16 vectors.

func DotProductUint16Blocked

func DotProductUint16Blocked(a, b []uint16) (float32, error)

DotProductUint16Blocked calculates dot product for uint16 vectors using blocked processing.

func DotProductUint32

func DotProductUint32(a, b []uint32) (float32, error)

DotProductUint32 calculates the dot product of two Uint32 vectors.

func DotProductUint32Blocked

func DotProductUint32Blocked(a, b []uint32) (float32, error)

DotProductUint32Blocked calculates dot product for uint32 vectors using blocked processing.

func DotProductUint64

func DotProductUint64(a, b []uint64) (float32, error)

DotProductUint64 calculates the dot product of two Uint64 vectors.

func DotProductUint64Blocked

func DotProductUint64Blocked(a, b []uint64) (float32, error)

DotProductUint64Blocked calculates dot product for uint64 vectors using blocked processing.

func DotSQ8Generic

func DotSQ8Generic(a, b []byte) (int32, error)

DotSQ8Generic calculates the dot product for SQ8 quantized vectors.

func Euclidean128Uint32

func Euclidean128Uint32(a, b []uint32) (float32, error)

func Euclidean384Float16

func Euclidean384Float16(a, b []float16.Num) (float32, error)

Euclidean384Float16 calculates Euclidean distance for 384-dim float16 vectors.

func Euclidean384Float64

func Euclidean384Float64(a, b []float64) (float32, error)

Euclidean384Float64 calculates Euclidean distance for 384-dim float64 vectors.

func Euclidean384Int8

func Euclidean384Int8(a, b []int8) (float32, error)

Euclidean384Int8 calculates Euclidean distance for 384-dim int8 vectors.

func Euclidean384Uint8

func Euclidean384Uint8(a, b []uint8) (float32, error)

func Euclidean384Uint16

func Euclidean384Uint16(a, b []uint16) (float32, error)

func Euclidean384Uint32

func Euclidean384Uint32(a, b []uint32) (float32, error)

func Euclidean384Uint64

func Euclidean384Uint64(a, b []uint64) (float32, error)

func Euclidean768Float16

func Euclidean768Float16(a, b []float16.Num) (float32, error)

Euclidean768Float16 calculates Euclidean distance for 768-dim float16 vectors.

func Euclidean768Float64

func Euclidean768Float64(a, b []float64) (float32, error)

Euclidean768Float64 calculates Euclidean distance for 768-dim float64 vectors.

func Euclidean768Int8

func Euclidean768Int8(a, b []int8) (float32, error)

Euclidean768Int8 calculates Euclidean distance for 768-dim int8 vectors.

func Euclidean768Uint8

func Euclidean768Uint8(a, b []uint8) (float32, error)

func Euclidean768Uint16

func Euclidean768Uint16(a, b []uint16) (float32, error)

func Euclidean768Uint32

func Euclidean768Uint32(a, b []uint32) (float32, error)

func Euclidean768Uint64

func Euclidean768Uint64(a, b []uint64) (float32, error)

func Euclidean1024Uint8

func Euclidean1024Uint8(a, b []uint8) (float32, error)

func Euclidean1024Uint16

func Euclidean1024Uint16(a, b []uint16) (float32, error)

func Euclidean1024Uint32

func Euclidean1024Uint32(a, b []uint32) (float32, error)

func Euclidean1024Uint64

func Euclidean1024Uint64(a, b []uint64) (float32, error)

func EuclideanDistance

func EuclideanDistance(a, b []float32) (float32, error)

EuclideanDistance calculates the Euclidean distance between two vectors. Uses unified dispatch table for optimal cache locality and reduced dispatch overhead.

func EuclideanDistanceBatch

func EuclideanDistanceBatch(query []float32, vectors [][]float32, results []float32) error

EuclideanDistanceBatch computes Euclidean distances between one query and multiple vectors. Uses unified dispatch table for optimal cache locality and reduced dispatch overhead.

func EuclideanDistanceBatchFlat

func EuclideanDistanceBatchFlat(query, flatVectors []float32, numVectors, dims int, results []float32) error

EuclideanDistanceBatchFlat computes distances against a flat array of vectors. Vectors are stored contiguously: [v1[0], v1[1], ..., v1[dims], v2[0], ...]

func EuclideanDistanceComplex64

func EuclideanDistanceComplex64(a, b []complex64) (float32, error)

EuclideanDistanceComplex64 calculates Euclidean distance for Complex64 vectors.

func EuclideanDistanceComplex64Batch

func EuclideanDistanceComplex64Batch(query []complex64, vectors [][]complex64, results []float32, f32Vecs [][]float32) error

EuclideanDistanceComplex64Batch computes Euclidean distances between one complex64 query and multiple complex64 vectors. f32Vecs is a pre-allocated scratch buffer of at least len(vectors) elements; it is reused to avoid allocation.

func EuclideanDistanceComplex128

func EuclideanDistanceComplex128(a, b []complex128) (float32, error)

EuclideanDistanceComplex128 calculates Euclidean distance for Complex128 vectors.

func EuclideanDistanceComplex128Batch

func EuclideanDistanceComplex128Batch(query []complex128, vectors [][]complex128, results []float32, f64Vecs [][]float64) error

EuclideanDistanceComplex128Batch computes Euclidean distances between one complex128 query and multiple complex128 vectors. f64Vecs is a pre-allocated scratch buffer of at least len(vectors) elements; it is reused to avoid allocation.

func EuclideanDistanceF16

func EuclideanDistanceF16(a, b []float16.Num) (float32, error)

EuclideanDistanceF16 calculates the Euclidean distance between two FP16 vectors.

func EuclideanDistanceF16Batch

func EuclideanDistanceF16Batch(query []float16.Num, vectors [][]float16.Num, results []float32) error

EuclideanDistanceF16Batch computes Euclidean distances between one query and multiple Float16 vectors.

func EuclideanDistanceFMA

func EuclideanDistanceFMA(a, b []float32) (float32, error)

EuclideanDistanceFMA dispatches to AVX512 or fallback implementation

func EuclideanDistanceFMA_AVX512

func EuclideanDistanceFMA_AVX512(a, b []float32) (float32, error)

EuclideanDistanceFMA_AVX512 computes squared Euclidean distance using AVX-512 FMA

func EuclideanDistanceFloat64

func EuclideanDistanceFloat64(a, b []float64) (float32, error)

EuclideanDistanceFloat64 calculates Euclidean distance for Float64 vectors. Returns float32 distance for consistency with other metrics.

func EuclideanDistanceFloat64Batch

func EuclideanDistanceFloat64Batch(query []float64, vectors [][]float64, results []float32) error

EuclideanDistanceFloat64Batch computes Euclidean distances between one float64 query and multiple float64 vectors.

func EuclideanDistanceInt8

func EuclideanDistanceInt8(a, b []int8) (float32, error)

EuclideanDistanceInt8 calculates Euclidean distance for Int8 vectors.

func EuclideanDistanceInt16

func EuclideanDistanceInt16(a, b []int16) (float32, error)

EuclideanDistanceInt16 calculates Euclidean distance for Int16 vectors.

func EuclideanDistanceInt32

func EuclideanDistanceInt32(a, b []int32) (float32, error)

EuclideanDistanceInt32 calculates Euclidean distance for Int32 vectors.

func EuclideanDistanceInt64

func EuclideanDistanceInt64(a, b []int64) (float32, error)

EuclideanDistanceInt64 calculates Euclidean distance for Int64 vectors.

func EuclideanDistanceSQ8

func EuclideanDistanceSQ8(a, b []byte) (int32, error)

EuclideanDistanceSQ8 computes the Euclidean distance between two uint8 vectors. It returns the squared Euclidean distance as an int32 to avoid overflow and expensive sqrt.

func EuclideanDistanceSQ8Adaptive

func EuclideanDistanceSQ8Adaptive(a, b []byte, calib *SQ8ChannelCalibration) float32

EuclideanDistanceSQ8Adaptive computes channel-scale normalized squared distance.

func EuclideanDistanceSQ8Batch

func EuclideanDistanceSQ8Batch(query []byte, vectors [][]byte, results []float32) error

EuclideanDistanceSQ8Batch computes Euclidean distances for SQ8 quantized vectors.

func EuclideanDistanceTiledBatch

func EuclideanDistanceTiledBatch(query []float32, vectors [][]float32, results []float32) error

EuclideanDistanceTiledBatch calculates distances for multiple vectors by tiling the dimension loop. This keeps chunks of the query vector in L1/L2 cache while processing multiple data vectors.

func EuclideanDistanceUint8

func EuclideanDistanceUint8(a, b []uint8) (float32, error)

EuclideanDistanceUint8 calculates Euclidean distance for Uint8 vectors.

func EuclideanDistanceUint16

func EuclideanDistanceUint16(a, b []uint16) (float32, error)

EuclideanDistanceUint16 calculates Euclidean distance for Uint16 vectors.

func EuclideanDistanceUint32

func EuclideanDistanceUint32(a, b []uint32) (float32, error)

EuclideanDistanceUint32 calculates Euclidean distance for Uint32 vectors.

func EuclideanDistanceUint64

func EuclideanDistanceUint64(a, b []uint64) (float32, error)

EuclideanDistanceUint64 calculates Euclidean distance for Uint64 vectors.

func EuclideanDistanceVerticalBatch

func EuclideanDistanceVerticalBatch(query []float32, vectors [][]float32, results []float32) error

EuclideanDistanceVerticalBatch optimally calculates distances for multiple vectors at once. Uses vertical processing to maximize SIMD register utilization.

func EuclideanFloat32BlockedPrefetch

func EuclideanFloat32BlockedPrefetch(a, b []float32) (float32, error)

EuclideanFloat32BlockedPrefetch calculates Euclidean distance using blocked processing with prefetch hints for very high dimensions (1536+).

func EuclideanFloat64Blocked

func EuclideanFloat64Blocked(a, b []float64) (float32, error)

EuclideanFloat64Blocked calculates Euclidean distance for float64 vectors using blocked processing.

func EuclideanInt8Blocked

func EuclideanInt8Blocked(a, b []int8) (float32, error)

EuclideanInt8Blocked calculates Euclidean distance for int8 vectors using blocked processing.

func EuclideanInt16Blocked

func EuclideanInt16Blocked(a, b []int16) (float32, error)

EuclideanInt16Blocked calculates Euclidean distance for int16 vectors using blocked processing.

func EuclideanInt32Blocked

func EuclideanInt32Blocked(a, b []int32) (float32, error)

EuclideanInt32Blocked calculates Euclidean distance for int32 vectors using blocked processing.

func EuclideanInt64Blocked

func EuclideanInt64Blocked(a, b []int64) (float32, error)

EuclideanInt64Blocked calculates Euclidean distance for int64 vectors using blocked processing.

func EuclideanSQ8Generic

func EuclideanSQ8Generic(a, b []byte) (int32, error)

EuclideanSQ8Generic calculates the squared Euclidean distance for SQ8 quantized vectors.

func EuclideanUint16Blocked

func EuclideanUint16Blocked(a, b []uint16) (float32, error)

EuclideanUint16Blocked calculates Euclidean distance for uint16 vectors using blocked processing.

func EuclideanUint32Blocked

func EuclideanUint32Blocked(a, b []uint32) (float32, error)

EuclideanUint32Blocked calculates Euclidean distance for uint32 vectors using blocked processing.

func EuclideanUint64Blocked

func EuclideanUint64Blocked(a, b []uint64) (float32, error)

EuclideanUint64Blocked calculates Euclidean distance for uint64 vectors using blocked processing.

func Exp

func Exp(src, dst []float32)

Exp applies the exponential function element-wise.

func FastWalshHadamardTransform32

func FastWalshHadamardTransform32(a []float32) error

FastWalshHadamardTransform32 implements the In-place Fast Walsh-Hadamard Transform for float32 vectors. The length of the vector must be a power of 2.

func FastWalshHadamardTransform32NEON

func FastWalshHadamardTransform32NEON(a []float32) error

FastWalshHadamardTransform32NEON is a stub for non-ARM64 platforms.

func FindNearestCentroid

func FindNearestCentroid(query, centroids []float32, subDim, k int) (int, float32)

FindNearestCentroid finds the index of the nearest centroid to query using batch distance computation. This is optimized for PQ encoding where we need to find the closest of K centroids for a subvector. centroids: flattened centroids [c0_0, c0_1, ..., c0_subDim-1, c1_0, ...] subDim: dimension of each centroid (and query) k: number of centroids Returns the index of the nearest centroid and the distance

func FindNearestCentroidInCodebook

func FindNearestCentroidInCodebook(query []float32, codebook [][]float32, m, k, subDim int) []byte

FindNearestCentroidInCodebook finds the nearest centroid in a codebook for PQ encoding. codebook: M slices of K*SubDim flattened centroids m: number of subvectors k: number of centroids per subspace subDim: dimension of each subvector Returns the encoded bytes (M bytes)

func Float16ToFloat32

func Float16ToFloat32(src []float16.Num, dst []float32)

Float16ToFloat32 converts a slice of float16 to float32 using SIMD if available.

func GenerateBatchBody

func GenerateBatchBody() []byte

GenerateBatchBody generates the WebAssembly body for a batch Euclidean distance calculation.

func GenerateBatchBodySIMD

func GenerateBatchBodySIMD() []byte

GenerateBatchBodySIMD generates the WebAssembly body for a SIMD-accelerated batch Euclidean distance calculation.

func GenerateKernels

func GenerateKernels(hasSIMD bool) []byte

GenerateKernels generates a WASM module with both scalar and batch Euclidean kernels

func GenerateScalarBody

func GenerateScalarBody() []byte

GenerateScalarBody generates the WebAssembly body for a scalar Euclidean distance calculation.

func GetImplementation

func GetImplementation() string

GetImplementation returns the selected SIMD implementation name

func GetImplementationDetails

func GetImplementationDetails() map[string]any

GetImplementationDetails returns a structured map describing the selected SIMD implementation and detected CPU flags. Used by the /diagnostics endpoint to enable remote debugging of SIMD fallback issues (e.g., on ancalagon).

func GetTurboQuantAngleDistanceMatrix

func GetTurboQuantAngleDistanceMatrix(bits int) []float32

GetTurboQuantAngleDistanceMatrix returns the precomputed distance matrix for bits (2, 4, 8).

func GetTurboQuantAngleInnerProductMatrix

func GetTurboQuantAngleInnerProductMatrix(bits int) []float32

GetTurboQuantAngleInnerProductMatrix returns the precomputed inner product matrix for bits (2, 4, 8).

func HammingDistance

func HammingDistance(a, b []uint64) int

HammingDistance computes the Hamming distance between two packed bit vectors. a and b must have the same length.

func HammingDistanceGeneric

func HammingDistanceGeneric(a, b []uint64) int

HammingDistanceGeneric is the pure-Go implementation.

func HaversineBatch

func HaversineBatch(centerLat, centerLon float64, points []lbcore.GeoPoint, earthRadius float64, results []float32)

HaversineBatch calculates the haversine distance between a center point and a batch of points.

func Int8ToFloat32

func Int8ToFloat32(src []int8, dst []float32)

Int8ToFloat32 converts a slice of int8 to float32 using SIMD if available.

func Int16ToFloat32

func Int16ToFloat32(src []int16, dst []float32)

Int16ToFloat32 converts a slice of int16 to float32 using SIMD if available.

func Int32ToFloat32

func Int32ToFloat32(src []int32, dst []float32)

Int32ToFloat32 converts a slice of int32 to float32 using SIMD if available.

func InverseRandomRotation

func InverseRandomRotation(a []float32, seed int64) error

InverseRandomRotation inverts the random rotation by applying FWHT, scaling by 1/N, and undoing sign flips.

func IsAllZeros

func IsAllZeros(src []byte) bool

IsAllZeros returns true if all bytes in src are zero.

func L2Float32Blocked

func L2Float32Blocked(a, b []float32) (float32, error)

L2Float32Blocked calculates Euclidean distance using blocked loop processing.

func L2Float32Int8

func L2Float32Int8(q []float32, v []int8) float32

L2Float32Int8 computes the Euclidean distance between a float32 query and unquantized int8 vector.

func L2Float32Uint8

func L2Float32Uint8(q []float32, v []uint8) float32

L2Float32Uint8 computes the Euclidean distance between a float32 query and unquantized uint8 vector.

func L2Squared

func L2Squared(a, b []float32) (float32, error)

L2Squared calculates the squared Euclidean distance between two vectors. Optimized for PQ training and ADC table construction.

func L2Squared384Float64

func L2Squared384Float64(a, b []float64) (float32, error)

L2Squared384Float64 calculates squared Euclidean distance for 384-dim float64 vectors.

func L2Squared768Float64

func L2Squared768Float64(a, b []float64) (float32, error)

L2Squared768Float64 calculates squared Euclidean distance for 768-dim float64 vectors.

func L2SquaredDistanceBatch

func L2SquaredDistanceBatch(query []float32, vectors [][]float32, results []float32) error

L2SquaredDistanceBatch computes L2 squared distances between one query and multiple vectors.

func L2SquaredFloat32

func L2SquaredFloat32(a, b []float32) (float32, error)

L2SquaredFloat32 calculates the squared Euclidean distance using a generic implementation. This is used for PQ training where we need precise control over the implementation.

func L2SquaredFloat64

func L2SquaredFloat64(a, b []float64) (float32, error)

L2SquaredFloat64 calculates the squared Euclidean distance between two Float64 vectors.

func L2SquaredInt8

func L2SquaredInt8(a, b []int8) (float32, error)

L2SquaredInt8 computes the squared L2 distance for Int8 vectors using the SIMD-accelerated Euclidean kernel, squaring the result to avoid sqrt.

func L2SquaredUint8

func L2SquaredUint8(a, b []uint8) (float32, error)

L2SquaredUint8 calculates squared Euclidean distance for Uint8 vectors.

func Log

func Log(src, dst []float32)

Log applies the natural logarithm function element-wise.

func ManhattanDistance

func ManhattanDistance(a, b []float32) (float32, error)

ManhattanDistance calculates the L1 distance between two vectors.

func ManhattanDistanceF16

func ManhattanDistanceF16(a, b []float16.Num) (float32, error)

ManhattanDistanceF16 calculates the L1 distance between two float16 vectors.

func ManhattanDistanceFloat32

func ManhattanDistanceFloat32(a, b []float32) (float32, error)

ManhattanDistanceFloat32 calculates the L1 distance between two float32 vectors.

func ManhattanDistanceFloat32AVX2

func ManhattanDistanceFloat32AVX2(a, b []float32) (float32, error)

ManhattanDistanceFloat32AVX2 is an AVX2 optimized implementation of Manhattan distance.

func MatMul

func MatMul(a, b []float32, m, n, k int, dst []float32)

MatMul performs matrix multiplication: dst = a * b

func MatchFloat32

func MatchFloat32(src []float32, val float32, op CompareOp, dst []byte) error

MatchFloat32 performs a comparison of src elements against val, storing the result (0 or 1) in dst. One byte per element is written to dst.

func MatchFloat64

func MatchFloat64(src []float64, val float64, op CompareOp, dst []byte) error

MatchFloat64 performs a comparison of src elements against val, storing the result (0 or 1) in dst. One byte per element is written to dst.

func MatchInt32

func MatchInt32(src []int32, val int32, op CompareOp, dst []byte) error

MatchInt32 performs a comparison of src elements against val, storing the result (0 or 1) in dst. One byte per element is written to dst.

func MatchInt64

func MatchInt64(src []int64, val int64, op CompareOp, dst []byte) error

MatchInt64 performs a comparison of src elements against val, storing the result (0 or 1) in dst. One byte per element is written to dst.

func MatchUint16

func MatchUint16(src []uint16, val uint16, op CompareOp, dst []byte) error

MatchUint16 performs an accelerated comparison of 16-bit unsigned integer values (e.g. dictionary codes).

func Max

func Max(src []float32) float32

Max finds the maximum value in a float32 slice.

func MemcpyNTA

func MemcpyNTA(dst, src unsafe.Pointer, n int)

MemcpyNTA performs a memory copy using non-temporal hints to avoid cache pollution.

func Min

func Min(src []float32) float32

Min finds the minimum value in a float32 slice.

func NotBytes

func NotBytes(dst []byte) error

NotBytes performs bitwise NOT: dst[i] = ^dst[i].

func OrBytes

func OrBytes(dst, src []byte) error

OrBytes performs bitwise OR: dst[i] |= src[i]. Assumes len(dst) == len(src).

func PackTQ2

func PackTQ2(src []float32, dst []byte)

PackTQ2 packs float32 data into 2-bit TurboQuant format.

func PackTQ2AVX2

func PackTQ2AVX2(src []float32, dst []byte)

PackTQ2AVX2 falls back to the generic implementation, which uses the updated 2-bit angle grid (midpoints) shared with the rest of the codec.

func PackTQ2AVX512

func PackTQ2AVX512(src []float32, dst []byte)

func PackTQ2AVX512VBMI

func PackTQ2AVX512VBMI(src []float32, dst []byte)

PackTQ2AVX512VBMI packs via VPMULTISHIFTQB.

The VBMI kernel is not used. It disagrees with PackTQ2Generic - the reference definition of the 2-bit code - for every length the parity test covers, and nothing caught that because no test compared the two: the only test that touched this packer round-tripped it through UnpackTQ2AVX512VBMI with a tolerance of 2.0, while adjacent 2-bit codes are 2*PI/3 = 2.094 apart, so a packer that is one code off everywhere passes it.

The defect was found by scripts/check_avx512_coverage.sh, which runs internal/simd under Intel SDE with an emulated Ice Lake / Sapphire Rapids (docs/roadmap.md item 5). Before that lane existed these kernels had never executed anywhere in CI, because every test that guards on HasVBMI skips on a standard runner.

PackTQ2 is dispatched instead: it is the entry point the index actually uses and it has always been checked against the generic packer. Fixing the VBMI kernel is tracked as docs/roadmap.md item 10; when it is fixed this function goes back to dispatching the kernel and TestPackTQ2AVX512VBMIMatchesGeneric is what says so.

TODO(roadmap-10): restore packTQ2AVX512VBMIKernel once it matches generic.

func PackTQ2Generic

func PackTQ2Generic(src []float32, dst []byte)

func PackTQ2NEON

func PackTQ2NEON(src []float32, dst []byte)

func PackTQ4

func PackTQ4(src []float32, dst []byte)

PackTQ4 packs float32 data into 4-bit TurboQuant format.

func PackTQ4AVX2

func PackTQ4AVX2(src []float32, dst []byte)

PackTQ4AVX2 is implemented in assembly.

func PackTQ4AVX512

func PackTQ4AVX512(src []float32, dst []byte)

func PackTQ4Generic

func PackTQ4Generic(src []float32, dst []byte)

func PackTQ4NEON

func PackTQ4NEON(src []float32, dst []byte)

func PackTQ8

func PackTQ8(src []float32, dst []byte)

PackTQ8 packs float32 data into 8-bit TurboQuant format.

func PackTQ8AVX2

func PackTQ8AVX2(src []float32, dst []byte)

PackTQ8AVX2 is implemented in assembly.

func PackTQ8AVX512

func PackTQ8AVX512(src []float32, dst []byte)

func PackTQ8Generic

func PackTQ8Generic(src []float32, dst []byte)

func PackTQ8NEON

func PackTQ8NEON(src []float32, dst []byte)

func PadToPowerOf2

func PadToPowerOf2(a []float32) []float32

PadToPowerOf2 pads a vector with zeros to the next power of 2.

func Pause

func Pause()

Pause yields the processor for a short time. On x86 it uses the PAUSE instruction, on ARM64 it uses YIELD.

func PauseN

func PauseN(n int)

PauseN calls Pause n times.

func Popcount

func Popcount(x uint64) int

Popcount returns the population count (number of set bits) of x. This usually maps to the POPCNT instruction on x86-64 (if supported and enabled) or an efficient software fallback.

func Prefetch

func Prefetch(p unsafe.Pointer)

Prefetch hints to the CPU to fetch data into cache for future use. It uses the PREFETCHNTA instruction on x86 for non-temporal access.

func QuantizeSQ8

func QuantizeSQ8(src []float32, dst []byte, minVal, maxVal float32)

QuantizeSQ8 converts a float32 vector to uint8 using min/max bounds. dst must be pre-allocated with correct length.

func QuantizeSQ8Adaptive

func QuantizeSQ8Adaptive(src []float32, dst []byte, calib *SQ8ChannelCalibration)

QuantizeSQ8Adaptive quantizes a float32 vector to uint8 using per-channel calibration.

func RandomRotation

func RandomRotation(a []float32, seed int64) error

RandomRotation rotates the vector using a randomized Hadamard transform. It applies a random sign flip (diagonal matrix D) followed by FWHT. seed is used to generate the deterministic sign flips for reconstruction.

func RandomRotationNEON

func RandomRotationNEON(a []float32, seed int64) error

RandomRotationNEON is a stub for non-ARM64 platforms.

func Sigmoid

func Sigmoid(src, dst []float32)

Sigmoid applies the sigmoid activation function element-wise.

func SinFloat32

func SinFloat32(src, dst []float32)

SinFloat32 calculates the sine of each element in src.

func SinFloat32AVX2Kernel

func SinFloat32AVX2Kernel(src, dst uintptr, n int)

func SincosFloat32

func SincosFloat32(src, sinDst, cosDst []float32)

SincosFloat32 calculates the sine and cosine of each element in src.

func SincosFloat32AVX2Kernel

func SincosFloat32AVX2Kernel(src, sinDst, cosDst uintptr, n int)

func Softmax

func Softmax(src, dst []float32)

Softmax applies the softmax activation function to the input slice.

func SqrtFloat32

func SqrtFloat32(src, dst []float32)

SqrtFloat32 calculates the square root of each element in src.

func Sum

func Sum(src []float32) float32

Sum calculates the sum of all elements in a float32 slice.

func TQApplyQJLCorrection

func TQApplyQJLCorrection(recon []float32, qjlBits []byte, correction float32)

TQApplyQJLCorrection applies QJL sign correction to recon using branchless arithmetic.

func TQPolarReconstructLevel

func TQPolarReconstructLevel(recon []float32, qIndices []byte, angleOffset int, levelSize int, lookup []float32)

TQPolarReconstructLevel executes 4-lane polar reconstruction for a single level where levelSize >= 4.

func TQPolarReconstructLevelAVX2

func TQPolarReconstructLevelAVX2(recon []float32, qIndices []byte, angleOffset, levelSize int, lookup []float32)

TQPolarReconstructLevelAVX2 runs the 4-lane AVX2 polar reconstruction kernel.

func TQPolarReconstructLevelGeneric

func TQPolarReconstructLevelGeneric(recon []float32, qIndices []byte, angleOffset int, levelSize int, lookup []float32)

TQPolarReconstructLevelGeneric executes 4-lane unrolled polar reconstruction with independent registers.

func ToFloat32

func ToFloat32(v []float64) []float32

ToFloat32 converts a float64 slice to a float32 slice (Allocates).

func TurboQuantAngleDistance

func TurboQuantAngleDistance(bits int, q1, q2 byte) float32

TurboQuantAngleDistance returns the precomputed squared distance between two quantized angle codes.

func TurboQuantAngleInnerProduct

func TurboQuantAngleInnerProduct(bits int, q1, q2 byte) float32

TurboQuantAngleInnerProduct returns the precomputed inner product between two quantized angle codes.

func TurboQuantDistanceAVX2

func TurboQuantDistanceAVX2(query []float32, tqData []byte, dim int, pow2 int, bitsPerAngle int) (float32, error)

func TurboQuantDistanceAVX512

func TurboQuantDistanceAVX512(query []float32, tqData []byte, dim int, pow2 int, bitsPerAngle int) (float32, error)

func TurboQuantDistanceBatch

func TurboQuantDistanceBatch(query []float32, codes [][]byte, dst []float32, dim, pow2, bitsPerAngle int) error

TurboQuantDistanceBatch computes the distance from one query to each of n TQ-encoded vectors, writing into dst, using the optimal SIMD kernel for the CPU.

dst must have room for n float32. codes[i] is one vector's packed payload. Every element of dst is bit-identical to what TurboQuantDistanceGeneric, TurboQuantDistanceAVX2, TurboQuantDistanceAVX512 or TurboQuantDistanceNEON would have produced for the same input, which is what lets a batched caller be substituted for the single-vector one without changing a search result.

func TurboQuantDistanceGeneric

func TurboQuantDistanceGeneric(query []float32, tqData []byte, dim int, pow2 int, bitsPerAngle int) (float32, error)

func TurboQuantDistanceNEON

func TurboQuantDistanceNEON(query []float32, tqData []byte, dim int, pow2 int, bitsPerAngle int) (float32, error)

TurboQuantDistanceNEON is the NEON-optimized version of TQ distance.

func TurboQuantPolarTransformAVX2

func TurboQuantPolarTransformAVX2(src []float32, dstRadii []float32, dstAngles []float32)

TurboQuantPolarTransformAVX2 is the AVX2-optimized version of the polar transform stage.

func TurboQuantPolarTransformNEON

func TurboQuantPolarTransformNEON(src []float32, dstRadii []float32, dstAngles []float32)

TurboQuantPolarTransformNEON is the NEON-optimized version of the polar transform stage.

func Uint8ToFloat32

func Uint8ToFloat32(src []uint8, dst []float32)

Uint8ToFloat32 converts a slice of uint8 to float32 using SIMD if available.

func Uint16ToFloat32

func Uint16ToFloat32(src []uint16, dst []float32)

Uint16ToFloat32 converts a slice of uint16 to float32 using SIMD if available.

func Uint32ToFloat32

func Uint32ToFloat32(src []uint32, dst []float32)

Uint32ToFloat32 converts a slice of uint32 to float32 using SIMD if available.

func UnpackTQ2

func UnpackTQ2(src []byte, dst []float32, scale, bias float32)

UnpackTQ2 unpacks 2-bit TurboQuant data.

func UnpackTQ2AVX2

func UnpackTQ2AVX2(src []byte, dst []float32, scale, bias float32)

UnpackTQ2AVX2 is implemented in assembly.

func UnpackTQ2AVX512

func UnpackTQ2AVX512(src []byte, dst []float32, scale, bias float32)

AVX-512 stubs

func UnpackTQ2AVX512VBMI

func UnpackTQ2AVX512VBMI(src []byte, dst []float32, scale, bias float32)

UnpackTQ2AVX512VBMI decodes a 2-bit TurboQuant payload.

Like PackTQ2AVX512VBMI, the VBMI kernel is not dispatched. It disagrees with UnpackTQ2Generic on bit order: byte 0x01 decodes to -3.1415927, which is code 0, where the generic unpacker decodes it to -1.0471976, which is code 1. The packer and the unpacker are two halves of one format, so leaving one of them correct and the other not would be worse than leaving both alone.

The delegation is to UnpackTQ2 rather than to UnpackTQ2AVX512: the raw AVX-512 unpack kernel disagrees with UnpackTQ2Generic on bit order for 172 of 256 elements, and UnpackTQ2 - the entry point the index actually uses - agrees with generic, so it is the reference for what these kernels are supposed to mean. None of these three symbols is called from production code; they are reachable only from tests, which is why the disagreement went unnoticed.

See the note on PackTQ2AVX512VBMI and docs/roadmap.md item 10.

func UnpackTQ2Generic

func UnpackTQ2Generic(src []byte, dst []float32, scale, bias float32)

func UnpackTQ2NEON

func UnpackTQ2NEON(src []byte, dst []float32, scale, bias float32)

func UnpackTQ4

func UnpackTQ4(src []byte, dst []float32, scale, bias float32)

UnpackTQ4 unpacks 4-bit TurboQuant data.

func UnpackTQ4AVX2

func UnpackTQ4AVX2(src []byte, dst []float32, scale, bias float32)

UnpackTQ4AVX2 is implemented in assembly.

func UnpackTQ4AVX512

func UnpackTQ4AVX512(src []byte, dst []float32, scale, bias float32)

func UnpackTQ4Generic

func UnpackTQ4Generic(src []byte, dst []float32, scale, bias float32)

func UnpackTQ4NEON

func UnpackTQ4NEON(src []byte, dst []float32, scale, bias float32)

func UnpackTQ8

func UnpackTQ8(src []byte, dst []float32, scale, bias float32)

UnpackTQ8 unpacks 8-bit TurboQuant data.

func UnpackTQ8AVX2

func UnpackTQ8AVX2(src []byte, dst []float32, scale, bias float32)

UnpackTQ8AVX2 is implemented in assembly.

func UnpackTQ8AVX512

func UnpackTQ8AVX512(src []byte, dst []float32, scale, bias float32)

func UnpackTQ8Generic

func UnpackTQ8Generic(src []byte, dst []float32, scale, bias float32)

func UnpackTQ8NEON

func UnpackTQ8NEON(src []byte, dst []float32, scale, bias float32)

func ValidateSIMDKernels

func ValidateSIMDKernels() error

ValidateSIMDKernels runs a known-answer test for the active distance kernels. If the result is incorrect (which can happen when AVX-512 instructions trap in virtualised environments), this function returns an error so callers can fall back to a safer implementation.

The reference case is a 128-dim L2 distance between a zero vector and a vector of all-ones, which should equal sqrt(128) ≈ 11.3137.

Types

type ActivationDispatch

type ActivationDispatch struct {
	Sigmoid func(src, dst []float32)
	Softmax func(src, dst []float32)
	Exp     func(src, dst []float32)
	Log     func(src, dst []float32)
}

ActivationDispatch holds non-linear activation kernels.

type BatchDispatch

type BatchDispatch struct {
	EuclideanDistanceBatch     distanceBatchFunc
	CosineDistanceBatch        distanceBatchFunc
	DotProductBatch            distanceBatchFunc
	EuclideanDistanceBatchFlat distanceBatchFlatFunc
	L2SquaredDistanceBatch     distanceBatchFunc
	TurboQuantDistanceBatch    distanceTQBatchFunc

	// Batch processing (GraphRAG expansion)
	AccumulateWeightedScatter func(dst []float32, targets []uint32, weights []float32, factor float32)

	// Sparse Search
	BM25ScoreBatch func(tfs []int, docLengths []int, avgDL, idf, k1, b float32) []float32

	// Geospatial
	HaversineBatch haversineBatchFunc
}

BatchDispatch holds batch and high-throughput vector processing routines.

type CPUFeatures

type CPUFeatures struct {
	Vendor        string
	HasAVX2       bool
	HasAVX512     bool
	HasVNNI       bool // AVX512-VNNI
	HasAVXVNNI    bool // AVX-VNNI (Alder Lake+)
	HasAVX512FP16 bool // AVX512-FP16 (Sapphire Rapids+)
	HasVBMI       bool // AVX512-VBMI (Ice Lake+)
	HasNEON       bool
	HasDotProd    bool // ARM64 FEAT_DotProd (udot/sdot)
	HasSVE        bool // ARM64 SVE (Graviton 3/4)
	HasSVE2       bool // ARM64 SVE2 (Graviton 3/4, Grace Hopper)
	HasAMX        bool // AMX-TILE (Sapphire Rapids+)
	HasAMXINT8    bool // AMX-INT8 tile dot product
	HasAMXBF16    bool // AMX-BF16 tile dot product
	HasAMXFP16    bool // AMX-FP16 tile dot product (Granite Rapids+)
	HasAMXCOMPLEX bool // AMX-COMPLEX (Granite Rapids+)
}

CPUFeatures contains detected CPU SIMD capabilities

func GetCPUFeatures

func GetCPUFeatures() CPUFeatures

GetCPUFeatures returns the detected CPU capabilities

type CompareOp

type CompareOp int

CompareOp represents a comparison operator for SIMD filters

const (
	// CompareEq represents equality (==).
	CompareEq CompareOp = iota
	// CompareNeq represents inequality (!=).
	CompareNeq
	// CompareGt represents greater than (>).
	CompareGt
	// CompareGe represents greater than or equal to (>=).
	CompareGe
	// CompareLt represents less than (<).
	CompareLt
	// CompareLe represents less than or equal to (<=).
	CompareLe
)

type CompatibilityLayer

type CompatibilityLayer struct {
	// contains filtered or unexported fields
}

CompatibilityLayer manages optimizations and migration paths for V23 compatibility.

func NewCompatibilityLayer

func NewCompatibilityLayer() *CompatibilityLayer

NewCompatibilityLayer creates a new CompatibilityLayer instance.

func (*CompatibilityLayer) EnableV23Optimizations

func (scl *CompatibilityLayer) EnableV23Optimizations()

EnableV23Optimizations enables V23 specific SIMD optimizations.

func (*CompatibilityLayer) EnhancedBatchOperations

func (scl *CompatibilityLayer) EnhancedBatchOperations() error

EnhancedBatchOperations applies enhanced batch operations for V23.

func (*CompatibilityLayer) GetOptimizationLevel

func (scl *CompatibilityLayer) GetOptimizationLevel() string

GetOptimizationLevel returns a string representation of the current optimization level.

func (*CompatibilityLayer) GetPerformanceMetrics

func (scl *CompatibilityLayer) GetPerformanceMetrics() PerformanceMetrics

GetPerformanceMetrics returns the current performance metrics.

func (*CompatibilityLayer) GetV23MigrationPath

func (scl *CompatibilityLayer) GetV23MigrationPath() []string

GetV23MigrationPath returns the list of migration steps for V23.

func (*CompatibilityLayer) IsV23Enabled

func (scl *CompatibilityLayer) IsV23Enabled() bool

IsV23Enabled returns true if V23 optimizations are currently enabled.

func (*CompatibilityLayer) PrepareForV23

func (scl *CompatibilityLayer) PrepareForV23() error

PrepareForV23 prepares the system for V23 migration.

func (*CompatibilityLayer) UpdatePerformanceMetrics

func (scl *CompatibilityLayer) UpdatePerformanceMetrics(pre, post float64)

UpdatePerformanceMetrics updates the performance metrics with new data.

func (*CompatibilityLayer) V23InstructionSetEnhancements

func (scl *CompatibilityLayer) V23InstructionSetEnhancements() error

V23InstructionSetEnhancements applies instruction set enhancements for V23.

func (*CompatibilityLayer) V23MemoryLayoutOptimizations

func (scl *CompatibilityLayer) V23MemoryLayoutOptimizations() error

V23MemoryLayoutOptimizations applies memory layout optimizations for V23.

func (*CompatibilityLayer) V23VectorizedOperations

func (scl *CompatibilityLayer) V23VectorizedOperations() error

V23VectorizedOperations applies vectorized operations for V23.

func (*CompatibilityLayer) V23ZeroCopyOptimizations

func (scl *CompatibilityLayer) V23ZeroCopyOptimizations() error

V23ZeroCopyOptimizations applies zero-copy optimizations for V23.

func (*CompatibilityLayer) ValidateV23Readiness

func (scl *CompatibilityLayer) ValidateV23Readiness() bool

ValidateV23Readiness validates if the system is ready for V23.

type Context

type Context struct {
	// Implementation is the name of the SIMD instruction set being used (e.g., "avx512", "neon").
	Implementation string
	// Calls tracks the number of SIMD operations performed within this context.
	Calls int64
}

Context tracks SIMD operations within a logical task (e.g., indexing a batch) to avoid frequent global metric increments and provides context for kernel selection.

func (*Context) RecordCall

func (c *Context) RecordCall()

RecordCall increments the local call counter for the context. This is not thread-safe.

type ConversionDispatch

type ConversionDispatch struct {
	Int8ToFloat32    func(src []int8, dst []float32)
	Uint8ToFloat32   func(src []uint8, dst []float32)
	Int16ToFloat32   func(src []int16, dst []float32)
	Uint16ToFloat32  func(src []uint16, dst []float32)
	Int32ToFloat32   func(src []int32, dst []float32)
	Uint32ToFloat32  func(src []uint32, dst []float32)
	Float16ToFloat32 func(src []float16.Num, dst []float32)
}

ConversionDispatch holds numerical type casting and normalization kernels.

type DataType

type DataType int

DataType is a local redeclaration of VectorDataType to avoid circular imports. It must stay in sync with the mapping in internal/store if used there.

const (
	// DataTypeFloat32 represents IEEE 754 single-precision floating point.
	DataTypeFloat32 DataType = iota
	// DataTypeFloat16 represents IEEE 754 half-precision floating point.
	DataTypeFloat16
	// DataTypeInt8 represents 8-bit signed integer.
	DataTypeInt8
	// DataTypeUint8 represents 8-bit unsigned integer.
	DataTypeUint8
	// DataTypeInt16 represents 16-bit signed integer.
	DataTypeInt16
	// DataTypeUint16 represents 16-bit unsigned integer.
	DataTypeUint16
	// DataTypeInt32 represents 32-bit signed integer.
	DataTypeInt32
	// DataTypeUint32 represents 32-bit unsigned integer.
	DataTypeUint32
	// DataTypeInt64 represents 64-bit signed integer.
	DataTypeInt64
	// DataTypeUint64 represents 64-bit unsigned integer.
	DataTypeUint64
	// DataTypeFloat64 represents IEEE 754 double-precision floating point.
	DataTypeFloat64
	// DataTypeComplex64 represents complex number with two float32s.
	DataTypeComplex64
	// DataTypeComplex128 represents complex number with two float64s.
	DataTypeComplex128
	// DataTypeInt4 represents 4-bit packed signed integer.
	DataTypeInt4
	// DataTypeInt2 represents 2-bit packed signed integer.
	DataTypeInt2
)

func GetDataType

func GetDataType[T any]() DataType

GetDataType returns the DataType for a given type T.

func (DataType) String

func (d DataType) String() string

type DistanceKernel

type DistanceKernel[T any] func(a, b []T) (float32, error)

DistanceKernel is a generic distance function type for cached kernels.

func GetKernel

func GetKernel[T any](metric MetricType, dims int) DistanceKernel[T]

GetKernel resolves the best available kernel for a given metric, type, and dimension. It returns a typed DistanceKernel that can be cached at the dataset level to avoid recurring registry lookups and interface assertions on hot paths.

type Float16Compatibility

type Float16Compatibility struct {
	// contains filtered or unexported fields
}

Float16Compatibility provides compatibility helpers for float16 operations.

func NewFloat16Compatibility

func NewFloat16Compatibility(f float16.Num) *Float16Compatibility

NewFloat16Compatibility creates a new Float16Compatibility instance.

func (*Float16Compatibility) GetBase

func (fc *Float16Compatibility) GetBase() float16.Num

GetBase returns the underlying float16 number.

func (*Float16Compatibility) V23EnhancedConversion

func (fc *Float16Compatibility) V23EnhancedConversion() float32

V23EnhancedConversion performs an enhanced conversion from float16 to float32.

type GlobalContext

type GlobalContext struct {
	// Implementation is the name of the SIMD instruction set being used.
	Implementation string
	// Calls tracks the total number of SIMD operations performed globally.
	Calls atomic.Int64
}

GlobalContext can be used for tasks that span multiple goroutines where atomic updates are necessary for tracking call counts across the entire system.

func (*GlobalContext) RecordCall

func (c *GlobalContext) RecordCall()

RecordCall increments the global call counter in a thread-safe manner using atomic operations.

type HadamardTransformer

type HadamardTransformer struct {
	// contains filtered or unexported fields
}

HadamardTransformer manages state for Fast Walsh-Hadamard Transforms. It can be reused to avoid allocations.

func NewHadamardTransformer

func NewHadamardTransformer(pow2 int) *HadamardTransformer

NewHadamardTransformer creates a new transformer for the given power-of-2 size.

func (*HadamardTransformer) InverseTransform

func (h *HadamardTransformer) InverseTransform(a []float32) error

InverseTransform applies the inverse FWHT. Since FWHT is its own inverse (up to a scaling factor), this just calls Transform and optionally scales.

func (*HadamardTransformer) Transform

func (h *HadamardTransformer) Transform(a []float32) error

Transform applies an in-place Fast Walsh-Hadamard Transform to the slice.

type ImplementationDispatch

ImplementationDispatch holds all SIMD function pointers for a specific implementation, grouped into typed sub-dispatchers while preserving flat field access via struct embedding.

type JitRuntime

type JitRuntime struct {
	// contains filtered or unexported fields
}

JitRuntime provides a WebAssembly-based JIT execution environment for SIMD kernels.

func (*JitRuntime) Euclidean

func (rt *JitRuntime) Euclidean(a, b []float32) float32

Euclidean calculates the Euclidean distance between two vectors using JIT.

func (*JitRuntime) EuclideanBatch

func (rt *JitRuntime) EuclideanBatch(query []float32, vectors [][]float32) ([]float32, error)

EuclideanBatch calculates Euclidean distances for a batch of vectors against a query using JIT.

func (*JitRuntime) EuclideanBatchInto

func (rt *JitRuntime) EuclideanBatchInto(query []float32, vectors [][]float32, results []float32) error

EuclideanBatchInto calculates Euclidean distances for a batch into a pre-allocated results slice using JIT.

type KernelKey

type KernelKey struct {
	// Metric specifies the distance metric.
	Metric MetricType
	// DataType specifies the vector element data type.
	DataType DataType
	// Dims specifies the vector dimension (0 means any/generic).
	Dims int
}

KernelKey identifies a specific kernel implementation.

type KernelRegistry

type KernelRegistry struct {
	// contains filtered or unexported fields
}

KernelRegistry manages the collection of available SIMD kernels.

func (*KernelRegistry) Get

func (r *KernelRegistry) Get(metric MetricType, dt DataType, dims int) any

Get retrieves a kernel from the registry. If a dimension-specific kernel isn't found, it falls back to the generic (Dims=0) one.

func (*KernelRegistry) Register

func (r *KernelRegistry) Register(metric MetricType, dt DataType, dims int, kernel any)

Register adds a kernel to the registry.

type MathDispatch

type MathDispatch struct {
	Sum    func(src []float32) float32
	Max    func(src []float32) float32
	Min    func(src []float32) float32
	MatMul func(a, b []float32, m, n, k int, dst []float32)
	Sin    func(src, dst []float32)
	Cos    func(src, dst []float32)
	Sincos func(src, sinDst, cosDst []float32)
	Sqrt   func(src, dst []float32)
	Atan2  func(y, x, dst []float32)
	ArgMax func(src []float32) int
	ArgMin func(src []float32) int
}

MathDispatch holds reductions, linear algebra, and transcendental functions.

type MetricDispatch

type MetricDispatch struct {
	// Core distance functions
	EuclideanDistance distanceFunc
	CosineDistance    distanceFunc
	DotProduct        distanceFunc

	// F16 distance functions
	EuclideanDistanceF16 distanceF16Func
	CosineDistanceF16    distanceF16Func
	DotProductF16        distanceF16Func

	// Specialized functions for fixed dimensions
	EuclideanDistance128  distanceFunc
	EuclideanDistance384  distanceFunc
	EuclideanDistance768  distanceFunc
	EuclideanDistance1024 distanceFunc
	EuclideanDistance1536 distanceFunc
	EuclideanDistance3072 distanceFunc

	DotProduct128  distanceFunc
	DotProduct384  distanceFunc
	DotProduct768  distanceFunc
	DotProduct1024 distanceFunc
	DotProduct1536 distanceFunc
	DotProduct3072 distanceFunc

	// L2Squared specialized (no sqrt) for fixed dimensions
	L2SquaredDistance128  distanceFunc
	L2SquaredDistance384  distanceFunc
	L2SquaredDistance768  distanceFunc
	L2SquaredDistance1024 distanceFunc
	L2SquaredDistance3072 distanceFunc

	// More distances
	ManhattanDistance  distanceFunc
	ChebyshevDistance  distanceFunc
	BrayCurtisDistance distanceFunc
	L2SquaredDistance  distanceFunc
}

MetricDispatch holds function pointers for vector distance and similarity metrics.

type MetricType

type MetricType int

MetricType defines the distance metric to use.

const (
	// MetricEuclidean uses the L2 norm (square root of sum of squares).
	MetricEuclidean MetricType = iota
	// MetricCosine uses 1 - cosine similarity.
	MetricCosine
	// MetricDotProduct uses the sum of products of corresponding elements.
	MetricDotProduct
	// MetricManhattan uses the L1 norm (sum of absolute differences).
	MetricManhattan
	// MetricChebyshev uses the L-infinity norm (maximum absolute difference).
	MetricChebyshev
	// MetricBrayCurtis uses the Bray-Curtis dissimilarity.
	MetricBrayCurtis
	// MetricL2Squared uses the squared Euclidean distance.
	MetricL2Squared
)

func (MetricType) String

func (m MetricType) String() string

type PerformanceMetrics

type PerformanceMetrics struct {
	PreMigrationOpsPerSecond  float64
	PostMigrationOpsPerSecond float64
	ImprovementRatio          float64
}

PerformanceMetrics tracks performance improvements from V23 optimizations.

type QuantDispatch

type QuantDispatch struct {
	UnpackTQ2 func(src []byte, dst []float32, scale, bias float32)
	UnpackTQ4 func(src []byte, dst []float32, scale, bias float32)
	UnpackTQ8 func(src []byte, dst []float32, scale, bias float32)
	PackTQ2   func(src []float32, dst []byte)
	PackTQ4   func(src []float32, dst []byte)
	PackTQ8   func(src []float32, dst []byte)
}

QuantDispatch holds TurboQuant bit-packing and unpacking kernels.

type SQ8ChannelCalibration

type SQ8ChannelCalibration struct {
	Dims   int
	Mins   []float32
	Maxs   []float32
	Scales []float32 // 255.0 / (Max - Min)
	InvSq  []float32 // 1.0 / (Scale * Scale) for fast weighted distance evaluation
}

SQ8ChannelCalibration contains per-channel calibration statistics for non-uniform scalar quantization of skewed high-dimensional embeddings.

func CalibrateSQ8Channels

func CalibrateSQ8Channels(vectors [][]float32, dims int) (*SQ8ChannelCalibration, error)

CalibrateSQ8Channels calculates per-channel empirical bounds with 3-sigma outlier clipping.

func NewSQ8ChannelCalibration

func NewSQ8ChannelCalibration(dims int) *SQ8ChannelCalibration

NewSQ8ChannelCalibration creates an empty calibration for dims dimensions.

type TurboQuantDistanceBatchFunc

type TurboQuantDistanceBatchFunc = distanceTQBatchFunc

TurboQuantDistanceBatchFunc is the function signature for batched TurboQuant distance.

func GetTurboQuantDistanceBatchFunc

func GetTurboQuantDistanceBatchFunc() TurboQuantDistanceBatchFunc

GetTurboQuantDistanceBatchFunc returns the optimal batched TQ distance function for the current CPU.

type TurboQuantDistanceFunc

type TurboQuantDistanceFunc func(query []float32, tqData []byte, dim int, pow2 int, bitsPerAngle int) (float32, error)

TurboQuantDistanceFunc calculates the distance between a query and a TQ-encoded vector.

func GetTurboQuantDistanceFunc

func GetTurboQuantDistanceFunc() TurboQuantDistanceFunc

GetTurboQuantDistanceFunc returns the optimal TQ distance function for the current CPU. The result is cached at init time to avoid repeated feature detection in the hot path.

type TurboQuantPolarTransformFunc

type TurboQuantPolarTransformFunc func(src []float32, dstRadii []float32, dstAngles []float32)

TurboQuantPolarTransform calculates the recursive polar transform for a vector. src: input vector (length n, power of 2) dstRadii: intermediate radii (length n/2) dstAngles: extracted angles (length n/2)

func GetTurboQuantPolarTransformFunc

func GetTurboQuantPolarTransformFunc() TurboQuantPolarTransformFunc

GetTurboQuantPolarTransformFunc returns the optimal TQ polar transform function for the current CPU.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL