Skip to content

Studio: HNSW (usearch) tier for gigantic RAG scopes, kept consistent with SQLite - #16145

Merged
danielhanchen merged 8 commits into
mainfrom
perf/rag-hnsw-tier
Oct 30, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
perf/rag-hnsw-tier

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Dense RAG search on a very large scope (a knowledge base past the exact cache's 256 MB budget, about 160k chunks at 384-d) falls back to sqlite-vec's scalar scan: 155 ms per query at 200k chunks, about a second at 1M. This adds an HNSW tier for those scopes.

Library: usearch 2.26.6 (Apache-2.0). It is the only HNSW library with prebuilt wheels for every Studio target: CPython 3.11 to 3.15; manylinux x86_64 and aarch64 plus musllinux; macOS arm64 11.0+ and x86_64 10.13+; Windows amd64 and arm64. Its one native dependency, numkong 7.8.6 (Apache-2.0), has the same coverage. faiss-cpu's macOS wheels need 14+ (arm64) / 15+ (x86_64) while Studio supports 12+; hnswlib ships no wheels; voyager and chroma-hnswlib lack win_arm64 and cp313. numkong's Linux wheels are manylinux_2_28, the floor Studio's torch wheels already set. No wheelhouse build is needed.

When. vec_cache gives a scope of RAG_VEC_ANN_MIN_ROWS (default 100000) or more an HNSW entry instead of an exact one; smaller scopes are unchanged. RAG_VEC_ANN=0 turns it off, and a missing or unloadable wheel leaves the exact and vec0 paths as they are.

Consistency with SQLite. Index keys are chunks.rowid; each query resolves its candidate keys with SELECT rowid, id FROM chunks WHERE rowid IN (...) inside the reader's own snapshot, so returned chunk ids are current and deleted rows drop out, then _drop_incompatible applies the identity and retired-scope rules as before. The index answers only when the reader's epoch equals its own: rows added since the build live in an exact float32 delta (fed by add_chunks, which now records the chunks rowids it inserts), and rows added by another writer, a delete, a re-embed or a width change send the query to vec0 while the index is rebuilt or caught up in the background.

Build and persistence. Built in the background from one read snapshot (vec0 scanned once, chunks probed by primary key), float16 vectors, M=16. Saved under rag_ann/ next to rag.db as <scope hash>-<epoch>.usearch + .json (temp name then os.replace) and reopened memory-mapped, so a restart maps the file instead of rebuilding; a restart with new appends reads only the delta. New epochs get new file names, so Windows never replaces a file still mapped by a reader; old generations are deleted after the swap and retried if still mapped. RAG_VEC_ANN_DISK_MB (default 4096) caps the directory.

One usearch caveat found here: parallel inserts in 2.26.6 leave a few nodes unreachable at any k (1 to 2 of 300 sampled rows with 4 to 16 threads, none with 1), so builds run on one thread (200k x 384: 46 s, 1M: 6 min, once, in the background). Fetches covering half the index or more search exactly.

Measured (real rag.db, search_dense k=10, 200k x 384 clustered vectors, 1 thread, main vs this branch):

main this PR
tier serving the scope vec0 HNSW
search, median 155.6 ms 0.91 ms
recall@10 vs vec0 1.0 1.0
one-time build none 50 s (background)
restart none 0.15 s (maps the saved index)

Tests. tests/test_rag_vec_ann.py (no SQLite, so it runs on every platform): recall@30 >= 0.99 vs exact, unscorable rows never indexed, exact delta merged with the index, saved generation reloads mapped with the same answers, mismatched or corrupt files rejected, every sampled row reachable with the build's thread count. tests/test_rag_vec_cache_ann.py: HNSW answers a gigantic scope without vec0 and matches it, appends join the delta without a rebuild, a delete or re-embed falls back to vec0 until the rebuild, rows another writer added are never missed, a restart maps the saved generation (and catches up appends) instead of rebuilding, superseded files are deleted, and with the tier off or the wheel missing the exact path answers. On CI a missing usearch fails these files instead of skipping them. Negative controls: ignoring the scope counter fails the re-embed test, ignoring the newest rowid fails the other-writer test, skipping the delta fails the append test. test_rag*.py: only the environment-dependent Office/PDF failures, same as main.

@danielhanchen danielhanchen self-assigned this Oct 30, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-30T16:07:06.648664Z 28b8fbd Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 30, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 32669925ba

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

The Windows xplat leg (Windows Server 2025) fails two of the new tests in studio/backend/tests/test_rag_vec_cache_ann.py:

  • test_superseded_generations_are_deleted (line 170)
  • test_the_disk_cap_evicts_the_least_recently_used_scope (line 212)

Both assert not os.path.exists(first.base + ".usearch") after the entry is dropped, and on Windows the file is still there. That looks like the index file is still open or memory-mapped when the delete runs (Windows refuses to unlink an open or mapped file, and a suppressed PermissionError leaves it behind). Closing or releasing the usearch index before removing its files, or retrying the delete once the handle is gone, should make it pass there. Linux and macOS are unaffected.

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 30, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 28b8fbd399

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

Separate from the Windows test failures above: the windows-11-arm leg failing while it builds pymupdf from source is not from this PR. pymupdf 2.0 has no win_arm64 wheel and the requirements only had pymupdf>=1.28.2 there; #16160 pins 1.28.2.

danielhanchen added a commit that referenced this pull request Oct 30, 2026
…ith a win_arm64 wheel (#16160)

## Problem

The `windows-11-arm` leg fails to install the Studio backend
requirements (seen on the staging run for #16145):

```
pymupdf
  ...
  File "...\pymupdf_...\setup.py", line 1046, in build_mupdf_windows
  subprocess.CalledProcessError: Command 'cd "...\mupdf-1.28.5-source" && ...
error: metadata-generation-failed
```

On Windows ARM64 the requirements say `pymupdf>=1.28.2`, added with
#10282. When that landed, 1.28.2 was the newest release and it ships a
`win_arm64` wheel. pymupdf 2.0 came out on 2026-10-19 with wheels for
macOS arm64, manylinux x86_64 / aarch64 and win_amd64 only, so on
Windows ARM64 `>=1.28.2` now resolves to the 2.0 sdist and tries to
build MuPDF from source. This is not only a CI problem: a Studio install
or update on a Windows-on-ARM machine goes the same way. Every other
platform is unaffected because it is pinned to `pymupdf==1.27.2.3`.

## Fix

- `studio/backend/requirements/studio.txt`,
`studio/backend/requirements/no-torch-runtime.txt` and the `studio`
extra in `pyproject.toml` pin `pymupdf==1.28.2` on Windows ARM64, the
only pymupdf release with a `win_arm64` wheel. The comments now say why.
- `tests/studio/install/test_pymupdf_platform_pins.py`:
- For each of win_arm64, win_amd64, linux x86_64 / aarch64 and macOS
arm64, every one of the three files must give pymupdf exactly one `==`
pin, and the three must agree.
  - Windows ARM64 must stay on 1.28.2.
- A lower bound alone (the shape that broke here) fails it, as does a
drift between the files.

## Verification

- `pip download "pymupdf==1.28.2" --platform win_arm64 --python-version
3.12 --only-binary=:all: --no-deps` resolves
`pymupdf-1.28.2-cp310-abi3-win_arm64.whl`.
- New tests pass (6 passed). With main's requirement files restored they
fail on the two win_arm64 cases.
- The existing tests that read these requirement files show the same 21
failing IDs on main and on this branch in my local environment
(`test_dependency_pass_skips.py`, which needs the CI install layout), so
this change adds no failures.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…/rag-hnsw-tier

# Conflicts:
#	studio/backend/requirements/no-torch-runtime.txt
#	studio/backend/requirements/studio.txt
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 30, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 30, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 30, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 30, 2026
@danielhanchen
danielhanchen merged commit 5c1dc91 into main Oct 30, 2026
21 of 27 checks passed
@danielhanchen
danielhanchen deleted the perf/rag-hnsw-tier branch October 30, 2026 17:02
danielhanchen added a commit that referenced this pull request Oct 30, 2026
## Problem

`Repo tests (CPU, studio-install)` is red on main since #16145 (seen on
the staging run for #16168, a frontend-only change):

```
tests/studio/install/test_studio_extra_matches_requirements.py::test_studio_extra_matches_requirements_file
AssertionError: studio.txt lists ['usearch'] but the `studio` extra does not.
tests/studio/install/test_studio_extra_matches_requirements.py::test_studio_extra_matches_requirement_versions
AssertionError: studio.txt specifies [('usearch', '==2.26.6', '')] but the `studio` extra does not.
```

#16145 added `usearch==2.26.6` to
`studio/backend/requirements/studio.txt` and `no-torch-runtime.txt` for
the HNSW RAG tier, but not to the `studio` extra in `pyproject.toml`. So
`pip install "unsloth[studio]"` resolves a different stack from the one
`install.sh` builds, which is exactly what this guard is for.

## Fix

Add `"usearch==2.26.6"` to the `studio` extra, next to `sqlite-vec`.
usearch 2.26.6 ships wheels for every target (manylinux / musllinux
x86_64 and aarch64, macOS x86_64 / arm64 / universal2, win_amd64,
win_arm64), so it needs no platform marker, matching `studio.txt`.

## Verification

- `tests/studio/install/test_studio_extra_matches_requirements.py`: 2
failed on main, all 7 pass with this change.
`tests/studio/install/test_pymupdf_platform_pins.py` still passes.
- `pyproject.toml` still parses.
danielhanchen added a commit that referenced this pull request Oct 31, 2026
…G imports (#16284)

`Document upload compatibility` (`Uploads (macos-latest)`, `Uploads
(windows-latest)`) has failed on every RAG PR since #16145, for example
#16280 now:

```
ERROR collecting studio/backend/tests/test_rag_vec_ann.py
studio/backend/tests/test_rag_vec_ann.py:13: in <module>
    import usearch  # noqa: F401
E   ModuleNotFoundError: No module named 'usearch'
ERROR collecting studio/backend/tests/test_rag_vec_cache_ann.py
```

The workflow's run history: `perf/rag-hnsw-tier` (#16145 itself),
`perf/r14-chat-search`, `dh/fix-engine-port-blocks-past-40-workers` and
`perf/r14-rag-ingest` all failed there, while the `flows-*` branches it
ran on passed.

### Why

#16145 pinned `usearch==2.26.6` in
`studio/backend/requirements/studio.txt` and the studio extra. Under
`CI`, its ANN tests import usearch unconditionally, by design: a missing
wheel where `studio.txt` was installed is a packaging failure, not a
skip. `tests/studio/rag_upload_ci.py` runs every
`studio/backend/tests/test_rag_*.py`, but in a venv built only from its
own pinned `tests/studio/rag_upload_requirements.txt`, and that list
never got usearch. The tests are right. The harness's requirements fell
behind.

### Change

- Pin `usearch==2.26.6` in `tests/studio/rag_upload_requirements.txt`,
matching `studio.txt`.
- New `tests/studio/test_rag_upload_requirements_cover_ci_imports.py`.
It reads each `test_rag_*.py` for `import`s made only under a `CI`
check, and requires each module to be pinned in
`rag_upload_requirements.txt` at the same version as `studio.txt`. It
has a control that the scan finds today's `usearch` import, so the
reader cannot pass by seeing nothing.

### Verification

- The new tests pass.
- Sabotage: dropping the usearch pin fails with `['test_rag_vec_ann.py:
usearch', 'test_rag_vec_cache_ann.py: usearch']`. Pinning `2.26.5` fails
with `usearch: upload 2.26.5 vs studio.txt 2.26.6`.
- The workflow's path filter includes `tests/studio/rag_upload*`, so
`Document upload compatibility` runs on this PR on macOS and Windows.
That run is the end-to-end check.
danielhanchen added a commit that referenced this pull request Nov 19, 2026
…nowledge base needs them (#16799)

Studio's HNSW tier (#16145) depends on usearch + numkong native wheels.
Today they are plain lines in `studio.txt` / `no-torch-runtime.txt`, so:

- every Studio install downloads and unpacks them (about 59 MB on disk
on Linux x86_64), although only knowledge bases of 100k+ chunks ever use
HNSW;
- a host with no matching wheel (glibc 2.26 / 2.27 no-torch installs, a
PyPI-blocked network) falls back to an sdist build and fails the whole
Studio deps step;
- the install manifest counts a missing usearch as a broken install
(Desktop preflight included), and an install that skipped the pair never
gets it.

This PR makes the pair an optional prebuilt that Studio and Desktop
download themselves, only when a knowledge base is large enough to use
it.

## What it adds

- On demand by default: installs and updates download nothing. When a
scope reaches `RAG_VEC_ANN_MIN_ROWS` (100k) and the pair is missing, the
backend starts one background install (never inside a SQLite transaction
or the cache lock; search keeps answering from the exact cache / vec0),
then rebuilds the waiting scopes as HNSW without a restart.
`UNSLOTH_HNSW_PREFETCH=1` installs it during install / update instead,
for a machine that will be offline later.
- `studio/install_hnsw_prebuilt.py` + `studio/hnsw_prebuilt.txt`, a
hash-pinned requirements file with every usearch 2.26.6 / numkong 7.8.6
wheel for cp311 to cp314 (`scripts/hnsw_catalog.py [--check]`
regenerates it from PyPI).
- uv (Studio's private copy is found without PATH; pip as fallback)
installs it with `--require-hashes --only-binary :all: --no-deps
--no-config`: uv picks the wheel for the interpreter, only the pinned
bytes are accepted, nothing is ever built from source, and a user's uv
config or `UV_CONSTRAINT` cannot interfere. Proxies, `UV_INDEX_URL` /
`PIP_INDEX_URL` and the OS trust store (macOS, Windows, Desktop, as
Studio's other downloads) are honoured. A platform with no wheel reports
`unsupported` and backs off.
- Strips the DWARF debug info the PyPI Linux builds ship (about 90% of
numkong) from the installed libraries in pure Python and rewrites
RECORD, so uninstall stays clean; files are replaced with new inodes so
uv's hardlinked cache is untouched. Each debug run is cut by a multiple
of the segment alignment, so no loaded byte moves. Linux x86_64 goes
from 58.7 MB to 10.2 MB installed, aarch64 from 32.2 MB to 6.5 MB; macOS
(3.7 / 4.1 MB) and Windows (2.2 MB) are unchanged.
- Installs only the half that is missing when one package is already
there; a pair from an older install or the user's own is probed, never
replaced.
- Writes an `unverified` marker before touching the venv and probes the
pair in a child interpreter (import, insert, search, save, memory-mapped
restore) before Studio imports it. A failed probe uninstalls only what
this run installed and writes `failed` (retried after 7 days or with
`--force`); a hung probe stays `unverified`. `vec_ann.usearch()` never
imports a failed, unverified or still-installing pair, so a bad native
build cannot crash the backend.
- Statuses: ready, already, missing (check-only), disabled
(`RAG_VEC_ANN_AUTO_INSTALL=0` or `RAG_VEC_ANN=0`), offline, unsupported,
failed, busy. Exit 0 for all of them; `--strict` exits 1 unless the pair
is ready.
- The pair leaves `studio.txt`, `no-torch-runtime.txt` and the `studio`
extra and is in no pip requirement at all (a test enforces it), so no
install can fail over it; `known_unmet_index` ignores it.

## Testing

- `test_hnsw_prebuilt.py`: the hash file pins both packages; install
flags and child env (constraints and secrets dropped, index / proxy /
TLS kept); offline, opt-out, check-only; probe failure, unverified
marker, an install killed halfway, no wheel for the platform, half a
pair already installed; ELF debug stripping (synthetic ELF with a
patchelf-style tail segment, unsafe layouts left alone) and in-place
RECORD rewrite that leaves a hardlinked cache copy alone; and a real
hash-pinned install, strip and probe of the pair that fails above 15 MB
installed or with any debug section left.
- `test_rag_hnsw_runtime.py`: one request per missing scope, switch to
HNSW after the install without a write, backoff per status, markers and
the install lock skipping the import, a module still initialising on
another thread.
- `test_hnsw_prebuilt_step.py`: installs and the `setup.sh` /
`setup.ps1` fast paths download nothing by default; with
`UNSLOTH_HNSW_PREFETCH=1` the step never raises and the fast paths stay
local when nothing is owed (bash and pwsh).
- Fresh venv with only numpy and tqdm: the backend's on-demand fetch was
ready in 2.0 s, imported in process, 10.1 MB on disk, no wheel cache
left.
- Cross-platform runs: the installer reported `ready` and the tests
passed on ubuntu x64 / arm64, macOS arm64 / x86_64 and Windows x64 /
arm64; on AMD Strix Halo (gfx1151) Linux with ROCm and Windows 11 the
pair installed and loaded and the HNSW suites passed (126 / 126).

Follow-ups: pre-stripped wheels to shrink the Linux download for the
users who fetch it (12.9 MB today), manylinux2014 builds for glibc 2.17
to 2.27, and signed Windows `.pyd` files.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant