diff --git a/CHANGELOG.md b/CHANGELOG.md index de8d10a..bfab279 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Fixed +- BQ initialization rejects packed binary storage before mutation instead of trapping in WASM. Binary search and buffer persistence remain usable after rejection. +- Runnable README/API examples construct `EdgeVecConfig` and enable BQ explicitly. BQ guidance distinguishes binary-code compression from retained F32 memory; Node examples verify real file save/load roundtrips. - Binary HNSW compaction preserves packed storage; compaction also retains scalar calibration and enabled BQ state. WASM metadata follows surviving vectors when IDs are reassigned. - Loaded TypeScript clients and indexes report saved dimensions and live counts. `EdgeVecIndex` exposes persistence buffers and the documented parsed sparse/hybrid methods. - Hybrid search pairs sparse and dense document IDs, filters deleted documents before sparse top-k, and updates pairings after compaction. `insertSparseForVector()` supports explicit pairing. diff --git a/README.md b/README.md index abfae86..f178a72 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ > **The first WASM-native vector database.** > Dense + sparse vectors, hybrid search, binary quantization, metadata filtering — all in the browser. -EdgeVec is an embedded vector database built in Rust with first-class WebAssembly support. It brings server-grade vector database features to the browser: **HNSW + FlatIndex**, **sparse vectors with BM25**, **hybrid search (RRF fusion)**, **32x memory reduction** via binary quantization, metadata filtering, soft delete, persistence, and sub-millisecond search. +EdgeVec is an embedded vector database built in Rust with first-class WebAssembly support. It brings server-grade vector database features to the browser: **HNSW + FlatIndex**, **sparse vectors with BM25**, **hybrid search (RRF fusion)**, **32x smaller binary codes**, metadata filtering, soft delete, persistence, and sub-millisecond search. --- @@ -55,12 +55,14 @@ npm install edgevec ``` ```typescript -import init, { EdgeVec } from 'edgevec'; +import init, { EdgeVec, EdgeVecConfig } from 'edgevec'; await init(); // Create index (768D for embeddings like OpenAI, Cohere) -const db = new EdgeVec({ dimensions: 768 }); +const config = new EdgeVecConfig(768); +const db = new EdgeVec(config); +config.free(); // Insert vectors with metadata (v0.6.0) const vector = new Float32Array(768).map(() => Math.random()); @@ -74,8 +76,9 @@ const id = db.insertWithMetadata(vector, { const query = new Float32Array(768).map(() => Math.random()); const results = db.searchWithFilter(query, 'category = "books" AND price < 50', 10); -// Fast BQ search with rescoring — 32x less memory, 95% recall (v0.6.0) -const fastResults = db.searchBQ(query, 10); +// Enable BQ explicitly, then rescore binary candidates with retained F32 vectors +db.enableBQ(); +const fastResults = db.searchBQRescored(query, 10, 5); // Monitor memory pressure (v0.6.0) const pressure = db.getMemoryPressure(); @@ -139,7 +142,10 @@ Read more: [Entity-Enhanced RAG in 300KB](docs/blog/entity-enhanced-rag.md) ## Performance -EdgeVec v0.9.0 uses **SIMD instructions** for 2x+ faster vector operations on modern browsers. +EdgeVec supports SIMD builds for modern browsers. The checked-in package and +GitHub Pages demo intentionally use a scalar compatibility build for older +Safari versions. The native benchmark figures below are separate from that +browser artifact. ### Distance Calculation (Native Benchmark) @@ -166,22 +172,33 @@ EdgeVec v0.9.0 uses **SIMD instructions** for 2x+ faster vector operations on mo ### Browser Support -| Browser | SIMD | Performance | -|:--------|:-----|:------------| -| Chrome 91+ | YES | Full speed | -| Firefox 89+ | YES | Full speed | -| Safari 16.4+ | YES | Full speed (macOS) | -| Edge 91+ | YES | Full speed | -| iOS Safari | NO | Scalar fallback | +| Browser | SIMD build support | +|:--------|:-------------------| +| Chrome 91+ | Yes | +| Firefox 89+ | Yes | +| Safari 16.4+ (macOS, iOS, iPadOS) | Yes | +| Edge 91+ | Yes | +| Safari 15–16.3 | Use the scalar build | + +[Safari 16.4 added WebAssembly SIMD](https://webkit.org/blog/13966/webkit-features-in-safari-16-4/). +SIMD and scalar are separate compile-time builds; there is no automatic runtime +fallback. The default source build (`npm run build`) enables SIMD. To reproduce +the checked-in compatibility artifact, use this Bash command: -> **Note:** iOS Safari doesn't support WASM SIMD. EdgeVec automatically uses scalar -> fallback, which is ~2x slower but still functional. +```bash +RUSTFLAGS="-C target-feature=-simd128" npm run build +``` ### Bundle Size -| Package | Size (gzip) | Notes | -|:--------|:------------|:------| -| edgevec | **217 KB** | SIMD enabled (541 KB uncompressed) | +| Checked-in scalar artifact | Bytes | Bytes (gzip) | +|:---------------------------|------:|-------------:| +| WASM | 698,412 | 266,010 | +| JavaScript glue | 162,843 | 29,492 | +| Combined | 861,255 | 295,502 | + +[Current artifact validation](docs/benchmarks/2026-10-20_onboarding.json) records +the compiler, build flags, hashes, and measured performance. [Full benchmark report ->](docs/benchmarks/2025-12-24_simd_benchmark.md) @@ -191,11 +208,16 @@ EdgeVec v0.9.0 uses **SIMD instructions** for 2x+ faster vector operations on mo ### Binary Quantization (v0.6.0) -32x memory reduction with minimal recall loss: +Binary codes use 1 bit per dimension, 32x smaller than F32 payloads. Enabling BQ +on a float index retains the original F32 vectors for rescoring. ```javascript -// BQ is auto-enabled for dimensions divisible by 8 -const db = new EdgeVec({ dimensions: 768 }); +// BQ requires dimensions divisible by 8 and explicit enablement +const config = new EdgeVecConfig(768); +const db = new EdgeVec(config); +config.free(); +db.enableBQ(); +db.insert(vector); // Raw BQ search (~85% recall, ~5x faster) const bqResults = db.searchBQ(query, 10); @@ -204,11 +226,14 @@ const bqResults = db.searchBQ(query, 10); const rescoredResults = db.searchBQRescored(query, 10, 5); ``` -| Mode | Memory (100k × 768D) | Speed | Recall@10 | +| Mode | Vector payloads (100k × 768D) | Speed | Recall@10 | |:-----|:---------------------|:------|:----------| -| F32 (baseline) | ~300 MB | 1x | 100% | -| BQ raw | **~10 MB** | 5x | ~85% | -| BQ + rescore(5) | **~10 MB** | 3x | ~95% | +| F32 (baseline) | ~293 MiB | 1x | 100% | +| BQ raw on a float index | ~302 MiB (F32 + codes) | 5x | ~85% | +| BQ + rescore(5) | ~302 MiB (F32 + codes) | 3x | ~95% | + +Payload sizes exclude graph, metadata, and capacity overhead. Speed and recall +depend on the data and hardware. [BQ memory details](docs/guides/BINARY_QUANTIZATION.md#memory-savings). ### Metadata Filtering (v0.6.0) @@ -287,12 +312,10 @@ const restored = EdgeVec.fromBytes(bytes); ### Scalar Quantization -```javascript -const config = new EdgeVecConfig(768); -config.quantized = true; // Enable SQ8 quantization - -// 3.6x memory reduction: 3.03 GB -> 832 MB at 1M vectors -``` +SQ8 is available in the native Rust storage API through +`StorageType::QuantizedU8(QuantizerConfig { min, max })`. The WASM +`EdgeVecConfig` has no SQ8 option; assigning `config.quantized` does not enable +quantization. For WASM, use the explicit BQ API shown above. ### FlatIndex (v0.9.0) diff --git a/docs/api/FLAT_INDEX.md b/docs/api/FLAT_INDEX.md index 971622e..d42da98 100644 --- a/docs/api/FLAT_INDEX.md +++ b/docs/api/FLAT_INDEX.md @@ -397,7 +397,10 @@ assert_eq!(index.capacity(), 2); // Reclaimed ## Binary Quantization -FlatIndex supports optional binary quantization (BQ) for approximate search with reduced memory usage. +Native FlatIndex supports optional binary quantization (BQ) for approximate +search using compact codes. It retains the original float vectors for rescoring. +The WASM Flat index uses packed binary storage and does not expose this native +float-index quantization option. ### How It Works diff --git a/docs/api/MEMORY.md b/docs/api/MEMORY.md index 620ffde..2da4a92 100644 --- a/docs/api/MEMORY.md +++ b/docs/api/MEMORY.md @@ -159,17 +159,21 @@ if (recommendation.includes('compact')) { ## Memory Optimization Strategies -### 1. Enable Binary Quantization +### 1. Budget for Binary Quantization -The most effective way to reduce memory: 32x reduction. +Binary codes are 32x smaller than F32 vector payloads. Enabling BQ on a float +index retains the original F32 vectors for rescoring, so it adds a code cache +rather than reducing total index memory. ```typescript -// BQ is auto-enabled for dimensions divisible by 8 -const index = new EdgeVec({ dimensions: 768 }); - -// Memory comparison (100k vectors, 768D): -// - F32: ~300 MB -// - BQ: ~10 MB +const config = new EdgeVecConfig(768); +const index = new EdgeVec(config); +config.free(); +index.enableBQ(); + +// Vector payloads (100k vectors, 768D; excludes graph and metadata): +// - F32: ~293 MiB +// - BQ codes: ~9 MiB, in addition to retained F32 vectors ``` ### 2. Periodic Compaction @@ -333,7 +337,7 @@ console.log(JSON.stringify(dashboard, null, 2)); 1. **Monitor regularly** - Check memory pressure before bulk operations 2. **Compact proactively** - Don't wait for critical pressure -3. **Use BQ when possible** - 32x memory savings with minimal recall loss +3. **Budget for BQ** - Binary codes are 32x smaller than F32 payloads; float indexes retain both for rescoring 4. **Set appropriate thresholds** - Lower on mobile, higher on desktop 5. **Handle insert blocks gracefully** - Provide user feedback diff --git a/docs/api/README.md b/docs/api/README.md index 34440d3..fedd451 100644 --- a/docs/api/README.md +++ b/docs/api/README.md @@ -35,12 +35,14 @@ npm install edgevec ``` ```typescript -import init, { EdgeVec } from 'edgevec'; +import init, { EdgeVec, EdgeVecConfig } from 'edgevec'; await init(); // Create index (768D for embeddings like OpenAI, Cohere) -const db = new EdgeVec({ dimensions: 768 }); +const config = new EdgeVecConfig(768); +const db = new EdgeVec(config); +config.free(); // Insert vectors with metadata (v0.6.0) const vector = new Float32Array(768).map(() => Math.random()); @@ -52,10 +54,11 @@ const id = db.insertWithMetadata(vector, { // Search with filter expression (v0.6.0) const query = new Float32Array(768).map(() => Math.random()); -const results = db.searchFiltered(query, 'category = "books" AND price < 50', 10); +const results = db.searchWithFilter(query, 'category = "books" AND price < 50', 10); -// Fast BQ search with rescoring (v0.6.0) -const fastResults = db.searchBQ(query, 10); +// Enable BQ explicitly, then rescore using retained F32 vectors +db.enableBQ(); +const fastResults = db.searchBQRescored(query, 10, 5); // Monitor memory pressure (v0.6.0) const pressure = db.getMemoryPressure(); @@ -94,11 +97,15 @@ fn main() -> Result<(), Box> { ## v0.6.0 Features Summary -### Binary Quantization (32x Memory Reduction) +### Binary Quantization (32x Smaller Codes) ```javascript -// BQ is auto-enabled for dimensions divisible by 8 -const db = new EdgeVec({ dimensions: 768 }); +// BQ requires dimensions divisible by 8 and explicit enablement +const config = new EdgeVecConfig(768); +const db = new EdgeVec(config); +config.free(); +db.enableBQ(); +db.insert(vector); // Raw BQ search (~85% recall, ~5x faster) const bqResults = db.searchBQ(query, 10); @@ -107,11 +114,14 @@ const bqResults = db.searchBQ(query, 10); const rescoredResults = db.searchBQRescored(query, 10, 5); ``` -| Mode | Memory (100k x 768D) | Speed | Recall@10 | +| Mode | Vector payloads (100k x 768D) | Speed | Recall@10 | |:-----|:---------------------|:------|:----------| -| F32 (baseline) | ~300 MB | 1x | 100% | -| BQ raw | **~10 MB** | 5x | ~85% | -| BQ + rescore(5) | **~10 MB** | 3x | ~95% | +| F32 (baseline) | ~293 MiB | 1x | 100% | +| BQ raw on a float index | ~302 MiB (F32 + codes) | 5x | ~85% | +| BQ + rescore(5) | ~302 MiB (F32 + codes) | 3x | ~95% | + +Float indexes retain their F32 vectors when BQ is enabled. Payload sizes exclude +graph, metadata, and capacity overhead; speed and recall depend on data/hardware. ### Metadata Filtering @@ -124,8 +134,8 @@ db.insertWithMetadata(vector, { }); // Search with filter -db.searchFiltered(query, 'category = "electronics" AND price < 500', 10); -db.searchFiltered(query, 'tags ANY ["featured"]', 10); +db.searchWithFilter(query, 'category = "electronics" AND price < 500', 10); +db.searchWithFilter(query, 'tags ANY ["featured"]', 10); ``` **Operators:** `=`, `!=`, `>`, `<`, `>=`, `<=`, `AND`, `OR`, `NOT`, `ANY` @@ -225,7 +235,7 @@ if (!db.canInsert()) { | Search (100k vectors) | <10 ms | 329 us | | Insert latency | <5 ms | ~2 ms | | Bundle size (gzip) | <500 KB | 227 KB | -| BQ memory reduction | 8-32x | 32x | +| Binary-code compression relative to F32 payloads | 32x | 32x (float index retains both) | | BQ recall@10 | >0.90 | 0.95 | --- diff --git a/docs/api/WASM_INDEX.md b/docs/api/WASM_INDEX.md index 7afa22e..0e4f0b2 100644 --- a/docs/api/WASM_INDEX.md +++ b/docs/api/WASM_INDEX.md @@ -154,12 +154,12 @@ for (const result of results) { --- -### searchFiltered(query, filter, k) +### searchWithFilter(query, filter, k) Search with metadata filter expression. **(v0.6.0)** ```typescript -searchFiltered( +searchWithFilter( query: Float32Array, filter: string, k: number @@ -177,16 +177,16 @@ searchFiltered( ```typescript // Simple equality -const results = index.searchFiltered(query, 'category = "electronics"', 10); +const results = index.searchWithFilter(query, 'category = "electronics"', 10); // Comparison -const results = index.searchFiltered(query, 'price > 100 AND price < 500', 10); +const results = index.searchWithFilter(query, 'price > 100 AND price < 500', 10); // Array membership -const results = index.searchFiltered(query, 'tags ANY ["featured"]', 10); +const results = index.searchWithFilter(query, 'tags ANY ["featured"]', 10); // Complex expression -const results = index.searchFiltered(query, +const results = index.searchWithFilter(query, '(category = "electronics" OR category = "computers") AND inStock = true', 10 ); @@ -204,16 +204,17 @@ searchBQ(query: Float32Array, k: number): SearchResult[] **Requirements:** - Dimension must be divisible by 8 -- BQ is auto-enabled for compatible dimensions +- Call `index.enableBQ()` explicitly before BQ search **Performance Characteristics:** - ~5x faster than F32 search - ~85% recall -- 32x memory reduction +- Binary codes are 32x smaller than F32 payloads; float vectors remain stored for rescoring **Example:** ```typescript +index.enableBQ(); const results = index.searchBQ(query, 10); ``` @@ -592,12 +593,12 @@ dimensions(): number ## Utility Methods -### vectorCount() +### Total vector count Total vectors including deleted. ```typescript -vectorCount(): number +const total = index.liveCount() + index.deletedCount(); ``` --- @@ -646,8 +647,9 @@ hasBQ(): boolean Enable binary quantization on this index. **(v0.6.0)** -Binary quantization reduces memory usage by 32x (from 32 bits to 1 bit per dimension) -while maintaining ~85-95% recall. BQ is required for `searchBQ()` and `searchBQRescored()`. +Binary codes use 1 bit per dimension, 32x smaller than F32 payloads. The float +index retains its F32 vectors for rescoring; enabling BQ adds a code cache. +BQ must be enabled before `searchBQ()` and `searchBQRescored()`. ```typescript enableBQ(): void @@ -655,6 +657,7 @@ enableBQ(): void **Requirements:** - Dimensions must be divisible by 8 +- The index must be HNSW with float storage; packed binary storage is rejected **Example:** @@ -679,7 +682,7 @@ EdgeVec methods may throw errors for invalid operations: ```typescript try { - const results = index.searchFiltered(query, 'invalid filter syntax', 10); + const results = index.searchWithFilter(query, 'invalid filter syntax', 10); } catch (e) { console.error('Search failed:', e.message); } diff --git a/docs/benchmarks/2026-10-20_onboarding.json b/docs/benchmarks/2026-10-20_onboarding.json new file mode 100644 index 0000000..fb619ab --- /dev/null +++ b/docs/benchmarks/2026-10-20_onboarding.json @@ -0,0 +1,150 @@ +{ + "baseCommit": "59146c7a0c26fc70819b219b94f428a8b5e9bfc9", + "artifacts": { + "wasm": { + "bytes": 698412, + "gzipBytes": 266010, + "sha256": "c276ac803ccc164048091c95ec635a68cff04177beea7d366b872ccbbb2df1d6" + }, + "js": { + "bytes": 162843, + "gzipBytes": 29492, + "sha256": "6966189e04a979b7ffd732db4c08ed710116065eea19c0a338ed844256b6af99" + } + }, + "snippets": { + "snippets/edgevec-59b9f14da3349a9d/src/js/storage.js": "6228b6720eb56b457de3dbdc00953569236e4915c9eba9e8d2855ff9672daf82" + }, + "snippetHashEncoding": "SHA256 of canonical Git LF bytes", + "environment": { + "node": "v22.21.0", + "platform": "win32", + "cpu": "Intel(R) Core(TM) Ultra 9 285H", + "wasmCompiler": "rustc 1.94.0-nightly", + "wasmFlags": "-C target-feature=-simd128" + }, + "validation": { + "nativeTargeted": 9, + "newNativeBqCases": 2, + "wasmPersistence": 10, + "sdkRuntime": 17, + "jest": 33, + "indexedDbShim": 11, + "packageGlue": 5, + "demoGlue": 5, + "readmeQuickstarts": 3, + "installedConsumers": [ + "Node 22.21.0 ESM/CommonJS", + "Node 16.20.2 ESM/CommonJS" + ], + "strictLint": [ + "cargo +1.96 clippy --all-targets -- -D warnings", + "cargo clippy --target wasm32-unknown-unknown --lib -- -D warnings" + ] + }, + "nodeBenchmark": { + "vectors": 100000, + "dimensions": 128, + "searches": 1000, + "metric": "cosine", + "data": "Unseeded random unit vectors; generated separately for this run", + "p99SearchMs": 1.143, + "fileSaveMs": 245.8, + "fileLoadMs": 125.92, + "restoredCountAndSearchVerified": true + }, + "loadTrials": [ + { + "trial": 1, + "mode": "plain", + "count": 100000, + "dimensions": 128, + "bytes": 57265029, + "firstLoadMs": 139.2944, + "samplesMs": [ + 139.2944, + 63.5035, + 64.29270000000002, + 63.39510000000001 + ], + "node": "v22.21.0" + }, + { + "trial": 2, + "mode": "plain", + "count": 100000, + "dimensions": 128, + "bytes": 57265029, + "firstLoadMs": 120.9965, + "samplesMs": [ + 120.9965, + 62.794599999999974, + 63.9914, + 65.71820000000002 + ], + "node": "v22.21.0" + }, + { + "trial": 3, + "mode": "plain", + "count": 100000, + "dimensions": 128, + "bytes": 57265029, + "firstLoadMs": 124.3527, + "samplesMs": [ + 124.3527, + 68.14630000000002, + 65.4479, + 66.66809999999998 + ], + "node": "v22.21.0" + }, + { + "trial": 1, + "mode": "bq", + "count": 100000, + "dimensions": 128, + "bytes": 57265029, + "firstLoadMs": 133.9524, + "samplesMs": [ + 133.9524, + 77.73589999999999, + 75.33609999999999, + 77.74790000000002 + ], + "node": "v22.21.0" + }, + { + "trial": 2, + "mode": "bq", + "count": 100000, + "dimensions": 128, + "bytes": 57265029, + "firstLoadMs": 134.0126, + "samplesMs": [ + 134.0126, + 77.97449999999998, + 76.55869999999999, + 76.23000000000002 + ], + "node": "v22.21.0" + }, + { + "trial": 3, + "mode": "bq", + "count": 100000, + "dimensions": 128, + "bytes": 57265029, + "firstLoadMs": 133.3219, + "samplesMs": [ + 133.3219, + 77.5121, + 78.29809999999998, + 77.99449999999996 + ], + "node": "v22.21.0" + } + ], + "loadMethod": "Each trial is a fresh process; WASM initialization and reading the cached EVWB bytes precede the fromBytes timer; four loads are recorded with the first as the cold sample. No other builds or benchmarks ran concurrently.", + "scope": "Packed-binary BQ rejection and runnable onboarding corrections; no package version publication" +} diff --git a/docs/demo/cyberpunk.html b/docs/demo/cyberpunk.html index 8c53d66..d0582e5 100644 --- a/docs/demo/cyberpunk.html +++ b/docs/demo/cyberpunk.html @@ -72,7 +72,7 @@

NEURAL_SEARCH_INTERFACE

- Binary Quantization + Metadata Filtering // 32x MEMORY REDUCTION + Binary Quantization + Metadata Filtering // 32x SMALLER BINARY CODES

diff --git a/docs/demo/hub.html b/docs/demo/hub.html index 2509a41..aa2f165 100644 --- a/docs/demo/hub.html +++ b/docs/demo/hub.html @@ -640,7 +640,7 @@

FILTER_PLAYGROUND

CYBERPUNK_DEMO

Binary Quantization vs F32. Memory pressure. Performance benchmarks.

-

Binary Quantization // 32x Memory

+

Binary Quantization // 32x Smaller Codes

BQ vs F32 Memory API diff --git a/docs/demo/pkg/edgevec.d.ts b/docs/demo/pkg/edgevec.d.ts index 4c82eb8..abc4caa 100644 --- a/docs/demo/pkg/edgevec.d.ts +++ b/docs/demo/pkg/edgevec.d.ts @@ -1585,14 +1585,15 @@ export class EdgeVec { /** * Enables binary quantization on this index. * - * Binary quantization reduces memory usage by 32x (from 32 bits to 1 bit per dimension) - * while maintaining ~85-95% recall. BQ is automatically enabled for dimensions divisible by 8. + * Binary codes use 1 bit per dimension, 32x smaller than F32 payloads. + * The original F32 vectors remain stored for rescoring. Enable BQ explicitly + * on a HNSW float index with dimensions divisible by 8. * * # Errors * * Returns an error if: * - Dimensions are not divisible by 8 (required for BQ) - * - BQ is already enabled + * - The index uses packed binary storage or is not HNSW * * # Example * @@ -1613,7 +1614,7 @@ export class EdgeVec { * * Binary quantization converts vectors to bit arrays (1 bit per dimension) * and uses Hamming distance for comparison. This provides: - * - ~32x memory reduction + * - Binary codes 32x smaller than F32 payloads (the original vectors remain stored) * - ~3-5x faster search * - ~70-85% recall (use `searchBQRescored` for higher recall) * @@ -2423,7 +2424,7 @@ export interface InitOutput { readonly edgevec_getVectorMetadata: (a: number, b: number) => number; readonly __wasm_bindgen_func_elem_2309: (a: number, b: number, c: number) => void; readonly __wasm_bindgen_func_elem_2293: (a: number, b: number) => void; - readonly __wasm_bindgen_func_elem_2877: (a: number, b: number, c: number, d: number) => void; + readonly __wasm_bindgen_func_elem_2876: (a: number, b: number, c: number, d: number) => void; readonly __wbindgen_export: (a: number, b: number) => number; readonly __wbindgen_export2: (a: number, b: number, c: number, d: number) => number; readonly __wbindgen_export3: (a: number) => void; diff --git a/docs/demo/pkg/edgevec.js b/docs/demo/pkg/edgevec.js index f985b4d..34d3bc8 100644 --- a/docs/demo/pkg/edgevec.js +++ b/docs/demo/pkg/edgevec.js @@ -315,8 +315,8 @@ function __wasm_bindgen_func_elem_2309(arg0, arg1, arg2) { wasm.__wasm_bindgen_func_elem_2309(arg0, arg1, addHeapObject(arg2)); } -function __wasm_bindgen_func_elem_2877(arg0, arg1, arg2, arg3) { - wasm.__wasm_bindgen_func_elem_2877(arg0, arg1, addHeapObject(arg2), addHeapObject(arg3)); +function __wasm_bindgen_func_elem_2876(arg0, arg1, arg2, arg3) { + wasm.__wasm_bindgen_func_elem_2876(arg0, arg1, addHeapObject(arg2), addHeapObject(arg3)); } const BatchInsertConfigFinalization = (typeof FinalizationRegistry === 'undefined') @@ -2891,14 +2891,15 @@ export class EdgeVec { /** * Enables binary quantization on this index. * - * Binary quantization reduces memory usage by 32x (from 32 bits to 1 bit per dimension) - * while maintaining ~85-95% recall. BQ is automatically enabled for dimensions divisible by 8. + * Binary codes use 1 bit per dimension, 32x smaller than F32 payloads. + * The original F32 vectors remain stored for rescoring. Enable BQ explicitly + * on a HNSW float index with dimensions divisible by 8. * * # Errors * * Returns an error if: * - Dimensions are not divisible by 8 (required for BQ) - * - BQ is already enabled + * - The index uses packed binary storage or is not HNSW * * # Example * @@ -2931,7 +2932,7 @@ export class EdgeVec { * * Binary quantization converts vectors to bit arrays (1 bit per dimension) * and uses Hamming distance for comparison. This provides: - * - ~32x memory reduction + * - Binary codes 32x smaller than F32 payloads (the original vectors remain stored) * - ~3-5x faster search * - ~70-85% recall (use `searchBQRescored` for higher recall) * @@ -4496,7 +4497,7 @@ function __wbg_get_imports() { const a = state0.a; state0.a = 0; try { - return __wasm_bindgen_func_elem_2877(a, state0.b, arg0, arg1); + return __wasm_bindgen_func_elem_2876(a, state0.b, arg0, arg1); } finally { state0.a = a; } diff --git a/docs/demo/pkg/edgevec_bg.wasm b/docs/demo/pkg/edgevec_bg.wasm index 46c7d45..48a94d8 100644 Binary files a/docs/demo/pkg/edgevec_bg.wasm and b/docs/demo/pkg/edgevec_bg.wasm differ diff --git a/docs/demo/pkg/edgevec_bg.wasm.d.ts b/docs/demo/pkg/edgevec_bg.wasm.d.ts index 589038e..38914dc 100644 --- a/docs/demo/pkg/edgevec_bg.wasm.d.ts +++ b/docs/demo/pkg/edgevec_bg.wasm.d.ts @@ -137,7 +137,7 @@ export const wasmbatchdeleteresult_uniqueCount: (a: number) => number; export const edgevec_getVectorMetadata: (a: number, b: number) => number; export const __wasm_bindgen_func_elem_2309: (a: number, b: number, c: number) => void; export const __wasm_bindgen_func_elem_2293: (a: number, b: number) => void; -export const __wasm_bindgen_func_elem_2877: (a: number, b: number, c: number, d: number) => void; +export const __wasm_bindgen_func_elem_2876: (a: number, b: number, c: number, d: number) => void; export const __wbindgen_export: (a: number, b: number) => number; export const __wbindgen_export2: (a: number, b: number, c: number, d: number) => number; export const __wbindgen_export3: (a: number) => void; diff --git a/docs/guides/BINARY_QUANTIZATION.md b/docs/guides/BINARY_QUANTIZATION.md index 2292107..20106cd 100644 --- a/docs/guides/BINARY_QUANTIZATION.md +++ b/docs/guides/BINARY_QUANTIZATION.md @@ -7,7 +7,9 @@ ## Overview -Binary Quantization (BQ) is a compression technique that reduces each dimension of a vector to a single bit. This achieves **32x memory reduction** (from 32-bit floats to 1-bit values) while maintaining search quality through rescoring. +Binary Quantization (BQ) encodes each dimension as a single bit, making binary +codes **32x smaller** than the original F32 payload. Enabling BQ on a float index +retains the F32 vectors for rescoring; the code cache is additional storage. --- @@ -15,15 +17,14 @@ Binary Quantization (BQ) is a compression technique that reduces each dimension ### Binarization Process -1. **Threshold:** Each dimension is compared to the mean of that dimension across all vectors -2. **Encoding:** Values above threshold become `1`, below become `0` -3. **Packing:** 8 bits are packed into a single byte (128D vector → 16 bytes) +1. **Threshold:** Each dimension is compared to zero; there is no training step +2. **Encoding:** Positive values become `1`; zero and negative values become `0` +3. **Packing:** 8 dimensions are packed into a byte, dimension 0 in the least significant bit (128D vector → 16 bytes) ``` F32 Vector: [0.2, -0.5, 0.8, 0.1, -0.3, 0.9, -0.1, 0.4] -Mean: [0.0, -0.2, 0.5, 0.0, -0.1, 0.6, 0.0, 0.2] Binary: [ 1, 0, 1, 1, 0, 1, 0, 1] -Packed Byte: 0b10110101 = 0xB5 +Packed Byte: 0b10101101 = 0xAD (dimension 0 is bit 0) ``` ### Distance Calculation @@ -43,6 +44,10 @@ Lower Hamming distance = more similar vectors. ## Memory Savings +These sizes compare vector encodings, excluding graph, metadata, and allocation +overhead. A BQ-enabled float index keeps **both** encodings: F32 payloads plus the +binary code cache, about 103% of the original float payload size. + | Dimensions | F32 Size | BQ Size | Reduction | |:-----------|:---------|:--------|:----------| | 128D | 512 bytes | 16 bytes | 32x | @@ -52,11 +57,11 @@ Lower Hamming distance = more similar vectors. ### At Scale (768D vectors) -| Vector Count | F32 Memory | BQ Memory | Savings | +| Vector Count | F32 Payload | Binary Codes | Encoding Reduction | |:-------------|:-----------|:----------|:--------| -| 10K | 30 MB | 0.9 MB | 33x | -| 100K | 300 MB | 9 MB | 33x | -| 1M | 3 GB | 92 MB | 33x | +| 10K | 29.30 MiB | 0.92 MiB | 32x | +| 100K | 292.97 MiB | 9.16 MiB | 32x | +| 1M | 2929.69 MiB | 91.55 MiB | 32x | --- @@ -65,12 +70,15 @@ Lower Hamming distance = more similar vectors. ### JavaScript/TypeScript ```typescript -import init, { EdgeVec } from 'edgevec'; +import init, { EdgeVec, EdgeVecConfig } from 'edgevec'; await init(); -// BQ is auto-enabled for dimensions divisible by 8 -const db = new EdgeVec({ dimensions: 768 }); +// Explicitly enable BQ on a compatible HNSW float index +const config = new EdgeVecConfig(768); +const db = new EdgeVec(config); +config.free(); +db.enableBQ(); // Insert vectors (automatically quantized) for (const vector of vectors) { @@ -214,11 +222,17 @@ console.log(restored.hasBQ()); // true if BQ was enabled when saved ```javascript // Error: BQ methods fail -const db = new EdgeVec({ dimensions: 100 }); // Not divisible by 8 -db.searchBQ(query, 10); // Throws error +const config = new EdgeVecConfig(768); +const db = new EdgeVec(config); +config.free(); +db.insert(vector); +db.searchBQ(query, 10); // Throws: BQ has not been enabled +db.enableBQ(); +const results = db.searchBQ(query, 10); ``` -**Fix:** Use dimensions divisible by 8 (128, 384, 768, 1536). +**Fix:** Call `enableBQ()` explicitly. It requires a HNSW float index with +dimensions divisible by 8 (128, 384, 768, 1536); incompatible indexes reject it. ### Low Recall diff --git a/docs/guides/COMPARISON_PGVECTOR.md b/docs/guides/COMPARISON_PGVECTOR.md index 503dbd7..b97fd0d 100644 --- a/docs/guides/COMPARISON_PGVECTOR.md +++ b/docs/guides/COMPARISON_PGVECTOR.md @@ -41,7 +41,7 @@ This guide compares EdgeVec with pgvector to help you choose the right vector da ### Quantization **EdgeVec** offers binary quantization (1-bit per dimension) which achieves: -- 32x memory reduction vs float32 +- Binary codes 32x smaller than float32 payloads; BQ-enabled float indexes retain F32 vectors for rescoring - 10-50x faster distance computation via Hamming distance - 85-95% recall retention (depends on data distribution) diff --git a/docs/guides/MOBILE_USAGE.md b/docs/guides/MOBILE_USAGE.md index 8857e14..1673ab9 100644 --- a/docs/guides/MOBILE_USAGE.md +++ b/docs/guides/MOBILE_USAGE.md @@ -28,7 +28,7 @@ platform-specific considerations for iOS Safari and Android Chrome. 1. **Lazy Loading**: Load EdgeVec only when needed 2. **Web Workers**: Use for background indexing 3. **Batch Operations**: Insert vectors in batches -4. **Quantization**: Use SQ8 for 4x memory reduction +4. **Memory Budgeting**: Limit retained vectors and compact tombstones; SQ8 configuration is available in native Rust, not the WASM API ## Example: Safe Mobile Initialization @@ -57,7 +57,7 @@ async function initEdgeVec() { ### "Out of memory" errors - Reduce the number of vectors stored in the index -- Use quantization (SQ8) for 4x memory reduction +- Compact deleted vectors to reclaim storage; enabling BQ retains the original float vectors - Implement pagination for large datasets ### Slow initial load diff --git a/docs/guides/REACT_INTEGRATION.md b/docs/guides/REACT_INTEGRATION.md index 3b2dd06..993b017 100644 --- a/docs/guides/REACT_INTEGRATION.md +++ b/docs/guides/REACT_INTEGRATION.md @@ -38,6 +38,17 @@ pnpm add edgevec react ## Quick Start +Initialize WASM once in your application bootstrap, before mounting components: + +```typescript +import init from 'edgevec'; +await init(); +// Mount your React application after initialization completes. +``` + +The packaged hook returns an `EdgeVecIndex`, whose insert/count APIs are `add()` +and `size`. Advanced examples that import `EdgeVec` use the separate raw API. + ```tsx import { useEdgeVec } from 'edgevec/react'; @@ -59,7 +70,7 @@ function App() { ## useEdgeVec Hook -Initialize an EdgeVec database with automatic WASM loading and lifecycle management. +Create or load an index after the application has initialized WASM. ### Basic Usage @@ -77,7 +88,7 @@ function VectorDatabase() { if (!isReady || !db) return; const vector = new Float32Array(384).map(() => Math.random()); - const id = db.insertWithMetadata(vector, { + const id = db.add(vector, { category: 'documents', timestamp: Date.now(), }); @@ -268,7 +279,7 @@ export function SemanticSearch() { for (const doc of docs) { const embedding = await getEmbedding(doc.text); - db.insertWithMetadata(new Float32Array(embedding), { + db.add(new Float32Array(embedding), { text: doc.text, category: doc.category, relevance: 1.0, @@ -606,17 +617,17 @@ function SearchWithRetry() { ### Suspense Integration (Experimental) -For React 18+ Suspense support, create a wrapper: +For React 19+ Suspense support with the stable `use` API, create a wrapper: ```tsx import { Suspense, use, useState } from 'react'; -import init, { EdgeVec } from 'edgevec'; +import init, { EdgeVec, EdgeVecConfig } from 'edgevec'; // Create a promise that resolves when WASM is loaded let wasmPromise: Promise | null = null; function initWasm() { if (!wasmPromise) { - wasmPromise = init(); + wasmPromise = init().then(() => undefined); } return wasmPromise; } @@ -627,7 +638,10 @@ function useEdgeVecSuspense(dimensions: number) { use(initWasm()); // Now safe to create EdgeVec - const [db] = useState(() => new EdgeVec({ dimensions })); + const [db] = useState(() => { + const config = new EdgeVecConfig(dimensions); + try { return new EdgeVec(config); } finally { config.free(); } + }); return db; } @@ -643,7 +657,7 @@ function App() { function SearchComponent() { const db = useEdgeVecSuspense(384); // db is guaranteed to be ready here - return
Ready! {db.vectorCount()} vectors
; + return
Ready! {db.liveCount()} vectors
; } ``` @@ -653,7 +667,7 @@ Share a single EdgeVec instance across your app: ```tsx import { createContext, useContext, ReactNode, useState, useEffect } from 'react'; -import init, { EdgeVec } from 'edgevec'; +import init, { EdgeVec, EdgeVecConfig } from 'edgevec'; interface EdgeVecContextType { db: EdgeVec | null; @@ -669,7 +683,18 @@ const EdgeVecContext = createContext({ error: null, }); -export function EdgeVecProvider({ +// Remount the provider subtree when its database identity changes. Cleanup then +// runs only after consumers of the old context have unmounted. +export function EdgeVecProvider(props: { + children: ReactNode; + dimensions?: number; + persistName?: string; +}) { + const identity = JSON.stringify([props.dimensions ?? 384, props.persistName ?? null]); + return ; +} + +function EdgeVecProviderInstance({ children, dimensions = 384, persistName, @@ -687,22 +712,32 @@ export function EdgeVecProvider({ useEffect(() => { let cancelled = false; + let ownedDb: EdgeVec | null = null; async function initialize() { try { await init(); if (cancelled) return; - const db = new EdgeVec({ dimensions }); + const config = new EdgeVecConfig(dimensions); + let db: EdgeVec; + try { db = new EdgeVec(config); } finally { config.free(); } if (persistName) { try { - await db.load(persistName); - } catch { - // No existing data, that's fine + const loaded = await EdgeVec.load(persistName); + db.free(); + db = loaded; + } catch (error) { + if (!(error instanceof Error) || error.name !== 'NotFoundError') { + db.free(); + throw error; + } } } + if (cancelled) { db.free(); return; } + ownedDb = db; setState({ db, isReady: true, @@ -725,6 +760,7 @@ export function EdgeVecProvider({ return () => { cancelled = true; + ownedDb?.free(); }; }, [dimensions, persistName]); @@ -788,7 +824,7 @@ For complex state management, integrate with Zustand: ```tsx import { create } from 'zustand'; -import init, { EdgeVec } from 'edgevec'; +import init, { EdgeVec, EdgeVecConfig } from 'edgevec'; interface VectorState { db: EdgeVec | null; @@ -813,7 +849,9 @@ export const useVectorStore = create((set, get) => ({ try { await init(); - const db = new EdgeVec({ dimensions }); + const config = new EdgeVecConfig(dimensions); + let db: EdgeVec; + try { db = new EdgeVec(config); } finally { config.free(); } set({ db, isReady: true, isLoading: false }); } catch (error) { set({ error: error as Error, isLoading: false }); @@ -1030,7 +1068,7 @@ module.exports = { **Checklist:** 1. Verify `isReady` is `true` 2. Verify `queryVector` is not `null` -3. Verify database has vectors: `db?.vectorCount()` +3. Verify the hook's `EdgeVecIndex` has vectors: `db?.size` 4. Check filter syntax is correct 5. Ensure `enabled` is `true` @@ -1039,10 +1077,9 @@ module.exports = { **Symptom:** Browser becomes unresponsive or crashes **Solutions:** -1. Use Binary Quantization: `db.searchBQ(query, k)` -2. Monitor memory: `db.getMemoryPressure()` -3. Compact regularly: `db.compact()` -4. Limit dataset size to ~100k vectors in browser +1. Limit retained vector count and dimensionality to the device's memory budget +2. For explicit pressure monitoring and compaction, use the raw `EdgeVec` API +3. Budget for retained F32 vectors when using BQ; enabling it adds binary codes ### Hooks called in wrong order diff --git a/docs/guides/VUE_INTEGRATION.md b/docs/guides/VUE_INTEGRATION.md index 66b4650..c65e0f8 100644 --- a/docs/guides/VUE_INTEGRATION.md +++ b/docs/guides/VUE_INTEGRATION.md @@ -38,6 +38,17 @@ pnpm add edgevec vue ## Quick Start +Initialize WASM once in your application bootstrap, before mounting components: + +```typescript +import init from 'edgevec'; +await init(); +// Mount your Vue application after initialization completes. +``` + +The composable returns an `EdgeVecIndex`, whose insert/count APIs are `add()` and +`size`. Advanced examples that import `EdgeVec` use the separate raw API. + ```vue