SurfSense icon indicating copy to clipboard operation
SurfSense copied to clipboard

The bundled embedding model is FP16, not the int8 ADR 0007 specifies

Open MODSetter opened this issue 2 months ago • 5 comments

The gap

docs/architecture/search.md lists this under Known gaps:

The bundled model is FP16, not the int8 ADR 0007 specifies: Qdrant/bge-small-en-v1.5-onnx-Q is named for quantization but its only ONNX file stores FLOAT16 weights. An int8 export would roughly halve the 63 MB and speed embedding, and needs checking for whether its vectors are close enough to skip a re-embed.

Why it matters

ADR 0007 says "bge-small-en-v1.5, int8 ONNX, 384 dimensions, about 66 MB", and the comment at the top of embedding.py repeats it. Neither is true: the repository is named for quantization and its one ONNX file holds FLOAT16 weights. The ADR is the document a reader trusts about what runs on the user's machine, so an ADR that is wrong about the artefact is worse than a missing one.

The cost is real as well as documentary. The model is bundled into every installer for three platforms, and embedding runs on the CPU in the ingest worker, where it is the slow half of a big import and competes with the parser. The retrieval proposal puts an int8 bge at about 33 MB against today's 63 MB, and it cites that figure when comparing bundle sizes for the multilingual swap — so the comparison in that proposal is resting on a number nobody has produced.

Where

What done looks like

This is an investigation with a code change at the end, not the other way round. Expect most of the work to be measurement.

  • The ADR and the code agree about what is bundled, and the numbers in the ADR are ones you measured: file size on disk, and embedding throughput on a CPU you name.
  • A decision, with the evidence behind it, on whether an int8 export's vectors are close enough to the FP16 model's to leave existing indexes alone. Cosine between the two models' vectors for the same passage, and the eval's per-slice ranks under each, are the two things that answer it. The threshold is yours to set and to defend.
  • If the answer is that a re-embed is needed, stop and say so on this issue. Then this stops being a small win and becomes part of the migration the retrieval proposal already designs, which is maintainer work — closing the ADR's documentary half is still worth a PR on its own.
  • Delete the Known gaps line from docs/architecture/search.md in the same PR as whichever half you land, and fix the Code line's claim if it changes.

What not to change

Do not quietly swap the model. _check_embedding_width() in shared/migrations.py refuses a database whose chunk_vectors width no longer matches the setting, and both ADR 0007 and the retrieval proposal say in as many words that a same-width replacement is undetectable: an existing library would go on searching vectors written by a different model, silently, with no error and slowly worsening results. An int8 bge is 384 dimensions, so that guard will not fire for you.

How to verify

surfsense_local/backend/tests/integration/search/test_retrieve.py covers keyword, paraphrase and Hindi retrieval; tests/integration/chunks/test_search_index.py covers the index's refusal of a vector of the wrong width. Both should pass unchanged — if one fails, the swap is not a swap. The eval is not a test and is run by hand.

cd surfsense_local/backend
uv run pytest -m unit
uv run pytest -m integration
uv run ruff check .

Before you start

Read CONTRIBUTING.md, the search doc, ADR 0007 and the retrieval proposal, which is the accepted design for changing the embedder and explains why the re-embed is the expensive part. Post your measurements on this issue before you open the PR — the numbers are the contribution here, and a maintainer will want to see them first. Open your PR against dev, not main. Comment here to claim this.

MODSetter avatar Sep 28 '26 22:09 MODSetter

I'd like to take this one. Measurements first, posted here before any PR: the on-disk size and CPU throughput of the bundled FP16 file and of an int8 export, the cosine between the two models' vectors for the same passages, and the retrieval eval's per-slice ranks under each. If the vectors are not close enough to leave existing indexes alone, I'll stop here and say so, and send only the ADR correction.

ybai08 avatar Oct 02 '26 08:10 ybai08

Measurements, as promised. One thing changed under this issue while it was open: ADR 0036 (merged 2 Oct) pins the bundled file by hash and says a different build can replace it only through a re-embed. So by this issue's own rule the int8 swap stops here. The numbers are still worth having, and they turned up something the issue did not ask about.

Setup. Apple M6 (12 logical CPUs), macOS arm64, onnxruntime 1.29.0, CPU provider, default threads. The app's own recipe from modules/embedding/encoder.py: the bundled tokenizer.json, truncation at 512, CLS pooling, L2 normalisation, batch 32. Text is the retrieval eval's corpus: 119 short passages (median 53 tokens) and 21 chunk-sized ones (512 tokens after truncation). Throughput is the median of 5 passes after a warm-up.

1. What is bundled

Qdrant/bge-small-en-v1.5-onnx-Q model_optimized.onnx at the pinned revision: 33.2 M weights, every one FLOAT16, 66,465,124 bytes. That is 66.5 MB, or 63.4 MiB, so ADR 0007's "about 66 MB" is right and search.md's "63 MB" is the same file in MiB. "int8" is what is wrong.

2. Size, speed and closeness

Build Size Short passages/s Chunk-sized passages/s Cosine to bundled (mean / min)
bundled FP16 66.5 MB 72 14.5 —
BAAI onnx/model.onnx (fp32) 133.1 MB 180 25.7 1.0000 / 0.999998
Xenova model_quantized.onnx (int8) 34.0 MB 147 23.8 0.998 / 0.978
Xenova model_int8.onnx 33.8 MB 156 not run 0.976 / 0.914
Xenova model_uint8.onnx 33.8 MB 212 not run 0.989 / 0.947
bundled file, weights widened to fp32 132.9 MB 202 34.4 1.0000 / 0.9999993

The last row is the bundled file's own weights rewritten as FLOAT: no other model, just the type.

3. The retrieval eval

run_retrieval_eval.py, 17 documents and 66 queries, with each build dropped in as the bge file. "Old index" means the index built by the bundled FP16 file, queried with the other build, which is the case of leaving an existing library alone.

Run In top 5 Mean rank Queries whose rank moved
bundled FP16 91% (60/66) 1.7 —
fp32, fresh index 91% 1.7 0
fp32 queries on the old index 91% 1.7 0
widened, fresh index 91% 1.7 0
widened queries on the old index 91% 1.7 0
int8 (model_quantized), fresh index 91% 1.6 1 (10 → 9)
int8 queries on the old index 91% 1.6 1 (3 → 2)

Every slice is identical across the runs; the six misses are the same cross-lingual queries each time. The eval is at its ceiling here, so it shows no harm rather than proving equivalence.

What I take from it

  • int8 would have been a real win and is not a drop-in. Half the size (the proposal's "about 33 MB" is right: 33.8 to 34.0 MB) and 1.6 times the speed on chunk-sized text. The vectors are close but not the same (mean cosine 0.998, one query in 66 moves a place), and ADR 0036 now makes any other file a different index. I am not pursuing the swap.
  • The FP16 file is the slow way to run these weights on a CPU. The same weights as fp32 embed 2.3 times as fast on chunk-sized text (14.5 → 34.4 passages/s) and 2.7 times on short text, and the vectors do not move: cosine at least 0.9999993, largest component difference 4.8e-4, no rank change on a fresh index or on the old one. onnxruntime's CPU provider evidently does FP16 badly; I did not look into why.
  • That is a speed-up for ingest that needs no new download and no re-embed in the sense of the vector space, but it is not free: 133 MB instead of 66.5 MB if shipped that way, or a one-time conversion on the user's machine and the larger file on disk, and it needs a decision under ADR 0036, whose spec pins the weights file by hash.

What I can send

  1. Now: the documentary half. ADR 0007 and the search.md line say what is bundled (FP16, 66.5 MB) with these measured numbers. I'd amend through the ADR's status line and a note, not rewrite its Decision, unless you prefer a correction in place.
  2. If you want it: a short proposal in docs/proposals/ for running the bundled weights as fp32, with the options (ship fp32, or widen at install or first run) and the numbers above. I would not write code for it before you say the idea fits.

Not measured: any x86 machine, Windows, Linux, a CPU without many cores (single-thread numbers on this machine: 11.1 passages/s for FP16 against 15.3 for BAAI fp32 on chunk-sized text), peak memory, or session start-up time.

ybai08 avatar Oct 02 '26 08:10 ybai08

A correction to my table above, found while fixing #2158: the "Cosine to bundled (mean / min)" column paired a mean over the passages with a minimum over the 66 queries. Per set, from the same runs' output (mean / min, not re-run):

Build 119 short passages 66 queries 21 chunk-sized passages
BAAI onnx/model.onnx (fp32) 1.0000 / 1.0000 1.0000 / 1.0000 0.999999 / 0.999998
Xenova model_quantized.onnx (int8) 0.9977 / 0.9922 0.9971 / 0.9782 0.9981 / 0.9965
Xenova model_int8.onnx 0.9760 / 0.9512 0.9782 / 0.9140 not run
Xenova model_uint8.onnx 0.9893 / 0.9799 0.9889 / 0.9473 not run

So for the int8 export the per-query figures are a mean of 0.997 and a minimum of 0.978, and the passages are closer than the queries (minimum 0.992). I have not split the widened-fp32 row the same way; its 0.9999993 is the lowest value I saw for it. The speeds, the eval results and the conclusions are unchanged.

ybai08 avatar Oct 05 '26 00:10 ybai08

@ybai08 we ran your fp32 finding on x86, because your table had no x86 machine. On x86 it is a bigger win than on your M6, so the idea fits. One decision on how, then it's yours to build.

Setup. AMD Ryzen 7 5800X (8 cores, 16 threads), 16 GB, Windows 11, the app's own venv (onnxruntime 1.29.0, CPU provider), and the recipe from encoder.py: the bundled tokenizer, truncation at 512, CLS pooling, L2 normalisation, batches of 32. The text is the eval corpus: 119 short passages and 13 chunk-sized ones. "fp32" below means the bundled file's own weights widened to FLOAT, the same transform as your last row.

Speed

Threads FP16 short/s FP16 chunk/s fp32 short/s fp32 chunk/s
default 5.0 1.5 37.2 8.0
4 5.0 1.4 41.1 7.5
1 5.5 1.2 15.6 3.0

Other work on the machine kept it about half busy, so the absolute numbers are low. To cancel that out, a second run timed the two builds in alternation in one process. On the chunk-sized set fp32 was 6.0 to 7.3 times as fast in each of 5 rounds. One search question at a time (a batch of 1) took 93 ms at the median for FP16 and 9 ms for fp32, and 125 ms against 32 ms at p95. On x86 the FP16 file does not scale with threads at all. Your single-thread numbers suggest it barely does on ARM either (14.5 against 11.1).

Vectors, memory, start-up

  • Cosine, FP16 against fp32: at least 0.9999993 on every set: short passages, chunk-sized passages and the 66 queries. The largest component difference is 5e-4.

  • Answers: we used a cosine-only check over the paragraphs, not run_retrieval_eval.py. The answer was in the top 5 for 54 of 66 queries in all three cases: FP16, a fresh fp32 index, and fp32 queries on the FP16 index. Two queries swapped near-tied neighbours inside their top 10; no answer moved.

  • Memory, each build in a fresh process, embedding the 13 chunks:

    After load Peak working set
    FP16 144 MiB 472 MiB
    fp32 file 196 MiB 460 MiB
  • Session start: 0.14 to 0.38 s for either.

Which way to ship it

  • Widening in memory at load: ruled out by measurement. The vectors are bit-identical to the fp32 file's, but the app would need onnx at runtime, which is 41 MB installed. It costs 0.3 s per load, holds 326 MiB after load against 199 MiB, and peaks at 639 MiB against 371 MiB.
  • Widening at build time: this is the way. The widening is deterministic: every run with onnx 1.20.1 gives sha256 eebe19e38b8bd17e3f5bd4cb0aef20579a9fa262ca573a37494e10b16c313805 (132,889,492 bytes). Each widened weight ends in 13 zero bits, so the file compresses well: it deflates to 77.6 MB against 61.0 MB for the FP16 file. That adds about 17 MB to installers of 1.08 to 1.30 GB, and 66 MB once installed.

What to send

One PR against dev:

  1. fetch_embedding_model.py: download the pinned FP16 file and check 51f1bd0a… as today. Widen it with an onnx pinned in a build-only dependency group, check the result against eebe19e3…, and stage only the fp32 file. A mismatch at either step fails the fetch.

  2. bundled.py and encoder.py: leave BGE and every stored snapshot exactly as they are. Their identity is the FP16 file, 51f1bd0a…. model_dir() recognises bge by (repo, revision, weights), and active.py embeds with the snapshot stored in embedding_indexes, so changing either would orphan every existing library. Instead:

    • add the widened file to bundled.py as bge's runtime file, pinned by eebe19e3…;
    • have _loaded() and missing_files() use that file for the bundled pack.

    No migration and no re-embed: these are the same weights, losslessly widened, so the vector space has not moved, and the numbers above are the evidence.

  3. A new ADR: ADR 0036 says "Its FP16 weights stay". The new ADR records that a lossless widening of the pinned weights is the same embedder, and why. 0036 takes only "Amended by" on its Status line, per docs/adr/README.md. Put both sets of measurements in it, yours from the M6 and these from the 5800X.

  4. embedding.md: update the Choosing paragraph and its numbers in the same PR.

test_retrieve.py and test_search_index.py should pass unchanged. Add a test that the staged file's hash is checked. Please push when it's ready.

MODSetter avatar Oct 07 '26 20:10 MODSetter

The FP32 upcast on Apple silicon, since embedding.md lists it as not measured: on the M6 it is about 1.9 times as fast at every thread count, the vectors and the eval do not move, and it holds more memory on macOS than the 5800X's numbers suggest.

Setup. Apple M6 (12 cores in three performance levels: 2, 4 and 6), 24 GB, macOS 27.0.1 arm64, Python 3.12.14, onnxruntime 1.29.0 CPU provider, dev at 51c593551. The bundled file is fetched with fetch_embedding_model.py, and both hashes match the pins. Each run is a fresh process calling encoder.embed() with SURFSENSE_LOCAL_EMBED_PRECISION=fp16 or fp32. In each one runs_at_fp32() matched the switch and no fallback warning was logged. The machine had other work on it: load averages were 3.7 at the start of the speed runs and 7.0 at the end, counting the runs themselves.

Speed

I couldn't find the 5800X's 64 passages, so these are 64 evenly spaced from the 957 the app's chunker (worker.ingestion.chunking.chunk) cuts from docs/architecture/*.md at that commit. They average 318 tokens (median 346, max 481) against 345 there, in batches of 32. The app sets no thread count. For 1, 4 and 8 threads, a wrapper around onnxruntime.InferenceSession sets intra_op_num_threads on the session the app opens, and nothing else changes. Each cell is 3 fresh processes, each with one warm-up pass and 3 timed passes of all 64, with FP16 and FP32 alternated. The table gives the median of the 9 passes and their range.

Threads FP16 passages/s FP32 passages/s FP32 / FP16 Per-process ratios
default 17.3 (15.9–19.0) 32.8 (32.3–35.1) 1.89 1.85, 1.91, 1.98
1 10.7 (9.5–11.3) 19.7 (17.8–21.1) 1.84 1.86, 1.81, 1.84
4 14.8 (14.0–15.2) 29.6 (27.4–31.7) 1.99 1.98, 1.97, 2.08
8 18.1 (17.0–18.8) 31.2 (28.8–34.4) 1.73 1.74, 1.80, 1.69

The FP16 file scales with threads on this chip, unlike on x86 (10.7 at one thread to about 18 at 8 or default), so the gain is smaller than the 5800X's 6.2 times. It is still about 1.7 to 2.0 times at each thread count, and it held in every pair of processes.

First load

Each figure is the median of 7 fresh processes, with the file already in the page cache and import onnxruntime (about 0.085 s for either) not counted.

FP16 FP32
encoder._loaded() as the app calls it 0.041 s (0.038–0.050) 0.096 s (0.091–0.122)
reading — 0.005 s
hashing — 0.020 s
the rewrite — 0.035 s
the session 0.033 s 0.024 s
tokenizer 0.007 s 0.007 s

That is 0.055 s more, once per process, against 0.22 s on the 5800X.

Memory

This is the one cost that is larger here. The figures are phys_footprint, which Activity Monitor shows as Memory, through the app's _loaded() and then embed() of the 64 passages:

FP16 FP32 Difference
After the load 231 MB 616 MB +385 MB
After embedding 1,251 MB 1,514 MB +263 MB

The 5800X figures are +52 MB and +18 MB. _model_bytes is cleared, and the attribute exists on this onnxruntime. Opening the same upcast model from a file on disk instead of from bytes holds only 50 MB more than FP16 after the load: 227 MB against 177 MB in that probe, against 563 MB from bytes. Turning off prepacking (session.disable_prepacking) made no difference (579 MB). So most of the extra on macOS comes from opening the session from bytes, not from the wider weights. I did not look into why it stays resident.

Vectors and the eval

  • Cosine, FP16 against FP32: at least 0.99999951 over the 64 passages and 0.99999935 over the eval's 66 queries. The largest component difference is 6.3e-4. Each precision gave bit-identical vectors at every thread count and in every process.
  • run_retrieval_eval.py, on a fresh index for each precision (the eval's cache root moved into a temp dir per run, --rebuild): the answer sat at the same rank on all 66 queries, with 60 of 66 in the top 5 both ways and a mean rank of 1.7. The 24 stored chunk vectors differ (cosine at least 0.9999997), so the FP32 index really was built at FP32. One query, wear-parts-zh, swapped two passages of the same document at places 8 and 9, below its answer at 1.
  • FP32 queries on the FP16 index, which is what an existing Mac library would see after the switch: the same rank on 66 of 66, and identical top-10 lists.

Not run

  • LIMIT-small. fetch_limit_small.py was not run, so the eval is the 66 authored queries, not 266.
  • Any other Apple chip, a laptop on battery or under thermal limits, the packaged app (this ran from a source venv), ingest end to end, and peak memory during the load on its own.

If the numbers are enough, I can send a PR that lets auto upcast on macOS arm64 as well and records these numbers in ADR 0058 and embedding.md. The memory cost is the open question there, and how much it matters is your call.

ybai08 avatar Nov 05 '26 18:11 ybai08