Build a similarity graph containing every vector pair meeting a cosine threshold. Each row can have any number of neighbors, so top-k search answers a different question. The library streams edges without storing the full score matrix. It can also generate deduplication candidates; similarity alone does not establish that two records are duplicates.
The engineering problem is making exhaustive matching practical without silently losing pairs, exceeding declared query scratch, or hiding setup costs. CUDA, FAISS CPU and Apple Silicon MLX backends are included. The experimental prepared CUDA API adds resident inputs, conservative projection screening, adaptive tiles and explicit memory accounting. Benchmarks include setup costs, which have an irritating habit of surviving into production.
Current result: automatic selection found screening gains of 1.20–3.17× on selected prepared-query workloads, including a predeclared holdout. All 36 calibrated auto first-use medians still lost to dense. Revision 7d46ea5 passed RTX 4090 correctness and sanitizer gates. The measurements and their limits are below.
flowchart LR
A[Normalize and own inputs] --> B[Score a pair tile]
B --> C[Count candidates]
C --> D{Choose tile execution}
D -->|Over budget| E[Split before output]
E --> B
D -->|Dense or sparse scores| F[Resolve numerical boundaries]
F --> G[Stream edge batches]
Three decisions shape the implementation:
- Account before allocating. Bound score, count, scan, candidate and classification buffers together. Split disjoint tiles before emitting any output, so retries cannot duplicate already delivered pairs.
- Separate rejection from acceptance. Outward projection bounds reject impossible matches; FP64 intervals and exact integer fallback resolve uncertain survivors. Exact refinement cannot repair a wrong early rejection.
- Choose from measured tile costs. Auto weights complete query-pipeline samples by tile geometry; per-tile candidate density can still trigger dense scoring. Calibration and preparation remain visible costs. Screening still performs quadratic projected comparisons.
Architecture and allocation ledger · Numerical assumptions · Engineering case study
From this checkout:
python -m pip install '.[cpu]' # FAISS CPU
# Other backends: '.[mlx]' on Apple Silicon; '.[cuda12]' on Linux/NVIDIA
python examples/similarity_graph.py \
--input benchmarks/data/arxiv/arxiv-100000.npy \
--rows 1000 --threshold 0.9 --backend faiss \
--output /tmp/gtj-arxiv-1000Follow the example guide to acquire the pinned public
arXiv embeddings or run a small smoke example. The command creates a new
output directory with streamed edges.csv and run.json, recording completion,
edge count and load/setup/query/sink costs. Interrupted or limited output
remains explicitly incomplete. It performs one graph construction.
With the CUDA extra installed, use --backend cuda-prepared --strategy dense
and a new output directory. --strategy screen enables projection screening
with density fallback; compare the entire job before choosing it for your data.
CUDA prerequisites and the example source
explain the execution options.
Measured revision: 7d46ea5, RTX 4090. The frozen selector campaign has
36 cells and 1,728 main timing observations across arXiv, COCO, GloVe and
synthetic controls. The predeclared holdout uses different thresholds, disjoint
real-data slices and a fresh synthetic seed.
| Matrix | Auto selected screening | Query speedup in those cells | Auto first-use losses |
|---|---|---|---|
| Existing workloads | 8 of 18 | 1.45–3.17× | 18 of 18 |
| Predeclared holdout | 10 of 18 | 1.20–3.17× | 18 of 18 |
The remaining cells selected dense; small timing differences there are not screening wins. Worst observed prepared-query time was 1.025× the best measured explicit route. This compares dense, forced screen and adaptive screen, not every possible rank: auto can choose rank128 while the high-dimensional explicit screening comparisons use rank64.
Selected medians show both query gains and their setup cost:
| Workload, 50k rows | Dense query | Auto query | Dense first use | Auto first use |
|---|---|---|---|---|
| Existing arXiv, 0.9 | 64.04 ms | 25.81 ms | 180.30 ms | 468.37 ms |
| Holdout arXiv, 0.925 | 63.89 ms | 24.77 ms | 182.91 ms | 453.88 ms |
| Holdout COCO, 0.85 | 102.58 ms | 85.56 ms | 185.52 ms | 569.42 ms |
Each cell has nine query and three first-use observations per route, with complete host-output consumption. First use includes preparation after route warmup, excluding cold context/JIT startup. Auto was asked to plan for 100 queries; the default of one query skips calibration and selects dense. The measurements do not establish a need to recompute an identical graph.
Both panels below include all 18 existing workloads and their losses. Below 1 is faster; above 1 is slower. Bars show observed ranges, not confidence intervals.
The real graph example exported the same 340 edges from 50k arXiv rows in 0.715 s dense, 0.792 s screen and 0.732 s auto. These are single invocations in separate fresh processes with a warm CuPy disk cache, including input, setup and CSV output—not a latency distribution. Auto planned one query and chose dense.
Current selector report and evidence
include every route choice, cost scope and comparison. The
earlier two-GPU campaign
belongs to d1a7f1e: its selector missed every manual screening win. Those
immutable results and profiles remain separate from the current revision.
pairs returns self-pairs with i < j; join supports cross-joins. Zero rows
never match. The top-level APIs compare backend-computed FP32 scores with an
inclusive FP32 threshold. The prepared API instead targets the exact real dot
of host-normalized FP32 vectors, conditional on the documented arithmetic
and backend reduction assumptions. Scores remain FP32 approximations.
Prepared query scratch defaults to 512 MiB. The bound excludes resident
inputs/projections, preparation, backend/context memory, allocator cache and
caller output; it is neither a total-VRAM cap nor an out-of-core interface.
Earlier d1a7f1e A6000 diagnostics measured 258.0–258.5 MiB of owned query
arrays within their bounds. Batches are independent host arrays. Only iterator exhaustion
means complete output; an output limit raises rather than truncating silently.
See the prepared API contract.
Revision 7d46ea5 passed 153 CUDA tests without skips on RTX 4090, plus
all 42 prepared/workspace/numerical cases under each of four sanitizers.
All 36 campaign cells passed complete-output checks, and 224 collected artifacts
were hash-verified. The rental was terminated with zero remaining task resources;
estimated cost was $0.17827, not a final invoice.
Independent small fixtures test membership; large-corpus recall remains
relative to dense, so shared omissions are not independently ruled out. New
changes require their own validation. Fixed prepared inputs and thresholds also
mean identical results can be cached rather than recomputed.
Testing and clean installation · Current work and remaining gates · Historical experiments · MIT license