Skip to content
Projets

Dicklesworthstone/fast_vector_similarity

Voir sur GitHub

À propos

High-performance vector similarity library in Rust with Python bindings: Spearman, Kendall, distance correlation, Jensen-Shannon, Hoeffding's D, and bootstrapped confidence intervals

Outils de développement

Comment ces chiffres sont mesurés

Progression mesurée des étoiles

in 24h
0
in 7 days
0
in 15 days
0
in 1 month
Historique en cours

Variations nettes sur des périodes qui se chevauchent, pas des totaux quotidiens. Les mesures absentes restent vides. Les étoiles indiquent l’intérêt, pas la qualité.

README.md

Original

Fast Vector Similarity Library

Introduction

The Fast Vector Similarity Library is a high-performance Rust-based tool for efficiently computing similarity measures between vectors. It is ideal for data analysis, machine learning, and statistical tasks where comparing vectors is essential. The library now includes several advanced measures, performance optimizations, and Python bindings, allowing seamless integration with Python workflows.

Features

Similarity Measures

The library implements a range of classical and modern similarity measures, including:

  1. Spearman's Rank-Order Correlation (spearman_rho)
  2. Kendall's Tau Rank Correlation (kendall_tau) (optimized for faster computation with large datasets)
  3. Approximate Distance Correlation (approximate_distance_correlation) (linear working storage)
  4. Jensen-Shannon Dependency Measure (jensen_shannon_dependency_measure) (revised for improved utility in dependency measurement)
  5. Hoeffding's D Measure (hoeffding_d)
  6. Normalized Mutual Information (normalized_mutual_information) (newly introduced for analyzing variable dependence)
  7. Cosine Similarity (cosine_similarity) (scale-safe directional similarity for embeddings)
  8. Full-Data Distance Correlation (distance_correlation) (deterministic O(n log n) dependence measurement)
  9. Pearson Product-Moment Correlation (pearson_correlation) (signed linear association after mean centering)

Bootstrapping Technique

The library includes robust bootstrapping functionality to estimate the distribution of similarity measures. Bootstrapping offers improved confidence in the results by randomly resampling the dataset multiple times.

For each measure, the summary removes floor(B / 4) scores from each tail, where B is the number of bootstrap replicates. It reports the mean and population standard deviation of the remaining scores. Both tails lose the same number of scores, including when B is not divisible by four; with two or three replicates, all scores are retained.

Performance Optimizations

Several enhancements have been introduced for optimal efficiency:

  • Parallel Processing: Utilizing the rayon crate for parallel computation, ensuring that operations scale with the number of CPU cores.
  • Efficient Algorithms: Algorithms like merge sort are used for inversion counting, which improves the speed of measures like Kendall's Tau.
  • Vectorized Operations: Many functions leverage vectorized operations using the ndarray crate to maximize performance in Rust.

All-measure scalar and bootstrap requests share compatible preparation: Spearman and Hoeffding reuse one pair of average-rank arrays. The same dominance-count sweep computes Hoeffding's joint ranks and Kendall's exact concordant, discordant, and tied pair counts. NMI and JSD reuse discretized labels and marginal statistics. Single-measure requests keep their scalar paths. The shared work preserves metric-specific random streams, logical observation order, undefined-value conventions, and bootstrap summaries and intervals.

Benchmarking and Verification

The library now includes a benchmarking suite that verifies the correctness of the numerical results while measuring performance gains from recent improvements. This ensures that any changes in computational speed do not affect accuracy (except in intended changes like the Jensen-Shannon measure).

Python Bindings

The Python interface exposes three JSON functions and reusable native search classes:

  • py_compute_vector_similarity_stats: For computing various vector similarity measures.
  • py_compute_bootstrapped_similarity_stats: For bootstrapping-based similarity calculations.
  • py_compute_batch_similarity_stats: For parallel query-to-corpus scoring or top-k search in one call.

All three functions return results in JSON format, making them easy to work with in Python environments.

CosineIndex keeps a prepared corpus in Rust and returns native Python lists. Use it for repeated cosine searches without serializing the corpus for each query. SimilarityIndex extends the same search engine to every supported metric, including reproducible single-query and many-query scoring and ranking.

Installation

Rust

Add the library to your Rust project by including it in your Cargo.toml file.

Python

The Python bindings can be installed directly from PyPI:

pip install fast_vector_similarity

Use with Text Embedding Vectors from LLMs

This library is highly compatible with modern language models like Llama2, enabling easy analysis of text embeddings. It integrates with the output of services like Llama2 Embeddings FastAPI Service and can handle high-dimensional embeddings (e.g., 4096-dimensional vectors).

Example Workflow

  1. Load Embeddings into a DataFrame: Convert text embeddings from a JSON format into a Pandas DataFrame.
  2. Compute Similarities: Use the Fast Vector Similarity Library to compute similarity measures between embeddings, leveraging the optimized functions.
  3. Analyze Results: Generate a ranked list of most similar vectors based on measures like Hoeffding's D.

Example Python Code

Here’s a Python snippet demonstrating the use of the library with large embedding vectors:

import time
import numpy as np
import json
import pandas as pd
import fast_vector_similarity as fvs
from random import choice

def convert_embedding_json_to_pandas_df(file_path):
    # Read the JSON file
    with open(file_path, 'r') as file:
        data = json.load(file)
    # Extract the text and embeddings
    texts = [item['text'] for item in data]
    embeddings = [item['embedding'] for item in data]
    # Determine the total number of vectors and the dimensions of each vector
    total_vectors = len(embeddings)
    vector_dimensions = len(embeddings[0]) if total_vectors > 0 else 0
    # Print the total number of vectors and dimensions
    print(f"Total number of vectors: {total_vectors}")
    print(f"Dimensions of each vector: {vector_dimensions}")
    # Convert the embeddings into a DataFrame
    df = pd.DataFrame(embeddings, index=texts)
    return df

def apply_fvs_to_vector(row_embedding, query_embedding):
    params = {
        "vector_1": query_embedding.tolist(),
        "vector_2": row_embedding.tolist(),
        "similarity_measure": "all"
    }
    similarity_stats_str = fvs.py_compute_vector_similarity_stats(json.dumps(params))
    return json.loads(similarity_stats_str)

def main():
    length_of_test_vectors = 15000
    print(f"Generating 2 test vectors of length {length_of_test_vectors}...")
    vector_1 = np.linspace(0., length_of_test_vectors - 1, length_of_test_vectors)
    vector_2 = vector_1 ** 0.2 + np.random.rand(length_of_test_vectors)
    print("Generated vector_1 using linear spacing and vector_2 using vector_1 with a power of 0.2 and some random noise.\n")

    similarity_measure = "all" # Or specify a particular measure
    params = {
        "vector_1": vector_1.tolist(),
        "vector_2": vector_2.tolist(),
        "similarity_measure": similarity_measure
    }
    
    # Time the exact similarity calculation
    print("Computing Exact Similarity Measures...")
    start_time_exact = time.time()
    similarity_stats_str = fvs.py_compute_vector_similarity_stats(json.dumps(params))
    similarity_stats_json = json.loads(similarity_stats_str)
    elapsed_time_exact = time.time() - start_time_exact
    print(f"Time taken for exact calculation: {elapsed_time_exact:.5f} seconds")

    # Print results
    print("_______________________________________________________________________________________________________________________________________________\n")
    print("Spearman's rho:", similarity_stats_json["spearman_rho"])
    print("Kendall's tau:", similarity_stats_json["kendall_tau"])
    print("Distance Correlation:", similarity_stats_json["approximate_distance_correlation"])
    print("Jensen-Shannon Dependency Measure:", similarity_stats_json["jensen_shannon_dependency_measure"])
    print("Normalized Mutual Information:", similarity_stats_json["normalized_mutual_information"])
    print("Hoeffding's D:", similarity_stats_json["hoeffding_d"])
    print("_______________________________________________________________________________________________________________________________________________\n")

    # Bootstrapped calculations
    number_of_bootstraps = 2000
    n = 15
    sample_size = int(length_of_test_vectors / n)

    print(f"Computing Bootstrapped Similarity Measures with {number_of_bootstraps} bootstraps and a sample size of {sample_size}...")
    start_time_bootstrapped = time.time()
    params_bootstrapped = {
        "x": vector_1.tolist(),
        "y": vector_2.tolist(),
        "sample_size": sample_size,
        "number_of_bootstraps": number_of_bootstraps,
        "similarity_measure": similarity_measure
    }
    bootstrapped_similarity_stats_str = fvs.py_compute_bootstrapped_similarity_stats(json.dumps(params_bootstrapped))
    bootstrapped_similarity_stats_json = json.loads(bootstrapped_similarity_stats_str)
    elapsed_time_bootstrapped = time.time() - start_time_bootstrapped
    print(f"Time taken for bootstrapped calculation: {elapsed_time_bootstrapped:.5f} seconds")

    time_difference = abs(elapsed_time_exact - elapsed_time_bootstrapped)
    print(f"Time difference between exact and robust bootstrapped calculations: {time_difference:.5f} seconds")
    
    # Print bootstrapped results
    print("_______________________________________________________________________________________________________________________________________________\n")
    print("Number of Bootstrap Iterations:", bootstrapped_similarity_stats_json["number_of_bootstraps"])
    print("Bootstrap Sample Size:", bootstrapped_similarity_stats_json["sample_size"])
    print("\nRobust Spearman's rho:", bootstrapped_similarity_stats_json["spearman_rho"])
    print("Robust Kendall's tau:", bootstrapped_similarity_stats_json["kendall_tau"])
    print("Robust Distance Correlation:", bootstrapped_similarity_stats_json["approximate_distance_correlation"])
    print("Robust Jensen-Shannon  Dependency Measure:", bootstrapped_similarity_stats_json["jensen_shannon_dependency_measure"])
    print("Robust Normalized Mutual Information:", bootstrapped_similarity_stats_json["normalized_mutual_information"])
    print("Robust Hoeffding's D:", bootstrapped_similarity_stats_json["hoeffding_d"])
    print("_______________________________________________________________________________________________________________________________________________\n")

    # Compute the differences between exact and bootstrapped results
    measures = ["spearman_rho", "kendall_tau", "approximate_distance_correlation", "jensen_shannon_dependency_measure", "normalized_mutual_information", "hoeffding_d"]
    for measure in measures:
        exact_value = similarity_stats_json[measure]
        bootstrapped_value = bootstrapped_similarity_stats_json[measure]
        absolute_difference = abs(exact_value - bootstrapped_value)
        percentage_difference = (absolute_difference / exact_value) * 100

        print(f"\nDifference between exact and bootstrapped {measure}: {absolute_difference}")
        print(f"Difference as % of the exact value: {percentage_difference:.2f}%")

    print("Now testing with a larger dataset, using sentence embedddings from Llama2 (4096-dimensional vectors) on some Shakespeare Sonnets...")
    # Load the embeddings into a DataFrame
    input_file_path = "sample_input_files/Shakespeare_Sonnets_small.json"
    embeddings_df = convert_embedding_json_to_pandas_df(input_file_path)
    
    # Select a random row for the query embedding
    query_embedding_index = choice(embeddings_df.index)
    query_embedding = embeddings_df.loc[query_embedding_index]
    print(f"Selected query embedding for sentence: `{query_embedding_index}`")

    # Remove the selected row from the DataFrame
    embeddings_df = embeddings_df.drop(index=query_embedding_index)

    # Apply the function to each row of embeddings_df
    json_outputs = embeddings_df.apply(lambda row: apply_fvs_to_vector(row, query_embedding), axis=1)

    # Create a DataFrame from the list of JSON outputs
    vector_similarity_results_df = pd.DataFrame.from_records(json_outputs)
    vector_similarity_results_df.index = embeddings_df.index

    # Add the required columns to the DataFrame
    columns = ["spearman_rho", "kendall_tau", "approximate_distance_correlation", "jensen_shannon_dependency_measure", "normalized_mutual_information", "hoeffding_d"]
    vector_similarity_results_df = vector_similarity_results_df[columns]
    
    # Sort the DataFrame by the hoeffding_d column in descending order
    vector_similarity_results_df = vector_similarity_results_df.sort_values(by="hoeffding_d", ascending=False)
    
    print("\nTop 10 most similar embedding results by Hoeffding's D:")
    print(vector_similarity_results_df.head(10))

if __name__ == "__main__":
    main()

Usage

In Rust

The core functions can be used directly within Rust projects. For example, use compute_vector_similarity_stats or compute_bootstrapped_similarity_stats with appropriate parameters for efficient computations.

In Python

Install the Python package and use the exposed functions to compute vector similarity or perform bootstrapped analysis, as demonstrated in the example above.

Batch scoring and top-k embedding search

Use one call to compare a query with a matrix of candidate rows. Cosine similarity is the default for this API. It measures direction: aligned vectors score 1, orthogonal vectors score 0, and opposite vectors score -1. The existing statistical dependence measures remain available by name; their interpretation differs from cosine, and all search rankings place larger scores first.

import json
import fast_vector_similarity as fvs

params = {
    "query": [1.0, 0.0, 0.0],
    "candidates": [
        [2.0, 0.0, 0.0],
        [0.0, 1.0, 0.0],
        [1.0, 0.0, 0.0],
        [-1.0, 0.0, 0.0],
        [0.0, 0.0, 0.0],
    ],
    "similarity_measure": "cosine_similarity",
    "top_k": 2,
    "seed": 42,
}
result = json.loads(fvs.py_compute_batch_similarity_stats(json.dumps(params)))
# result["matches"] == [{"index": 0, "score": 1.0}, {"index": 2, "score": 1.0}]

params.pop("top_k")
scores = json.loads(fvs.py_compute_batch_similarity_stats(json.dumps(params)))["scores"]
# [1.0, 0.0, 1.0, -1.0, None]

Without top_k, scores preserves the candidate row order and represents an undefined score as null. With top_k, matches contains at most that many finite scores in descending order; exact score ties use the lower original row index first. Undefined rows are excluded from ranking. Zero top_k and an empty corpus return no matches. The response includes input_vector_dimensions, number_of_candidates, and similarity_measure, plus the requested top_k for ranked results. A missing or null measure defaults to cosine; "all" is not a single ranking measure and is rejected by this API.

Every row must have the same dimension as the query, and all supplied coordinates must be finite JSON numbers. All rows are validated even with top_k: 0. A zero or empty query has undefined cosine scores. Cosine independently scales vectors before multiplying and uses compensated sums, avoiding overflow for finite large values and preserving vectors made entirely of subnormal values. Cosine is also available through the existing pairwise and bootstrap functions.

The batch implementation parallelizes rows. Its cosine path prepares the query once and reads candidate rows directly. Top-k scans the full corpus but keeps bounded heaps instead of building and sorting all scores: result storage is O(workers * min(k, rows)), plus the input matrix and metric working storage. It is an exact scan under the selected metric; approximate_distance_correlation retains its 1000-observation approximation and JSD retains its shuffled baseline. The separate distance_correlation metric uses all observations.

For randomized metrics, seed fixes independent streams by original candidate index. Batch scores and top-k scores agree for the same corpus, measure, and seed, regardless of worker count. Reordering rows assigns different streams; a batch row's stream is distinct from a standalone pairwise call with the same root seed. For the README's DataFrame workflow, pass embeddings_df.to_numpy().tolist() as candidates once and map each returned index back to embeddings_df.index.

Rust callers can avoid JSON entirely:

use fast_vector_similarity::{
    batch_similarity, cosine_similarity, top_k_similarity, SimilarityMeasure,
};
use ndarray::array;

let query = array![1.0, 0.0];
let candidates = array![[2.0, 0.0], [0.0, 1.0], [-1.0, 0.0]];
let scores = batch_similarity(&query, &candidates, SimilarityMeasure::CosineSimilarity, None);
let matches = top_k_similarity(&query, &candidates, 2, SimilarityMeasure::CosineSimilarity, None);
assert_eq!(scores, vec![1.0, 0.0, -1.0]);
assert_eq!(matches[0].index, 0);
assert_eq!(cosine_similarity(&[1.0, 0.0], &[-2.0, 0.0]), -1.0);

Rust shape mismatches assert, as in the existing scalar APIs. Non-finite rows produce NaN in batch scores and are excluded from top-k. Reversed, strided, and column-major ndarray layouts preserve logical coordinates and row indices.

Pairwise matrices for clustering

pairwise_similarity and pairwise_distances compare every pair of rows in one corpus in Rust, returning a symmetric square matrix as native Python lists. Both accept the same finite numeric sequences and NumPy buffers as the index APIs, support every measure, and release the GIL during computation.

import numpy as np
import fast_vector_similarity as fvs

vectors = np.array([[1.0, 0.0], [0.0, 1.0], [-1.0, 0.0]])
similarities = np.asarray(fvs.pairwise_similarity(vectors))
distances = np.asarray(fvs.pairwise_distances(vectors))
assert np.array_equal(distances, [[0.0, 1.0, 2.0],
                                 [1.0, 0.0, 1.0],
                                 [2.0, 1.0, 0.0]])

rank_distances = fvs.pairwise_distances(
    vectors, "spearman_rho", seed=42,
)

The distance API returns score-complement dissimilarities: an off-diagonal entry is max(0, 1 - similarity), and every diagonal entry is exactly zero. The nonnegative clipping handles scores that slightly exceed one. Undefined off-diagonal statistics remain nan; an undefined self-statistic still has a zero distance diagonal. The similarity API keeps the actual self-statistic on its diagonal, which need not be one for every measure.

For clustering evaluation, pass a finite distance matrix to silhouette_score with metric="precomputed":

from sklearn.metrics import silhouette_score

embeddings = np.array([[1.0, 0.0], [0.99, 0.01],
                       [-1.0, 0.0], [-0.99, 0.01]])
distances = np.asarray(fvs.pairwise_distances(embeddings))
score = silhouette_score(distances, [0, 0, 1, 1], metric="precomputed")

Choose the measure according to the relationship you want to group. Cosine, Spearman, and Kendall can distinguish opposite directions, with dissimilarities up to two. Dependence measures can treat inverse or nonlinear relationships as similar. These complements do not generally satisfy the triangle inequality or require distinct vectors to have positive distance. Handle undefined off-diagonal values before using consumers that require finite distances.

Each unordered pair is evaluated only once, in the orientation where the lower row index is the query, and then mirrored exactly. This guarantees symmetry even for randomized JSD baselines and approximate distance-correlation samples. An explicit seed gives reproducible pair streams independent of worker count; row reordering changes the pair identities and can change randomized scores. Pairwise streams are distinct from the existing query-to-corpus streams, so scores_many(vectors) is not an interchangeable seeded matrix operation.

Cosine, Spearman, NMI, and JSD reuse prepared corpus state. Scoring uses the upper triangle and one quadratic output buffer, plus corpus preparation and metric working storage. The complete output still requires O(rows²) memory; use top-k or streamed search when a full matrix is unnecessary. Empty corpora return an empty list, and a one-row distance matrix is [[0.0]].

Rust exposes pairwise_similarity(&corpus, measure, seed) and pairwise_distances(&corpus, measure, seed), both returning Array2<f64>. Logical ndarray layouts and original row order are preserved, and non-finite Rust inputs retain the existing undefined-score convention.

Condensed pairs for hierarchical clustering

Use pairwise_distances_condensed when a consumer accepts one distance per distinct unordered pair, such as SciPy hierarchical clustering. This computes the condensed vector directly: no square output matrix, diagonal, or mirrored triangle is allocated. pairwise_similarity_condensed provides similarities in the same order for consumers that need the original scores.

import numpy as np
import fast_vector_similarity as fvs
from scipy.cluster.hierarchy import linkage

vectors = [[1.0, 2.0, 3.0], [2.0, -1.0, 4.0], [-2.0, 3.0, 1.0]]
distances = np.asarray(fvs.pairwise_distances_condensed(vectors), dtype=float)
clusters = linkage(distances, method="average")

For n input rows, each function returns n * (n - 1) / 2 floats in the SciPy condensed order: (0, 1), (0, 2), ..., (0, n-1), (1, 2), ..., (n-2, n-1). Empty and singleton inputs produce an empty list; no self-statistics are included. All supported metrics, finite-input validation, array layouts, and seeds follow the square API. With the same explicit seed, each value is bit-identical to the corresponding upper-triangle square result. Undefined scores remain NaN, which must be handled before using a consumer that requires finite values. Distance values retain the square API's score-complement interpretation.

The output remains quadratic, but requires roughly half the numerical storage of a square matrix: 4 * n * (n - 1) bytes for Rust f64 values, compared with 8 * n * n bytes. Python returns a flat list, whose objects have additional overhead. Work is divided by pair count to balance the parallel scan, with a bounded number of live query preparations. Rust exposes both functions with the same arguments as the square versions and returns Vec<f64>.

Bounded pairwise chunks for large outputs

pairwise_similarity_chunks and pairwise_distances_chunks return a PairwiseChunks iterator. Each iteration yields (offset, values), where values is a list of at most chunk_size floats and offset is its position in the complete condensed result. The default chunk size is 65,536. Consume or write each chunk before requesting the next to avoid retaining the complete quadratic output.

import numpy as np
import fast_vector_similarity as fvs

# candidates is your matrix of row vectors.
chunks = fvs.pairwise_distances_chunks(
    candidates, "cosine_similarity", seed=42, chunk_size=65_536,
)
if chunks.total_pairs:  # Empty and singleton corpora yield no pairs.
    output = np.memmap(
        "distances.f64", mode="w+", dtype=np.float64,
        shape=(chunks.total_pairs,),
    )
    for offset, values in chunks:
        output[offset:offset + len(values)] = values
    output.flush()
    del output

For an explicit seed, concatenating the chunks gives exactly the corresponding *_condensed result, independently of chunk size and worker count. An omitted seed is chosen once per iterator. Diagonal entries are omitted, undefined values remain NaN, and distance values retain the score-complement interpretation described above. The iterator exposes read-only total_pairs, offset (the next condensed position), and chunk_size properties.

Input is validated and copied when the iterator is created, so later caller mutations do not change its results. Rust retains one prepared corpus representation; the input copy is moved into preparation without keeping a second raw-coordinate matrix. Preparation runs once, and both preparation and each next() release the GIL. The corpus must still fit in memory. Resident storage is O(rows × dimensions + chunk_size), plus metric working storage. Previously returned chunks are not retained by the iterator. Stopping early avoids scoring the remaining pairs. Computing all pairs still takes quadratic work in the number of rows, and consumers that collect all chunks or build a complete matrix still need quadratic output storage.

Rust exposes the same pairwise_similarity_chunks and pairwise_distances_chunks factories. They take ownership of an Array2<f64> followed by the measure, optional seed, and chunk size, and return Result<PairwiseChunks, PairwiseChunksError>. The iterator yields (usize, Vec<f64>), implements ExactSizeIterator and FusedIterator, and rejects zero/oversized chunks or a pair count that cannot fit in usize before preparing the corpus.

A saved condensed offset is sufficient to resume an interrupted write. Recreate the iterator with the same row order, measure, and explicit seed, then call seek(offset). The next chunk starts at that offset, even in the middle of a triangle row. Seeking to total_pairs marks the traversal complete. For independent reads, read_range(start, stop) returns just those scores and leaves the cursor in place. Each read is limited to chunk_size values.

pairs = fvs.pairwise_distances_chunks(rows, seed=17, chunk_size=4096)
# Read a sample from the far end without scoring the preceding pairs.
tail = pairs.read_range(max(0, pairs.total_pairs - 10), pairs.total_pairs)
# Resume a sequential consumer at its first unwritten pair.
pairs.seek(first_unwritten_offset)
for offset, values in pairs:
    output[offset:offset + len(values)] = values

In Rust the same operations are chunks.seek(offset)? and chunks.read_range(start..stop)?. Invalid ranges leave the cursor untouched. Overlapping reads on one traversal reproduce the same pair values, including when it chose a random seed at construction.

Exact nearest-neighbor graphs

Use pairwise_top_k to find the strongest neighbors of every row in one corpus. It returns one list of (neighbor_index, similarity) tuples per input row. An optional min_score includes neighbors whose score equals the threshold. Self-pairs and undefined scores are omitted. Equal scores favor the smaller original row index. Each row selects its own neighbors, so an edge can appear in only one direction.

import fast_vector_similarity as fvs

rows = [[1.0, 0.0], [1.0, 0.0], [0.0, 1.0], [-1.0, 0.0]]
neighbors = fvs.pairwise_top_k(rows, k=2, min_score=0.0)
assert neighbors == [
    [(1, 1.0), (2, 0.0)],
    [(0, 1.0), (2, 0.0)],
    [(0, 0.0), (1, 0.0)],
    [(2, 0.0)],
]

For a corpus of n rows, the search evaluates at most n * (n - 1) / 2 distinct pairs and retains up to min(k, n - 1) matches per row. You can request a small graph without allocating the square or condensed score matrix. All supported measures use the same pair scores as pairwise_similarity with the same explicit seed, including randomized measures. Rust exposes pairwise_top_k(&corpus, k, measure, seed, min_score) and returns Result<Vec<Vec<SimilarityMatch>>, SearchError>.

Pairwise calculations directly from prepared or saved indexes

Both SimilarityIndex and CosineIndex expose all seven pairwise operations: pairwise_similarity, pairwise_distances, pairwise_similarity_condensed, pairwise_distances_condensed, pairwise_similarity_chunks, pairwise_distances_chunks, and pairwise_top_k. They use the index's stored measure, row order, and prepared representation. An index loaded from a snapshot can build a neighbor graph or clustering input without reconstructing the original vectors or preparing a second corpus.

import fast_vector_similarity as fvs

index = fvs.SimilarityIndex.load("embeddings.fvs")

# Keep only the strongest neighbors; no dense pairwise matrix is allocated.
neighbors = index.pairwise_top_k(20, seed=42, min_score=0.0)

# For a consumer that accepts a complete condensed distance vector:
distances = index.pairwise_distances_condensed(seed=42)

# For larger outputs, consume chunks independently or resume at a saved offset.
pairs = index.pairwise_distances_chunks(seed=42, chunk_size=65_536)
del index  # The iterator keeps the shared prepared corpus alive.
for offset, values in pairs:
    write_distance_chunk(offset, values)  # Your file or database sink.

Square methods return nested lists; condensed methods return flat lists; pairwise_top_k(k, *, seed=None, min_score=None) returns neighbor lists. The other methods accept seed as a keyword, and chunk methods additionally accept chunk_size. With the same explicit seed, results match the corresponding raw-corpus pairwise functions, including sampled statistics and tie-breaking. The unordered-pair seed streams differ from query-to-corpus search streams; scores_index(index, seed=...) is therefore not a substitute for seeded pairwise calculations. Undefined pairwise values remain NaN, including on CosineIndex. Distance diagonals are exactly zero, and similarity diagonals retain the actual self-statistics.

Prepared pairwise computations release the GIL. Each chunk iterator shares the index's immutable corpus and owns its own seed and cursor. Creating several iterators does not copy the corpus, and they remain usable after the original index is released. The existing seek and read_range operations work unchanged. In Rust, SimilarityIndex::clone() also shares prepared storage. Its seven pairwise methods take the same seed, size, and threshold arguments as the corresponding free functions, without the corpus and measure arguments. Rust CosineIndex users can access these methods through index.as_ref().

The prepared corpus must still fit in memory. Square and complete condensed outputs remain quadratic; chunk iterators bound output storage, and top-k graphs retain at most min(k, rows - 1) neighbors per row. Exhaustive scoring still takes quadratic work. Applying a pairwise method separately to blocks from SimilarityIndexReader computes only pairs within each block; it does not include pairs across blocks.

Complete pairwise output when the corpus exceeds memory

PairwiseFileTiles computes a complete pairwise matrix directly from a saved prepared index, including pairs that cross input-block boundaries. It retains bounded query and candidate blocks, their metric preparation, and one output tile. Each iteration yields (row_offset, column_offset, values), where values is a nested list with at most block_rows rows and columns. The default block size is 128 rows. Only the upper triangle of the block grid is emitted, in row-major block order; diagonal tiles are already symmetric. Mirror each off-diagonal tile by transposing it to fill the lower triangle.

The following example writes a disk-backed distance matrix and publishes it only after the complete input has validated:

import os
from pathlib import Path
from tempfile import TemporaryDirectory
import numpy as np
import fast_vector_similarity as fvs

destination = Path("distances.f64")
with TemporaryDirectory(dir=destination.parent) as temporary:
    staged = Path(temporary) / "distances.f64"
    with fvs.PairwiseFileTiles(
        "embeddings.fvs", block_rows=128, seed=42, distances=True,
    ) as tiles:
        row_count = tiles.total_rows
        if row_count == 0:
            staged.write_bytes(b"")  # A zero-length file cannot be memory-mapped.
        else:
            output = np.memmap(
                staged, mode="w+", dtype=np.float64,
                shape=(row_count, row_count),
            )
            try:
                for row, column, values in tiles:
                    block = np.asarray(values, dtype=np.float64)
                    height, width = block.shape
                    output[row:row + height, column:column + width] = block
                    if row != column:
                        output[column:column + width, row:row + height] = block.T
                output.flush()
            finally:
                del output
    os.replace(staged, destination)

Omit distances=True to obtain similarities. With the same explicit seed, the assembled output is bit-identical to pairwise_similarity or pairwise_distances on the original corpus, independently of block size and worker count. An omitted seed is selected once per iterator. Similarity diagonals contain the actual self-statistics, distance diagonals are exactly zero, and undefined off-diagonal scores remain NaN. Distances retain the score-complement interpretation and limitations described above. All nine measures and legacy Hoeffding snapshots are supported.

The iterator keeps one source file open and uses independent logical read positions for query and candidate passes. Replacing its pathname does not switch later passes to the replacement. The source contents must remain unchanged: complete passes verify the checksum and exact EOF, and their checksums must agree. Earlier tiles are provisional; the final tile is withheld until validation succeeds. A read, decoding, or checksum error closes the source, raises an exception, and permanently ends iteration. Stage output as above so an error cannot publish a partial matrix.

finish() validates unfinished input with bounded memory and skips remaining pair calculations. It closes the iterator and is idempotent after success. close() and abandonment release the source without validation. A normal context-manager exit calls finish(); an exceptional exit closes without masking the original exception. An explicit early close followed by a normal context exit raises ValueError, preserving the context's validation promise. The read-only properties are total_rows, dimensions, similarity_measure, block_rows, distances, closed, and validated. No collection length hint is derived from untrusted file headers. Returned tiles remain usable after closure, and the iterator does not retain previous output tiles.

For n rows, d dimensions, and a block size b, resident corpus and output storage is O(b × d + b²), plus metric working storage and Python object overhead. Kendall ordering and full distance-correlation query preparation are retained across candidate blocks. Full distance-correlation tiles also share candidate marginals when multiple nonconstant queries can reuse them. These caches remain bounded by the active blocks. Candidate data is rescanned for each query block; larger blocks reduce repeated input decoding at the cost of more memory. Exhaustive pairwise scoring and a complete matrix on disk still require quadratic work and output space. File I/O and numerical work release the GIL; use separate iterators for concurrent consumers.

Rust exposes PairwiseFileTiles::open(path, seed, block_rows, distances) and an iterator of io::Result<(usize, usize, Array2<f64>)>. Its metadata, finish, close, is_closed, and is_validated follow the same contracts. The iterator is fused after exhaustion or error and retains no borrowed caller data.

Resuming and partitioning file-backed pairwise jobs

PairwiseFileTiles accepts start_tile=0 and stop_tile=None to select a half-open range of tile positions in the complete upper-triangle traversal. These positions count tiles, not vector rows or individual pairs. A range can start or end in the middle of a block-grid row. Skipped input is decoded with bounded memory without scoring the preceding tiles, so an interrupted job can restart at its next tile and independent workers can process disjoint ranges.

import fast_vector_similarity as fvs

# Use the same immutable snapshot contents and block size for every partition.
with fvs.PairwiseFileTiles("embeddings.fvs", block_rows=128, seed=42) as plan:
    total_tiles = plan.total_tiles
    actual_seed = plan.seed
    # Context exit validates the source without computing the tile matrix.

worker_count = 4
worker_number = 2
start = total_tiles * worker_number // worker_count
stop = total_tiles * (worker_number + 1) // worker_count
with fvs.PairwiseFileTiles(
    "embeddings.fvs", block_rows=128, seed=actual_seed,
    start_tile=start, stop_tile=stop,
) as tiles:
    for row, column, values in tiles:
        write_tile(row, column, values)  # Your staged output sink.
        next_tile_to_save = tiles.tile_offset

The read-only tile_offset is the next actual tile position. Save it only after durably writing that tile's output, together with block_rows, distances, seed, and the immutable source version. Resuming with the saved seed also reproduces a run that originally omitted seed: the chosen root seed is now available through the property. A successful explicit finish() validates input and skips omitted calculations; it does not advance tile_offset over uncomputed work.

start_tile and stop_tile expose the chosen range, while total_tiles always describes the whole source. For m = ceil(total_rows / block_rows) blocks, there are m * (m + 1) / 2 tiles. Rust uses u128 tile positions and Python uses integers, so valid positions do not overflow a machine-sized row index. The mapping from tile positions to row/column offsets uses integer arithmetic. Ranges must satisfy 0 <= start_tile <= stop_tile <= total_tiles.

The final selected tile is withheld until the entire source validates, including unselected prefixes and suffixes. An empty range performs validation and yields no tiles. Each partition must complete successfully before its staged output is published, and output from separate runs must refer to the same immutable source contents. The existing lifetime, corruption, and no-allocation-hint contracts apply to ranged traversal too.

Rust provides PairwiseFileTiles::open_range(path, seed, block_rows, distances, range), accepting standard RangeBounds<u128>, including start..stop, start.., and ... Existing open calls still traverse the complete source.

Exact neighbor graphs from corpora larger than memory

pairwise_top_k_file builds a complete exact nearest-neighbor graph directly from a saved prepared index. It uses the snapshot's stored measure and row order, including all nine metrics and legacy Hoeffding snapshots. The corpus does not have to fit in RAM, and no complete pairwise matrix is allocated or written to disk.

import fast_vector_similarity as fvs

neighbors = fvs.pairwise_top_k_file(
    "embeddings.fvs", 20, seed=42, block_rows=128, min_score=0.0,
)
for row_id, matches in enumerate(neighbors):
    # Each match is (original_neighbor_row_id, similarity).
    store_neighbors(row_id, matches)  # Your graph or database sink.

With the same explicit seed, results exactly match pairwise_top_k on the original corpus, independently of block size and worker count. Every distinct unordered pair is evaluated once and considered at both endpoints. Self-pairs and undefined scores are excluded; duplicate vectors in different rows remain eligible. The optional finite min_score is inclusive. Neighbors are ordered by decreasing score, with smaller original row IDs winning exact ties, and each row independently retains at most min(k, rows - 1) matches.

Input memory is bounded by two prepared blocks and one score tile. For n rows, d coordinates, and block size b, resident storage is O(b × d + b² + n × (1 + min(k, n - 1))), plus metric working storage and Python objects. The returned graph must fit in memory, even though its source corpus need not. Asking for every neighbor makes the result quadratic. The exact scan still takes quadratic scoring work and rescans candidate data for each query block. Larger blocks reduce repeated decoding at the cost of more temporary memory.

The function pins one open source file throughout the computation. Keep its contents unchanged in place; atomic pathname replacement does not switch the scan to another snapshot. No graph is returned unless all source scans pass checksum, exact-EOF, and consistency validation. A damaged or truncated file raises an error without exposing a partial graph. k=0, empty indexes, singletons, and zero-width rows still validate the full input; they skip unnecessary scoring and return the corresponding empty neighbor lists. Python accepts strings, bytes, and os.PathLike paths and releases the GIL during I/O and numerical work.

Rust exposes pairwise_top_k_file(path, k, seed, block_rows, min_score) returning std::io::Result<Vec<Vec<SimilarityMatch>>>. Invalid sizes and thresholds report InvalidInput, malformed snapshots retain their I/O error categories, and output allocation failures report OutOfMemory. The existing in-memory and saved-file APIs share score preparation, pair seeds, and ranking rules.

Streaming graph rows when the neighbor lists exceed memory

Use PairwiseFileTopK to write the strongest neighbors for each row of a saved index. Each batch contains a starting row ID and complete neighbor lists for up to block_rows consecutive rows. Neighbor IDs refer to the entire corpus. With an explicit seed, the lists match index.pairwise_top_k for every supported measure, regardless of block size. Self-pairs and undefined scores are omitted. Equal scores favor the smaller row ID, and min_score includes the threshold itself.

This example writes one JSON line per row and publishes the graph after the snapshot passes validation.

import json
import os
from pathlib import Path
from tempfile import TemporaryDirectory
import fast_vector_similarity as fvs

destination = Path("neighbors.jsonl")
with TemporaryDirectory(dir=destination.parent) as tmp:
    staged = Path(tmp) / "neighbors.jsonl"
    with staged.open("w", encoding="utf-8") as output:
        with fvs.PairwiseFileTopK(
            "embeddings.fvs", k=10, block_rows=128, seed=42,
        ) as graph:
            for offset, neighbors in graph:
                for row_id, matches in enumerate(neighbors, start=offset):
                    print(json.dumps([row_id, matches]), file=output)
    os.replace(staged, destination)

For block size b, row width d, and corpus size n, working storage is O(b × d + b² + b × min(k, n − 1)), plus per-worker metric workspace. Each query block scans the file, so cross-block pairs can be evaluated twice. Total scoring work remains quadratic in the row count. A zero k returns empty lists while still validating the input. Snapshot pinning, finish(), close(), and context-manager behavior follow PairwiseFileTiles.

Rust exposes PairwiseFileTopK::open(path, k, seed, block_rows, min_score). Its iterator yields io::Result<(usize, Vec<Vec<SimilarityMatch>>)>.

An omitted seed is chosen once per graph iterator. Read graph.seed and save it with the immutable source identity to reproduce the graph in another run. The existing k, min_score, schema, block-size, and lifecycle properties remain available. Exhaust the iterator before publishing a complete graph; finish() validates unread input while omitting any uncomputed neighbor batches.

To resume at a saved row or split the graph between workers, pass start_row (inclusive) and stop_row (exclusive). Omitting stop_row continues through the last row. Each requested row still searches the entire corpus and emits global neighbor IDs. Use the same snapshot and explicit seed for every partition. For example, PairwiseFileTopK(path, 10, seed=42, start_row=4000, stop_row=6000) returns the same neighbor lists as rows 4000 through 5999 of the full graph. Complete query blocks outside the range incur no pair scoring. Exhaustion and finish() validate the full snapshot, including for an empty range. In Rust, pass a range such as 4000..6000 or 4000.. as the final argument to PairwiseFileTopK::open_range.

Grouping duplicates by threshold connectivity

connected_components_file turns a saved index into native similarity groups without materializing its full score matrix or edge graph. Two distinct rows are connected when their finite pairwise similarity meets an inclusive threshold. The result contains one integer label per original row; each label is the smallest row ID in that connected component.

import fast_vector_similarity as fvs

labels = fvs.connected_components_file(
    "embeddings.fvs", min_score=0.9, seed=42, block_rows=128,
)

# Keep the first original row from each connected group.
representative_rows = [row for row, label in enumerate(labels) if row == label]
duplicate_count = len(labels) - len(representative_rows)

Connectivity is transitive, also called single linkage. If A matches B and B matches C, all three receive the same label even when A's direct similarity to C is below the threshold. For example, labels [0, 0, 0, 3, 3, 5] describe groups {0, 1, 2}, {3, 4}, and {5}. Labels follow snapshot row order and need not be consecutive. Isolated rows, including rows with only undefined similarities, label themselves; an empty snapshot returns an empty list.

All nine similarity measures and legacy Hoeffding snapshots are supported. The threshold must be finite and uses the selected metric's score scale. Pass an explicit seed to reproduce sampled pairwise statistics across runs and block sizes. The result matches connected components of index.pairwise_similarity(seed=seed) after applying the same finite, inclusive threshold. block_rows defaults to 128 and must be positive.

The native implementation streams bounded edge chunks into a union-find structure. With n rows, d coordinates, and block size b, storage is O(n + b × d + b²), plus metric scratch space and Python object overhead. The returned labels and component state must fit in memory, while the complete corpus and graph may exceed it. General-case scoring is still quadratic. Once every row belongs to one component, remaining scores cannot change the labels, so the implementation skips those calculations and validates the remaining input directly.

Labels are returned only after the complete pinned snapshot passes checksum, exact EOF, and consistency checks. Corrupt inputs raise an error without returning partial groups. Component storage grows from decoded edges, and the final label allocation occurs after validation. File I/O, numerical work, and component construction release the GIL. The labels can be passed directly to the saved-index silhouette functions when the resulting grouping meets their cluster-count and finite-distance requirements.

Rust exposes connected_components_file(path, min_score, seed, block_rows) with an io::Result<Vec<usize>> result and the same semantics. dbscan_file(..., min_samples=1) uses this same component scan, then remaps representative IDs to its usual consecutive cluster labels.

Streaming complete similarity-threshold graphs

PairwiseFileEdges emits every unordered pair whose finite similarity meets an inclusive threshold. It supports duplicate detection and similarity graphs where different rows can have very different neighbor counts. There is no per-row top-k limit. Each qualifying pair appears exactly once as (row_id, column_id, score), with row_id < column_id; self pairs and undefined scores are omitted.

import csv
import os
from pathlib import Path
from tempfile import TemporaryDirectory
import fast_vector_similarity as fvs

destination = Path("similarity_edges.csv")
with TemporaryDirectory(dir=destination.parent) as temporary:
    staged = Path(temporary) / "edges.csv"
    with staged.open("w", newline="", encoding="utf-8") as output:
        writer = csv.writer(output)
        writer.writerow(["row", "column", "similarity"])
        with fvs.PairwiseFileEdges(
            "embeddings.fvs", min_score=0.9, seed=42,
            block_rows=128, chunk_size=4096,
        ) as edges:
            for chunk in edges:
                writer.writerows(chunk)
    os.replace(staged, destination)

The threshold must be a finite real number in the selected metric's score scale. All nine metrics and legacy Hoeffding snapshots are supported. With a fixed seed, scores exactly match the strict upper triangle of index.pairwise_similarity(seed=seed), independently of block and chunk sizes. Traversal follows the upper-triangle tile order and then row order inside each tile. Changing block_rows can change edge order, while preserving the same pairs and scores. Output chunks are nonempty and contain at most chunk_size edges; both size parameters must be positive.

The source, a score tile, and the current edge chunk are bounded in memory. For block size b, dimension d, and chunk size e, resident storage is O(b × d + b² + e), plus metric working storage and Python object overhead. The complete corpus and graph may both exceed memory. The threshold reduces the emitted output, while exhaustive pair scoring still takes quadratic work. Consume or write each chunk before requesting the next to bound retained output as well.

Use start_tile and stop_tile to process a half-open range of the same tile ordinals exposed by PairwiseFileTiles. Separate consumers can handle disjoint tile ranges with the same immutable source, block_rows, threshold, and seed. These bounds select tiles, not edge offsets; a tile can produce several chunks or no edges. Complete each selected range before publishing its output.

Earlier chunks remain provisional until validation completes. The final matching chunk is withheld until the whole snapshot validates, even when trailing tiles contain no matches. Empty ranges and graphs still validate the source. File identity stays pinned across scans. finish() validates unread input while skipping remaining edge calculations; close() releases the source without validation. Normal context exit finishes and exceptional exit closes. A decoding or I/O error is raised once and permanently ends iteration. File I/O and numerical work release the GIL.

Read-only metadata includes total_rows, dimensions, similarity_measure, block_rows, chunk_size, min_score, seed, total_tiles, start_tile, stop_tile, closed, and validated. Rust exposes PairwiseFileEdges::open(path, min_score, seed, block_rows, chunk_size) and open_range with a final RangeBounds<u128> argument. Items are io::Result<Vec<SimilarityEdge>>; each edge has row, column, and score fields with the same conventions.

Complete threshold joins between saved corpora

ScoreFileEdges streams every finite query-to-candidate score at or above a chosen inclusive threshold. Use it for record linkage, catalog matching, or cross-corpus similarity joins when both inputs and the matching output can exceed memory. It retains bounded input blocks, one score tile, and one output chunk. There is no per-query k limit.

import fast_vector_similarity as fvs

with fvs.ScoreFileEdges(
    "queries.fvs", "candidates.fvs", min_score=0.85, seed=42,
    query_block_rows=64, candidate_block_rows=512, chunk_size=4096,
) as matches:
    for chunk in matches:
        # Each tuple is (original_query_id, original_candidate_id, score).
        write_staged_matches(chunk)
# Publish the staged output only after the context exits successfully.

Each nonempty chunk contains at most chunk_size tuples; defaults are 128 rows for both input block sizes and 4096 matches per chunk. The inputs must share their measure and dimensions. Undefined scores are omitted. Equal IDs remain eligible because query and candidate row numbers belong to independent corpora, including when both paths refer to the same file. Every directed qualifying matrix cell is emitted once. PairwiseFileEdges instead emits canonical unordered pairs within one corpus.

Scores match candidates.scores_index(queries, seed=seed) exactly. An omitted seed is selected once and exposed for replay. Global candidate IDs preserve random streams across input and output chunk sizes; pairwise random streams are not substituted. Order is query-block outer, candidate-block inner, then row-major inside each tile. Changing block sizes can change output order.

Optional start_tile and stop_tile select the same half-open rectangular tile range as ScoreFileTiles. Adjacent ranges partition the complete join when snapshots, seed, threshold, and both block sizes are identical. A tile may yield many chunks or none, so a chunk boundary is not a tile checkpoint. Even empty ranges validate both complete inputs.

Both files stay pinned. Earlier chunks are provisional, and the final chunk is withheld until both full inputs validate, including trailing tiles with no qualifying scores. Normal context exit and finish() validate unread input while discarding unreturned matches without scoring additional tiles; close() and exceptional context exit abandon traversal without validation. Errors close the iterator and are returned once. File I/O and numerical work release the GIL; retained chunks own their data independently.

With block sizes q and c, dimensions d, and chunk size e, storage is O((q + c) × d + q × c + e), plus metric working storage and Python objects. Chunk allocations grow with discovered matches instead of reserving the requested maximum up front. Thresholding reduces the output size; exhaustive scoring still visits every pair in the selected tiles.

Read-only properties expose query_rows, candidate_rows, dimensions, similarity_measure, query_block_rows, candidate_block_rows, chunk_size, min_score, seed, total_tiles, start_tile, stop_tile, closed, and validated. Rust exposes ScoreFileEdges::open and open_range, yielding io::Result<Vec<SimilarityEdge>>; each edge has row, column, and score.

Streaming full score matrices between saved corpora

ScoreFileTiles produces every score between a saved query corpus and a saved candidate corpus while bounding both inputs and the output buffer. It yields (query_offset, candidate_offset, values) in query-block outer order and candidate-block inner order. Each tile has at most query_block_rows rows and candidate_block_rows columns; both defaults are 128. The two snapshots must use the same measure and dimensions, while their row counts may differ.

With an explicit seed, the complete result is exactly candidates.scores_index(queries, seed=seed). Original global candidate IDs determine random streams across all blocks. This matters for sampled metrics: calling scores_index separately on candidate blocks would restart their row IDs at zero and change those streams. Every matrix cell is scored, including diagonal cells when both paths refer to the same file. This API preserves directed query-to-corpus semantics; PairwiseFileTiles separately provides symmetric unordered-pair semantics. Undefined scores remain NaN.

For a complete matrix on disk, write a NumPy file directly. Both native writers return the seed used and publish the destination after validating the inputs and syncing the output. NumPy can open the result as a memory map, including its shape and dtype, without loading the complete matrix into RAM.

import numpy as np
import fast_vector_similarity as fvs

seed = fvs.write_score_matrix_npy(
    "queries.fvs", "candidates.fvs", "scores.npy",
    query_block_rows=64, candidate_block_rows=512, seed=42,
)
scores = np.load("scores.npy", mmap_mode="r")
first_ten = scores[0, :10]

# For symmetric pairwise distances within one corpus:
fvs.write_pairwise_matrix_npy(
    "candidates.fvs", "distances.npy", block_rows=128, seed=seed, distances=True,
)

The output is a row-major little-endian float64 array and occupies eight bytes per cell plus a small header. Both functions accept a new or existing output path distinct from the input. Empty axes retain their shape. For symmetric similarities, omit distances=True. Rust exposes the same two functions.

Query scorers are prepared once per query block and reused for every candidate block, including Kendall ordering and full-data distance-correlation caches. For full distance correlation, a tile with at least two nonconstant queries also prepares candidate normalization and marginal statistics once per candidate block. The pair-dependent scoring step reuses both sets of marginals; the additional cache is linear in the candidate block's size. The candidate file is rescanned for each query block. With query block size q, candidate block size c, and vector dimension d, resident storage is O((q + c) × d + q × c), plus metric working storage and Python object overhead. The complete output still contains query_rows * candidate_rows values; write or consume each tile before requesting the next to keep output buffers bounded.

Both open file handles are retained throughout traversal, and input contents must stay unchanged. Every completed candidate pass validates its checksum and exact EOF and must agree with earlier passes. The final tile is withheld until both complete inputs validate. Empty query or candidate corpora yield no tiles but still validate both sources, including on normal context exit. finish() validates unread input without computing omitted scores; close() and exceptional context exits release resources without validation. Earlier tiles remain provisional, so publish staged output only after successful completion. The native NumPy writers handle staging and publication automatically. Errors close and permanently end the iterator.

Read-only properties expose query_rows, candidate_rows, dimensions, similarity_measure, both block sizes, seed, total_tiles, start_tile, stop_tile, tile_offset, closed, and validated. An omitted seed is chosen once and exposed for replay. File I/O, preparation, and scoring release the GIL. Returned tiles own their data, and no collection length hint is derived from input headers. Rust exposes ScoreFileTiles::open(query_path, candidate_path, seed, query_block_rows, candidate_block_rows) with the same metadata and lifecycle contracts and items of type io::Result<(usize, usize, Array2<f64>)>.

Resuming and partitioning rectangular score jobs

start_tile and stop_tile select a half-open range of rectangular tile ordinals. The default range covers the complete matrix. If there are C candidate blocks, ordinal t selects query block t // C and candidate block t % C, in the same order as an uninterrupted scan. The block sizes determine this grid, so retain both sizes along with the immutable query/candidate snapshots and seed when resuming or assigning partitions.

# resume_tile is the next ordinal after the last durably staged output tile.
with fvs.ScoreFileTiles(
    "queries.fvs", "candidates.fvs", seed=saved_seed,
    query_block_rows=64, candidate_block_rows=512,
    start_tile=resume_tile, stop_tile=partition_stop,
) as tiles:
    for query, candidate, values in tiles:
        write_staged_tile(query, candidate, values)
        save_progress(tiles.seed, tiles.tile_offset)

Independent adjacent ranges produce exactly the same tiles and scores as the complete traversal, including random measures and partial blocks at either matrix edge. Omit stop_tile to continue to total_tiles. Positions are exact integers, including grids larger than the platform's addressable memory. tile_offset advances only when a tile is successfully returned; finish() validates unread input without claiming that omitted tiles were computed.

Range scans skip preceding score calculations while still decoding skipped input in bounded batches. They save numerical work, not the I/O required to validate both complete snapshots. Every range, including an empty range, validates both files. The selected final tile is withheld until this succeeds; earlier tiles remain provisional. Continue to stage output until successful completion, and keep both input files unchanged across all partitions. In Rust, use ScoreFileTiles::open_range(query_path, candidate_path, seed, query_block_rows, candidate_block_rows, start..stop) or start...

Exporting condensed distances from a saved index

write_pairwise_condensed_npy writes a one-dimensional float64 NumPy file in SciPy condensed order. For n rows it stores exactly n * (n - 1) / 2 values. The writer reads the prepared corpus in bounded blocks and writes strict upper-triangle row segments directly into their final positions. It validates the snapshot before publishing the file. Empty and singleton snapshots produce shape (0,).

import fast_vector_similarity as fvs
import numpy as np
from scipy.cluster.hierarchy import linkage

seed = fvs.write_pairwise_condensed_npy("vectors.fvs", "distances.npy", block_rows=128)
distances = np.load("distances.npy", mmap_mode="r")
clusters = linkage(distances, method="average")

The default stores distances. Pass distances=False for similarities or pass the returned seed to replay sampled statistics. As with the in-memory condensed calculation, undefined statistics yield NaN. SciPy linkage requires finite distances and has its own working-memory requirements.

Density clustering a saved corpus

dbscan_file returns one integer cluster label per saved row. Pass an inclusive similarity cutoff and the minimum neighborhood size, which includes the row itself. Finite pair scores at or above the cutoff define neighbors. A label of -1 identifies noise. With min_samples=1, the labels identify connected components of the threshold graph, including isolated rows.

labels = fvs.dbscan_file("embeddings.fvs", min_score=0.88, min_samples=5,
                         seed=42, block_rows=128)

Clusters are numbered by their smallest core row ID. A border row adjacent to multiple core components joins the lowest-numbered one. The algorithm retains O(rows) clustering state and one bounded score tile. It can rescan the pinned snapshot to resolve core membership and border assignments without storing all matching edges. Reuse a seed for repeatable sampled similarities. Rust exposes dbscan_file with the same threshold and labeling rules.

Evaluating a clustering from a saved index

silhouette_score_file gives the mean silhouette for cluster labels in snapshot row order. silhouette_samples_file returns each row's coefficient for inspecting poorly assigned points. Both functions use the index's pairwise distance semantics and accumulate cluster totals directly from bounded tiles.

import fast_vector_similarity as fvs

# One label for each row of the saved index.
labels = ["blue", "blue", "green", "green", "green"]
score = fvs.silhouette_score_file("candidates.fvs", labels, block_rows=128, seed=42)
samples = fvs.silhouette_samples_file("candidates.fvs", labels, block_rows=128, seed=42)

A row compares its mean distance within its cluster with the smallest mean distance to another cluster. Singleton clusters and rows with zero distance to both clusters receive 0. Supply at least two clusters and fewer clusters than rows. An undefined pairwise distance raises an error identifying its row IDs. Both functions validate the snapshot before returning a result.

With n rows, c clusters, and a block size of b, the calculation retains O(n + b × c + b²) labels, sums, and scores, plus the prepared input blocks and metric working storage. Every row is compared with every other row. An explicit seed reproduces sampled distances across block sizes. Rust exposes the same functions and accepts a slice of integer labels.

To compare candidate clusterings, supply their label sequences together. Each distance tile contributes to every clustering before it is released. Sampled metrics use the same draws for every assignment, and scores are returned in input order. Working cluster totals grow with the sum of the cluster counts.

means = fvs.silhouette_scores_file(
    "candidates.fvs", [labels_k2, labels_k3, labels_k4], seed=42, block_rows=128,
)
best_k = [2, 3, 4][max(range(len(means)), key=means.__getitem__)]

Sampling rows for large-corpus silhouette evaluation

Pass sample_indices to evaluate selected original rows against all members of the original clusters. Each returned coefficient matches the same row in a full evaluation, including its seeded pairwise distances. This reduces score work from O(n²) to O(m × n) for m distinct selected rows; it does not redefine clusters using only the sample.

import random

# Sample original row IDs uniformly without replacement, independently of
# the optional seed controlling randomized similarity measures.
sample = random.Random(42).sample(range(len(labels)), min(1000, len(labels)))
estimated_mean = fvs.silhouette_score_file(
    "candidates.fvs", labels, sample_indices=sample, block_rows=128, seed=42,
)
selected_coefficients = fvs.silhouette_samples_file(
    "candidates.fvs", labels, sample_indices=sample, block_rows=128, seed=42,
)

Supply the complete label sequence and IDs from the original saved corpus. Returned coefficients follow sample_indices order. Repeated IDs appear in the output repeatedly, but their distances are computed once; repeated IDs also receive repeated weight in the selected mean. Use a sample without replacement to avoid that weighting. A one-row selection is valid when the full labeling has enough clusters. An empty selection returns no coefficients; the mean function requires at least one selected row. Omitting sample_indices or passing None retains complete evaluation. IDs must be nonnegative integers; NumPy integer arrays, including strided arrays, are supported.

The mean over selected rows estimates the complete mean; its accuracy depends on which rows are selected and how many. The selected coefficients themselves use the full cluster denominators and original pairwise scoring order. Only anchor-to-corpus distances are evaluated, so undefined distances exclusively between unselected rows do not block the selected result. An undefined distance involving a selected row raises an error with the original row IDs.

All source records, checksums, and end-of-file are validated, even for an empty selection. Repeated scans retain the same opened file identity and reject in-place changes. Input memory stays bounded by the source block size, plus O(n + m + block_rows × cluster_count) label, selection, and accumulation storage and metric preparation. Candidate data is reread for each source block containing selected rows; storage bandwidth can therefore remain significant even when pair scoring is greatly reduced. Rust exposes silhouette_samples_file_selected(path, labels, sample_indices, seed, block_rows); average its returned coefficients for a selected mean.

For model selection, pass the same sample_indices to silhouette_scores_file:

means = fvs.silhouette_scores_file(
    "candidates.fvs", [labels_k2, labels_k3, labels_k4],
    sample_indices=sample, seed=42, block_rows=128,
)

Every anchor-to-corpus distance is computed once and contributes to all clusterings. With p clusterings and m distinct anchors, expensive metric work is O(m × n); updating cluster totals still costs O(p × m × n). Each clustering uses all of its original members and denominators. The returned means follow the supplied clustering order and exactly match separate selected evaluations with the same seed, including the requested sample order and repeated-ID weighting. The function requires at least one clustering and a nonempty sample. Omitting sample_indices retains complete evaluation.

Memory includes O(p × n) encoded labels, O(p × m) cached coefficients, the sample-position mapping, and at most block_rows times the sum of all cluster counts in accumulators, plus bounded source blocks and metric preparation. The implementation retains no selected-row-by-corpus distance matrix. It validates the same pinned snapshot across all passes before returning any means. Rust exposes silhouette_scores_file_selected(path, labelings, sample_indices, seed, block_rows).

Reusable cosine index and native array inputs

For repeated queries over the same embeddings, construct a CosineIndex once. It owns a snapshot of the corpus, prepares each candidate's scale and norm once, and reuses those values for every query. The Python class accepts nested numeric sequences and float32/float64 array buffers, including NumPy arrays. NumPy is optional. Results are native lists, without JSON encoding or decoding.

import fast_vector_similarity as fvs

index = fvs.CosineIndex([
    [2.0, 0.0],
    [0.0, 1.0],
    [1.0, 0.0],
    [-1.0, 0.0],
    [0.0, 0.0],
])

assert len(index) == 5
assert index.dimensions == 2
assert index.top_k([1.0, 0.0], k=2) == [(0, 1.0), (2, 1.0)]
assert index.scores([1.0, 0.0]) == [1.0, 0.0, 1.0, -1.0, None]

# Query order is preserved; each result contains (original_row_index, score).
matches = index.top_k_many([[1.0, 0.0], [-1.0, 0.0]], k=2)
scores = index.scores_many([[1.0, 0.0], [-1.0, 0.0]])

# For an empty list, retain the desired query dimension explicitly.
empty_index = fvs.CosineIndex([], dimensions=768)

For a NumPy corpus, pass the array directly: index = fvs.CosineIndex(embeddings). Native float32/float64 buffers are copied in logical row order; Fortran arrays, reversed axes, noncontiguous slices, and read-only arrays are supported. Float32 values are promoted to float64. Nonnative-endian NumPy arrays use numeric conversion. An empty two-dimensional array retains its column count. An optional dimensions argument must agree with the corpus shape.

All supplied Python coordinates must be finite real numbers; complex and boolean inputs are rejected, including NumPy scalars and arrays. Wrong dimensions and invalid coordinates raise ValueError, including with k=0; every query row is validated. Zero vectors have undefined cosine scores: scores returns None at their original positions, and top_k excludes them. Ties prefer the smaller original row index. k defaults to 10, and values larger than the corpus return every finite match. A zero query produces no ranked matches. An empty query is valid for a zero-dimensional index and also produces no ranked matches.

Changing the original corpus after construction does not change the index. Python buffers are copied while holding the GIL, and numerical computation releases it. The immutable index can be queried concurrently. Multiple query rows are processed in parallel, with bounded top-k storage and no full score matrix. scores_many explicitly requests that full matrix and therefore uses O(queries * rows) output storage.

The Rust API exposes the same reusable operations:

use fast_vector_similarity::CosineIndex;
use ndarray::array;

let corpus = array![[1.0, 0.0], [0.0, 1.0], [-1.0, 0.0]];
let index = CosineIndex::new(&corpus);
let matches = index.top_k(&array![1.0, 0.0], 2);
assert_eq!(matches[0].index, 0);
let results = index.top_k_many(&array![[1.0, 0.0], [-1.0, 0.0]], 2);
assert_eq!(results[1][0].index, 2);

Rust callers receive NaN for undefined full scores; non-finite corpus rows retain their indices and are excluded from ranking. Dimension mismatches assert. Construction and queries support logical ndarray layouts. The cached coordinates and norms preserve the existing cosine arithmetic and rankings, including extreme finite values and subnormals. Index storage is O(rows * dimensions), plus one norm per row. Each search still scans the complete corpus; this is an exact cosine index with no approximate-neighbor recall tradeoff. The existing batch JSON API remains available for every metric.

To compare repeated searches with the existing JSON API, run python python/benchmark_cosine_index.py --threads 4 --repeats 9 from the repository after building the release extension and installing NumPy. The benchmark uses the bundled Shakespeare embeddings and a seeded synthetic corpus, verifies rankings against both the existing API and NumPy, and reports index construction separately from query latency. Its preencoded JSON baseline excludes serialization.

Approximate nearest-neighbor retrieval for cosine embeddings

For repeated queries against a large cosine corpus, CosineLshIndex builds random-hyperplane hash tables over an existing prepared index. Queries visit selected buckets and deduplicate the original row IDs. The final ranking uses exact cosine scores within that shortlist. A true nearest neighbor can fall outside it.

cosine = fvs.CosineIndex.load("embeddings.fvs")
lookup = fvs.CosineLshIndex(cosine, tables=8, bits=12, seed=42)
neighbors = lookup.top_k(query, 10, probes_per_table=4)
neighbor_batches = lookup.top_k_many(queries, 10, probes_per_table=16)

# Rerank retrieved rows with a different prepared measure in one operation.
ranked = lookup.top_k_reranked_many(
    queries, spearman_index, 10, probes_per_table=4,
)

One probe visits the matching bucket in each table. Additional probes cross combinations of hyperplane boundaries, ordered by the sum of squared query projection margins. A bounded best-first search visits each signature at most once; it does not construct all possible bit combinations. Increasing probes on a fixed index can only add candidates. The maximum is min(2**bits, 65536), also available as lookup.max_probes_per_table. With at most 16 bits, probing all 2**bits buckets recovers the exact cosine ranking. The probe budget counts empty buckets as well as occupied ones, and larger budgets require more work. More bits generally make individual buckets smaller. More tables cost build time and memory but give neighbors more opportunities to collide. Use exhaustive CosineIndex.top_k to measure recall on representative queries.

The default is 8 tables of 12 bits with seed 0. Rust exposes CosineLshIndex::from_index, candidates, candidates_many, top_k, and top_k_many. Batched ranking preserves query order, accepts an inclusive min_score and one optional original row ID per query in exclude_indices, and matches independent single-query calls. Ranking streams the retrieved row IDs directly into bounded top-k heaps. Batched searches parallelize across query rows and retain ranking scratch space only for active workers. Python releases the GIL during retrieval and ranking; NumPy arrays and ordinary sequences follow the same logical row order and input validation as exact search. The index shares the prepared cosine coordinates and stores the hyperplanes plus one signature and row ID per valid row per table. Zero or nonfinite rows have no postings.

Ranking large buckets with bounded candidate memory

top_k, top_k_many, top_k_index, and the approximate graph APIs merge borrowed streams of sorted row IDs from the probed buckets. Each eligible row is scored once even if it appears in many tables. They do not materialize the complete candidate union before ranking, so a large or duplicate-heavy bucket does not require a corpus-sized temporary candidate list.

Apart from the stored index, query preparation, supplied filters, and returned results, ranking keeps one cursor per nonempty eligible bucket, the probe search frontier, and at most k retained matches per active worker. Single-query parallel scoring also uses one reusable block of at most 1,024 scores. This changes temporary memory use without capping candidates or changing the probed buckets, score bits, thresholds, or tie ordering. Every eligible row in those buckets is still scored, so broad probing or crowded buckets can still require a full-corpus scan per query.

The explicit candidates, candidates_many, and candidates_index methods continue to materialize complete CandidateSelection objects when the caller needs row IDs for reranking with another metric.

Fused retrieval and reranking with another similarity measure

top_k_reranked and top_k_reranked_many combine cosine bucket retrieval with ranking by any supported prepared similarity measure. Supply the original raw query vectors and a SimilarityIndex representing the same original corpus rows, in the same order. The scoring index may use Spearman, Kendall, Pearson, Hoeffding, either distance-correlation measure, NMI, JSD, or cosine:

lookup = fvs.CosineLshIndex.load("embeddings.fvslsh")
scoring = fvs.SimilarityIndex.load("spearman.fvs")
neighbors = lookup.top_k_reranked(
    query, scoring, 10, probes_per_table=16, min_score=0.5,
    candidate_indices=allowed_row_ids,
)
ranked_batches = lookup.top_k_reranked_many(
    queries, scoring, 10, probes_per_table=16, seed=42,
    candidate_indices_by_query=allowed_by_query,
    exclude_indices=query_source_ids,
)

Both indexes must have identical row counts and dimensions. These shape checks cannot establish that two indexes represent the same documents: keep their row order and any replacements/removals aligned. Returned scores and the inclusive min_score belong to the scoring index's measure. Shared and per-query metadata filters, common exclusions, and per-query self exclusions use the original candidate IDs and apply before ranking.

For a deterministic measure or explicit seed, results match retrieving the angular candidate IDs and passing them as selections to the scoring index's existing top-k API. Seeded metrics retain original candidate identities, and query ordering, batch boundaries, and worker counts do not change those scores. Each query prepares its scoring representation once; prepared target rows are reused directly. The bucket union streams into the bounded top-k heap, avoiding a materialized shortlist for a single query or a complete batch of shortlists. Both supplied indexes remain resident; metric-specific working storage is additional to bucket streams, query preparation, and retained matches.

Recall remains determined by cosine retrieval. A row that ranks highly under the target measure can lie outside the probed buckets. Undefined angular queries return no matches, and zero/nonfinite angular corpus rows remain ineligible even if the target measure could score them. Exhaustive probing therefore recovers target-metric ranking over the angular-eligible corpus.

Rust exposes top_k_reranked, top_k_reranked_filtered, top_k_reranked_many, top_k_reranked_many_filtered, and top_k_reranked_many_with_options, using the existing SearchOptions and optional original-row exclusions.

Metadata filters for approximate search

Apply the same original-row metadata selections used by exact search directly to LSH ranking. candidate_indices accepts a sequence of row IDs or a reusable CandidateSelection. The filter is intersected with the probed buckets before deduplication and ranking, so ineligible rows are not scored and do not consume top-k slots. Sparse filters search the smaller side of each bucket/selection intersection instead of scanning a large bucket unnecessarily.

eligible = fvs.CandidateSelection(allowed_row_ids, corpus_size=len(lookup))
neighbors = lookup.top_k(
    query, 10, probes_per_table=16, candidate_indices=eligible,
    min_score=0.6,
)
neighbor_batches = lookup.top_k_many(
    queries, 10, probes_per_table=16,
    candidate_indices_by_query=[allowed_for_first_query, allowed_for_second_query],
    exclude_indices=[first_query_source_row, None],
)

For a batch, use either one shared candidate_indices selection or one entry per query in candidate_indices_by_query. Each entry may be a sequence, a CandidateSelection, or None to allow all rows; an empty selection allows none. A shared exclude_index and per-query exclude_indices both apply. Scores, tie ordering, and the inclusive min_score use the original corpus IDs. All selections, bounds, query counts, and probe budgets are validated even for k=0 or empty inputs. Selection objects can be reused across concurrent searches and restored LSH snapshots with the same row numbering.

Filtering does not expand the probe budget or make retrieval exhaustive. A selective filter may yield fewer than k matches even if other eligible rows exist outside the visited buckets. Increase probes for wider retrieval, or use the exact index for an exhaustive filtered search. Rust exposes top_k_filtered, top_k_many_filtered, and top_k_many_with_options, using the existing SearchOptions and CandidateSelection types.

Prepared queries and approximate neighbor graphs

Query an angular index with a saved cosine query corpus using top_k_index. Both CosineIndex and cosine SimilarityIndex queries are accepted. Their stored coordinates and norms are reused, so the original query vectors are unnecessary and normalization is not repeated. Contiguous rows are borrowed; strided rows may need a temporary row copy during scoring. The query index must have the same dimension and cosine measure, but may have a different number of rows.

queries = fvs.CosineIndex.load("queries.fvs")
lookup = fvs.CosineLshIndex.load("embeddings.fvslsh")
matches = lookup.top_k_index(queries, 10, probes_per_table=16)
shortlists = lookup.candidates_index(queries, probes_per_table=16)

# Build a directed neighbor graph from the stored corpus itself.
graph = lookup.pairwise_top_k(10, probes_per_table=16, min_score=0.6)

top_k_index accepts the same shared and per-query selections, exclusions, threshold, and probe budget as top_k_many. Results retain query order and original candidate row IDs, and match searches using the original raw queries. It retains borrowed bucket streams and a bounded ranking heap per active worker. candidates_index returns reusable selections for reranking with another index.

pairwise_top_k searches the stored corpus rows and excludes each row's own ID. Distinct rows containing the same vector remain eligible, and undefined rows have empty neighbor lists. The result contains one list per original row. Each edge uses the same canonical lower-ID scoring order as the exact pairwise API, preserving its score bits, inclusive threshold behavior, and tie ordering. Exhausting all buckets with at most 16 bits therefore reproduces the exact cosine neighbor graph. At smaller probe budgets, true neighbors can be missed and retrieved edges need not be symmetric.

The approximate graph scores retrieved candidates instead of requiring every pair. It keeps the existing index, worker-local bucket streams and top-k heaps, plus O(rows × min(k, rows - 1)) graph output; it never creates a dense score matrix. Large buckets or exhaustive probing can still require quadratic scoring. Python releases the GIL for both prepared search and graph construction, and both work after restoring a complete LSH snapshot. Rust exposes candidates_index, top_k_index, top_k_index_filtered, top_k_index_with_options, and pairwise_top_k.

Bounded and resumable approximate neighbor graphs

Use pairwise_top_k_batches when the complete neighbor lists are too large to keep in memory. It yields (first_row, neighbor_lists) batches, scoring only the requested original query rows against the full indexed corpus:

lookup = fvs.CosineLshIndex.load("embeddings.fvslsh")
with lookup.pairwise_top_k_batches(
    20, probes_per_table=16, min_score=0.6, batch_rows=256,
    start_row=resume_row, stop_row=partition_stop,
) as batches:
    for first_row, neighbors in batches:
        write_graph_rows(first_row, neighbors)
        save_progress(batches.row_offset)

start_row defaults to zero and stop_row defaults to len(lookup). The half-open range may begin or end between batches. Skipped rows are not scored. Neighbor IDs still refer to the complete original corpus, and every returned list exactly matches the corresponding row of pairwise_top_k, including canonical score bits, ties, inclusive thresholds, self exclusion, and empty lists for undefined rows. Adjacent ranges concatenate to the complete graph. Resume using the same saved LSH index, k, probe budget, and threshold; the batch size can change without changing results.

The iterator shares the prepared corpus, planes, and postings; it keeps them alive if the source index is released. It retains at most one output batch, with O(batch_rows × (1 + min(k, rows - 1))) output storage plus borrowed bucket streams, the probe search frontier, and a ranking heap per active worker. Large buckets can still contain the complete corpus, and exhaustive probing can still require quadratic scoring. Previously returned batches belong to the caller and are not retained by the iterator. Creation does no graph scoring, and computation releases the GIL.

row_offset identifies the next original query row and advances after each successful batch. seek_rows(row) moves within the configured range without scoring skipped rows. close() and context exit discard the remaining work; completion and errors also release the shared index. A closed or exhausted iterator cannot be restarted. The read-only properties include total_rows, dimensions, k, probes_per_table, min_score, batch_rows, start_row, stop_row, row_offset, seed, and closed.

Rust exposes CosineLshTopKRows through lookup.pairwise_top_k_batches(k, probes, min_score, batch_rows, start..stop). For one partition returned directly, use lookup.pairwise_top_k_rows(k, probes, min_score, start..stop).

Saving an approximate search index

Save the complete LSH index to retain its actual hyperplanes and bucket entries across process restarts. The snapshot includes the prepared cosine corpus, so loading it does not need the original embedding matrix or a separate index file:

lookup.save("embeddings.fvslsh")
restored = fvs.CosineLshIndex.load("embeddings.fvslsh")
neighbors = restored.top_k_many(queries, 10, probes_per_table=16)

# The same self-contained format can be stored in a database or object store.
snapshot = lookup.to_bytes()
restored = fvs.CosineLshIndex.from_bytes(snapshot)

Rust provides save, load, write_to, and read_from. The versioned little-endian format stores the exact prepared coordinates, norms, hyperplane float bits, sorted postings, and configuration. Loading uses the saved planes; it does not regenerate them from the seed or sort the buckets again. Query results and candidate IDs are preserved for the same execution platform.

The loader checks both the embedded corpus and the complete LSH checksum, rejects inconsistent lengths, invalid configurations, malformed planes, duplicate or incorrect postings, truncation, and trailing bytes, and allocates storage only after reading its data. It verifies each posting against the stored corpus and planes, so load validation costs O(tables * bits * dimensions * valid_rows). Checksums detect accidental corruption; they do not authenticate a snapshot.

save writes and syncs a private sibling temporary file before atomically replacing the destination; failures preserve the previous file. Existing file permissions are retained, and new Unix files use mode 0600. String, bytes, and os.PathLike paths are accepted. LSH snapshots use a separate FVSLSH format: restore them with CosineLshIndex, while ordinary .fvs prepared-corpus snapshots continue to use CosineIndex or SimilarityIndex.

Searching one saved ANN index larger than memory

CosineLshFileIndex searches an existing .fvslsh snapshot while keeping its embedding corpus and bucket postings on disk. It opens the same version 1/2 format written by CosineLshIndex.save; no conversion or rebuilt index is needed. Keep the object open to reuse validation and saved hyperplanes across many searches:

with fvs.CosineLshFileIndex.open("embeddings.fvslsh") as disk:
    neighbors = disk.top_k(query, 10, probes_per_table=16, min_score=0.6)
    batch = disk.top_k_many(queries, 10, probes_per_table=16)
    corpus_rows = len(disk)

Single and many-query results match loading the same file into a CosineLshIndex, including score bits, inclusive thresholds, ties favoring lower original IDs, undefined rows, and the actual saved planes. The candidate_indices, candidate_indices_by_query, exclude_index, and exclude_indices options have the same meanings as the in-memory query APIs. Each candidate ID in the retrieved bucket union is scored once. Sparse metadata filters search the smaller side of each bucket intersection.

Resident index storage follows tables * bits * dimensions for the saved hyperplanes and a small table directory. Each active query adds a fixed-size posting-page cache, one decoded candidate row, a union cursor per nonempty probed bucket, the probe frontier, and its bounded top-k heap. It does not retain the complete corpus, postings, or candidate union. Returned batches still require up to queries * k matches; supplied query matrices and metadata selections are additional. Query work depends on retrieved candidates and disk access, so frequently queried small indexes may be faster in memory.

Opening performs full validation before returning: the embedded prepared corpus, actual hyperplanes, every posting's signature and original row, both checksums, declared lengths, and exact EOF. This costs O(tables * bits * dimensions * valid_rows) computation and makes a positioned corpus-row read for each posting. Opening can therefore be expensive for a large index; reuse the handle or group queries into batches. The corpus scan uses bounded blocks, and posting validation needs no corpus-sized bitmap.

Treat the opened file's contents as immutable. The handle pins the original file, so an atomic save replacement leaves existing readers on their original generation. Length, modification time, and saved header/checksum tokens are checked before and after query calls, including zero-work calls. These checks detect ordinary in-place changes and touched malformed records; they do not promise detection of deliberately concealed edits that preserve metadata and tokens. Queries do not recompute the complete file checksum. The implementation uses checked reads rather than unsafe memory mapping.

Python accepts string, bytes, and path-like paths, and releases the GIL for opening and searches. The context manager or close() releases the file; closed reports its state. Header properties remain readable after closure, and further searches raise ValueError. Concurrent read-only queries may share an open object. Close it after outstanding queries complete. As with other ANN APIs, probing only some buckets can miss true neighbors; exhaustive coverage is possible with 2**bits probes when bits <= 16.

Rust exposes CosineLshFileIndex::open, top_k, top_k_filtered, top_k_many, top_k_many_filtered, and top_k_many_with_options, returning io::Result. Invalid query arguments use InvalidInput; malformed snapshots or detected changes use InvalidData or an I/O error. Dropping the object releases the pinned file.

Adding embeddings without rehashing the existing corpus

with_appended creates a new LSH index containing the old rows followed by new embeddings. with_appended_index accepts an already prepared CosineIndex or cosine SimilarityIndex, so its normalization is reused too:

lookup = fvs.CosineLshIndex.load("embeddings.fvslsh")
first_new_id = len(lookup)
updated = lookup.with_appended(new_embeddings)
updated.save("embeddings.fvslsh")

new_shard = fvs.CosineIndex.load("new_embeddings.fvs")
updated_from_shard = lookup.with_appended_index(new_shard)

Old row IDs stay fixed; the appended rows begin at first_new_id. Duplicate vectors remain separate candidates, and undefined rows still occupy IDs. Dimensions and the cosine measure must match even for an empty append. The existing index and iterators remain usable with their original snapshot; publish the returned index when the new generation is ready. Recreate CandidateSelection objects with the returned corpus size before reusing metadata filters, because selections validate their original corpus length. Python snapshots mutable input arrays and releases the GIL during preparation, hashing, and merging.

The operation preserves the actual stored hyperplane bits and computes hash signatures only for new valid rows. It sorts the new postings and merges them with the existing sorted postings. Existing prepared coordinate/norm bits and all search, graph, and persistence behavior are retained. If an index has never contained a valid row, its first valid append initializes planes from the configured seed. Empty appends share the original storage; appends with only undefined rows share the existing tables.

This is immutable growth: the new generation copies the contiguous prepared corpus and merged postings. Peak memory includes both generations. With N old rows, M new rows, D dimensions, T tables, and B bits per table, it avoids the old rows' O(T × B × D × N) hashing work while retaining O((N + M) × D + T × (N + M)) copy/merge work, new-row hashing/sorting, and a copy of the plane coefficients. Append useful batches instead of repeatedly adding individual rows. Use the editing operations below for existing row slots. Rust exposes with_appended(Array2<f64>) and with_appended_index(&SimilarityIndex) with the same immutable semantics.

Replacing and removing embeddings while preserving row IDs

Use with_replaced to update existing embeddings without rebuilding every row's angular signatures. Replacement rows correspond to row_ids in their supplied order; IDs need not be sorted. with_replaced_index accepts already prepared cosine rows and preserves their coordinate and norm bits:

lookup = fvs.CosineLshIndex.load("embeddings.fvslsh")
updated = lookup.with_replaced([12, 4], replacement_embeddings)
updated = updated.without_rows([7, 20])
updated.save("embeddings.fvslsh")

# A removed slot can be reused later without changing any other row IDs.
replacement = fvs.CosineIndex.load("replacement.fvs")
updated = updated.with_replaced_index([20], replacement)

These operations return new immutable generations. The original index and its existing graph iterators remain usable. without_rows deactivates slots by replacing their embeddings with undefined zero vectors and removing their bucket postings. It does not compact or renumber the corpus: len(updated) still counts every original slot. Removed IDs are absent from candidate retrieval and ranking, and their graph rows are empty. Existing CandidateSelection objects remain valid because the corpus size is unchanged.

Replacement IDs must be unique and in range, and their count must equal the number of replacement rows. Dimensions and the cosine measure must match, including for empty edits. Removal accepts repeated IDs, which have the same effect as removing each ID once. Empty edits share the original storage. Python validates row-ID sequences and snapshots mutable embedding arrays before releasing the GIL for the numerical work.

Only changed valid rows are hashed. Unchanged prepared rows and signatures retain their exact bits; removals require no new signatures. The operation filters old postings and merges sorted replacement postings. It still copies the contiguous corpus and table data into a new generation, so peak memory includes both generations. Batch edits together to amortize these copies.

Actual hyperplanes survive removing every valid row, saving and restoring that empty generation, and later refilling it. Existing version-1 snapshots remain readable, and ordinary generations retain the same version-1 encoding. An empty generation that retains previously created planes uses a version-2 snapshot with an explicit plane-presence flag; older readers reject that version. Refilling those slots reuses the retained planes instead of drawing new ones from the saved seed.

Rust exposes with_replaced(&[usize], Array2<f64>), with_replaced_index(&[usize], &SimilarityIndex), and without_rows(&[usize]), all returning a new CosineLshIndex.

Approximate retrieval across independent saved shards

Cosine StreamingTopK and StreamingTopKMany accumulators accept add_lsh_index and add_lsh_file to combine approximate retrieval from independent LSH shards. Prepare the queries once, load and search one shard at a time, and retain only the global best matches:

search = fvs.StreamingTopKMany(queries, 20)
for path in lsh_shard_paths:
    search.add_lsh_file(path, probes_per_table=16, min_score=0.6)
neighbors = search.matches()
total_row_slots = search.rows_seen

# Search an already loaded shard without loading or preparing it again.
single = fvs.StreamingTopK(query, 20)
single.add_lsh_index(lookup, probes_per_table=16)

The combined corpus need not fit in memory. Each add_lsh_file loads and fully validates one complete .fvslsh snapshot, searches it for every owned query, and releases it. That individual shard must fit in memory. Already loaded indexes are borrowed by add_lsh_index without being retained or copied. Query coordinates and norms are reused, and ranking streams bucket postings without materializing their complete candidate union. Persistent accumulator storage follows the prepared queries and their retained k matches; active work additionally needs the current shard and worker-local probe/ranking storage.

Every accepted shard continues the same global row numbering as exact add_block, add_index, and add_file calls. These methods may be interleaved in one cosine stream. Undefined, filtered, and removed row slots still advance rows_seen. A match's ID is its shard-local ID plus the number of preceding row slots. Scores use the exact cached cosine arithmetic, and ties favor the lower global ID.

candidate_indices, candidate_indices_by_query, and exclude_index address the current shard's local IDs. The many-query exclude_indices argument uses global stream IDs, including IDs in future shards; an exclusion affects the shard containing that ID. Common and per-query exclusions both apply before ranking. min_score is inclusive and applies to the current append, as with the exact streaming methods. Invalid dimensions, measures, probe budgets, filters, row-count overflow, or corrupt files leave all previous matches and progress unchanged. File validation also runs for k=0 and empty query batches.

Shards may have different seeds, actual planes, table counts, and signature widths. probes_per_table is validated against each shard. Results rank the union of candidates retrieved from these independent shards; changing the sharding can change approximate recall. Probing every bucket in every shard (possible with at most 16 bits per table) recovers exhaustive cosine results over the same eligible rows. For saved shards, loading still validates every posting against its stored embedding and planes, so batch queries together to share that load/validation cost or reuse a loaded index.

Rust provides add_lsh_index/add_lsh_file and their _filtered variants on both accumulators. StreamingTopKMany also provides add_lsh_index_with_options and add_lsh_file_with_options for per-query SearchOptions, with global optional self IDs in exclude_indices.

Reusable indexes for every similarity measure

Build a SimilarityIndex once when a corpus will serve multiple queries. It owns a snapshot of the candidate matrix and fixes the metric at construction. Cosine is the default; its candidate scaling and compensated norms are computed once. Each search then prepares its query and computes compensated dot products against the cached corpus. Spearman indexes similarly cache centered average ranks and their norms, so later queries do not re-sort the candidate rows. NMI and JSD indexes store compact bin labels and marginal statistics instead of the raw floating-point corpus. Every path uses the shared metric implementation and the same seeded row streams as the JSON batch API.

Hoeffding indexes also cache average ranks, retaining one representation of each candidate. A raw query is ranked once per search; a prepared query index supplies its ranks directly. Only joint ranking and the statistic remain pair-dependent.

import numpy as np
import fast_vector_similarity as fvs

corpus = np.array([[2, 0], [0, 1], [1, 0], [-1, 0], [0, 0]], dtype=np.float32)
index = fvs.SimilarityIndex(corpus)
query = np.array([1, 0], dtype=np.float64)

assert len(index) == 5
assert index.dimensions == 2
assert index.similarity_measure == "cosine_similarity"
assert index.top_k(query, 2) == [(0, 1.0), (2, 1.0)]
scores = index.scores(query)  # [1.0, 0.0, 1.0, -1.0, nan]

queries = np.array([[1, 0], [0, 1]], dtype=np.float64)
matches = index.top_k_many(queries, 2)
# [[(0, 1.0), (2, 1.0)], [(1, 1.0), (0, 0.0)]]
all_scores = index.scores_many(queries)  # one corpus-ordered list per query

# Every supported measure is available, including reproducible random metrics:
dependence = fvs.SimilarityIndex(corpus, "jensen_shannon_dependency_measure")
replayed = dependence.top_k_many(queries, 2, seed=42)

The native input handling is shared with CosineIndex: numeric sequences and float buffers are accepted, including reversed, sliced, and column-major arrays. Native float32/float64 buffers use bulk copying; other numeric arrays, including non-native byte order, use numeric conversion. Inputs are snapshotted while the GIL is held; index preparation and searches release it. Later mutations of the source matrix do not change the index, and concurrent searches may share it.

SimilarityIndex score lists use floating-point nan for undefined statistics, including zero cosine rows. Top-k returns (original_row_index, score) pairs, excluding undefined scores and breaking exact score ties by the lower row index. All supplied coordinates must be finite; malformed shapes, NaN/infinity, invalid metric names, and invalid sizes/seeds raise ValueError. Query validation still runs with k=0 or an empty index. For an empty sequence corpus, use SimilarityIndex([], dimensions=d) to declare its width; a shaped empty buffer already carries this information. Empty query lists return empty results.

The index is an exact scan under its chosen metric. top_k_many stores at most queries * min(k, rows) returned matches and does not allocate a full score matrix. Multiple queries run in bounded parallel chunks with one bounded heap per active chunk. A single query instead parallelizes corpus partitions. Metric working storage is additional. scores_many intentionally returns the full queries * rows score matrix. With a seed, each many-query result equals a separate single-query call using that same seed; splitting or reordering queries does not change their scores.

Rust exposes the same reusable core:

use fast_vector_similarity::{SimilarityIndex, SimilarityMeasure};
use ndarray::array;

let index = SimilarityIndex::new(
    array![[2.0, 0.0], [0.0, 1.0], [-1.0, 0.0]],
    SimilarityMeasure::CosineSimilarity,
);
let matches = index.top_k(&array![1.0, 0.0], 2, None);
let batches = index.top_k_many(&array![[1.0, 0.0], [0.0, 1.0]], 2, None);
assert_eq!(matches[0].index, 0);
assert_eq!(batches[1][0].index, 1);

The existing CosineIndex API delegates to this same search engine and retains its None convention for undefined Python scores and default k=10.

Rust SimilarityIndex construction takes ownership of an Array2; it reuses that storage for cosine scaling or centered Spearman ranks and adds one norm per row. Rust methods retain the existing dimension-assertion and NaN contracts, including non-finite corpus rows.

Updating a prepared corpus without repeating existing preparation

SimilarityIndex and CosineIndex support the same immutable lifecycle as CosineLshIndex: with_appended, with_appended_index, with_replaced, with_replaced_index, and without_rows. This works for all nine measures, including indexes restored from saved snapshots after the raw vectors have been discarded. Existing scaled coordinates, norms, ranks, histogram labels, and marginal statistics are copied exactly. Raw operations prepare only the incoming rows; the _index forms copy already prepared rows with the same measure and dimension.

scoring = fvs.SimilarityIndex(corpus, "spearman_rho")
lookup = fvs.CosineLshIndex(fvs.CosineIndex(corpus), tables=8, bits=12, seed=42)

# Apply the same row operations to angular retrieval and its scoring corpus.
new_rows = np.array([[3., 1.], [1., 4.]])
scoring = scoring.with_appended(new_rows)
lookup = lookup.with_appended(new_rows)

replacements = np.array([[5., 2.], [2., 7.]])
scoring = scoring.with_replaced([3, 1], replacements)
lookup = lookup.with_replaced([3, 1], replacements)
scoring = scoring.without_rows([2])
lookup = lookup.without_rows([2])

matches = lookup.top_k_reranked(query, scoring, 3, probes_per_table=8)
scoring.save("updated-spearman.fvs")

# Prepared-only ingestion needs no original floating-point observations.
incoming = fvs.SimilarityIndex(new_rows, "spearman_rho")
another_generation = scoring.with_appended_index(incoming)

Appending assigns IDs starting at the previous len(). Replacements preserve length and every row ID; incoming rows correspond to row_ids in their supplied order, and duplicate replacement IDs are rejected. Removals preserve length and store undefined row slots instead of compacting the corpus. Those rows are excluded from rankings and yield undefined scores both as candidates and as prepared queries, across every measure. Replacing a removed slot revives its original ID. Duplicate removal IDs are harmless. The existing saved-index format preserves these states without a format change.

Existing generations and their owned pairwise iterators remain usable during concurrent updates. Empty edits share the original storage after validation. Nonempty edits copy retained storage into a new generation, so peak memory includes both generations and incoming rows; these are not in-place updates. Append requires new CandidateSelection objects for the enlarged corpus. Selections remain valid after replacement or removal because IDs and length stay fixed. Seeded scores continue to use those original IDs, including for sampled distance correlation and shuffled JSD scoring.

Python copies raw input while holding the GIL and releases it for preparation and editing. Bad dimensions, metrics, IDs, counts, or duplicate replacement IDs raise ValueError, including on empty operations. Unsupported prepared-index objects raise TypeError; checked allocation failures raise MemoryError. Rust exposes the same five methods on both index types and returns Result<Self, IndexEditError>; prepared arguments borrow &SimilarityIndex (use CosineIndex::as_ref() for the cosine convenience wrapper).

Searching with prepared query indexes

scores_index and top_k_index use the rows of one prepared index as queries against another. This supports comparing saved corpora without keeping the original raw query vectors. Both indexes must have the same measure and dimension; their row counts can differ.

import fast_vector_similarity as fvs

candidates = fvs.SimilarityIndex.load("candidates.fvs")
queries = fvs.SimilarityIndex.load("queries.fvs")

# One ranked list per query row; each match ID belongs to candidates.
matches = candidates.top_k_index(queries, 10, seed=42, min_score=0.0)

# A dense query-by-candidate matrix, when every score is needed.
scores = candidates.scores_index(queries, seed=42)

# An index can query itself, excluding only each row's own candidate ID.
neighbors = candidates.top_k_index(
    candidates, 10, seed=42, exclude_indices=list(range(len(candidates))),
)

Cosine/Pearson coordinates and norms, Spearman and Hoeffding ranks, and NMI/JSD histogram labels and marginals are borrowed directly from the query index. They are not normalized, centered, ranked, or binned again. Raw-only metrics and noncontiguous coordinate rows need at most one query-row copy per active worker; no complete query corpus is duplicated. Both indexes stay immutable and can be shared across concurrent searches, including when they are the same object. Python releases the GIL during numerical work.

With an explicit seed or a deterministic metric, results match scores_many and top_k_many on the original raw query rows, including score bits and tie ordering. Query rows retain their order; result IDs refer to the candidate index. The seed follows the query-to-corpus contract: each query uses the same supplied seed independently, and candidate row IDs determine random streams. Pairwise graph APIs use their separately documented pair streams.

top_k_index accepts candidate_indices, exclude_index, exclude_indices, and min_score. Shared selections and exclusions refer to candidate row IDs. Per-query exclude_indices contains one candidate ID or None for each query row. All filters and both index schemas are validated even for k=0 or empty inputs, and filtering happens before top-k selection.

The dense scores_index result requires O(query rows × candidate rows) output storage. top_k_index uses O(query rows × min(k, eligible candidates)) output, bounded worker heaps, and metric working storage, without a dense intermediate. Both prepared indexes remain resident in memory during these calls.

Both Python index classes expose these methods and accept either index class when its measure matches. SimilarityIndex.scores_index retains undefined scores as NaN; CosineIndex.scores_index uses None, following their existing score methods. Top-k excludes undefined results in both classes.

Rust exposes scores_index(&SimilarityIndex, seed), top_k_index(&SimilarityIndex, k, seed), and top_k_index_filtered(&SimilarityIndex, k, seed, SearchOptions, exclusions) on SimilarityIndex, with forwarding methods on CosineIndex that omit the seed argument, matching its existing deterministic API. These return Result<_, SearchError>; mismatched measures report SearchError::IndexMeasureMismatch. Existing saved-index formats are unchanged.

For batched reranking, pass candidate_indices_by_query to top_k_many or top_k_index. Supply one shortlist per query. Each entry can be a sequence of original candidate IDs, a reusable CandidateSelection, or None to search the full index. An empty shortlist yields no matches for that query. This lets a first retrieval stage pass distinct candidates to an exact scoring stage without first scoring their union.

index = fvs.CosineIndex([[1, 0], [0, 1], [-1, 0], [1, 0]])
matches = index.top_k_many(
    [[1, 0], [-1, 0], [0, 1]], k=2,
    candidate_indices_by_query=[[3, 0, 3], [1, 2], []],
)
assert matches == [[(0, 1.0), (3, 1.0)], [(2, 1.0), (1, 0.0)], []]

Use either candidate_indices_by_query or the shared candidate_indices. Shared and per-query exclusions and the inclusive score threshold still apply. Scores, seeded sampling, and tie ordering refer to the original row IDs. Rust exposes SimilarityIndex::top_k_many_with_options for raw queries and SimilarityIndex::top_k_index_with_options for prepared queries. Pass a slice of SearchOptions in query order and the optional per-query exclusions.

Saving and restoring prepared indexes

Save a prepared SimilarityIndex or CosineIndex once and restore it in another process without supplying the original embeddings. The snapshot stores the fixed measure, dimensions, row order, and the representation already used for search: scaled cosine coordinates and norms, centered Pearson coordinates and Spearman ranks with their norms, compact NMI/JSD bins and marginals, or raw coordinates for the other measures. Loading restores that state directly, without reranking or rebinning it.

from pathlib import Path
import fast_vector_similarity as fvs

index = fvs.SimilarityIndex(
    [[10, 20, 20, 40], [4, 3, 3, 1], [7, 7, 7, 7]],
    "spearman_rho",
)
path = Path("corpus.fvs")
index.save(path)

restored = fvs.SimilarityIndex.load(path)
query = [1, 2, 2, 4]
assert restored.top_k(query, 2, seed=42) == index.top_k(query, 2, seed=42)
assert restored.dimensions == 4
assert len(restored) == 3

payload = index.to_bytes()  # optional explicit transport as immutable bytes
copy = fvs.SimilarityIndex.from_bytes(payload)

Both classes accept string, bytes, and os.PathLike paths, including pathlib.Path. CosineIndex shares the same format with a cosine SimilarityIndex and rejects snapshots for other measures. Restored indexes remain immutable and safe for concurrent searches, including filtered and many-query operations. Original row IDs, empty-matrix dimensions, undefined rows, and cached floating-point bits are retained. Within the same numerical runtime, deterministic and explicitly seeded searches reproduce their saved index's score bits and rankings. Queries, filters, and seeds are supplied when searching and are not part of the snapshot.

The versioned little-endian format includes a checksum for accidental corruption. Loading rejects unsupported versions, inconsistent shapes or prepared data, truncated streams, checksum failures, and trailing bytes. It validates sizes and grows allocations only after reading actual payload bytes. The checksum does not authenticate a file's origin. Invalid snapshots raise ValueError in Python; filesystem failures retain OSError subclasses.

Hoeffding snapshots use version 2 to store average ranks and row validity. Existing version-1 raw Hoeffding snapshots remain readable and are ranked once during loading or streamed chunk decoding. Saving them writes the prepared version-2 representation. Other measures retain their existing version-1 encoding. Older library versions cannot read the new Hoeffding representation.

save writes and syncs a sibling temporary file before atomically replacing the destination. Parent directories must already exist; a failed write preserves an existing destination and cleans up its temporary file. Path-based save/load stream the representation without constructing another serialized corpus in memory. to_bytes/from_bytes explicitly hold the byte representation as well as the index. Loading still creates an owned in-memory index.

Rust provides write_to(impl Write) and read_from(impl Read) for stream I/O, and save(path) / load(path) for files, on both index types. All return std::io::Result. Stream writes may leave partial output on failure; use save when replacing a file. The reader consumes one complete snapshot and requires EOF after its checksum.

Building saved indexes from bounded input batches

SimilarityIndexWriter creates a saved prepared corpus without holding the complete corpus in memory. Its measure and dimension are fixed at construction. Each add_block prepares and writes just the supplied rows, and add_index writes a matching prepared SimilarityIndex or CosineIndex directly.

import fast_vector_similarity as fvs

# batches yields matrices with 768 coordinates per row.
with fvs.SimilarityIndexWriter(
    "corpus.fvs", dimensions=768, similarity_measure="cosine_similarity",
) as writer:
    for block in batches:
        writer.add_block(block)
    print(writer.rows_written)

# Search the resulting file without loading the complete index.
search = fvs.StreamingTopKMany(queries, 10, seed=42)
search.add_file("corpus.fvs", chunk_rows=2048)
neighbors = search.matches()

Raw and prepared blocks can be interleaved, including empty blocks. Their rows are concatenated in append order, and undefined statistics retain their row positions. All nine metrics are supported. For the same input rows and metric, the resulting bytes match a snapshot saved from one complete index. The output uses the existing format and works with load, read_from, and streamed add_file searches.

The writer holds bounded I/O buffers plus the current block and its preparation; it retains no previous blocks. Because the final row count and histogram payload size may be unknown initially, finish() fills the final header and makes one bounded sequential pass over the temporary file to compute its checksum. That pass adds disk I/O without loading the corpus into memory.

The destination is published atomically only after finalization and syncing. An existing destination remains unchanged while blocks are appended. On Unix, the temporary file is private; the published file preserves an existing destination's permission bits, or uses mode 0600 for a new file. Parent directories must already exist. Python accepts strings, bytes, and os.PathLike paths, and releases the GIL during preparation and I/O.

A normal context-manager exit calls finish(); an exception before publication calls abort() and propagates the exception. Explicit abort() and abandoning an unfinished writer also discard its temporary output. finish() is idempotent after success. Appending after closure or finishing an aborted or failed writer raises ValueError; aborting an already finished writer leaves the published file intact.

Invalid block data, dimensions, or measures do not consume rows and leave the writer usable. A write or publication failure closes the writer and preserves the destination; filesystem errors retain their OSError subclasses. Read-only properties expose rows_written, dimensions, similarity_measure, closed, and finished. Serialize operations on one writer; separate writers can build different files concurrently.

Rust exposes SimilarityIndexWriter::create(path, dimensions, measure), add_block(Array2<f64>), add_index(&SimilarityIndex), finish(), and abort(), with std::io::Result errors and matching lifecycle behavior. The writer takes ownership of raw blocks and borrows prepared indexes only during each append. Dropping an unfinished writer abandons its temporary file.

Reading saved indexes in bounded batches

SimilarityIndexReader(path, chunk_rows=4096) reads a saved index as successive (row_offset, prepared_index) batches. It supports every measure and preserves the saved row order, dimensions, undefined rows, and cached preparation. The offset identifies each batch's rows in the complete file. A returned index owns its data and remains usable after the reader closes.

For exact top-k retrieval across two saved indexes, ScoreFileTopK reads a batch of queries, scans the candidate file, and emits (first_query_row, match_lists). Each list holds up to k pairs of global candidate ID and similarity. Higher scores rank first, exact ties favor the smaller ID, and min_score is inclusive. Matching query and candidate IDs are eligible by default, including when the same snapshot supplies both inputs.

import json
import os
from pathlib import Path
from tempfile import TemporaryDirectory
import fast_vector_similarity as fvs

destination = Path("neighbors.jsonl")
with TemporaryDirectory(dir=destination.parent) as staging:
    pending = Path(staging) / "neighbors.jsonl"
    with pending.open("w", encoding="utf-8") as output:
        with fvs.ScoreFileTopK(
            "queries.fvs", "candidates.fvs", 10, seed=42,
            query_block_rows=128, candidate_block_rows=2048,
        ) as neighbors:
            for offset, rows in neighbors:
                for local_row, matches in enumerate(rows):
                    output.write(json.dumps({
                        "query_index": offset + local_row,
                        "matches": matches,
                    }) + "\n")
    os.replace(pending, destination)

Both block sizes default to 128. Memory depends on the active query and candidate blocks, the per-query top-k results, and the metric's work space. The iterator pins both open files and validates the complete snapshots on exhaustion or successful finish(). The example publishes staged output after validation. Set start_row and stop_row to partition or resume work on a half-open range of query IDs. Each selected query searches every eligible candidate. Reuse the iterator's seed to reproduce randomized scores across partitions. Rust exposes the same traversal through ScoreFileTopK::open and ScoreFileTopK::open_range.

Filtering saved-file top-k searches

ScoreFileTopK accepts candidate_indices, exclude_index, and exclude_self=False alongside min_score. Candidate IDs refer to the entire saved candidate corpus, even when start_row resumes inside a query block. A selection may be an integer sequence, a NumPy integer array, or a reusable CandidateSelection. It is validated, sorted, deduplicated, and owned by the iterator; the caller can release its original filter after construction.

with fvs.ScoreFileTopK(
    "queries.fvs", "candidates.fvs", 10, seed=42,
    candidate_indices=eligible_candidate_ids,
    exclude_index=blocked_candidate_id, min_score=0.75,
    exclude_self=True, start_row=resume_query_row,
    query_block_rows=64, candidate_block_rows=512,
) as neighbors:
    for offset, rows in neighbors:
        write_staged_neighbor_rows(offset, rows)

exclude_index removes one candidate for every query. With exclude_self=True, original query row i excludes candidate row i, regardless of the two paths; use it when those ID spaces identify the same entities. A query ID beyond the candidate count excludes nothing. Different rows containing identical vectors remain eligible. By default matching IDs are included, preserving existing directed retrieval behavior.

All filters combine before ranking. Returned IDs and sampled streams remain global across sparse gaps, candidate blocks, and resumed query ranges. The owned selection occupies O(m) IDs for m unique selected rows; additional filter storage is bounded by the active query and candidate blocks. Unselected data still passes schema, checksum, and EOF validation. Empty selections, k=0, and empty query ranges preserve that validation contract and all argument checks. No full score matrix is allocated.

The iterator also exposes read-only exclude_index and exclude_self. Rust adds ScoreFileTopK::open_filtered and open_range_filtered, accepting a SearchOptions value and an explicit exclude_self boolean. Existing Rust constructors retain their signatures and behavior.

The reader exposes total_rows, rows_read, dimensions, similarity_measure, chunk_rows, closed, and validated. rows_read counts successfully decoded rows, including rows discarded by finish(). A checksum failure can leave rows_read == total_rows while validated is false.

The checksum is stored at the end of the snapshot. Earlier batches remain provisional until exhaustion or successful finish(). The last batch is returned only after the checksum and exact end of file have been validated. finish() consumes and validates any unread data with bounded memory; a normal context-manager exit calls it automatically, including after an early break. close() releases the input without validating unread data, and exceptional context exits close without masking the original exception. A normal context exit requires validation, so explicitly closing an unfinished reader inside that context raises ValueError at exit. An I/O or data error closes the reader and subsequent iteration stops. Keep the file unchanged during reading; atomic replacement by the index writer leaves an already-open reader attached to its original file.

The same reader composes with SimilarityIndexWriter for bounded copying, repacking, and legacy Hoeffding snapshot upgrades:

with fvs.SimilarityIndexReader("source.fvs", chunk_rows=512) as reader:
    with fvs.SimilarityIndexWriter(
        "copy.fvs", reader.dimensions, reader.similarity_measure,
    ) as writer:
        for _, block in reader:
            writer.add_index(block)
        reader.finish()  # Validate before the writer publishes its destination.

Rust exposes SimilarityIndexReader::open(path, chunk_rows) for files and SimilarityIndexReader::new(reader, chunk_rows) for any Read, including nonseekable streams. Its iterator yields io::Result<(usize, SimilarityIndex)>. It provides the same metadata and lifecycle methods; Rust callers explicitly exhaust the iterator or call finish() to validate the complete source.

Prepared Spearman search

For repeated rank-correlation searches, select "spearman_rho" when building the index. Tied coordinates receive average ranks, and each row's centered ranks and norm are computed once. Queries are ranked once per search, then compared with the cached corpus using dot products. The scalar, raw batch, and prepared-index paths share the same rank and scoring kernels, preserving exact score bits and ranking ties.

index = fvs.SimilarityIndex(
    [[10, 20, 20, 40], [4, 3, 3, 1], [7, 7, 7, 7]],
    "spearman_rho",
)
scores = index.scores([1, 2, 2, 4])  # approximately [1, -1, nan]
matches = index.top_k([1, 2, 2, 4], 2, min_score=0.0)
assert [row for row, score in matches] == [0]

For R rows and D coordinates, construction costs O(R D log D). Each later query costs O(D log D + R D) for scoring, plus any top-k selection work; a sparse candidate selection replaces R with its selected-row count. Raw batch searches also reuse query ranks, but still rank each candidate. Constant vectors and vectors with fewer than two observations remain undefined, and all array layouts retain logical coordinate order. The index replaces its owned coordinates with ranks and stores one norm per row, without retaining a second corpus copy.

examples/benchmark_spearman_index.rs compares the native Rust raw-batch and prepared-index paths in the same process, verifies identical outputs before timing, and reports construction separately from repeated query latency. It accepts corpus size, dimensionality, query count, repetitions, and worker count; run it through the repository's DSR quality workflow.

Reusable Kendall query preparation

Kendall tau-b searches prepare each query's sorted observation order, equal-value groups, and exact marginal pair count once. Each candidate is gathered in that saved order, with sorting restricted to groups where the query has ties, before counting discordant pairs. Untied queries avoid the complete lexicographic pair sort for every candidate. Pair counts remain integers until the final score calculation, preserving the scalar statistic and its tie correction.

This preparation is shared by batch scoring, single/many-query index methods, streaming searches across raw and saved blocks, and active pairwise source rows. Kendall indexes continue to retain raw candidate coordinates and use their existing snapshot encoding. Candidate inversion counting remains O(D log D); the cache removes repeated query work and pair-tuple allocation without changing the metric's scoring or undefined-input contracts.

examples/benchmark_kendall_search.rs checks exact scalar score bits, then compares repeated scalar, batch, and indexed scans for deterministic untied and tied inputs with one worker. Run it in release mode through DSR to measure the effect on the current runtime; index construction is reported separately.

Prepared NMI and JSD search

Indexes for "normalized_mutual_information" and "jensen_shannon_dependency_measure" prepare the fixed 20-bin discretization once per corpus row. Each query is binned once, and comparisons reuse the candidate labels, marginal probabilities, and entropy.

corpus = [[0, 1, 2, 3, 4, 5], [5, 4, 3, 2, 1, 0], [0, 0, 1, 1, 2, 2]]
query = [0, 1, 1, 2, 3, 5]

nmi = fvs.SimilarityIndex(corpus, "normalized_mutual_information")
scores = nmi.scores(query)
matches = nmi.top_k(query, 2, candidate_indices=[0, 2])

jsd = fvs.SimilarityIndex(corpus, "jensen_shannon_dependency_measure")
replayed = jsd.top_k_many(
    corpus, 2, seed=42, exclude_indices=list(range(len(corpus))),
)
assert replayed == jsd.top_k_many(
    corpus, 2, seed=42, exclude_indices=list(range(len(corpus))),
)

The persistent coordinate payload falls from eight-byte floats to one-byte bin labels, plus 20 marginal probabilities, one entropy, and container metadata per valid row. The original floating-point corpus is released after construction; it is not retained alongside the prepared data. Construction temporarily holds the input matrix and the growing prepared representation. Total memory savings depend on dimensionality because each row also has fixed metadata.

NMI comparisons need one fixed 400-cell joint histogram. JSD uses a fixed joint histogram and a fresh copy of the candidate's compact labels for its shuffled baseline. Cached labels and marginals are immutable, so searches can share the same index concurrently. Preparation and scoring preserve the existing bin boundaries, entropy/divergence arithmetic order, constant-vector conventions, and seeded results. In particular, a filtered row keeps its original batch stream, followed by the same JSD stream used by scalar dispatch; filtering or regrouping queries does not alter its seeded score.

Raw batch searches reuse the prepared query too, while preparing each raw candidate on demand. Scalar NMI retains a streaming path with fixed-size histograms and no per-observation label allocation; it shares entropy and normalization with the prepared kernel. Empty or non-finite Rust rows remain at their original positions with undefined scores; Python still rejects non-finite input. Constant rows are valid prepared data: NMI is undefined when both vectors have zero entropy, while JSD retains its existing zero-dependence convention.

examples/benchmark_histogram_index.rs compares native Rust raw batch scoring with prepared NMI/JSD indexes, reports construction separately, and checks exact score bits before timing. Its default workload uses 512 rows, 1,536 coordinates, four queries, seven alternating repetitions, and two workers. Run it through the repository's DSR quality workflow.

Streaming exact top-k for large corpora

StreamingTopK searches successive candidate blocks without retaining the complete corpus. It prepares the query once, scans each block, and merges that block's best matches into a bounded running result. All supported metrics use the same scoring kernels as the existing batch and index APIs.

import fast_vector_similarity as fvs

search = fvs.StreamingTopK([1.0, 0.0], 3, "cosine_similarity", seed=42)
search.add_block([[1.0, 0.0], [0.0, 1.0]])
search.add_block([])  # empty blocks are valid and do not consume row IDs
search.add_block([[2.0, 0.0], [-1.0, 0.0]])

assert search.rows_seen == 4
assert search.matches() == [(0, 1.0), (2, 1.0), (1, 0.0)]

For an existing NumPy file, a memory-mapped array can supply blocks without loading the entire candidate matrix into application memory:

import numpy as np

query = np.load("query.npy")
candidates = np.load("embeddings.npy", mmap_mode="r")
search = fvs.StreamingTopK(query, 20, "cosine_similarity")
for start in range(0, len(candidates), 8192):
    search.add_block(candidates[start:start + 8192])
neighbors = search.matches()

Blocks form one corpus in append order. Returned IDs are global row positions in that concatenation; empty blocks add no rows, while rows with undefined scores still consume their original positions. Scores are ranked descending, with lower global IDs winning exact ties. For deterministic metrics or an explicit seed, arbitrary block boundaries produce the same results as a single full-corpus search. Randomized metrics derive their streams from global row IDs, not positions within a block.

matches() returns the best results seen so far and can be called after any append. The query, measure, seed, and k remain fixed for the accumulator. Append blocks sequentially to an instance; independent accumulators can run concurrently. A dimension or input-validation error leaves its existing result and row count unchanged, including when k=0. Python uses the same finite real-number sequence and NumPy-buffer validation as the index APIs, snapshots each block before releasing the GIL, and does not retain that block afterward.

Persistent accumulator storage is O(query dimensions + k). Processing a block adds O(workers × min(k, block rows)) selection storage and the metric's working storage; Python also owns the converted block during that call. Only the best matches are retained between calls. Applications control candidate memory by choosing their block size.

Rust exposes StreamingTopK and StreamingSearchError directly:

use fast_vector_similarity::{StreamingTopK, SimilarityMeasure};
use ndarray::array;

let mut search = StreamingTopK::new(
    array![1.0, 0.0], 2, SimilarityMeasure::CosineSimilarity, Some(42),
);
search.add_block(&array![[1.0, 0.0], [0.0, 1.0]]).unwrap();
search.add_block(&array![[2.0, 0.0], [-1.0, 0.0]]).unwrap();
assert_eq!(search.rows_seen(), 4);
let matches = search.into_matches();
assert_eq!(matches.iter().map(|entry| entry.index).collect::<Vec<_>>(), [0, 2]);

The Rust accumulator takes ownership of the query and borrows each candidate block. It accepts all logical ndarray layouts, preserves NaN/undefined-score semantics, and rejects dimension mismatches or row-count overflow before changing its state.

Filtering streamed candidate blocks

Apply metadata eligibility, self-neighbor exclusion, or a score threshold while adding each block. Filters run before top-k selection, so ineligible high-scoring rows cannot displace eligible results. candidate_indices and exclude_index refer to positions within the supplied block; returned matches and seeded random streams keep their global row IDs. Every supplied row advances rows_seen, including filtered-out and undefined rows.

search = fvs.StreamingTopK([1.0, 0.0], 2, seed=42)
search.add_block(
    [[1.0, 0.0], [0.0, 1.0], [-1.0, 0.0]],
    candidate_indices=[1, 2],  # metadata permits only these block-local rows
    min_score=0.0,
)
search.add_block(
    [[2.0, 0.0], [1.0, 0.0]],
    exclude_index=0,  # skip this block's first row (global row 3)
    min_score=0.0,
)
assert search.rows_seen == 5
assert search.matches() == [(4, 1.0), (1, 0.0)]

A CandidateSelection can replace the index sequence; its corpus_size must equal the current block's row count. Duplicate indices are deduplicated, an absent selection admits every row, and an empty selection admits none. Sparse selections skip metric evaluation for unselected rows. The finite min_score threshold is inclusive. Options affect only the block being added; use the same threshold on every block to apply it throughout the stream. Invalid filters leave both results and progress unchanged, even for k=0, empty selections, or undefined queries. Python still validates all supplied coordinates.

Rust callers use add_block_filtered(&block, SearchOptions { ... }) with the same block-local convention, reusing CandidateSelection and SearchOptions from in-memory search. Filter failures return StreamingSearchError::InvalidFilter containing the underlying SearchError. The existing add_block(&block) method continues to search every row.

Streaming many queries in one corpus pass

Use StreamingTopKMany to search a fixed matrix of queries over a corpus that does not fit in memory. Every block is converted from Python once and shared across the query batch. For cosine, Pearson, Spearman, Hoeffding, NMI, and JSD, multiple queries also share one prepared representation of that block, avoiding repeated candidate scaling, ranking, or binning. Each query retains its own best matches as the scan progresses.

import fast_vector_similarity as fvs

search = fvs.StreamingTopKMany([[1.0, 0.0], [-1.0, 0.0]], 2)
search.add_block([[1.0, 0.0], [0.0, 0.0]])
search.add_block([[2.0, 0.0], [-1.0, 0.0]])

assert len(search) == 2  # number of queries
assert search.rows_seen == 4  # number of corpus rows consumed
assert search.matches() == [
    [(0, 1.0), (2, 1.0)],
    [(3, 1.0), (0, -1.0)],
]

For example, retrieve neighbors for a query matrix while making one pass over a memory-mapped embedding file:

import numpy as np

queries = np.load("queries.npy")
candidates = np.load("embeddings.npy", mmap_mode="r")
search = fvs.StreamingTopKMany(queries, 20, "spearman_rho", seed=42)
for start in range(0, len(candidates), 8192):
    search.add_block(candidates[start:start + 8192])
neighbors_by_query = search.matches()

matches() returns a new list for every query in its original order, containing up to k (original_row_id, score) pairs. It can be called after any block; earlier result snapshots do not change when new blocks arrive. Undefined scores are omitted independently for each query. Exact ties prefer the smaller global row ID. All similarity measures are supported; omitting the measure or passing None selects cosine.

A fixed seed gives each query the same scores as a separate StreamingTopK or full-corpus batch search using that seed. Query regrouping or reordering and candidate block boundaries do not change those results. Randomized measures without an explicit seed retain their usual nondeterminism. One-query batches use the single-query scanning path without preparing a separate candidate corpus for one use.

Query arrays and candidate blocks accept the same finite numeric sequences and float32/float64 buffers as the other native APIs, including strided, reversed, Fortran, and read-only arrays. Construction snapshots the query matrix; each add_block snapshots that block. Python validation finishes before processing, so an invalid block changes neither the row count nor any query's matches. Validation and row counting still apply with k=0 or no query rows. For an empty query list, use StreamingTopKMany([], k, dimensions=d) to retain a width of d; a two-dimensional empty array already carries its width. A zero-dimensional query row is retained with an empty match list. dimensions, k, similarity_measure, and rows_seen are read-only properties.

With Q queries and D coordinates, persistent storage is O(Q * (D + k)), independent of the total corpus size. Each call additionally holds the supplied candidate block, its shared preparation when applicable, bounded selection heaps, and metric working storage. No full query-by-corpus score matrix is allocated. Choose the candidate block size to control that temporary storage; split a large query matrix into groups if needed to bound query and result storage. Numerical work releases the GIL. Append blocks sequentially to each accumulator; independent accumulators can run concurrently.

For full-data distance-correlation searches, and sampled distance searches with at most 1,000 dimensions, multiple nonconstant queries can share each eligible candidate's normalization and marginal distance sums. The streaming ranker prepares up to 32 candidates at a time and feeds their scores directly into the per-query top-k heaps. Shared sparse selections and common or per-query exclusions retain original row IDs; excluded candidates are skipped before scoring. This applies to raw blocks, prepared indexes, and saved files, including two-file retrieval with ScoreFileTopK. The cache stays bounded even when a complete in-memory candidate index is supplied.

examples/benchmark_streaming_distance_cache.rs compares prepared-index scans with streaming scans on dense and sparse selections, verifies exact score bits, and reports timings for full and sampled distance correlation. Run the release example through DSR; timings depend on the workload and machine.

Small query batches also use spare workers to divide large candidate scans. The same bounded scheduling applies to dense and top-k searches on SimilarityIndex, raw and prepared streaming blocks, and saved-file searches. Each query is prepared once and shared across its candidate partitions; the total number of active partitions and partial top-k heaps is bounded by the worker count. Sparse selections determine the amount of eligible work, and short scans keep their existing query-based scheduling. Seeded scores, original row IDs, filters, self exclusions, and tie ordering remain unchanged.

Rust provides StreamingTopKMany::new(queries, k, measure, seed) with the same add_block, matches, into_matches, rows_seen, dimensions, k, and measure methods as StreamingTopK, plus len and is_empty for the query count. It owns the query matrix and borrows each candidate block for that call. Dimension mismatches and cumulative row-count overflow return StreamingSearchError before any query's results are changed.

Filtering a query batch and excluding each query's own row

StreamingTopKMany.add_block accepts shared metadata eligibility and a separate self-neighbor exclusion for each query. Filtering happens before bounded top-k selection, so ineligible high scores cannot displace eligible neighbors.

Option Row numbering and behavior
candidate_indices Positions within the current block, or a CandidateSelection created for that block's row count. None admits every row; [] admits none. Duplicate indices are removed.
candidate_indices_by_query One shortlist per query. Each entry accepts row IDs, a CandidateSelection, or None to search all rows. An empty entry selects no candidates.
exclude_index One position within the current block to omit for every query.
exclude_indices One global corpus row ID or None per query. IDs outside the current block are ignored, so the same self IDs can be passed on every append.
min_score A shared finite, inclusive lower score bound for this block.

Pass candidate_indices_by_query to add_block, add_index, or add_file when each query has its own candidates, for example after approximate retrieval. Choose one of candidate_indices_by_query and candidate_indices per append. For a saved file, shortlist IDs address the entire file independently of chunk_rows. All queries share the decoded chunks. A failed file validation discards the append and its provisional matches.

search.add_file(
    "shard.fvs", chunk_rows=1024,
    candidate_indices_by_query=[[17, 1029], [2, 8, 1029]],
)

Rust exposes add_block_with_options, add_index_with_options, add_reader_with_options, and add_file_with_options with one SearchOptions per query.

When multiple active queries rerank a raw block using cosine, Pearson, Spearman, Hoeffding, NMI, or JSD, their shortlists share one preparation of the eligible candidate union. Overlapping IDs are deduplicated while collecting that union, so temporary ID storage grows with unique eligible rows. Sparse shortlists copy and prepare only those rows; an unrestricted active query uses the complete block. Each query still scores only its own eligible IDs, and exclusions, sampled streams, and tie ordering use the original global row IDs. Prepared shards retain their existing representations. Shortlist query tasks are bounded by the worker count to limit simultaneous metric workspaces and ranking heaps.

Per-query shortlists also share full-distance-correlation candidate marginals, including approximate distance correlation at or below 1,000 dimensions. The ranker merges the sorted eligible IDs incrementally and prepares at most 32 shared candidates at a time. It retains O(query count) cursor and membership metadata, without collecting the complete candidate union or copying the raw corpus. Only candidates used by multiple nonconstant queries receive this shared preparation. Candidates used once keep ordinary scoring, and constant queries retain their inexpensive candidate-validity checks. An initial scan of the eligible IDs detects completely disjoint shortlists and keeps them on the existing ranking path before allocating cache windows.

This applies to raw blocks, prepared shards, readers, and saved files with distinct per-query selections. Original IDs still control both exclusions and tie ordering. Above the sampling cap, approximate distance correlation keeps its candidate-specific sampled streams. File appends remain transactional. The example benchmark_streaming_shortlist_distance_cache checks exact result parity against independent single-query streams before comparing overlapping and disjoint shortlists at several dimensions.

The common options use the same block-local convention as StreamingTopK. Per-query self IDs refer to the concatenation of all supplied blocks, matching the IDs returned in results. Both exclusions apply together, and all supplied rows advance rows_seen, even when filtered out or undefined. Duplicate vectors in other corpus rows remain eligible when a query's own row is excluded.

search = fvs.StreamingTopKMany([[1.0, 0.0], [-1.0, 0.0]], 2)
self_ids = [0, 3]  # the queries' positions in the complete streamed corpus
search.add_block(
    [[1.0, 0.0], [0.0, 1.0]],
    exclude_indices=self_ids, min_score=0.0,
)
search.add_block(
    [[2.0, 0.0], [-1.0, 0.0], [0.0, 0.0]],
    candidate_indices=[0, 1],  # this block's positions, global rows 2 and 3
    exclude_indices=self_ids, min_score=0.0,
)
assert search.rows_seen == 5
assert search.matches() == [[(2, 1.0), (1, 0.0)], [(1, 0.0)]]

Filters apply only while adding the current block; they never remove earlier matches retroactively. Pass the same self IDs and threshold on every block for stream-wide exclusion and thresholding. Global self IDs may refer to future rows because the eventual corpus size need not be known when streaming starts. The exclusion list must always contain one entry per query, including when k=0, the selection is empty, or all queries have undefined scores. Invalid filters, dimensions, and coordinates leave every query's results and progress unchanged. Python validates the complete supplied block and converts it once, including rows that will be filtered out.

For multiple queries using cosine, Pearson, Spearman, Hoeffding, NMI, or JSD, a sparse candidate_indices selection also limits candidate preparation to the selected rows. The common exclude_index is removed before preparation. With M selected rows of D coordinates, this preparation uses O(M * D) storage plus O(M) original row IDs; it does not prepare the other rows of the block. Scores, seeded random streams, exclusions, and tie ordering still use the original global IDs. The Python conversion and finite-value validation described above still cover the entire input block. Already-prepared shards passed to add_index are borrowed directly.

Rust exposes add_block_filtered(&block, SearchOptions { ... }, Some(&self_ids)), where self_ids is a slice of Option<usize> global row IDs in query order. The existing add_block(&block) delegates to unrestricted filtering. Filter and exclusion-count errors use StreamingSearchError::InvalidFilter with the underlying SearchError; memory remains bounded by the query batch, its retained matches, and the current block.

Streaming saved prepared index shards

Both StreamingTopK and StreamingTopKMany accept add_index(index) to search a prepared SimilarityIndex or CosineIndex as the next candidate block. This connects saved indexes with bounded-memory retrieval: prepare and save corpus shards once, then load and search one shard at a time for each query batch. Cached cosine/Pearson norms, Spearman/Hoeffding ranks, and NMI/JSD histograms are used directly. Adding an index does not reconstruct or copy its whole corpus, or repeat its cached preparation. Metrics that retain raw coordinates still use their usual per-comparison working allocations.

import fast_vector_similarity as fvs

# Prepare shards once. These can be written by a separate indexing process.
fvs.SimilarityIndex([[1.0, 0.0], [0.0, 0.0]]).save("shard-0.fvs")
fvs.SimilarityIndex([[2.0, 0.0], [-1.0, 0.0]]).save("shard-1.fvs")

search = fvs.StreamingTopKMany([[1.0, 0.0], [-1.0, 0.0]], 2, seed=42)
for path in ["shard-0.fvs", "shard-1.fvs"]:
    shard = fvs.SimilarityIndex.load(path)
    search.add_index(shard)
    del shard  # the accumulator retains only its query state and best matches

assert search.rows_seen == 4
assert search.matches() == [
    [(0, 1.0), (2, 1.0)],
    [(3, 1.0), (0, -1.0)],
]

Raw add_block calls and prepared add_index calls can be interleaved. Every row advances the global corpus position, including filtered-out or undefined rows. With deterministic measures or an explicit seed, the results match searching the concatenated original corpus, regardless of shard boundaries. In particular, randomized metrics use the global row ID, so searching separate indexes and simply merging their local results is not an equivalent way to preserve seeded scores.

add_index accepts the same keyword filters as add_block: candidate_indices and exclude_index are local to the supplied shard, and min_score is inclusive. The many-query version also accepts exclude_indices, with one global self ID or None per query. Filters apply only to this append. The shard must have the stream's fixed similarity measure and dimensions; mismatches and invalid filters leave progress and results unchanged, even for an empty shard, k=0, or an empty query batch. A CosineIndex is accepted only by a cosine stream.

The index remains immutable and can be shared between independent concurrent accumulators. Python borrows its owned Rust representation and releases the GIL during scoring. One append retains no reference to its shard afterward. Storage is the current prepared shard plus the existing query state, bounded selection heaps, and metric working memory; the stream never assembles the whole corpus. Loading a shard still reads and validates that shard's complete saved payload.

Rust exposes add_index(&SimilarityIndex) and add_index_filtered(&SimilarityIndex, SearchOptions { ... }) on StreamingTopK. The many-query filtered method also takes the optional slice of global self IDs. Use cosine_index.as_ref() to borrow a CosineIndex as a SimilarityIndex. Metric mismatches return StreamingSearchError::IndexMeasureMismatch; dimension, filter, and row-count errors keep the existing streaming error types.

Starting a stream from prepared query indexes

StreamingTopKMany.from_index starts a search from the rows of a prepared query index. StreamingTopK.from_index selects one query row, defaulting to row zero. The query index determines the measure and dimensions. This lets saved query corpora search candidate files or shards without reconstructing the original query vectors or loading all candidates together.

import fast_vector_similarity as fvs

queries = fvs.SimilarityIndex.load("queries.fvs")
search = fvs.StreamingTopKMany.from_index(queries, 10, seed=42)

for path in ["candidates-0.fvs", "candidates-1.fvs"]:
    search.add_file(path, chunk_rows=512)

matches_by_query = search.matches()

# Select a single row from the same prepared query corpus.
single = fvs.StreamingTopK.from_index(queries, 10, query_row=0, seed=42)
single.add_file("candidates-0.fvs", chunk_rows=512)

Both constructors accept SimilarityIndex and CosineIndex. They copy cached query coordinates/ranks or histogram labels and marginals directly into owned stream state, without repeating the cached preparation. The source index can then be released; the stream is independent of its lifetime. Raw-only index representations use the usual query preparation, including the full-data distance-correlation cache. Storage depends on the query batch and retained top-k matches, plus the current candidate block.

All existing raw-block, prepared-index, file, filtering, and global row-ID contracts continue to apply. With a deterministic measure or explicit seed, results match a stream constructed from the original raw query rows. A many-query source may have zero rows while retaining its declared dimension; a single-query source must contain the selected row, even when k=0.

Rust exposes StreamingTopKMany::from_index(&queries, k, seed) and StreamingTopK::from_index(&queries, query_row, k, seed). The single-query constructor returns Result<_, SearchError> for an out-of-bounds query row.

Searching saved indexes with bounded memory

StreamingTopK.add_file(path) and StreamingTopKMany.add_file(path) search a saved SimilarityIndex or CosineIndex directly. The file can be larger than available memory: rows are decoded and scored in chunks, using their saved preparation, without loading the whole snapshot or reconstructing raw vectors.

import fast_vector_similarity as fvs

# A previously prepared snapshot can be much larger than this query batch.
search = fvs.StreamingTopKMany(queries, 10, "spearman_rho", seed=42)
search.add_file("corpus.fvs", chunk_rows=2048)
neighbors = search.matches()

# More files and in-memory blocks continue the same global row sequence.
search.add_file("new-corpus.fvs", chunk_rows=2048)

chunk_rows is a positive maximum number of resident candidate rows; omission or None uses 4096. Working storage includes that prepared chunk, query state, top-k selection heaps, staged best matches, and each metric's working memory. It does not grow with the number of rows in the saved file. Use SimilarityIndexWriter to construct new snapshots from bounded input batches as well.

The same filters are available as with add_index. candidate_indices and exclude_index refer to positions within the whole file, independent of chunk boundaries. The many-query exclude_indices values are global self IDs, including rows in preceding blocks or files. min_score is inclusive. Every saved row consumes a global ID, including filtered or undefined rows. For an explicit seed, changing chunk_rows preserves scores and ordering.

Each append is transactional. The stream stages its best matches while reading and adopts them only after validating all saved rows, the checksum, and the end of the file. A truncated, corrupt, incompatible, or unreadable snapshot leaves both rows_seen and every query's matches unchanged. An empty selection, k=0, or an empty query batch still requires a valid complete snapshot. Filters and the metric/dimension schema are validated before scoring. Files must remain unchanged while they are being read.

Python accepts strings, bytes, and os.PathLike paths. File I/O and numerical work release the GIL; separate accumulators can read the same file concurrently. The file is closed before the call returns. Invalid snapshots and arguments raise ValueError; filesystem failures retain their OSError subclasses.

Rust provides add_file(path, chunk_rows) and add_reader(reader: impl std::io::Read, chunk_rows) on both streaming types. Their *_filtered variants take SearchOptions, with optional global per-query exclusions on StreamingTopKMany. Reader methods support sources that cannot seek, including decompression adapters and network streams. All return std::io::Result<()>; invalid arguments use InvalidInput, invalid payloads use InvalidData or UnexpectedEof, and reader errors propagate without publishing partial search results.

Filtered retrieval and self-neighbor exclusion

Search an eligible subset of an existing corpus without copying its rows or rebuilding the index. Both native index classes accept these keyword options on top_k and top_k_many:

Option Behavior
candidate_indices Original corpus row IDs to consider, or a reusable CandidateSelection. None considers every row; [] considers none. Duplicates are removed.
exclude_index One original corpus row to omit. On top_k_many, this exclusion applies to every query.
exclude_indices On top_k_many, one row ID or None per query. These exclusions combine with exclude_index.
min_score A finite, inclusive lower score bound. None applies no threshold.
import fast_vector_similarity as fvs

corpus = [[2.0, 0.0], [0.0, 1.0], [1.0, 0.0], [-1.0, 0.0]]
index = fvs.SimilarityIndex(corpus)

# Reuse a metadata filter across queries. IDs retain their corpus positions.
eligible = fvs.CandidateSelection([3, 2, 0, 2], corpus_size=len(index))
assert eligible.indices == [0, 2, 3]
matches = index.top_k(
    corpus[0], 10,
    candidate_indices=eligible,
    exclude_index=0,
    min_score=0.0,
)
assert matches == [(2, 1.0)]

# Build nearest-neighbor lists for corpus rows, excluding each row itself.
# Distinct rows containing the same vector remain eligible neighbors.
neighbors = index.top_k_many(
    corpus, 2, exclude_indices=list(range(len(corpus))),
)
assert neighbors[0] == [(2, 1.0), (1, 0.0)]

# Queries can arrive in any order; provide the corresponding source row IDs.
reordered = index.top_k_many(
    [corpus[3], corpus[0]], 2, exclude_indices=[3, 0],
)
assert reordered == [neighbors[3], neighbors[0]]

Selections contain only row IDs and are immutable snapshots. Their constructor validates bounds, sorts IDs, and removes duplicates once; reusing the object avoids repeating that work. A selection may be shared by concurrent callers. Its corpus_size must match the searched corpus, and its IDs must describe that corpus's original row order. Plain integer sequences and one-dimensional NumPy integer arrays are accepted directly as candidate_indices too.

Filtering happens before scoring, so a sparse selection scans only its eligible rows. The bounded top-k heaps retain original IDs and use the same score ordering and tie-breaking as unrestricted searches. With an explicit seed, filtering leaves each retained candidate's randomized score unchanged; it does not renumber the rows or their random streams. These options apply to every metric. Undefined scores remain excluded, and the result can contain fewer than k matches after exclusions and thresholding. The minimum score is interpreted in the selected metric's own scale.

Invalid IDs, mismatched selection sizes, non-finite thresholds, and a wrong number of per-query exclusions raise ValueError, including when k=0, the selection is empty, or no queries are supplied. Boolean and floating-point row IDs are rejected. None in exclude_indices means that query has no additional row exclusion.

The JSON batch function accepts candidate_indices, exclude_index, and min_score together with top_k, using the same semantics. Supplying a non-null filter without top_k raises ValueError; full-score output continues to represent every corpus row. number_of_candidates always reports the complete input corpus size, and match indices always refer to that original corpus.

Rust exposes reusable selections and fallible filtered methods while retaining the existing unfiltered methods:

use fast_vector_similarity::{CandidateSelection, SearchOptions, SimilarityIndex,
                             SimilarityMeasure};
use ndarray::array;

let index = SimilarityIndex::new(
    array![[2.0, 0.0], [0.0, 1.0], [1.0, 0.0], [-1.0, 0.0]],
    SimilarityMeasure::CosineSimilarity,
);
let eligible = CandidateSelection::new(index.len(), [3, 2, 0, 2]).unwrap();
let options = SearchOptions {
    selection: Some(&eligible),
    exclude_index: Some(0),
    min_score: Some(0.0),
};
let matches = index.top_k_filtered(&array![1.0, 0.0], 10, None, options).unwrap();
assert_eq!(matches[0].index, 2);

let exclusions = [Some(0), Some(3)];
let neighbors = index.top_k_many_filtered(
    &array![[1.0, 0.0], [-1.0, 0.0]], 2, None,
    SearchOptions::default(), Some(&exclusions),
).unwrap();
assert_eq!(neighbors[0][0].index, 2);

top_k_similarity_filtered provides the same options for a one-shot matrix search. CosineIndex::top_k_filtered and top_k_many_filtered use the same core without a seed parameter. New filtered Rust methods return SearchError for invalid dimensions or options; existing methods retain their dimension-assertion behavior. Selection storage is proportional to the selected row count, with no additional corpus matrix or query-by-corpus score matrix.

Native Python pairwise and bootstrap statistics

Pairwise and bootstrap computations accept ordinary Python sequences and one-dimensional NumPy arrays directly. These entry points return dictionaries, so applications do not need to convert vectors to JSON or parse response text.

import numpy as np
import fast_vector_similarity as fvs

x = np.array([-2.0, -1.0, 0.0, 1.0, 2.0], dtype=np.float64)
y = x ** 2

pair = fvs.compute_vector_similarity_stats(x, y, "distance_correlation")
score = pair["distance_correlation"]

bootstrap = fvs.compute_bootstrapped_similarity_stats(
    x, y,
    sample_size=len(x),
    number_of_bootstraps=500,
    similarity_measure="distance_correlation",
    seed=42,
    confidence_level=0.95,
)
interval = bootstrap["bootstrap_intervals"]["distance_correlation"]

# Omit the measure, pass None, or use "all" to evaluate every supported metric.
all_stats = fvs.compute_vector_similarity_stats(x, y, seed=42)
Entry point Return value
compute_vector_similarity_stats(vector_1, vector_2, similarity_measure=None, *, seed=None) Pairwise statistics and input-dimension metadata
compute_bootstrapped_similarity_stats(x, y, sample_size, number_of_bootstraps, similarity_measure=None, *, seed=None, confidence_level=None) Trimmed bootstrap means and standard deviations, plus percentile intervals when requested

The dictionary keys and values match the existing JSON APIs for identical inputs and an explicit seed, including None for undefined statistics. The py_compute_... JSON functions remain available. All supported measures work through both interfaces.

Native float32/float64 buffers are copied in logical order before computation; strided, reversed, and nonnative-endian arrays are supported. Other real numeric sequences use element conversion. NumPy is optional for using the package. Python-owned storage is read while the GIL is held, and the numerical computation releases the GIL. Both vectors must have equal lengths and finite real values; boolean and complex values are rejected. Bootstrap sizes must be positive integers, seeds must fit an unsigned 64-bit integer, and an optional confidence level must be finite and strictly between zero and one.

Bootstrap evaluation runs at most one outer chunk per Rayon worker and reuses one sampled vector pair in each chunk. Temporary resample storage is therefore O(workers × sample_size), in addition to metric working storage and the O(number_of_bootstraps × selected_measures) score matrix. The replicate index continues to determine its random streams, so changing chunk boundaries or worker counts preserves seeded results. Percentile intervals retain the existing full-distribution and undefined-replicate rules described below.

Pearson correlation

Use pearson_correlation to compare how two rows vary around their own means. Adding a constant or multiplying by a positive factor preserves the coefficient when the transformed input values retain their variation. A negative factor reverses its sign. Constant vectors and inputs with fewer than two observations have undefined correlation.

import fast_vector_similarity as fvs

rows = [[10., 11., 12., 13.], [13., 12., 11., 10.], [2., 2., 2., 2.]]
query = [0., 1., 2., 3.]
index = fvs.SimilarityIndex(rows, "pearson_correlation")
# Scores are approximately +1, -1, and NaN. Ranking excludes the constant row.
neighbors = index.top_k(query, 3)

Rust exposes pearson_correlation(&[f64], &[f64]) and SimilarityMeasure::PearsonCorrelation. The metric also participates in all statistics, bootstrap intervals, and every pairwise and retrieval API. The implementation range-scales each vector before centering, then computes the correlation with compensated sums. A reusable index centers each corpus row once and saves its coordinates and norm, so each prepared comparison costs one linear dot product.

Full-data distance correlation

distance_correlation computes the biased sample distance-correlation statistic using every paired coordinate. Its sorted distance sums and weighted Fenwick sweep require O(n log n) time and O(n) working storage, with no sampling cap and no dense distance matrices. High/low floating-point intermediates preserve rounding residuals through the cancellation-sensitive centering calculation. Here, full-data or exact means no subsampling; arithmetic still has finite precision. Inputs are independently normalized using the same scale-safe range handling as the existing numerical APIs.

Measure Observations used Randomness Working cost
distance_correlation All n paired coordinates None O(n log n) time; O(n) storage
approximate_distance_correlation At most m = min(n, 1000) paired coordinates Seeded sampling above the cap O(n + m log m) time; O(m) storage

Both measure statistical dependence and return values in [0, 1]. They do not measure vector direction: reversing an affine relationship can still score 1. For directional embedding retrieval, cosine has the signed-angle interpretation. A constant marginal or singleton sample has distance correlation 0; empty or non-finite Rust input is undefined. Python boundaries reject non-finite input, and JSON represents undefined scores as null. Both complete input vectors are checked before any constant-input shortcut.

import json
import fast_vector_similarity as fvs

result = json.loads(fvs.py_compute_vector_similarity_stats(json.dumps({
    "vector_1": [-2, -1, 0, 1, 2],
    "vector_2": [4, 1, 0, 1, 4],
    "similarity_measure": "distance_correlation",
})))
score = result["distance_correlation"]

# The same metric works with native corpus reuse and many-query top-k:
index = fvs.SimilarityIndex(
    [[4, 1, 0, 1, 4], [2, 1, 0, -1, -2]],
    "distance_correlation",
)
matches = index.top_k([-2, -1, 0, 1, 2], 2)

Rust exposes distance_correlation(&x, &y) and SimilarityMeasure::DistanceCorrelation. The metric is integrated into typed scoring, selected and "all" JSON statistics, paired bootstrapping, optional bootstrap percentile intervals, batch scoring, and both reusable-index query methods. A seed does not change the scalar full-data score; it still determines which paired observations are drawn by a bootstrap. Existing approximate sampling behavior and named random streams are unchanged.

Batch scoring, index searches, and streaming searches prepare each full-data distance-correlation query once. The cached query contains normalized values, sorted coordinate order, marginal distance sums, and centered variance. Each candidate still needs its own preparation and the pair-dependent mixed-distance sweep. Equal query values require sorting candidate values within those tied groups; queries without ties reuse their sorted order directly. The overall per-comparison bounds remain O(D log D) time and O(D) working storage.

Streaming searches retain this query preparation across raw blocks, prepared indexes, and saved-file chunks. Many-query searches bound active preparation by their worker count; streaming query batches retain one cache per query. Pairwise APIs reuse it across each active source row's comparisons. Distance-correlation indexes continue to store raw candidate coordinates, so their existing snapshot format and memory representation are unchanged. Scalar and sampled APIs use the same numerical kernel and retain their score and sampling contracts.

Bounded file score and pairwise tiles can also share candidate marginals across multiple nonconstant queries. Each candidate block is normalized, sorted, and reduced once for that tile; every cell still performs its own mixed-distance sweep with the same numerical reduction order. These caches are limited to active blocks, including tiles used by PairwiseFileTopK; the complete resident index does not acquire a second corpus-wide representation. Single-query and constant-only tiles do not allocate a separate candidate cache.

examples/benchmark_prepared_distance_tiles.rs compares one complete saved-query and saved-candidate tile with loading both indexes and calling scores_index. Both paths include input decoding, validation, query preparation, and output allocation. It checks score bits before reporting repeated timings for single and multiple queries on tied and untied data. Run this release example through DSR. Candidate caches consume additional linear storage within the configured blocks; benchmark timings are specific to their workload and machine.

examples/benchmark_dependence_search.rs compares repeated scalar, batch, and indexed searches for both Hoeffding and full-data distance correlation. It checks exact score bits before timing, uses one worker and deterministic tied and untied corpora, and reports median scan latency separately from index construction. Run the release-mode example through DSR, following the repository's validation policy. Timings depend on the workload and machine.

The approximate metric evaluates its selected observations with the same fast kernel as the full-data metric. It retains the 1,000-observation cap, reservoir sampling, and caller-owned RNG continuation. Scores may differ in their last floating-point bits from the previous quadratic evaluator, but they estimate the same biased statistic on the same paired sample. With at most 1,000 input observations, both APIs evaluate all observations and return the same score. This also removes quadratic pair scans from approximate-distance bootstrap replicates and corpus comparisons. The DSR workload can run cargo run --release --example benchmark_sampled_distance to compare with an independent dense reference and measure selected/all-metric bootstrap workloads.

Sampled distance-correlation searches reuse full-data query and bounded candidate preparation when dimensions do not exceed 1,000. Above the cap, queries are validated once and each candidate is checked and sampled through a logical array view, avoiding a full candidate-row copy. The 1,000-observation reservoir, per-candidate seeded streams, and scalar RNG continuation remain unchanged.

Reproducible random sampling

Pass an optional seed (an unsigned 64-bit integer, including zero) to the pairwise or bootstrap Python JSON function to reproduce the complete calculation:

params = {
    "x": x.tolist(),
    "y": y.tolist(),
    "sample_size": 1000,
    "number_of_bootstraps": 200,
    "similarity_measure": "all",
    "seed": 42,
}
result = json.loads(fvs.py_compute_bootstrapped_similarity_stats(json.dumps(params)))

The seed controls paired bootstrap resampling, distance-correlation subsampling, and the Jensen-Shannon shuffled baseline. Each replicate and measure has an independent random stream. Selecting one measure produces the same score and bootstrap summary as selecting "all" with that seed. Results are independent of Rayon worker count and concurrent Python calls for the same library build. Identical streams across dependency upgrades or different floating-point platforms are not guaranteed. Omit seed (or set it to null) for fresh random sampling.

Rust callers can use compute_vector_similarity_stats_seeded and compute_bootstrapped_similarity_stats_seeded, which take the same arguments as the original functions followed by a u64 seed. SimilarityMeasure and score_similarity provide typed selection without a JSON round trip; the two randomized scalar measures also expose _with_rng variants for caller-owned RNGs. The original Rust signatures and result keys remain available. Selecting "all" includes cosine_similarity and distance_correlation, together with their bootstrap standard deviations and any requested percentile intervals.

Bootstrap computation keeps numerical scores until the final summary rather than allocating a JSON object per replicate. The Python wrappers release the GIL while Rust computes, allowing other Python threads to progress. Pairwise and bootstrap selectors must name a supported measure or "all"; unknown names and non-string selectors raise ValueError. For those functions, an absent or null selector continues to mean all measures; the batch function defaults to cosine.

Bootstrap percentile intervals

Add confidence_level to a bootstrap request to return percentile bounds and replicate counts alongside the existing trimmed mean and standard deviation:

import json
import fast_vector_similarity as fvs

x = [float(i + 1) for i in range(40)]
y = [float(i + 1 + (i * 7) % 11) for i in range(40)]
params = {
    "x": x,
    "y": y,
    "sample_size": len(x),
    "number_of_bootstraps": 499,
    "similarity_measure": "cosine_similarity",
    "seed": 42,
    "confidence_level": 0.95,
}
result = json.loads(fvs.py_compute_bootstrapped_similarity_stats(json.dumps(params)))
interval = result["bootstrap_intervals"]["cosine_similarity"]
print(interval["lower"], interval["upper"])
print(interval["finite_replicates"], interval["undefined_replicates"])

The confidence level must be a finite number strictly between zero and one. Omitting it, or setting it to null, preserves the existing response format. With intervals enabled, the response adds confidence_level and bootstrap_intervals, containing one entry per selected measure:

Interval field Meaning
lower Lower percentile bound, or null when undefined
upper Upper percentile bound, or null when undefined
finite_replicates Number of finite bootstrap scores
undefined_replicates Number of undefined bootstrap scores

For confidence 0.95, the bounds are the 2.5th and 97.5th percentiles of the complete, untrimmed bootstrap distribution. Quantiles use linear interpolation at positions p * (B - 1) in the sorted scores. The existing mean and population standard deviation still describe the scores retained after removing floor(B / 4) from each tail. All outputs use the same paired resamples and metric streams, so enabling intervals or changing confidence does not change seeded scores. Each replicate is evaluated once.

Any undefined replicate makes both interval bounds null; undefined scores are counted and never silently discarded. Fewer than two replicates also produce null bounds and summaries. One requested replicate is evaluated to provide accurate counts. Empty source vectors treat every requested replicate as undefined without evaluation. Python retains its existing requirement for positive sample sizes and bootstrap counts.

For an ordinary n-out-of-n bootstrap, use sample_size == len(x). Another size describes the statistic at that resample size and requires separate calibration for inference. These percentile bounds describe the sampled statistic; the trimmed summary is a separate quantity. Nominal confidence does not guarantee coverage, especially with small or degenerate samples, few replicates, dependent observations, or randomness inside approximate measures.

Rust callers can use compute_bootstrapped_similarity_stats_with_intervals(x, y, sample_size, number_of_bootstraps, similarity_measure, seed, confidence_level), where seed is Option<u64>. It returns Result<Value, BootstrapIntervalError> and preserves the equal-length assertion of the existing APIs. Invalid source values or a zero sample size mark all requested replicates undefined; zero requested replicates return zero counts. The original Rust bootstrap functions retain their signatures and result fields.

Non-finite and undefined values

Input vectors must have equal lengths; the Rust APIs assert this precondition, and the Python wrappers raise ValueError when it is violated. The Rust scalar similarity functions return f64::NAN if either vector is empty or contains NaN, positive infinity, or negative infinity. They do not discard, replace, or rank non-finite observations. Validation covers the complete vectors before distance-correlation subsampling or bootstrapping.

The Rust JSON statistics functions represent undefined scores as null, while preserving the requested measure names and metadata. For bootstrap results, an invalid source vector or any undefined replicate makes both the corresponding average and stdev_<measure> value null; undefined replicates are not silently removed or trimmed away. Empty inputs, zero-sized bootstrap samples, and fewer than two bootstrap replicates also produce null summaries.

Finite inputs can still yield an undefined statistic. Spearman's rho and Kendall's tau-b are undefined when either vector is constant or there are fewer than two observations. Hoeffding's D requires at least five observations, including within each bootstrap sample. NMI is undefined when both vectors are constant because their total marginal entropy is zero. Cosine is undefined when either vector has zero norm or no coordinates. These results are NaN directly and null through the JSON APIs, including bootstrapping. Sampling with replacement can create a constant replicate even from nonconstant source vectors.

The Python wrappers accept JSON arrays of finite numbers. They raise ValueError for malformed JSON (including NaN, Infinity, and out-of-range numeric literals), missing or non-array vectors, null or nonnumeric vector elements, unequal lengths, and non-positive or invalid bootstrap counts/sizes. Undefined results from valid finite inputs are returned as JSON null, which json.loads converts to None.

Finite scales and array layouts

NMI and the Jensen-Shannon dependency measure use the same equal-width binning rule. Constant vectors occupy one bin; nonconstant vectors are normalized by their actual range. This preserves tiny and subnormal differences and handles opposite-sign finite extremes without adding a fixed epsilon to the range.

The approximate distance-correlation function normalizes each sampled vector independently before evaluating distance moments. Translation and scaling preserve the statistic, while bounded coordinates keep the distance variances stable across tiny and huge overall scales. Sorted distance sums and a weighted Fenwick sweep evaluate the biased centered-distance estimate without enumerating every pair. High/low floating-point intermediates retain rounding residuals through centering, including the diagonal contributions. The existing convention of zero distance correlation for a constant sample is preserved.

All Rust entry points taking Array1<f64> support reversed and strided owned arrays. Computation follows logical element order, preserving observation pairs and ignoring unused backing-storage elements. Contiguous data is borrowed when a rank function needs a slice; other layouts are copied in logical order.

JSON float parsing uses Serde's float_roundtrip mode so serialized f64 values retain their distinctions, including adjacent representable values. This matters for both rank ties and finite-range normalization at the Python boundary.


Detailed Overview of Similarity Measures

1. Spearman's Rank-Order Correlation (spearman_rho)

Spearman’s Rank-Order Correlation is a non-parametric measure of the strength and direction of the monotonic relationship between two variables. Unlike Pearson's correlation, which measures linear relationships, Spearman's correlation can capture non-linear monotonic relationships. This makes it useful in many real-world applications where variables have complex relationships but still follow a consistent directional trend.

How It Works:

  • First, both input vectors are converted into ranks, where the lowest value is assigned rank 1, the second-lowest rank 2, and so on. If ties are present, the average rank for the tied values is computed.
  • Once the ranks are assigned, the measure reduces to computing the Pearson correlation on these ranks. However, the key difference lies in its robustness to non-linearity.

The implementation computes Pearson correlation of the average ranks, so tied observations receive the correct normalization. It does not use the squared-rank- difference shortcut, which assumes there are no ties.

Optimizations in Our Implementation:

  • Parallel Sorting: The library uses parallel sorting with the rayon crate to assign ranks, ensuring that this operation scales efficiently even for large datasets.
  • Efficient Rank Calculation: The average rank computation in the presence of ties is optimized with a direct look-up mechanism, minimizing redundant operations when processing multiple tied values in sequence.

Why It Stands Out:

  • Robust Against Outliers: Since it uses ranks rather than raw data values, Spearman's correlation is less sensitive to outliers.
  • Monotonic Relationships: It captures monotonic trends, making it suitable for many practical scenarios where linear correlation fails but directional trends exist.

2. Kendall's Tau Rank Correlation (kendall_tau)

Kendall’s Tau is a rank-based measure that evaluates the strength of ordinal association between two variables by comparing the relative ordering of data points. Positive scores favor concordant pairs, while negative scores favor discordant pairs.

How It Works:

  • Kendall’s Tau compares all possible pairs of observations. For each pair, if the ranks of both variables agree (i.e., are concordant), the count of concordant pairs is increased. If the ranks disagree (i.e., are discordant), the discordant count is incremented.
  • The implementation returns tau-b, normalizing the difference between concordant and discordant pairs with corrections for ties in either coordinate. Pairs tied in both coordinates are excluded from the concordant and discordant counts.

Optimizations in Our Implementation:

  • Inversion Counting Using Merge Sort: The implementation sorts observation pairs by both coordinates, then counts strict inversions in the second coordinate. This excludes ties in the first coordinate from discordant pairs and runs in O(n log n) time with O(n) storage. Pair counts use wide integers before floating-point normalization.
  • Parallel Sorting: The rayon crate is used to parallelize the sorting process, allowing the calculation to scale effectively on multi-core systems.

Why It Stands Out:

  • Tie Handling: Kendall’s Tau inherently handles ties (when two elements have the same rank), making it more robust for datasets with tied values compared to other rank-based measures.
  • Pairwise Interpretation: Tau-b summarizes concordant versus discordant ordering, with normalization that accounts for ties in each variable.
  • Fast with Inversion Counting: Our use of merge sort for counting inversions dramatically improves the performance, making it feasible for large datasets where traditional implementations would be too slow.

3. Approximate Distance Correlation (approximate_distance_correlation)

Distance correlation measures both linear and non-linear dependence. This function computes the biased sample estimator on up to 1,000 paired observations. Larger inputs use a random subset, so their estimates can vary between calls.

How It Works:

  • Up to 1,000 paired observations are selected without replacement and independently normalized to a bounded range.
  • Sorted gaps give each observation's total absolute distance. A weighted Fenwick sweep computes the mixed distance moment without constructing or scanning either distance matrix.
  • A centering identity combines these moments with high/low floating-point arithmetic, including centered diagonal contributions. Normalization gives the same biased centered-distance statistic as the full matrix formulation, up to floating-point rounding.

Optimizations in Our Implementation:

  • Fast Sample Evaluation: The selected subset uses the same O(m log m) kernel as full-data distance correlation, eliminating quadratic scans from repeated comparisons and bootstrap replicates.
  • Linear Working Storage: Sorted indices, row sums, and the Fenwick tree require O(m) auxiliary storage. No dense distance matrices are allocated.
  • Stable Centering: High/low sums and products protect covariance and both variances from cancellation, including samples with rare outliers and near independence.
  • Bounded Sampling: Complete-input validation remains in place before sampling. With n input observations and m = min(n, 1000) sampled observations, time is O(n + m log m) and auxiliary storage is O(m). Existing seeded subsets and RNG consumption are preserved.

4. Jensen-Shannon Dependency Measure (jensen_shannon_dependency_measure)

The Jensen-Shannon Dependency Measure is derived from the Jensen-Shannon Divergence (JSD), a symmetric and smooth version of Kullback-Leibler divergence. JSD quantifies the similarity between two probability distributions. In the context of vector similarity, we use this measure to assess how much the distribution of values in one vector depends on the distribution in another.

How It Works:

  • Both vectors are discretized into bins, creating histograms that approximate their probability distributions.
  • We compute the joint distribution and the marginal distributions of the two vectors. The Jensen-Shannon Divergence is calculated as the difference between the joint and marginal entropies.
  • The Jensen-Shannon Dependency Measure is defined as the difference between the observed JSD and a baseline JSD derived from shuffled data, normalized to lie between 0 and 1.

Optimizations in Our Implementation:

  • Efficient Histogram Binning: The vectors are discretized into bins using optimized techniques that ensure minimal overhead, even for large vectors.
  • Parallel Computation of JSD: The computation of the joint and marginal distributions is fully parallelized, which significantly speeds up the calculation.
  • Shuffling for Baseline Estimation: The shuffled baseline is computed by randomizing the order of one vector and re-computing the JSD. This baseline helps differentiate between real dependencies and coincidental overlaps in the distributions.

Why It Stands Out:

  • Smooth and Symmetric: Unlike KL-divergence, which can be asymmetric and undefined when one distribution has zero probabilities, JSD is symmetric and always well-defined.
  • Useful for Non-Overlapping Distributions: It is especially powerful for comparing distributions with non-overlapping support, where other similarity measures might fail.
  • Dependency Measure: The inclusion of a baseline JSD (derived from shuffled data) makes this a robust measure of dependency, filtering out spurious similarities.

5. Hoeffding's D Measure (hoeffding_d)

Hoeffding’s D is a powerful non-parametric measure that detects complex and potentially non-linear relationships between variables. Unlike traditional correlation measures, Hoeffding’s D is designed to detect general dependencies without assuming any specific form of the relationship.

How It Works:

  • Hoeffding's D measures the joint ranks of two variables. It counts how many times a pair of observations follows a consistent pattern across the two variables.
  • The statistic is based on the empirical distribution of the ranks and includes terms that account for joint and marginal distributions.

Optimizations in Our Implementation:

  • Parallel Computation of Ranks: Like Spearman’s rho, Hoeffding’s D involves computing ranks, and this is optimized using parallel sorting algorithms.
  • Joint Ranks in O(n log n) Time: A Fenwick tree counts observations with smaller ranks in both coordinates. Equal ranks in the first coordinate are processed as one group before the tree is updated, preserving the half-weight contributions from ties in one coordinate and quarter-weight contributions from ties in both. The complete calculation uses O(n) storage and retains the same tie-adjusted statistic without scanning every pair of observations.

Why It Stands Out:

  • Non-Parametric and General: Hoeffding’s D can detect relationships where other correlation measures fail, especially when the relationship between variables is neither linear nor monotonic.
  • Sensitivity to Complex Patterns: It is particularly effective when the relationship between variables is complex or unknown, providing a more general-purpose measure of dependence.

6. Normalized Mutual Information (normalized_mutual_information)

Normalized Mutual Information (NMI) is a measure of the mutual dependence between two variables. It is based on the concept of entropy from information theory and quantifies how much information one variable provides about another.

How It Works:

  • First, both vectors are discretized into bins (histograms). The joint and marginal distributions are then computed.
  • The mutual information is calculated as the difference between the joint entropy and the sum of the marginal entropies.
  • The result is normalized to lie between 0 and 1, where 1 indicates perfect dependence and 0 indicates no dependence.

Optimizations in Our Implementation:

  • Efficient Histogram Calculation: The binning process is optimized to handle large datasets efficiently, ensuring that the mutual information can be computed quickly even for high-dimensional vectors.
  • Parallel Entropy Calculation: The calculation of joint and marginal entropies is parallelized, reducing the time required for large-scale datasets.

Why It Stands Out:

  • Interpretable and Scalable: NMI is easy to interpret and particularly useful for

comparing variables with different distributions, making it a versatile tool for high-dimensional data.

  • Handles Non-Linear Relationships: Like distance correlation, NMI captures both linear and non-linear dependencies but does so in a way that is grounded in information theory, providing a complementary perspective on data dependence.

Bootstrapping Technique for Robust Estimation

Bootstrapping is a statistical method that improves the reliability of similarity estimates by resampling the dataset. The Fast Vector Similarity Library offers this feature for robust estimation of similarity measures.

Advantages of Bootstrapping

  1. Robustness to Outliers: By resampling the data, the technique reduces the influence of outliers, providing more reliable estimates.
  2. Model-Free Estimation: It makes no assumptions about the underlying data distribution, making it suitable for diverse datasets.
  3. Confidence Intervals: Bootstrapping allows the construction of confidence intervals, adding interpretability to the results.
  4. Deeper Insights: By examining the distribution of similarity measures across bootstrap samples, bootstrapping offers a richer understanding of the underlying relationships.

Thanks for your interest in my open-source project! I hope you find it useful. You might also find my commercial web apps useful, and I would really appreciate it if you checked them out:

YoutubeTranscriptOptimizer.com makes it really quick and easy to paste in a YouTube video URL and have it automatically generate not just a really accurate direct transcription, but also a super polished and beautifully formatted written document that can be used independently of the video.

The document basically sticks to the same material as discussed in the video, but it sounds much more like a real piece of writing and not just a transcript. It also lets you optionally generate quizzes based on the contents of the document, which can be either multiple choice or short-answer quizzes, and the multiple choice quizzes get turned into interactive HTML files that can be hosted and easily shared, where you can actually take the quiz and it will grade your answers and score the quiz for you.

FixMyDocuments.com lets you submit any kind of document— PDFs (including scanned PDFs that require OCR), MS Word and Powerpoint files, images, audio files (mp3, m4a, etc.) —and turn them into highly optimized versions in nice markdown formatting, from which HTML and PDF versions are automatically generated. Once converted, you can also edit them directly in the site using the built-in markdown editor, where it saves a running revision history and regenerates the PDF/HTML versions.

In addition to just getting the optimized version of the document, you can also generate many other kinds of "derived documents" from the original: interactive multiple-choice quizzes that you can actually take and get graded on; slick looking presentation slides as PDF or HTML (using LaTeX and Reveal.js), an in-depth summary, a concept mind map (using Mermaid diagrams) and outline, custom lesson plans where you can select your target audience, a readability analysis and grade-level versions of your original document (good for simplifying concepts for students), Anki Flashcards that you can import directly into the Anki app or use on the site in a nice interface, and more.

Explorer des projets similaires

Chargement…