# USearch Templates

> Search, attention and sparse algebra over one proximity graph in RAM, VRAM or on NVMe, inside ClickHouse, DuckDB and YugabyteDB, from C++ Templates

`find_package(usearch CONFIG REQUIRED)` 8122c932

`include/usearch/` holds the core C++ 23 templates and containers USearch's engine is built from: graph indexes over any payload, metric and key, the dense kernel kits, and the RAM, VRAM and NVMe residencies of every modality.

They serve advanced users who build their own indexes, metrics or file formats rather than calling the engine. These headers carry no stability promise: their names, layouts and signatures change with the engine in any release, while the C ABI of `c/usearch/*.h` and the C++ SDK of `cpp/usearch/*.hpp` are versioned. Pin a commit, not a version, when building on them. Every subfolder `usearch/<dir>/` opens `unum::usearch::<dir>`, and every header is spelled `<usearch/<dir>/...>`.

## Installation

8122c932

#### Getting Them

`usearch::header` is the in-RAM basic tier: `basic/ram_index.hpp`, `basic/ram_indexes.hpp` and the eight `utilities/` headers under them, over the standard library and the C types of `usearch::abi`, with nothing to compile. An install carries it, so a program finds it as it finds the libraries:

```cmake
find_package(usearch CONFIG REQUIRED)
target_link_libraries(your_target PRIVATE usearch::header)
```

The rest, the dense kits, the NVMe and VRAM tiers and the sequence, shapes and geospatial modalities, includes NumKong, ForkUnion, StringZilla and SmashTable, so no install carries it. Vendor USearch through `FetchContent`, which fetches those siblings at the commits USearch pins, and link their targets beside `usearch::header`:

```cmake
FetchContent_Declare(usearch GIT_REPOSITORY https://github.com/unum-cloud/USearch.git GIT_SHALLOW TRUE)
FetchContent_MakeAvailable(usearch)
target_link_libraries(your_target PRIVATE usearch::header numkong::types forkunion::header forkunion::cpp
                                          stringzilla::types smashtable::header)
```

## Quickstart

8122c932

#### Building & Searching

A single `basic::ram_index` is a complete index on its own. It needs no SafeGraphs files, no sharded index around it and no UUIDs. Keys may be any hashable type, node IDs may be 32 or 64 bits wide, and every record keeps its own key. The sharded indexes in `ram_indexes.hpp`, `vram_nvidia_indexes.hpp`, `vram_amd_indexes.hpp` and `vram_apple_indexes.hpp` are what the compiled library builds on top. Only they narrow the choice, to 32-bit shards whose nodes a shard table locates in 8 bytes.

An index is a template over the payload, the key, the node ID width and the distance type. It allocates nothing until its first `reserve` or insert, then grows on demand in chunks of node records that never move, so `reserve` is only a hint that covers ahead. Every record builds its value from the index’s allocator by uses-allocator construction, so the values a caller inserts are best built from `index.get_allocator()` too. Each thread brings its own metric instance and its own traversal context, which holds the walk’s scratch, sits on any allocator such as a per-thread arena, and receives the matches:

```cpp
using index_t = us::basic::ram_index<std::vector<float>, us::util::u64_t>;
index_t index;
if (!index.reserve(1000)) return 1;

manhattan_metric_t metric;
index_t::traversal_context_t context {/* seed */ 42};
std::vector<std::vector<float>> values = {{0, 0, 1}, {0, 1, 0}, {1, 0, 0}};
std::vector<us::util::u64_t> keys = {10, 20, 30};
auto const [inserted, insert_status] = index.insert(std::span {values}, std::span<us::util::u64_t const> {keys},
                                                    metric, std::span<us::util::u64_t> {}, context,
                                                    us::basic::keep_diverse_t {16});

std::vector<float> const query = {0, 0, 0.9f};
auto const [found, search_status] = index.search(query, metric, context);
for (std::size_t i = 0; i != found.count; ++i) {
    auto const [key, key_status] = index.key_of(context.results[i].node_id);
    // `context.results[i].distance` is the match's score, ascending.
}
```

- `insert` moves a batch of payloads in under their keys and is all-or-nothing: capacity and scratch for the whole batch are secured before the first value moves.
- `plan_insert` spreads one batch over threads: it claims, covers and dispenses the whole ID range, each thread places a disjoint slice through the plan’s own `insert` with a context `reserve_traversal` sized, and `finish` publishes the batch at once. Nothing can fail past the dispense, so every position of a plan must be placed, and a refused fan-out places on the calling thread.
- The selector decides which candidates become neighbors, and holds the neighbors-per-node budget: `basic::keep_diverse_t` prunes by diversity, `basic::keep_closest_t` keeps the nearest. Both are per-call values, so heuristics and budgets can change between batches.
- `search` leaves its matches in `context.results`, nearest first, and `key_of`, `value_of`, `find` and `count` translate between node IDs and keys.
- A search may score with a different metric than the one the graph was built with, and a `fold` passed to `search` reads every scored round, for walks that reduce to something other than the nearest matches.

## Metrics

8122c932

#### Writing Metrics

A metric is a builder that scores one round of candidates against one query at a time, so an expensive metric can batch, pack or upload its candidates before scoring them all at once:

- `reset(query)` opens a round for one query; a walk reopens the same query every round, so a metric that prepares its query keeps that work when nothing changed.
- `push(value)` stages one candidate and answers `staged_k`, or `refused_k` once its staging is full, which makes the walk drain before staging more.
- `drain(distances, radius)` scores everything staged, writes the distances in push order, and clears the staging.

A distance within `radius` must be exact, while one above it may be any value above it, so a kernel can stop scoring a candidate the moment it cannot come back under. Every verb runs with no locks held, so a `drain` may take milliseconds without stalling another thread, and the values a round pushed stay valid until its `drain` returns. A metric marked `is_transparent` accepts query forms other than the stored value, such as a `std::string_view` for `std::string` payloads.

```cpp
#include <cmath>  // `std::fabs`
#include <span>   // `std::span`
#include <vector> // `std::vector`

#include <usearch/basic/ram_index.hpp>

namespace us = unum::usearch;

/** Manhattan distance over vectors of any length, scored one staged round at a time. */
struct manhattan_metric_t {
    std::vector<float> const* query_ = nullptr;
    std::vector<std::vector<float> const*> staged_;

    void reset(std::vector<float> const& query) noexcept { query_ = &query, staged_.clear(); }
    us::basic::metric_staging_t push(std::vector<float> const& value) noexcept {
        return staged_.push_back(&value), us::basic::metric_staging_t::staged_k;
    }
    void drain(std::span<double> distances, double) noexcept {
        for (std::size_t i = 0; i != staged_.size(); ++i) {
            double sum = 0;
            for (std::size_t j = 0; j != query_->size(); ++j) sum += std::fabs((*query_)[j] - (*staged_[i])[j]);
            distances[i] = sum;
        }
        staged_.clear();
    }
};
```

## Serialization

8122c932

#### Saving & Loading

Payloads are arbitrary objects, so `save` and `load` take a codec that encodes each value into its own slice and back:

- `storage_requirements(value)` sizes one value’s slice.
- `save(value, output)` encodes it.
- `load(input, value)` decodes it into a pre-constructed record.

`save` fills five caller-placed columns sized from `columns_extents`, while searches keep running, and `load` reads them back into an empty index, publishing everything at once.

## Concurrency

8122c932

#### Concurrent Calls

The leading template parameter of `insert` and `search` is the caller’s synchronization contract:

- `concurrent_k`, the default, admits any mix of readers and writers.
- `immutable_k` certifies no live mutators, so searches read neighbor lists without locks.
- `exclusive_k` certifies sole ownership, compiling every lock out for single-threaded builds.

A violated certification answers `contended_k` instead of returning a silently wrong result. `save`, `load`, `clear` and `health` never run concurrently with inserts, while `reserve` runs at any time.

## Platform Notes

8122c932

#### Deeper Layers

- [`basic/`](https://github.com/unum-cloud/USearch/blob/main/include/usearch/basic/README.md): the reference graph index the sequence, shapes and geospatial modalities instantiate, its residencies, any on-disk format and the NVMe walk.
- [`dense/`](https://github.com/unum-cloud/USearch/blob/main/include/usearch/dense/README.md): dense vectors, their NumKong kits per capability tier, and the RAM, VRAM and NVMe residencies with their sharded indexes and reshard plans.
- [`shapes/`](https://github.com/unum-cloud/USearch/blob/main/include/usearch/shapes/README.md): 3D point clouds, their scoring kinds and residencies, and moving from overlay screeners.
- `sequence/` and `geospatial/`: the byte-string and Earth-fixed instantiations of `basic/`.
- `utilities/`: devices, shards, walks, buffers, sorts and the SafeGraphs format every folder stands on.
