RAM
Mutable graphs, partitioned by memory domain. Insertions and searches can overlap.
init_ram · load_ramUSearch · Open source · Search engine · Unum
Text, genomes, maps or embeddings: a graph only needs a way to compare two entries.
Search and attention across modalities, behind one C ABI. Inside ClickHouse, DuckDB, YugabyteDB and 100M+ devices. From a laptop to a trillion vectors.
Get started
Insert a batch and search with a reusable arena.
Python
from usearch import Arena, DenseIndex, DenseMetric, Executor, Scalar
index = DenseIndex.init_ram(768, DenseMetric.ANGULAR, Scalar.BF16)
index.insert(keys, vectors)
pool = Executor.for_ram()
arena = Arena(pool)
matches = index.on(pool).search(queries, 10, arena)HNSW never needed vectors of equal length, only a way to compare two entries.
An inverted index has carried search for sixty years, and for exact terms it is still right: a posting list is a lookup and ranking the matches is cheap. It runs out when meaning is geometry rather than vocabulary; “a town at sunset” and “a city at dusk” share no token, so nothing is looked up. Trees and hashes partition the space before seeing the data, and past a few dozen dimensions every query lands beside a seam.
A proximity graph links each entry to its actual neighbors and walks toward the query, so a billion entries are a few hundred hops away. Embeddings from UForm, genomes, molecules and flight paths take the same walk; only the comparison changes.
The cross is the query, blue is what each structure reads for it, and the dashed ring is its true nearest neighbor. Every structure before the graph misses it across a boundary drawn from the data’s shape: a token it lacks, a seam, a split, a hyperplane.
Sources Bentley, CACM 1975 · Weber, Schek & Blott, VLDB 1998 · Indyk & Motwani, STOC 1998 · Malkov & Yashunin, 2016
At 100 million tokens, no model can afford to read its whole context for every generated token.
Dense matrix multiplication is the best-optimized operation in computing, and attention is one: every query against every key. It stops paying at a 100-million-token context, where no model can read its whole context for every generated token and most of the product goes to keys that contribute nothing.
A nearest-neighbor walk is a sparse product that chooses its own rows. multiply returns the scored pairs of A × Bᵀ, attend folds an online softmax into the walk in place of the sweep over key tiles, and maxsim finds each query token’s best match within a document, with NumKong kernels beneath all three. Folding attention into the walk may not be the final design, but it is the algorithmically correct direction, and we keep pursuing it and testing it in experiments, including with our own models.
Inner, angular, euclidean, hamming and jaccard all derive from one inner-product kernel with precomputed magnitudes, cutting angular arithmetic 3×.
Dense GEMM
100%
4×4 tiles
2:4 structured
50%
2 of every 4
Mixture-of-Experts
top-2 ≈ 12.5%
2 of 16 blocks per row
multiply
Dense & sparse BLAS-like multiplication
tiled GEMM, 2:4 masks, expert-routed blocks, approximate A × Bᵀ
Sparse attention
~2% of keys
99% recall
attend
Softmax attention
over a KV-cache
Proximity graph
O(log N) hops
connected by refine
search
Nearest neighbors
maxsim
Late-interaction scoring
fraction of products computed: 100% → 50% → 12.5% → ~2% → log N / N
99%
recall, scoring only 1.15–2.7% of the keys
A carry of running maxima and softmax denominators recombines this sparse branch
with a dense recent window, or with another shard of the same context.
Python
arena = Arena(pool)
products = index.on(pool).multiply(rows, 0, arena)
row_keys, row_scores = products.query(0)
carry = np.zeros((len(queries), 2), dtype=np.float32)
row_of = {key: row for row, key in enumerate(context_keys)}.get
outputs = kv_cache.on(pool).attend(queries, values, row_of, arena, carry=carry)
documents = passages.on(pool).maxsim(query_tokens, 32, 10, arena)Each call reuses the arena. Consume or copy its results before the next call. These operations use inner-product indexes.
Measured onM5 Pro · 1M–10.5M keys
Everything lived in RAM, and a server’s worth of NVMe drives sat idle beside it.
A graph in RAM is the right default, and every engine on the chart starts there. Past 10 million vectors it outgrows one box’s memory or a 24-hour build, and the usual answer is sharding across machines, which puts a network hop on every walk; Faiss stops at 100 million.
USearch shards inside the box first: across cores and sockets, across eight GPUs, or across local NVMe through io_uring and SPDK with fine-grained reads, before it crosses a network. Hardware sets the limit.
On 192 Graviton5 cores USearch builds 1.9× faster than Faiss HNSW at equal search speed.
| Engine | 10M | 100M |
|---|---|---|
| USearch 3.0 B300 | 558.5K | 431.5K |
| USearch 3.0 Graviton5 · 192 cores | not run | — |
| Faiss HNSW 1.15.1 Graviton5 · 192 cores | not run | — |
| USearch 2.25 Xeon 6 · 96 cores | 35.4K | under 99% recall |
| Faiss HNSW 1.12 Xeon 6 · 96 cores | 26.4K | killed after 9 h |
| Finished | 3 engines | 1 engine |
Measured onone B300 · one 192-core Graviton5 host · one 96-core Xeon 6 host · Sources RetriEval, the harness · NumKong kernels and bandwidth
A batch becomes visible all at once. Readers never see a half-wired graph.
Rebuilding an index and swapping it in is correct, simple, and how most deployments serve. It runs out when ingestion never stops: the swap trails the writes, and a writer that locks the graph stalls every reader.
Readers never modify links. Writers claim rows, wire them locally and publish completed batches in order behind a watermark, so a search sees the whole batch or none of it. Separate GPU executors let retrieval overlap one active insertion, and each call owns its outputs and arena.
usearch_arena_init(&(usearch_arena_init_t){.arena = &arena, .executor = executor}); Each concurrent search gets its own arena.usearch_dense_insert(&(usearch_dense_insert_t){.index = index, .count = 256, .keys = keys, .vectors = rows}); The writer claims every row, then wires its links, not yet visible.usearch_dense_search(&(usearch_dense_search_t){.index = index, .arena = arena, .wanted = 10}); Searches keep running on the published rows.outcome.status == usearch_status_success_k The whole batch becomes visible at once, or none of it.Predicates check keys during traversal, preserving recall at low selectivity. The same walk filters by database, Bloom filter or tenant key set; pairs near-copies; joins by distance; and streams best-first to the caller’s cutoff.
Filter during the walk
predicate=allowed
rejected keys still route it
Deduplicate
index.search(rows, 2)
copies are first neighbors
Join on distance
left.search(right, 1)
nearest row, not an equal key
Stream best-first
index.find(query)
stop when you have enough
The bindings share a C interface, with explicit capabilities for each engine and residency.
A query language is the right contract between teams and the wrong one inside a loop: each call formats, parses, plans and serializes, and floats lose precision on the way. USearch exposes typed verbs over one C interface, and every binding calls them natively.
The same verbs reach RAM, VRAM and NVMe, with explicit capabilities per engine and residency. Change the shared library to change where the work runs; UStore takes the same ABI further, and the docs list every verb.
Mutable graphs, partitioned by memory domain. Insertions and searches can overlap.
init_ram · load_ramOne shard per NVIDIA, AMD or Apple GPU, fed from NVMe through GPUDirect Storage. Build, refine, absorb and search on device; NVIDIA also serves exact scans.
init_vram · load_vramImmutable SafeGraphs checkpoints, searched in place. Build new parts in RAM or VRAM.
view_nvmePython
import numpy as np
from usearch import Arena, DenseIndex, DenseMetric, Executor, Scalar
vectors = np.random.rand(10_000, 256).astype(np.float32)
keys = np.arange(len(vectors))
index = DenseIndex.init_ram(256, DenseMetric.ANGULAR, Scalar.BF16, connectivity=16)
index.reserve(len(vectors))
index.insert(keys, vectors) # Build on the calling thread
pool = Executor.for_ram()
arena = Arena(pool) # Reuse memory beside the workers
matches = index.on(pool).search(vectors[:100], 10, arena) # 100 queries, up to 10 hits each
key, distance = matches[0][0] # First query, nearest matchRust
use usearch::*;
let options = DenseOptions { dimensions: 4, metric: DenseMetric::Angular,
quantization: Scalar::BF16, ..DenseOptions::default() };
let index = DenseIndex::init_ram(&options, &[])?;
let keys = [Key::from(42u64), Key::from(43u64)];
let slab = [0.2f32, 0.1, 0.2, 0.1, 0.1, 0.2, 0.1, 0.2];
index.reserve(1_000)?;
index.insert(&keys, &rows(&slab, 4)?)?; // Build on the calling thread
let pool = Executor::for_ram(&[], None, 0)?;
let mut arena = Arena::new_in(&pool)?; // Reuse memory beside the workers
let queries = rows(&slab, 4)?;
let matches = index.on(&pool).search(&queries, 10, &mut arena)?; // Two queries, up to 10 hits each C
#include <stdio.h>
#include <usearch/usearch.h>
int main(void) {
usearch_outcome_t outcome = {0};
usearch_executor_t executor = NULL;
usearch_arena_t arena = NULL;
usearch_dense_index_t index = NULL;
usearch_key_t keys[2] = {{.bytes[15] = 1}, {.bytes[15] = 2}};
float vectors[2][128] = {{0}};
usearch_matches_view_t matches = {0};
usearch_executor_for_ram(&(usearch_executor_for_ram_t) {.executor = &executor, .outcome = &outcome});
if (outcome.status != usearch_status_success_k) goto cleanup;
usearch_arena_init(&(usearch_arena_init_t) {.arena = &arena, .executor = executor, .outcome = &outcome});
if (outcome.status != usearch_status_success_k) goto cleanup;
usearch_dense_init_ram(&(usearch_dense_init_ram_t) {.index = &index,
.outcome = &outcome,
.metric = usearch_dense_metric_angular_k,
.quantization = usearch_scalar_bf16_k,
.dimensions = 128});
if (outcome.status != usearch_status_success_k) goto cleanup;
usearch_dense_insert(
&(usearch_dense_insert_t) {.index = index,
.executor = executor,
.outcome = &outcome,
.count = 2,
.keys = {keys, sizeof(usearch_key_t)},
.vectors = {vectors, sizeof(vectors[0]), 128, usearch_scalar_f32_k}});
if (outcome.status != usearch_status_success_k) goto cleanup;
usearch_dense_search(&(usearch_dense_search_t) {.index = index,
.executor = executor,
.outcome = &outcome,
.count = 1,
.queries = {vectors[0], 0, 128, usearch_scalar_f32_k},
.matches = &matches,
.arena = arena,
.wanted = 10});
if (outcome.status != usearch_status_success_k) goto cleanup;
printf("Found %zu matches\n", matches.counts[0]);
cleanup:
if (outcome.message) fprintf(stderr, "%s: %s\n", usearch_status_name(outcome.status), outcome.message);
usearch_dense_free(index);
usearch_arena_free(arena);
usearch_executor_free(executor);
return outcome.status == usearch_status_success_k ? 0 : 1;
} JavaScript
const { Arena, DenseIndex, DenseMetric, Executor } = require('usearch');
const index = DenseIndex.initRam({ dimensions: 3, metric: DenseMetric.Euclidean, connectivity: 16 });
const vector = new Float32Array([0.2, 0.6, 0.4]);
index.insert(42n, vector); // Build on the calling thread
const pool = Executor.forRam();
const arena = new Arena(pool); // Reuse memory beside the workers
const matches = index.on(pool).search(vector, 10, arena); // One query, up to 10 hits
const found = matches.get(0); Go
package main
import (
"fmt"
"log"
usearch "github.com/unum-cloud/USearch/golang"
)
func main() {
const dimensions = 3
const entries = 100
options := usearch.DefaultDenseOptions()
options.Dimensions = dimensions
options.Metric = usearch.DenseMetricAngular
options.Quantization = usearch.ScalarF32
index, err := usearch.DenseInitRam(options, nil)
if err != nil {
log.Fatal(err)
}
defer index.Close()
if err := index.Reserve(entries); err != nil {
log.Fatal(err)
}
keys := make([]usearch.Key, entries)
vectors := make([]float32, entries*dimensions)
for entry := range entries {
keys[entry] = usearch.KeyFromUint64(uint64(entry))
for dimension := range dimensions {
vectors[entry*dimensions+dimension] = float32(entry + dimension)
}
}
if err := index.Insert(keys, usearch.RowsOf(vectors, dimensions), nil); err != nil {
log.Fatal(err)
}
arena, err := usearch.NewArena(nil)
if err != nil {
log.Fatal(err)
}
defer arena.Close()
query := []float32{0.0, 1.0, 2.0}
matches, err := index.Search(usearch.RowsOf(query, dimensions), 3, arena, nil)
if err != nil {
log.Fatal(err)
}
found, distances, err := matches.Query(0)
if err != nil {
log.Fatal(err)
}
for rank := range found {
fmt.Println(found[rank], distances[rank])
}
} Swift
import NumKong
import USearch
let options = DenseOptions(dimensions: 3, metric: .angular, quantization: .bf16)
let index = try DenseIndex.initRam(options)
let vectors = try Tensor.fromArray([Float](arrayLiteral: 0.3, 0.5, 1.2, 0.4, 0.2, 1.2), rows: 2, columns: 3)
try index.reserve(2)
try index.insert(keys: [42, 43], vectors: RowsView(vectors)) // Build on the calling thread
let pool = try Executor.forRam()
let arena = try Arena(on: pool) // Reuse memory beside the workers
let matches = try index.on(pool).search(RowsView(vectors), wanted: 10, arena: arena) Mojo
from usearch import Arena, DenseIndex, DenseMetric, DenseOptions, Executor, Key, Library, RowsView, ScalarKind
def main() raises:
var library = Library()
var options = DenseOptions(3, DenseMetric.ANGULAR, ScalarKind.BF16)
var index = DenseIndex.init_ram(library, options)
index.reserve(1_000)
var keys = [Key(integer=42), Key(integer=43)]
var vectors = [Float32(0.2), 0.6, 0.4, Float32(0.1), 0.3, 0.9]
index.insert(keys, RowsView.of(vectors, 3))
var executor = Executor.for_ram(library, threads=4)
var arena = Arena(executor)
var query = [Float32(0.2), 0.6, 0.4]
var matches = index.on(executor).search(RowsView.of(query, 3), 10, arena)
print(matches.query_keys(0)[0], matches.query_distances(0)[0]) Java
DenseOptions options = new DenseOptions()
.dimensions(3).metric(DenseMetric.ANGULAR).quantization(Scalar.BF16);
try (Executor pool = Executor.forRam(new int[0], null, 0);
Arena arena = new Arena(pool);
DenseIndex index = DenseIndex.initRam(options, new int[0])) {
index.reserve(100);
Key[] keys = {Key.of(42), Key.of(43)};
float[] vectors = {0.1f, 0.2f, 0.3f, 0.3f, 0.2f, 0.1f};
index.insert(keys, RowsView.of(vectors, 3));
RowsView query = RowsView.of(new float[] {0.1f, 0.2f, 0.3f}, 3);
Matches matches = index.on(pool).search(query, 10, arena);
for (int rank = 0; rank < matches.count(0); ++rank) {
System.out.println(
matches.key(0, rank) + " at " + matches.score(0, rank));
}
} C#
using Cloud.Unum.USearch;
DenseOptions options = DenseOptions.Default with
{
Metric = DenseMetric.Angular,
Quantization = Scalar.BF16,
Dimensions = 3,
Connectivity = 16,
ValuesPerKey = 1,
};
using DenseIndex index = DenseIndex.InitRam(options);
index.Reserve(1_000);
Key[] keys = [42UL];
float[] vector = [0.2f, 0.6f, 0.4f];
index.Insert(keys, RowsView.RowsOf<float>(vector, dimensions: 3));
using Executor pool = Executor.ForRam();
using Arena arena = new(pool);
Matches found = index.On(pool).Search(RowsView.RowsOf<float>(vector, 3), wanted: 10, arena);
Key nearest = found[0].Keys[0];
double distance = found[0].Distances[0]; Zig
const std = @import("std");
const usearch = @import("usearch");
var index = try usearch.DenseIndex.initRam(.{
.dimensions = 4,
.metric = .angular,
.quantization = .i8,
}, &.{});
defer index.deinit();
try index.reserve(1_000);
const keys = [_]usearch.Key{ .fromInteger(42), .fromInteger(43) };
const slab = [_]f32{ 0.2, 0.1, 0.2, 0.1, 0.1, 0.2, 0.1, 0.2 };
try index.insert(&keys, try .of(f32, &slab, 4), .{});
const query = [_]f32{ 0.2, 0.1, 0.2, 0.1 };
var arena = try usearch.Arena.init(null);
defer arena.deinit();
const matches = try index.search(try .of(f32, &query, 4), 10, &arena, .{});
for ((try matches.query(0)).keys) |key| std.debug.print("{f}\n", .{key});
var executor = try usearch.Executor.forRam(.{});
defer executor.deinit();
_ = try index.on(executor).search(try .of(f32, &query, 4), 10, &arena, .{}); Wolfram
PrependTo[$LibraryPath, "build_release"];
Get["wolfram/USearch.wl"];
index = DenseInitRam["inner", "bf16", 3];
DenseReserve[index, 10];
rows = {{0.2, 0.6, 0.4}, {0.4, 0.6, 0.2}};
DenseInsert[index, {FromDigits["5f9c2b718e4d4a63b2f10c7a9d3e6b58", 16], 43}, rows];
local = ArenaInit[];
matches = DenseSearch[index, rows, 5, local]
matches["Keys"]
matches["Scores"]
executor = ExecutorForRam[];
arena = ArenaInit["Executor"->executor];
matches = DenseSearch[DenseIndexOn[index, executor], rows, 5, arena];
DenseGet[index, 43, arena]
products = DenseMultiply[DenseIndexOn[index, executor], rows, arena];
DenseDescribe[index]
DenseSave[DenseIndexOn[index, executor], "index.safegraphs"];
loaded = DenseLoadRam["index.safegraphs", "Executor"->executor];
ClearAll[loaded, index, arena, local, executor]; The connectivity, the number of edges per node, is fixed when the index is created, while the expansion_factor, the breadth of the candidate pool, rides on every insert, refine and search call, so one immutable index serves a whole recall sweep with no rebuild. Our benchmarks use connectivity 32 with expansions of 256 on insertion and 96 on search; hnswlib defaults to 16, 200 and 10, and Faiss to 32, 40 and 16, so compare libraries at matched recall, never at defaults. When recall must be exactly 1, or the collection fits in a few million rows, skip the index: NumKong's cdist scores every pair with the same kernels the index dispatches to.
refine re-selects every entry's neighbors against the finished graph, so a cheap insertion pass with a narrow expansion and one or two wide refinements reach a better graph in less total time than one expensive pass. It returns how many nodes changed their edges, zero meaning the graph has settled, and every pass, even a cancelled one, ends by re-linking whatever no search can reach, a gap classic HNSW leaves open. health then audits the graph read-only, reporting how many entries a walk from the landmarks reached, and searches keep running on a RAM index throughout.
bf16, in most cases. The kernels are bandwidth-bound, so throughput scales with how few bytes a vector takes: i8 runs about 4× faster than f32, and the 16-bit types about 2×. On Turing-ANNS, 10M 100-dimensional vectors at 99% recall@10 in RetriEval, bf16 matched f32 recall in 10.9 instead of 13.0 GB, e5m2 and e4m3 stayed within 0.001 of it in 9.8 GB, e3m2 gave up two points, and the 6-bit e2m3, spanning only ±7.5, fell to 0.79 on unit-scale embeddings that were not scaled to fit it. Binary u1x8 pairs with Hamming and Jaccard, which take no other type.
RetriEval builds every engine with shuffled parallel construction and sweeps its parameters until recall matches on 1–10M rows before scaling up, reporting recall@K as each library defines it, since one-recall@K is always at least K-recall@K. On SIFT in u8 on a dual Xeon 6, USearch built 10M vectors at 35K a second and searched 81K queries a second, against 26K and 38K for Faiss HNSW, and at 100M it finished in 48.7 minutes where Faiss was killed after 9 hours. The arithmetic is deterministic, with ties ranked by key and NumKong holding one error bound on every instruction set, but concurrent insertion interleaves threads, so pin your tests to recall, not to exact neighbor lists.
The vectors at their stored width, the 16-byte keys, and a fixed-degree row of 32-bit neighbor ids per entry, with each shard capped at 2³² − 1 rows: a 100M build of 128-dimensional u8 vectors needs about 50 GB resident at connectivity 32. storage_requirements answers for a checkpoint before you write it, and memory_usage for a live handle. Provision huge pages: traversal is bound by memory latency, and on a dual-socket Sapphire Rapids they alone were worth 29% of build and 20% of search throughput.
Use load_ram to copy a checkpoint into host memory, load_vram to upload it to devices, or view_nvme to search immutable SafeGraphs parts in place. NVMe views refuse mutations. Build and refine new parts in RAM or VRAM, save them, and serve their checkpoint from the drives. Object storage is reached through filesystem mounts. absorb combines compatible mutable donors of the same residency and consumes their handles.
Build on GPUs and serve wherever it's cheapest: on SIFT-10M in u8, a laptop RTX 4060 inserted 114.5K vectors a second against 12.8K on a 24-core i9, at 98.6% and 98.5% recall@10, so the fast way to a large CPU graph is to build most of it on the device, save, and insert the rest on the CPU. GPU kernels cover NVIDIA Ampere, Ada, Hopper, Blackwell, Blackwell RTX and Rubin, AMD CDNA 3 to 5 through ROCm and Apple GPUs through Metal, with GPUDirect Storage from NVMe drives into GPU memory, one shard per device and never replicated, failing rather than quietly paging to the host once the devices are full. CPU builds run on Linux, macOS, Windows, FreeBSD, iOS, Android and the browser, across x86, Arm, RISC-V, LoongArch, Power and WebAssembly, whose 64-bit build brings relaxed SIMD, shared-memory threads and more than 4 GiB of memory.
A key is 16 bytes, rendered as a lowercase dashed UUID with integers in the trailing bytes big-endian, so Key(42) prints as 00000000-0000-0000-0000-00000000002a. It's the key type UStore uses. Keys need not be unique: values_per_key bounds how many entries share one and count reports how many a key holds, which is how a document becomes one key over its token rows for late interaction.
Not one at a time. Entries are only ever added, which keeps every search read-only, lets any number of them overlap insertions, and keeps the graph's connectivity guarantees provable; clear erases everything while keeping the capacity and geometry. To retire an entry, filter its key out with a predicate until a rebuild excludes it; to update one, add the new vector under the same key and filter obsolete keys. Filtering only by the shared key cannot distinguish two versions of that key.
Very little. It runs on every scored candidate, far more often than there are results, and concurrently on every executor thread. Keep it cheap and thread-safe: a bitset, a Bloom filter, a byte of the key. A Python lambda re-enters the interpreter and serializes the walk, and GPU-resident indexes take no predicate at all.
Images and text can share dense embeddings from UForm, and molecular fingerprints use packed-bit search. Sequences compare raw bytes and text through edit distances and alignment. Shape indexes compare point clouds, while geospatial indexes address WGS-84 points, sets and sampled routes.
Yes, on a RAM index: searches read only entries published behind the visibility watermark and never write to the graph, while insertions synchronize through per-node locks and publish in order, fully wired; only saving needs a window without mutations. It's the executor that serializes, never the index: each admits one driver at a time, so give every thread its own, and with threads=0 it takes 7/8 of the cores in its NUMA domains, since full occupancy starves the ordered publication path. The Python extension runs on free-threaded interpreters without the GIL.
Nothing half-valid survives: a single-file checkpoint writes its header last and a sharded one its manifest last, so an interrupted save is rejected or reads as absent, and a cancelled load publishes nothing. Checkpoints are SafeGraphs: an 8-byte magic, a JSON header and buffers laid out as Arrow lays them out. They load into any shard count, normalize byte order to little-endian and keep logical rows, so they move across machines, SIMD kits, and between VRAM and RAM. Without a progress handler, insert is all-or-nothing, and a severe accelerator fault latches the handle unusable rather than leaving it partially applied.