Overview / Machine learning

VectorIndex

Beta

Embeddable nearest-neighbor search: hnswlib-style HNSW, with exact brute force alongside. Below about 10,000 vectors the automatic mode picks brute force.

Optional module: turn it on with -DETHEREAL_VECTORINDEX=ONInclude #include <ethereal/cpp/ml/vectorindex/distance.hpp>C layer

distance.hpp

#include <ethereal/cpp/ml/vectorindex/distance.hpp>

Distances of the Ml::VectorIndex module.

About 90% of the time of a search is spent here.

Every path and every platform gives the same bits. An index built with the same seed has to be the same graph on Linux and Windows, on x64 and ARM64 (spec 35 asks for it), and the graph depends on every distance comparison. So the sum has a canonical order: 32 lanes, lane k adds the elements i with i % 32 == k in increasing order, and the 32 lanes are always joined by the same tree (k + 16, then + 8, + 4, + 2, + 1). The scalar, SSE2 and AVX2 paths all do exactly that, and the tail of a dimension that is not a multiple of 32 adds zeros, which is exact. With 32 lanes AVX2 has four independent sum chains. With 16 it was bound by the add latency (measured).

No FMA, on purpose. A fused 'a*b + c' rounds once, a separate one rounds twice. SSE2 has no FMA, and a path with it and one without would build different graphs. The cost is measured in 'ml.vectorindex.measurements' (in a search the distance is bound by memory).

The quantized (int8) and binary distances use integer math and are exact everywhere.

enum

EMetric

Ethereal::Ml::VectorIndex#
C++
enum class   EMetric : ETL_UINT32
{
    /// @brief  Squared euclidean distance. The root does not change the order.
    eL2 = 0,

    /// @brief  1 - <a, b>, the hnswlib convention. May be negative.
    eInnerProduct,

    /// @brief  1 - <a, b> over normalized vectors. The index normalizes them on input.
    eCosine,

    /// @brief  Number of different bits. Vectors come in as floats, > 0 is bit 1.
    eHamming,

    /// @brief  1 - |a and b| / |a or b| over bits.
    eJaccard
};

Distance metric. In all of them, smaller is closer.

enum

EKernelPath

Ethereal::Ml::VectorIndex#
C++
enum class   EKernelPath : ETL_UINT32
{
    /// @brief  Plain C++.
    eScalar = 0,

    /// @brief  SSE2 kernels.
    eSse2,

    /// @brief  AVX2 kernels.
    eAvx2
};

Kernel path in use.

function

ActiveKernelPath

Ethereal::Ml::VectorIndex#
EKernelPath ActiveKernelPath() noexcept;

Path the distances use. Resolved once, the 'Cpu' ceiling can lower it.

function

L2Squared

Ethereal::Ml::VectorIndex#
float L2Squared( const float * pA, const float * pB, std::size_t n ) noexcept;

Squared euclidean distance, in the canonical order, on the active path.

pA
First vector.
pB
Second vector.
n
Number of elements.
The distance.
function

Dot

Ethereal::Ml::VectorIndex#
float Dot( const float * pA, const float * pB, std::size_t n ) noexcept;

Dot product, in the canonical order, on the active path.

pA
First vector.
pB
Second vector.
n
Number of elements.
The dot product.
function

L2SquaredScalar

Ethereal::Ml::VectorIndex#
float L2SquaredScalar( const float * pA, const float * pB, std::size_t n ) noexcept;

Squared euclidean distance, always on the scalar path.

The canonical order that the SIMD paths must match bit for bit.

pA
First vector.
pB
Second vector.
n
Number of elements.
The distance.
function

DotScalar

Ethereal::Ml::VectorIndex#
float DotScalar( const float * pA, const float * pB, std::size_t n ) noexcept;

Dot product, always on the scalar path.

The canonical order that the SIMD paths must match bit for bit.

pA
First vector.
pB
Second vector.
n
Number of elements.
The dot product.
function

L2SquaredU8

Ethereal::Ml::VectorIndex#
ETL_INT32 L2SquaredU8( const ETL_UINT8 * pA, const ETL_UINT8 * pB, std::size_t n ) noexcept;

Squared euclidean distance of 8 bit codes (0..255). Exact, in 32 bit integers.

pA
First vector of codes.
pB
Second vector of codes.
n
Number of codes.
The distance.
function

DotU8

Ethereal::Ml::VectorIndex#
ETL_INT32 DotU8( const ETL_UINT8 * pA, const ETL_UINT8 * pB, std::size_t n ) noexcept;

Dot product of 8 bit codes (0..255). Exact, in 32 bit integers.

pA
First vector of codes.
pB
Second vector of codes.
n
Number of codes.
The dot product.
function

Hamming

Ethereal::Ml::VectorIndex#
ETL_UINT32 Hamming( const ETL_UINT64 * pA, const ETL_UINT64 * pB, std::size_t nWords ) noexcept;

Number of different bits, in 64 bit words.

pA
First bit vector.
pB
Second bit vector.
nWords
Number of 64 bit words.
The number of different bits.
function

Jaccard

Ethereal::Ml::VectorIndex#
float Jaccard( const ETL_UINT64 * pA, const ETL_UINT64 * pB, std::size_t nWords ) noexcept;

1 - |a and b| / |a or b|, in 64 bit words.

pA
First bit vector.
pB
Second bit vector.
nWords
Number of 64 bit words.
The distance. Two empty vectors give 0.
function

Normalize

Ethereal::Ml::VectorIndex#
void Normalize( std::span< float > V ) noexcept;

Scales the vector to a 2-norm of 1. The null vector stays null.

The norm is summed in the canonical order, so the result is the same everywhere.

V
The vector, changed in place.
function

Distance

Ethereal::Ml::VectorIndex#
float Distance( EMetric e, const float * pA, const float * pB, std::size_t n ) noexcept;

Distance of a metric between two float vectors.

eHamming and eJaccard compare the bits 'x > 0'.

e
The metric.
pA
First vector.
pB
Second vector.
n
Number of elements.
The distance.

vector_index.hpp

#include <ethereal/cpp/ml/vectorindex/vector_index.hpp>

Vector neighbor search for the Ml::VectorIndex module.

Embeddable, with no dependencies (spec 35). The index is an HNSW (hierarchical navigable small world graphs, by Malkov and Yashunin) with an exact brute force search next to it. The brute force is the ground truth of every recall number, and below ~10 000 vectors it is faster than any graph, so the automatic mode picks it.

Lock free reads, one writer at a time (the Storage model). Searches run on any number of threads, also while a writer adds or removes. Writes wait for each other. The capacity is reserved in Init, so nothing moves under a reader, and the neighbor lists are read and written atomically. A reader may or may not see a new node, but never a broken state. Compact, MakeWritable and Load are exclusive (no searches at the same time).

Removing leaves a tombstone. HNSW cannot remove a node cheaply. The removed node stays in the graph (searches walk through it) but is never returned. With many tombstones recall and speed drop (measured in the README), and Compact rebuilds the graph with the live nodes only.

No allocations in a search. The scratch of each search (the visited set, the two heaps, the query) comes from a pool reserved in Init, one per concurrent search.

Same bits on every platform. The distances have a canonical order (see distance.hpp), the level of each node comes from a seeded generator, and ties are broken by id. The same index built on Linux and on Windows is the same file.

enum

EStorage

Ethereal::Ml::VectorIndex#
C++
enum class   EStorage : ETL_UINT32
{
    /// @brief  As they come in.
    eFloat32 = 0,

    /// @brief  Quantized to 8 bits. 4x less memory, the recall lost is measured in the README.
    eInt8
};

How vectors are stored.

enum

ESearchMode

Ethereal::Ml::VectorIndex#
C++
enum class   ESearchMode : ETL_UINT32
{
    /// @brief  Brute force below 'uFlatThreshold' live vectors, the graph above.
    eAuto = 0,

    /// @brief  Always the graph.
    eGraph,

    /// @brief  Always the brute force, which is exact.
    eFlat
};

How a search runs.

struct

IMetric

Ethereal::Ml::VectorIndex#
C++
struct   IMetric
{
    /// @brief  Distance between two vectors of n floats. Smaller is closer.
    ///
    virtual float Distance( const float * pA, const float * pB, std::size_t n ) ETL_NOEXCEPT = 0;

    /// @brief  Destructor.
    ///
    virtual ~IMetric() = default;
};

A metric supplied by the integrator.

Loses the SIMD kernels: every distance is a virtual call into the integrator's code.

struct

SIndexParams

Ethereal::Ml::VectorIndex#
C++
struct   SIndexParams   final
{
    /// @brief  Number of floats per vector.
    ETL_UINT32        uDimension = 0u;

    /// @brief  Distance metric.
    EMetric            eMetric = EMetric::eL2;

    /// @brief  Maximum number of vectors, reserved in Init.
    ETL_UINT64        uCapacity = 0u;

    /// @brief  Neighbors per node on the upper layers (the bottom layer has 2M).
    ///             More gives better recall and more memory. 12 to 48 is usual.
    ETL_UINT32        uM = 16u;

    /// @brief  Search width while building. More gives a better graph and a slower build.
    ETL_UINT32        uEfConstruction = 200u;

    /// @brief  Seed of the node levels. The same seed gives the same graph.
    ETL_UINT64        uSeed = 0x5EEDu;

    /// @brief  How vectors are stored.
    EStorage        eStorage = EStorage::eFloat32;

    /// @brief  Largest 'uEf' of a search. The scratch is sized by it.
    ETL_UINT32        uMaxEf = 512u;

    /// @brief  Searches that can run at the same time, each with its own scratch.
    ETL_UINT32        uConcurrentSearches = 16u;

    /// @brief  Below this many live vectors, the automatic mode uses brute force.
    ETL_UINT32        uFlatThreshold = 10000u;

    /// @brief  Also stores a binary code of each vector (the sign of x minus the
    ///             trained mean of the dimension), used as the brute force prefilter.
    ///             Only with eFloat32.
    bool            bBinaryPrefilter = false;

    /// @brief  Custom metric. Only with eFloat32. Must outlive the index.
    IMetric *        pCustomMetric = nullptr;
};

Index parameters.

struct

SSearchParams

Ethereal::Ml::VectorIndex#
C++
struct   SSearchParams   final
{
    /// @brief  Search width on the graph, the recall versus latency knob.
    ///             max( uEf, k ) is used.
    ETL_UINT32        uEf = 64u;

    /// @brief  How the search runs.
    ESearchMode        eMode = ESearchMode::eAuto;

    /// @brief  In a filtered search, below this fraction of passing vectors
    ///             (estimated from a sample) brute force is used, since the graph would
    ///             visit almost everything. The measured crossover was 5% (100 000 x 128,
    ///             ml.vectorindex.measurements). It depends on size and dimension.
    float            fFlatBelowSelectivity = 0.05f;

    /// @brief  In a brute force with the binary prefilter, candidates per result to
    ///             rescore with the exact distance. 0 disables the prefilter.
    ETL_UINT32        uBinaryRescore = 0u;
};

Search parameters.

struct

SSearchResult

Ethereal::Ml::VectorIndex#
C++
struct   SSearchResult   final
{
    /// @brief  Id of the vector.
    ETL_UINT64        uId = 0u;

    /// @brief  Distance to the query, in the index metric.
    float            fDistance = 0.0f;

    /// @brief  Always zero. The padding after fDistance made into a member, so that a
    ///             result has no undefined bytes: two equal results compare equal with memcmp.
    ///
    /// @details  As implicit padding, those 4 bytes held whatever the compiler copied
    ///               there, and on 32 bit MSVC the same search gave different bytes on
    ///               each thread. The layout is the same as before.
    ///
    ETL_UINT32        uReserved = 0u;
};

One search result.

struct

SVectorBatch

Ethereal::Ml::VectorIndex#
C++
struct   SVectorBatch   final
{
    /// @brief  First float of the first row.
    const float *    pData = nullptr;

    /// @brief  Number of rows.
    std::size_t        uCount = 0u;

    /// @brief  Floats from one row to the next. At least the dimension.
    std::size_t        uStride = 0u;
};

Many vectors in a row: 'uCount' rows of 'uStride' floats.

class

CFilterRef

Ethereal::Ml::VectorIndex#
class CFilterRef final

Non owning reference to a 'bool( ETL_UINT64 id )' predicate.

Does not allocate. The 'function_ref' of the spec.

struct

SGraphReport

Ethereal::Ml::VectorIndex#
C++
struct   SGraphReport   final
{
    /// @brief  Occupied slots, live and removed.
    ETL_UINT64        uNodes = 0u;

    /// @brief  Live nodes.
    ETL_UINT64        uLive = 0u;

    /// @brief  Highest node level.
    ETL_UINT32        uMaxLevel = 0u;

    /// @brief  Nodes with level >= l, for each l.
    ETL_UINT64        aLevelCounts[ 32 ] = {};

    /// @brief  Lists above M (or 2M on the bottom layer).
    ETL_UINT64        uOverfull = 0u;

    /// @brief  Links from a node to itself.
    ETL_UINT64        uSelfLoops = 0u;

    /// @brief  Links that appear twice in a list.
    ETL_UINT64        uDuplicates = 0u;

    /// @brief  Links outside the occupied slots, or to a node without that layer.
    ETL_UINT64        uBadLinks = 0u;

    /// @brief  Nodes reachable from the entry point on the bottom layer.
    ETL_UINT64        uReachable = 0u;

    /// @brief  Nothing wrong above. Reachability is only reported.
    bool            bOk = false;
};

What the graph checker found.

class

CVectorIndex

Ethereal::Ml::VectorIndex#

HNSW index with brute force search next to it.

class CVectorIndex final
constructor

CVectorIndex

#
CVectorIndex() noexcept;

Default constructor. Call Init or Load before use.

constructor

CVectorIndex

#
CVectorIndex( CVectorIndex && Other ) noexcept;

Move constructor. Other is left empty.

operator

operator=

#
CVectorIndex & operator=( CVectorIndex && Other ) noexcept;

Move assignment. Other is left empty.

function

Init

#
EStatus Init( const SIndexParams & Params );

Validates the parameters and reserves everything.

The vectors, the graph, the id map and the scratch pool.

Params
Index parameters.
eOk, eInvalidArgument or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
function

Train

#
EStatus Train( const SVectorBatch & Sample );

Learns from a sample what the storage needs. Before the first Add.

With eInt8, the quantization range (smallest and largest value of the sample). With the binary prefilter, the mean of each dimension.

Sample
Sample vectors.
eOk, eInvalidArgument, eNotLoaded or eUnsupported.
function

Add

#
EStatus Add( ETL_UINT64 uId, std::span< const float > Vector ) noexcept;

Adds a vector.

uId
Id of the vector. Must not be in the index.
Vector
The vector, with the index dimension.
eOk, eInvalidArgument, eFeatureMismatch, eTableFull, eNotLoaded or eUnsupported.
function

AddBatch

#
EStatus AddBatch( std::span< const ETL_UINT64 > Ids, const SVectorBatch & Batch ) noexcept;

Adds many vectors, in order. Stops at the first error.

Ids
One id per row.
Batch
The vectors.
eOk, or the error of the first vector that failed.
function

Remove

#
EStatus Remove( ETL_UINT64 uId ) noexcept;

Removes a vector. It becomes a tombstone.

uId
Id of the vector.
eOk, eUnknownEntity, eNotLoaded or eUnsupported.
function

Update

#
EStatus Update( ETL_UINT64 uId, std::span< const float > Vector ) noexcept;

Removes and adds again: a new node with the same id.

uId
Id of the vector. Must be in the index.
Vector
The new vector.
eOk, eUnknownEntity, eTableFull (nothing changed) or the errors of Add.
function

SearchFiltered

#
EStatus SearchFiltered( std::span< const float > Query, std::size_t k, std::span< SSearchResult > Out, std::size_t * pCount, CFilterRef Filter, const SSearchParams & Params = SSearchParams() ) const noexcept;

Same as Search, only with the ids the filter lets through.

The filter is applied inside the graph search, which goes on until it has k that pass. With a very selective filter the search switches to brute force (see 'fFlatBelowSelectivity').

Query
The query vector.
k
Number of results wanted.
Out
Receives the results. Must have room for k.
pCount
Receives the number of results.
Filter
The id predicate.
Params
Search parameters.
eOk, or the errors of Search.
function

RangeSearch

#
EStatus RangeSearch( std::span< const float > Query, float fRadius, std::span< SSearchResult > Out, std::size_t * pCount, const SSearchParams & Params = SSearchParams() ) const noexcept;

All vectors closer than fRadius, as many as fit in Out.

The radius is in the metric, so with eL2 it is the squared radius. Exact on brute force. On the graph it is approximate: the ones a search as wide as Out finds.

Query
The query vector.
fRadius
The radius.
Out
Receives the results.
pCount
Receives the number of results.
Params
Search parameters.
eOk, or eBufferTooSmall when more than Out can hold were inside.
function

Compact

#
EStatus Compact();

Rebuilds the graph with the live nodes only. The slots of removed nodes become free again. Exclusive.

function

Save

#
EStatus Save( std::string_view sPath ) const;

Writes the index to a file.

sPath
File path.
eOk, eIoError, eNotLoaded, eInvalidArgument or eUnsupported.
function

Load

#
static EStatus Load( std::string_view sPath, CVectorIndex * pOut );

Maps a file, read only, with no parsing. Exclusive.

Validating the graph indices is the only pass over the file. A loaded index can only search. To write, call MakeWritable.

sPath
File path.
pOut
Receives the index.
eOk, eIoError, eTruncated, eCorrupt, eBadMagic, eVersionTooNew or eUnsupported. EStatus::eNotLicensed when the library is not licensed.
function

MakeWritable

#
EStatus MakeWritable( ETL_UINT64 uCapacity = 0u );

Copies a loaded index to its own memory and drops the mapping. Exclusive.

uCapacity
Slots of the copy. 0 keeps the ones it has.
eOk, eNotLoaded, eCorrupt or the errors of Init.
function

Size

#
std::size_t Size() const noexcept;

Number of live vectors.

function

Capacity

#
std::size_t Capacity() const noexcept;

Number of slots.

function

MemoryUsage

#
std::size_t MemoryUsage() const noexcept;

Bytes used by the index.

function

IsReadOnly

#
bool IsReadOnly() const noexcept;

true for a loaded index that was not made writable.

function

Params

#
const SIndexParams & Params() const noexcept;

Parameters of the index.

function

CheckGraph

#
EStatus CheckGraph( SGraphReport * pOut ) const;

Checks the graph: lists, links, levels and reachability. O(n M).

pOut
Receives the report.
eOk, eInvalidArgument or eNotLoaded.